成本函数和梯度似乎有效,但 scipy.optimize 函数无效

2024-03-21

我正在为 Andrew NG Coursera 课程编写 Matlab 代码,并将其转换为 python。我正在研究非正则化逻辑回归,在编写梯度和成本函数后,我需要类似于 fminunc 的东西,经过一番谷歌搜索后,我找到了几个选项。它们都返回相同的结果,但与 Andrew NG 的预期结果代码中的内容不匹配。其他人似乎让它正常工作,但我想知道为什么我的特定代码在使用 scipy.optimize 函数时似乎没有返回所需的结果,但在代码前面的成本和梯度部分却返回了预期的结果。

我正在使用的数据可以在下面的链接中找到;

ex2data1 https://drive.google.com/file/d/0B2hAHTxAKpLdUVdRR0QyaV9pRmc/view?usp=sharing

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as op


#Machine Learning Online Class - Exercise 2: Logistic Regression

#Load Data
#The first two columns contains the exam scores and the third column contains the label.

data = pd.read_csv('ex2data1.txt', header = None)
X = np.array(data.iloc[:, 0:2]) #100 x 3
y = np.array(data.iloc[:,2]) #100 x 1
y.shape = (len(y), 1)


#Creating sub-dataframes for plotting
pos_plot = data[data[2] == 1]
neg_plot = data[data[2] == 0]


#==================== Part 1: Plotting ====================
#We start the exercise by first plotting the data to understand the 
#the problem we are working with.

print('Plotting data with + indicating (y = 1) examples and o indicating (y = 0) examples.')

plt.plot(pos_plot[0], pos_plot[1], "+", label = "Admitted")
plt.plot(neg_plot[0], neg_plot[1], "o", label = "Not Admitted")
plt.xlabel('Exam 1 score')
plt.ylabel('Exam 2 score')
plt.legend()
plt.show()


def sigmoid(z):
    '''
    SIGMOID Compute sigmoid function
    g = SIGMOID(z) computes the sigmoid of z.
    Instructions: Compute the sigmoid of each value of z (z can be a matrix,
    vector or scalar).
    '''
    g = 1 / (1 + np.exp(-z))
    return g


def costFunction(theta, X, y):
    '''
    COSTFUNCTION Compute cost and gradient for logistic regression
    J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the
    parameter for logistic regression and the gradient of the cost
    w.r.t. to the parameters.
    '''
    m = len(y) #number of training examples

    h = sigmoid(X.dot(theta)) #logisitic regression hypothesis
    J = (1/m) * np.sum((-y*np.log(h)) - ((1-y)*np.log(1-h)))

    #h is 100x1, y is %100x1, these end up as 2 vector we subtract from each other
    #then we sum the values by rows
    #cost function for logisitic regression
    return J

def gradient(theta, X, y):
    m = len(y)
    grad = np.zeros((theta.shape))
    h = sigmoid(X.dot(theta))
    for i in range(len(theta)): #number of rows in theta
        XT = X[:,i]
        XT.shape = (len(X),1)
        grad[i] = (1/m) * np.sum((h-y)*XT) #updating each row of the gradient
    return grad


#============ Part 2: Compute Cost and Gradient ============
#In this part of the exercise, you will implement the cost and gradient
#for logistic regression. You neeed to complete the code in costFunction.m


#Add intercept term to x and X_test
Bias = np.ones((len(X), 1))
X = np.column_stack((Bias, X))


#Initialize fitting parameters
initial_theta = np.zeros((len(X[0]), 1))


#Compute and display initial cost and gradient
(cost, grad) = costFunction(initial_theta, X, y), gradient(initial_theta, X, y)

print('Cost at initial theta (zeros): %f' % cost)
print('Expected cost (approx): 0.693\n')
print('Gradient at initial theta (zeros):')
print(grad)
print('Expected gradients (approx):\n -0.1000\n -12.0092\n -11.2628')


#Compute and display cost and gradient with non-zero theta
test_theta = np.array([[-24], [0.2], [0.2]]);
(cost, grad) = costFunction(test_theta, X, y), gradient(test_theta, X, y)

