【发布时间】:2017-07-26 21:35:03
【问题描述】:
我目前正在 python 上编写单变量线性回归的实现:
# implementation of univariate linear regression
import numpy as np
def cost_function(hypothesis, y, m):
return (1 / (2 * m)) * ((hypothesis - y) ** 2).sum()
def hypothesis(X, theta):
return X.dot(theta)
def gradient_descent(X, y, theta, m, alpha):
for i in range(1500):
temp1 = theta[0][0] - alpha * (1 / m) * (hypothesis(X, theta) - y).sum()
temp2 = theta[1][0] - alpha * (1 / m) * ((hypothesis(X, theta) - y) * X[:, 1]).sum()
theta[0][0] = temp1
theta[1][0] = temp2
return theta
if __name__ == '__main__':
data = np.loadtxt('data.txt', delimiter=',')
y = data[:, 1]
m = y.size
X = np.ones(shape=(m, 2))
X[:, 1] = data[:, 0]
theta = np.zeros(shape=(2, 1))
alpha = 0.01
print(gradient_descent(X, y, theta, m, alpha))
这段代码将在无穷大之后输出 theta 的 NaN - 我不知道出了什么问题,但这肯定与我在梯度下降函数中更改 theta 有关。
我使用的数据是我上网的一个简单的线性回归对数据集 - 并且加载正确。
谁能指出我正确的方向?
【问题讨论】:
标签: python machine-learning linear-regression