在python中使用梯度下降

2024-05-13 09:18:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图实现梯度下降,将符合我的封闭形式的解决方案。有一件事还没有解决,那就是我的θ要么因为错误而不能通过我的预测

ValueError: shapes (400,2) and (400,2) not aligned: 2 (dim 1) != 1 (dim 0)

或者在我的θ公式中,错误操作数不能与形状(2,)(2400)一起广播。我想知道这是否是因为θ的初始化是错误的,无论我是制作一个数组还是使用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) 


Tags: importalphaas错误onesnumdothypothesis