pytorch入门——基于pytorch构建一个线性回归学习模型
import torch
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
# 1.读取数据
data = pd.read_csv(r'C:\Users\22789\Desktop\Income1.csv')
# 2.数据预处理
X = torch.from_numpy(data.Education.values.reshape(-1,1).astype(np.float32))
Y = torch.from_numpy(data.Income.values.reshape(-1,1).astype(np.float32))
# 3.构建神经网络模型
from torch import nn
model = nn.Linear(1,1)
loss_fn = nn.MSELoss()
opt = torch.optim.SGD(model.parameters(),lr=0.001)
for i in range(1000):
for x,y in zip(X,Y):
y_pred = model(x)
loss = loss_fn(y,y_pred)
opt.zero_grad()
loss.backward()
opt.step()
if i%50==0:
print(f'第{i}轮训练结束,model_parameters:{model.bias}')
# 4.验证模型学习效果
plt.scatter(X.numpy(),Y.numpy())
plt.xlabel('Education')
plt.ylabel('Income')
plt.plot(X.numpy(),model(X).data.numpy(),c='red')
本文来自博客园,作者:TCcjx,转载请注明原文链接:https://www.cnblogs.com/tccjx/articles/16470271.html