print('\nCost at test theta: %f' % cost)
print('Expected cost (approx): 0.218\n')
print('Gradient at test theta:')
print(grad)
print('Expected gradients (approx):\n 0.043\n 2.566\n 2.647\n')


result = op.fmin_tnc(func = costFunction, x0 = initial_theta, fprime = gradient, args = (X,y))
result[1]


Result = op.minimize(fun = costFunction, 
                                 x0 = initial_theta, 
                                 args = (X, y),
                                 method = 'TNC',
                                 jac = gradient, options={'gtol': 1e-3, 'disp': True, 'maxiter': 1000})


theta = Result.x
theta

test = np.array([[1, 45, 85]]) 
prob = sigmoid(test.dot(theta))
print('For a student with scores 45 and 85, we predict an admission probability of %f,' % prob)
print('Expected value: 0.775 +/- 0.002\n')

这是一个非常难以调试的问题,并且说明了该问题的文档记录不足的一个方面scipy.optimize界面。该文档模糊地表明theta将作为vector:

一个或多个变量的标量函数的最小化。

一般来说,优化问题的形式如下:

minimize f(x) subject to

g_i(x) >= 0,  i = 1,...,m
h_j(x)  = 0,  j = 1,...,p 

其中 x 是一个或多个变量的向量。

重要的是它们的真正含义vector最原始意义上的一维数组。所以你必须预料到,无论何时theta被传递到您的回调之一中,它将作为一维数组传递。但在numpy,一维数组的行为有时与二维行数组不同(显然,也与二维列数组不同)。

我不知道为什么它会在你的情况下引起问题,但无论如何它很容易修复。您只需在成本函数和梯度函数的顶部添加以下内容:

theta = theta.reshape(-1, 1)                                           

这保证了theta正如预期的那样,将是一个二维列数组。完成此操作后,结果就是正确的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

成本函数和梯度似乎有效,但 scipy.optimize 函数无效 的相关文章

