学习视频:B站 刘二大人《PyTorch深度学习实践》完结合集
一、线性模型
三个步骤:
- 数据集
- 选择模型
- 训练
损失函数:
代码:
import numpy as np
import matplotlib.pyplot as plt
x_data = [1.0,2.0,3.0] #输入x
y_data = [2.0,4.0,6.0] #输出y
def forward(x): #线性模型
return x * w
def loss(x,y):
y_pred = forward(x) #计算y_hat
return (y_pred - y) * (y_pred - y) #损失函数,(y_hat-y)的平方
w_list = [] #记录下w与其对应的mse
mse_list = []
for w in np.arange(0.0,4.1,0.1): #列举w
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) #输出x,y以及y_hat,还有loss
print("MSE=",l_sum / 3)
w_list.append(w)
mse_list.append(l_sum / 3)
plt.plot(w_list,mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()
运行结果:
课后习题:
代码:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from pylab import *
#这里假设模型是y = 2*x + 2
x_data = [1.0,2.0,3.0] #输入x
y_data = [4.0,6.0,8.0] #输出y
def forward(x): #线性模型
return x * w + b
def loss(x,y):
y_pred = forward(x) #计算y_hat
return (y_pred - y) * (y_pred - y) #损失函数,(y_hat-y)的平方
mse_list = []
W = np.arange(0.0,4.1,0.1)
B = np.arange(0.0,4.1,0.1)
[w,b] = np.meshgrid(W,B)
l_sum = np.zeros_like(w)
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) #输出x,y以及y_hat,还有loss
# #查找loss最低的w,b取值
target = {'loss':float('inf'),'w':0,'b':0} #定义字典 将loss设为正无穷大,w=0,b=0
for i in range(l_sum.shape[0]): #读取l_sum的行数
for j in range(l_sum.shape[1]): #读取列数
if l_sum[i][j] < target['loss']:
target['loss'] = l_sum[i][j]
target['w'] = w[i][j]
target['b'] = b[i][j]
print('target linear model is y = %.2f * x + %.2f' % (target['w'], target['b']))
#定义三维坐标轴
fig = plt.figure()
ax = Axes3D(fig)
fig.add_axes(ax)
ax.plot_surface(w, b, l_sum/3,cmap=plt.cm.coolwarm)
ax.set_xlabel('w')
ax.set_ylabel('b')
ax.set_zlabel('loss')
plt.show()
参考资料:
https://blog.csdn.net/qq_36271858/article/details/115868825