【发布时间】:2022-01-13 19:45:08
【问题描述】:
目前正在尝试使用 jupyter 笔记本上的一些测试数据点运行非常基本的线性回归。下面是我的代码,正如你所看到的,如果你运行它,预测线肯定会朝着它应该去的地方移动,但是由于某种原因它停止了,我不确定为什么。谁能帮帮我?
起始权重
结束权重
损失
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook
plt.style = "ggplot"
y = np.array([30,70,90,120,150,160,190,220])
x = np.arange(2,len(y)+2)
N = len(y)
weights = np.array([0.2,0.2])
plt.figure()
plt.scatter(x, y, color="red")
plt.plot(y_hat)
x_ticks = np.array([[1,x*0.1] for x in range(100)])
y_hat = []
for j in range(len(x_ticks)):
y_hat.append(np.dot(weights, x_ticks[j]))
def plot_model(x, y, weights, loss):
x_ticks = np.array([[1,x*0.1] for x in range(100)])
y_hat = []
for j in range(len(x_ticks)):
y_hat.append(np.dot(weights, x_ticks[j]))
plt.figure()
plt.scatter(x, y, color="red")
plt.plot(y_hat)
plt.figure()
plt.plot(loss)
def calculate_grad(weights, N, x_proc, y, loss):
residuals = np.sum(y.reshape(N,1) - weights*x_proc, 1)
loss.append(sum(residuals**2)/2)
#print(residuals, x_proc)
return -np.dot(residuals, x_proc)
def adjust_weights(weights, grad, learning_rate):
weights -= learning_rate*grad
return weights
learning_rate = 0.006
epochs = 2000
loss = []
x_processed = np.array([[1,i] for i in x])
for j in range(epochs):
grad = calculate_grad(weights, N, x_processed, y, loss)
weights = adjust_weights(weights, grad, learning_rate)
if j % 200 == 0:
print(weights, grad)
plot_model(x, y, weights, loss)
【问题讨论】:
-
你能检查水平轴是否正确对齐?
-
函数之前有一些额外的代码 - 问题不存在,但有点混乱。
-
我认为@fuenfundachtzig 有一点,尝试用相似的轴绘制 y 和 y_hat,例如:xx=np.linspace(x[0],x[-1],len(y_hat)) plt.plot(x, y,'.',xx,y_hat,'-')
标签: python numpy machine-learning regression linear-regression