随机推荐

  • Mongoid has_and_belongs_to_many 关联

    我试图让 mongoid 来保存关联 但我只能让一侧工作 如果我有以下测试 test should add a user as a follower when a user follows the group do cali group f
  • 没有“isPresent()”检查的“Optional.get()”

    我有以下 Java 搜索代码 return getTableViewController getMe getColumns stream filter gt Database equalsColumnName getId columnId
  • ActionController::Live 是否可以检查连接是否仍然有效?

    我正在尝试使用 Rails 4 的实时流媒体来实现文本 事件流 它工作得很好 我遇到的唯一麻烦是我无法在不发送任何消息的情况下检查连接是否有效 我想到的唯一解决方案是使用循环刻度生成器创建支持通道 以便某些后台任务会定期向那里发送消息 但看
  • 调用构造函数重新初始化对象

    是否可以使用类的构造函数重新初始化类的对象 有点 给定 A 类 A a a A 最后一条语句不是初始化 而是赋值 但它可能会执行您想要的操作
  • 如何在jboss中生成resteasy的wadl文件

    我想为我的项目生成一个 wadl 文件 该文件使用resteasy Jboss 6 4 Maven 有很多关于球衣的例子 但不是关于resteasy的 有人用它来resteasy吗 Resteasy 从 3 0 14 Final 开始支持
  • 对 Cassandra 术语感到困惑(行与分区)

    我希望有人能够消除我对 Cassandra 中的行和分区之间的区别的困惑 我认为一行将是一组列 就像在 SQL 数据库中 如架构中指定的那样 按分区键跨节点分布 并按每个分区内的集群键排序 但后来我遇到了这个教程 https academy
  • 我应该如何处理非常非常长的 URL?

    我想知道这是否是一个错误 但现在我对所有搜索 URL 都使用 GET 原因是 通过 GET Url 用户可以简单地复制地址栏上的链接并轻松共享或保存 例如 Google 似乎也使用 GET Url 表单 由于它是一个带有过滤器 排序器等的搜
  • 在nodebox opengl中向图形的边缘添加标签

    我正在尝试向图表中的每个边添加标签 如下所示 基本上上面的每个边缘都有标签在中心 当我向每个图表添加边时 我尝试添加标签 就像这样 对于图表g g add edge label edge distance 经过一番研究 我发现这样的标签是可
  • 将值分配给特定的 data.table 列和行

    仍然理解这个伟大的包 有人可以解释一下这个错误的原因吗 谢谢 library data table DT lt data table id LETTERS var1 rnorm 26 var2 rnorm 26 gt DT 2 list v
  • 如何在heroku上的两个不同应用程序之间共享worker?

    我有两个独立的应用程序在heroku上运行并指向同一个数据库 第一个负责user interface第二个为admin interface 我在用sidekiq with redis对于后台作业处理 我添加了一个工作人员 并且可以通过设置指
  • 对大文件使用 Rijndael 加密

    我面临的情况是 我需要安全地加密 解密 n 长度的文件 最好使用 Rijndael 但绝对是 256 位加密 我以前玩过加密 并且非常高兴地加密 解密了字符串和字节数组 但是 因为我不知道文件的大小 并且有问题的文件可能非常大 2 5gb
  • 从 VB.NET 应用程序将文件发送到 PHP 脚本

    我需要将一些数据从内部网络上的 SQL DB 服务器发送到外部 Web 服务器 我希望通过编写一个每天调用一次的 VB NET 应用程序来实现此目的 该应用程序将大约 1 MB 的数据发送到 Web 服务器上的 PHP 脚本 然后将其存储在
  • node.js -- 同步执行命令并获取结果

    我试图在 node js 中同步执行 child process 是的 我知道这很糟糕 我有充分的理由 并检索 stdout 上的任何输出 但我不太清楚如何 我发现这个帖子 Node js同步执行系统命令 https stackoverfl
  • 如何在 VBA Sub 中应用 SumIf 公式?出现错误 1004

    我正在尝试创建一个 Sub 来放置SUMIF单元格中的公式 我已将问题简化为简单的设置 Private Sub CommandButton1 Click Cells 2 3 Formula SUMIF A1 A5 D1 B1 B5 End
  • Azure 云存储帐户的连接字符串

    如何创建到云存储帐户的连接字符串以便可以访问表 blob 和队列 示例代码表示赞赏 如果您在 Azure 门户中查看相关存储帐户下的内容 并查看左侧导航栏中的 访问密钥 项 则会显示提供的两个密钥以及访问存储帐户所需的整个连接字符串
  • 链接 C++ 流

    我正在考虑将几个 C iostream 链接 在一起以过滤输入两次 我正在使用 gzstreams 读取 zlib 压缩文件 并且正在考虑编码一个从流中读取并执行编码转换的流 也许通过传递一个打开的流作为构造函数参数 您认为这可以最好地实现
  • 水晶报表-关闭数据库连接

    这是C Visual Studio 2008 VS2008附带的水晶报表 我有一个驻留在 DLL 中的水晶报表查看器表单 DLL 负责加载水晶报表 基于报表文件名 并将报表显示在窗体上 当我完成水晶报表后 我对加载的报表文档对象调用 dis
  • Yeomen webapp 生成器在 Windows 上的 grunt 构建上失败

    我正在尝试 yeomen 脚手架工具 唯一的问题是我遇到了一些问题和咕噜声 我正在尝试使用 webapp 生成器组装一个简单的网站 搭建应用程序并使用grunt serve工作完美 仅在使用时失败grunt build 它失败并显示以下消息
  • 在for循环中取消NSOperation?

    我正在尝试使用在后台线程上实现搜索NSOperation on iOS 我不想子类化NSOperation所以这就是我正在做的 searchQueue cancelAllOperations NSInvocationOperation op
  • 成本函数和梯度似乎有效,但 scipy.optimize 函数无效

    我正在为 Andrew NG Coursera 课程编写 Matlab 代码 并将其转换为 python 我正在研究非正则化逻辑回归 在编写梯度和成本函数后 我需要类似于 fminunc 的东西 经过一番谷歌搜索后 我找到了几个选项 它们都