-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex02.py
More file actions
42 lines (32 loc) · 1.01 KB
/
ex02.py
File metadata and controls
42 lines (32 loc) · 1.01 KB
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
import numpy as np
import matplotlib.pyplot as plt
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
def foward(x):
return x*w
def loss(x, y):
return (x*w-y)**2
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):
y_pred_val = foward(x_val)
loss_val = loss(x_val, y_val) #注
l_sum += loss_val
print('\t', x_val, y_val, y_pred_val)
print('MSE=', l_sum / 3, '\n')
w_list.append(w)
mse_list.append(l_sum/len(x_data))
plt.plot(w_list, mse_list)
plt.xlabel('w')
plt.ylabel('MSE')
plt.show()
#You used the same name loss for:
#the function def loss(x, y): ...
#a variable inside the loop: loss = loss(x_val, y_val)
#This line redefines (overwrites) the name loss — so after the first iteration,
#loss is no longer a function, it’s just a float number.
#Then, on the next loop, when Python tries to do loss(x_val, y_val),
#it fails — because loss is now a number, not a callable function.