指路 ☞ 《PyTorch深度学习实践》完结合集_哔哩哔哩_bilibili
知识补充:
1、zip(x_data, y_data) 表示将将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。即x_data和y_data一一对应,形成9个坐标
2、append()表示在列表最后再添加一个元素
a=[1,2,3]
a.append(6)
运行结果为[1,2,3,6]
3、Python enumerate() 函数 | 菜鸟教程
**********************************************************************************************************
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 forward(x):
return x * w
def loss(x, y):
y_p = forward(x)
return (y_p - 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_p_val = forward(x_val)
loss_val = loss(x_val, y_val)
l_sum += loss_val
print('\t', x_val, y_val, y_p_val, l_sum)
print('MSE =', l_sum / 3)
w_list.append(w)
mse_list.append(l_sum / 3)
plt.plot(w_list, mse_list)
plt.xlabel('w')
plt.ylabel('Loss')
plt.show()
部分运行结果如下:
*****************************************************************************************
作业:实现y=2.5x+1,并输出loss的3D图像
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#这里设函数为y=3x+2
x_data = [1.0,2.0,3.0]
y_data = [5.0,8.0,11.0]
#前向传播
def forward(x):
return x * w + b
#损失函数
def loss(x,y):
y_pred = forward(x)
return (y_pred-y)*(y_pred-y)
l_sum =0
w_list =[]
b_list =[]
mse_list = np.zeros((40, 40), dtype=float)
for i, w in enumerate(np.arange(0.0, 4.0, 0.1)):
print("w=", w)
for j, b in enumerate(np.arange(-2.0, 2.0, 0.1)):
print("b=", b)
l_sum =0.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 = l_sum+loss_val
#print('\t', x_val, y_val, y_pred_val, loss_val)
# print("MSE=", l_sum/3)
mse_list[i][j] = l_sum/3
if w == 0:
b_list.append(b)
print('b_list=', b_list)
w_list.append(w)
#print('b_list=', b_list)
print('w_list=', w_list)
x, y = np.meshgrid(w_list, b_list)
z = np.array(mse_list)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(x, y, z)
plt.show()