PyTorch深度学习实战 第二讲

第二讲 线性模型 (b站刘二大人)

课堂代码

使用jupyter notebook

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):
    pred = forward(x)
    
    return (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)
# plot
plt.plot(w_list, mse_list)
plt.ylabel("LOSS")
plt.xlabel("w")
plt.show()

输出如图:
PyTorch深度学习实战 第二讲_第1张图片

作业代码:

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

x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]

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

def loss(x, y):
    pred_y = forward(x)
    
    return (pred_y - y)**2

W = np.arange(0.0, 4.0, 0.1)
B = np.arange(-2.0, 2.1, 0.1)
w, b = np.meshgrid(W, B)

mse = 0
for x, y in zip(x_data, y_data):
    mse += loss(x, y)
    
mse /= len(x_data)

fig = plt.figure()
ax = Axes3D(fig)
plt.xlabel(r'w', fontsize=20, color='cyan')
plt.ylabel(r'b', fontsize=20, color='cyan')
ax.plot_surface(w, b, mse, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
plt.show()

输出结果如图:
PyTorch深度学习实战 第二讲_第2张图片

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