[Master Liu Er] Pytorch deep learning practice (1): code and drawing implementation of linear models y=w*x and y=w*x+b


Learning video: Master Liu pytorch1-linear model

Question description

1. y=w*x

Use the linear model y = w*x to calculate the loss value of the model and use matplotlib to give the cost function image.

Insert image description here

2. y=w*x+b

Use the linear model y = w*x+b to give the cost function image, and use 3D graphics to draw the image.

Insert image description here

code

Question 1: y = w*x

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_pred = forward(x)
    return (y-y_pred)*(y-y_pred)

# 记录画图的x值和y值
w_list = []
loss_mse_list = []
# 计算数据集中数据个数
n = len(x_data)
for w in np.arange(0.0,4.1,0.1):
    w_list.append(w)
    print("w=",w)
    # 存储每一个数据对的loss值的和
    loss_sum = 0
    for x,y in zip(x_data,y_data):
        y_pred = forward(x)
        # 一个数据对的loss值
        loss1 = loss(x,y)
        loss_sum += loss1
        print('\t',x,y,y_pred,loss1)
        # 对loss和求平均
    loss_mse_list.append(loss_sum/n)
    print('MSE=',loss_sum/n)

plt.plot(w_list,loss_mse_list)
plt.xlabel("w")
plt.ylabel("mse loss")
plt.show()

Why should process information be printed?

Record logs to prevent loss of training data when the program stops abnormally during training.

Insert image description here

Insert image description here

Question 2: y = wx+b

Drawing:matplotlib-3d drawing method

import numpy as np
import matplotlib.pyplot as plt

# 训练数据
x_data = [1.0,2.0,3.0]
y_data = [3.0,5.0,7.0]

# 前向传播计算预测值
def forward(x):
    return x*w+b

# 计算损失值的平方
def loss(x,y):
    y_pred = forward(x)
    return (y-y_pred)*(y-y_pred)

# 记录画图的x值和y值
w_list = np.arange(0.0,4.1,0.1)
b_list = np.arange(-2.0,2.1,0.1)
loss_mse_list = []
# 计算数据集中数据个数
n = len(x_data)

for w in w_list:
    for b in b_list:
        l_sum = 0
        for x,y in zip(x_data,y_data):
            l_sum+=loss(x,y)
        loss_mse_list.append(l_sum/n)

w_list, b_list=np.meshgrid(w_list, b_list)
mse_list=np.array(loss_mse_list).reshape(len(w_list),-1)

fig = plt.figure()  # 创建图片
sub = fig.add_subplot(111, projection='3d')  # 添加子图,
surf = sub.plot_surface(w_list, b_list, mse_list, cmap=plt.cm.brg)  # 绘制曲面,并设置颜色cmap
cb = fig.colorbar(surf, shrink=0.8, aspect=15)  # 设置颜色棒

sub.set_xlabel(r"$w$")
sub.set_ylabel(r"$b$")
sub.set_zlabel(r"$loss$")
plt.show()

Insert image description here

drawing tools

wisdom :wisdom usage

Guess you like

Origin blog.csdn.net/weixin_45662399/article/details/134031644