首页 > 解决方案 > 在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) 

标签: pythonnumpymachine-learninglinear-regression

解决方案


推荐阅读