import numpy as np import matplotlib.pyplot as plt import random x_data = [1, 2, 3, 4, 5] y_data = [x + random.uniform(1, 2) for x in x_data] w = 1 learning_rate = 0.01 def forward(x): return x * w def loss(x, y): loss = 0 for x, y in zip(x_data, y_data): y_pred = forward(x) loss += (y_pred - y) ** 2 return loss / len(x_data) def gradient(x, y): grad = 0 for x, y in zip(x_data, y_data): grad += 2 * x *(x * w - y) return grad / len(x_data) for epoch in range(100): loss_val = loss(x_data, y_data) grad_val = gradient(x_data, y_data) w -= learning_rate * grad_val print(f"第{epoch}轮,w={w}, loss={loss_val}") plt.plot(loss_val, w) plt.xlabel('w') plt.ylabel('loss') plt.show() print(f'预测值是{forward(6)}'),哪里错了怎么改
时间: 2023-11-14 16:04:23 浏览: 145
python绘制直方图方法
代码中有一些问题:
1. `plt.plot(loss_val, w)` 应该改为 `plt.plot(w, loss_val)`,因为 `plt.plot()` 的第一个参数是 x 轴的值,第二个参数是 y 轴的值。
2. `loss_val` 在每个 epoch 中都被计算,但是只有在最后一个 epoch 才被用于绘图,应该将其记录在一个列表中,每个 epoch 结束后将其添加到列表末尾。
3. `print(f'预测值是{forward(6)}')` 应该放在循环外面,因为它不需要在每个 epoch 中都被计算。
下面是修改后的代码:
```python
import numpy as np
import matplotlib.pyplot as plt
import random
x_data = [1, 2, 3, 4, 5]
y_data = [x + random.uniform(1, 2) for x in x_data]
w = 1
learning_rate = 0.01
loss_list = [] # 记录每个 epoch 的 loss
def forward(x):
return x * w
def loss(x, y):
loss = 0
for x, y in zip(x_data, y_data):
y_pred = forward(x)
loss += (y_pred - y) ** 2
return loss / len(x_data)
def gradient(x, y):
grad = 0
for x, y in zip(x_data, y_data):
grad += 2 * x *(x * w - y)
return grad / len(x_data)
for epoch in range(100):
loss_val = loss(x_data, y_data)
loss_list.append(loss_val) # 记录每个 epoch 的 loss
grad_val = gradient(x_data, y_data)
w -= learning_rate * grad_val
print(f"第{epoch}轮,w={w}, loss={loss_val}")
plt.plot(w_list, loss_list) # 绘制 loss 曲线
plt.xlabel('w')
plt.ylabel('loss')
plt.show()
print(f'预测值是{forward(6)}')
```
运行上面的代码后,你应该会得到一个 loss 曲线和一个预测值。
阅读全文