python - 在python中使用梯度下降
问题描述
我正在尝试实现与我的封闭形式解决方案相匹配的梯度下降。无法解决的一件事是我的 theta 要么由于错误而无法通过我的预测
ValueError: shapes (400,2) and (400,2) not aligned: 2 (dim 1) != 1 (dim 0)
或者在我的 theta 公式中,错误操作数不能与形状 (2,) (2,400) 一起广播。我想知道这是否是因为 theta 的初始化是错误的,无论我只是创建一个数组还是使用 zeros 函数。
import numpy as num
import pandas
import matplotlib.pyplot as plot
#gradient descent solution
def gradient_descent(X, y, theta, alpha, iterations):
for iteration in range(iterations):
hypothesis = X.dot(theta)
print(hypothesis)
loss = hypothesis-y
gradient = X.T.dot(loss)/m
theta = theta - alpha*gradient
return theta
ones = num.ones((x.shape[0], 1))
X = num.hstack((x,ones))
m=x.shape[0]
theta=num.array([0,0])
iterations =1500
alpha = 0.1
#calling gradient descent function
t = gradient_descent(X,y,theta,alpha,iterations)
print(t)
解决方案
推荐阅读
- c# - Ef core : 从列表的列表中过滤掉一个项目
- c# - SharePoint CSOM:从 GetChanges() 加载 FileSystemObjectType 属性
- listview - 无法在 ListView 的突出显示中引用内容
- spring - 使用多种配置保护同一端点
- c# - Microsoft Graph 发布操作以创建组“错误请求”
- vuejs2 - 从 nativescript-vue 应用程序中的 js 文件导入字符串
- python - 将列标签格式从日期时间更改为日期
- sql - SQL Server中从位置到位置的子字符串
- unix - SFTP 传输完成状态
- quartz-scheduler - 石英触发器消失 - 分钟 cron 与分钟间隔