python - TypeError:gradientDesc() 正好采用 1 个参数(给定 4 个)
问题描述
尝试在 Python 中实现逻辑回归:
下面是成本函数:
def costFunction(theta_array):
m = len(X1)
theta_matrix = np.transpose(np.mat(theta_array))
H_x = 1 / (1 + np.exp(-X_matrix * theta_matrix))
J_theta = ((sum(np.multiply((-Y_matrix), np.log(H_x)) - np.multiply((1 - Y_matrix), np.log(1 - H_x)))) / m )[0, 0]
return J_theta
下面是梯度函数:
def gradientDesc(theta_tuple):
theta_matrix = np.transpose(np.mat(theta_tuple))
H_x = 1 / (1 + np.exp(-X_matrix * theta_matrix))
G_theta0 = (sum(np.multiply(H_x - Y_matrix, X_matrix[:, 0])) / m)[0, 0]
G_theta1 = (sum(np.multiply(H_x - Y_matrix, X_matrix[:, 1])) / m)[0, 0]
G_theta2 = (sum(np.multiply(H_x - Y_matrix, X_matrix[:, 2])) / m)[0, 0]
return np.array((G_theta0, G_theta1, G_theta2))
然后我运行 optimize.fmin_bfgs 函数,如下所示:
initial_theta = np.zeros((3, 1))
theta_tuple = (0, 0, 0)
theta_optimize = op.fmin_bfgs(costFunction, initial_theta, gradientDesc, args = (theta_tuple))
然后我收到以下错误:
**TypeError: gradientDesc() takes exactly 1 argument (4 given)**
谁能告诉我如何解决?:) 谢谢!
解决方案
对于参数,您应该指定一个带有逗号args
的单项元组(也称为单例);否则括号只会对表达式进行分组。
改变:
theta_optimize = op.fmin_bfgs(costFunction, initial_theta, gradientDesc, args = (theta_tuple))
至:
theta_optimize = op.fmin_bfgs(costFunction, initial_theta, gradientDesc, args = (theta_tuple,))
此外,您应该根据文档gradientDesc
接受一个附加参数。
改变:
def gradientDesc(theta_tuple):
至:
def gradientDesc(x, theta_tuple):
推荐阅读
- maven - 黄瓜+Maven+TestNG
- django - Django中数组的复选框值
- r - 如何在维恩图 R 中的每个图上添加标题
- c# - Visual Studio 2017 未在完成模式下突出显示
- git - 如何在不合并的情况下用另一个分支替换 Git 中的一个分支
- asp.net-core-2.1 - EF Core 2.1 Code First,如何实现运行时自动迁移。。
- php - twilio whatsapp api 响应状态不正确
- android - 材质 TextInputLayout 样式不起作用
- android - MutableliveData 从存储库返回 null 到 singleLiveEvent
- c# - Visual Studio 错误消息上的 XAML 预览器