PyTorch深度学习实践L2——线性模型

文章目录

  • 1、linear_model 源代码
  • 2、作业代码

1、linear_model 源代码

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_pred - 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 = 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.ylabel('Loss')
plt.xlabel('w')
plt.show()

2、作业代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

# y = x*2.5-1 构造训练数据
x_data = [1.0, 2.0, 3.0]
y_data = [1.5, 4.0, 6.5]
W, B = np.arange(0.0, 4.1, 0.1), np.arange(-2.0, 2.1, 0.1)  # 规定 W,B 的区间
'''
针对本题,传入的 w、b 都是一列数据,
利用np.meshgrid()函数将 w、b两列数据转化成二维矩阵,
而后再传入参数
'''
# 将W,B变成二位矩阵
[w, b] = np.meshgrid(W, B, indexing='ij')  # 构建矩阵坐标


def forward(x):
    return x * w + b

def loss(y_pred, y):
    return (y_pred - y) * (y_pred - y)


# Make data.
mse_lst = []
l_sum = 0.
for x_val, y_val in zip(x_data, y_data):
    y_pred_val = forward(x_val)
    loss_val = loss(y_pred_val, y_val)
    l_sum += loss_val
mse_lst.append(l_sum / 3)

# 定义figure
fig = plt.figure(figsize=(10, 10), dpi=300)
# 将figure变为3d
ax = fig.add_subplot(projection='3d')
# 绘图,rstride:行之间的跨度  cstride:列之间的跨度
surf = ax.plot_surface(w, b, np.array(mse_lst[0]), rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0,
                       antialiased=False)
# Customize the z axis.
ax.set_zlim(0, 40)
# 设置坐标轴标签
ax.set_xlabel("w")
ax.set_ylabel("b")
ax.set_zlabel("loss")
ax.text(0.2, 2, 43, "Cost Value", color='black')
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()

注意
将W,B变成二位矩阵
[w, b] = np.meshgrid(W, B, indexing=‘ij’)

你可能感兴趣的:(PyTorch,深度学习实践,深度学习,pytorch,python)