【问题标题】:function returning nan in for loop when performing multivariate linear regression执行多元线性回归时在 for 循环中返回 nan 的函数
【发布时间】:2017-08-28 05:33:53
【问题描述】:

从下面的代码中可以看出,我正在纯 python 中执行多元线性回归。有人可以告诉我他的代码有什么问题吗? 我对单变量线性回归做了同样的事情。在里面表现不错!

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

x_df=pd.DataFrame([[2.0,70.0],[3.0,30.0],[4.0,80.0],[4.0,20.0],[3.0,50.0],[7.0,10.0],[5.0,50,0],[3.0,90.0],[2.0,20.0]])
y_df=pd.DataFrame([79.4,41.5,97.5,36.1,63.2,39.5,69.8,103.5,29.5])
x_df=x_df.drop(x_df.columns[2:], axis=1)

#print(x_df)

m=len(y_df)
#print(m)

x_df['intercept']=1
X=np.array(x_df)
#print(X)
#print(X.shape)
y=np.array(y_df).flatten()
#print(y.shape)
theta=np.array([0,0,0])
#print(theta)

def hypothesis(x,theta):
    return np.dot(x,theta)

#print(hypothesis(X,theta))

def cost(x,y,theta):
    m=y.shape[0]
    h=np.dot(x,theta)
    return np.sum(np.square(y-h))/(2.0*m)

#print(cost(X,y,theta))

def gradientDescent(x,y,theta,alpha=0.01,iter=1500):
    m=y.shape[0]

    for i in range(1500):
        h=hypothesis(x,theta)
        error=h-y
        update=np.dot(error,x)
        theta=np.subtract(theta,((alpha*update)/m))


    print('theta',theta)
    print('hyp',h)
    print('y',y)
    print('error',error)
    print('cost',cost(x,y,theta))

print(gradientDescent(X,y,theta))

我得到的输出是:-

theta [ nan  nan  nan]
hyp [ nan  nan  nan  nan  nan  nan  nan  nan  nan]
y [  79.4   41.5   97.5   36.1   63.2   39.5   69.8  103.5   29.5]
error [ nan  nan  nan  nan  nan  nan  nan  nan  nan]
cost nan

有人可以帮我解决这个问题吗?我已经尝试了将近 5 个小时!

【问题讨论】:

    标签: python machine-learning linear-regression


    【解决方案1】:

    您的学习率太大而无法收敛,请尝试 alpha=0.00001。

    【讨论】:

    • 非常感谢杨!你怎么知道的?学习率收敛的东西!只看代码?
    • print(error=h-y), 如果每次迭代都没有缩小,尝试更小的学习率。学习率意味着你接近最佳点的速度。如果 alpha 太大,它将在每次迭代中运行到最佳点。假设当前点和最佳点之间的距离是 5 个单位。您采取的步骤是 alpha*update = 10 单位。事实证明,梯度下降不会收敛到最佳点,因为您在每次迭代中都会遇到它。
    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 2020-12-28
    • 2014-12-30
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 2019-12-31
    • 2019-06-02
    相关资源
    最近更新 更多