PyTorch Tutorial 07 - Linear Regressi...

教程Python代碼如下:
# 1) Design model(input, output size, forward pass)
# 2) Construct loss and optimizer
# 3) Training loop 訓(xùn)練循環(huán)
#??- forward pass: compute prediction
#??- backward pass: gradients
#??- update weights
import torch
import torch.nn as nn
import numpy as np
# ModuleNotFoundError: No module named 'sklearn':需要注意報(bào)錯(cuò)的sklearn是scikit-learn縮寫(xiě),pip install scikit-learn
# 清華源:pip install scikit-learn -i https://pypi.tuna.tsinghua.edu.cn/simple
from sklearn import datasets
import matplotlib.pyplot as plt
# 0) prepare data
X_numpy, Y_numpy = datasets.make_regression(n_samples=100, n_features=1, noise=20, random_state=1)
X = torch.from_numpy(X_numpy.astype(np.float32))
Y = torch.from_numpy(Y_numpy.astype(np.float32))
#重塑張量
Y = Y.view(Y.shape[0],1)
n_samples,n_features = X.shape
# 1) model
input_size = n_features
output_size = 1
model = nn.Linear(input_size,output_size)
# 2) loss and optimizer
learning_rate = 0.01 #學(xué)習(xí)速率
criterion = nn.MSELoss() #均方誤差
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) #優(yōu)化器
# 3) training loop
num_epochs = 100
for epoch in range(num_epochs):
??# forward pass
??y_predicted = model(X)
??loss = criterion(y_predicted,Y)
??# backward pass
??loss.backward()
??# update
??optimizer.step()
??optimizer.zero_grad() # 清空grad
??if(epoch+1) % 10 == 0:
????print(f'epoch: {epoch+1}, loss = {loss.item():.4f}')
#plot,Matplotlib下的函數(shù),plot函數(shù):繪圖
predicted = model(X).detach().numpy()
plt.plot(X_numpy, Y_numpy,'ro')
plt.plot(X_numpy, predicted, 'b')
plt.show()