日期:2020.10.31
主题:PyTorch入门
内容:
- 学习如何构建线性模型解决问题。
问题:学习时长 x 与考试成绩 y 的关系?
学习时长 x | 考试成绩 y |
---|---|
1 | 2 |
2 | 4 |
3 | 6 |
4 | ? |
思路:
具体代码如下 ↓
import numpy as np
import matplotlib.pyplot as plt
# Import necessary library to draw the graph
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
# Prepare the train set
def forward(x):
return x * w
# Define the model
def loss(x, y):
y_pred = forward(x)
return (y_pred - y) ** 2
# Define the loss function
w_list = [] # Save the weights w
mse_list = [] # Save the cost values of each w
for w in np.arange(0.0, 4.1, 0.1):
# Compute cost value at [0.0, 0.1, 0.2, ..., 4.0]
print('w = ', w)
l_sum = 0
for x_val, y_val in zip(x_data, y_data): # get [(x1, y1), ...]
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)
# For each sample in train set, the loss function values were computed.
MSE = l_sum / 3
print('MSE = ', MSE)
w_list.append(w)
mse_list.append(MSE)
plt.plot(w_list, mse_list)
plt.ylabel('Loss')
plt.xlabel('w')
plt.show()
# Draw the graph
结果: