-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1.py
More file actions
44 lines (34 loc) · 986 Bytes
/
1.py
File metadata and controls
44 lines (34 loc) · 986 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import numpy as np
import matplotlib.pyplot as plt
x_data = [1.0, 2.0, 3.0, 4.0, 5.0]
y_data = [2.0, 4.0, 6.0, 8.0, 10.0]
def forward(x):
return x * w
def loss(x, y):
y_pred = forward(x)
return (y_pred - y) * (y_pred - y)
w_list = []
mse_list = []
for w in np.arange(0.0, 4.1, 0.1):
print('w=', w)
l_sum = 0
for x_val, y_val in zip(x_data, y_data):
print('w=',w)
l_sum = 0
for x_val, y_val in zip(x_data, y_data):
y_pred_val = forward(x_val)
loss_val = loss(x_val, y_val)
l_sum += loss_val
print('\t', x_val, y_val, y_pred_val, loss_val)
print('MSE=', l_sum / 3)
w_list.append(w)
mse_list.append(l_sum / 3)
plt.plot(w_list, mse_list)
plt.title('MSE vs w')
plt.xlabel('w')
plt.ylabel('MSE')
plt.grid(True)
# 保存图片(推荐)
plt.savefig('./mse_vs_w.png', dpi=200, bbox_inches='tight')
print("✅ 图形已保存为 mse_vs_w.png")
plt.show()