数据集ref:https://raw.githubusercontent.com/justinge/pic-go-for-xbotgo/master/Income1.csv
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))
y_pred = model(x) # 预测
loss = loss_fn(y, y_pred) # 计算损失
opt.zero_grad() # 梯度清零
loss.backward() # 反向传播
opt.step() # 下一次
总的来说
python
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv("/home/data_for_ai_justin/01learn/dataset/Income1.csv")
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))
loss_fn = nn.MSELoss()
int_features, out_features = 1, 1
model = nn.Linear(int_features,out_features)
opt = torch.optim.SGD(
model.parameters(),
lr=0.0001
)
for i in range(5000):
for x,y in zip(X,Y):
y_pred = model(x)
loss = loss_fn(y, y_pred)
opt.zero_grad()
loss.backward()
opt.step()
plt.scatter(data.Education, data.Income)
plt.plot(X.numpy(), model(X).data.numpy(),c='r')
plt.savefig("1.jpg")
分解写法
python
df = pd.read_csv("/home/data_for_ai_justin/01learn/dataset/Income1.csv")
X=torch.from_numpy(df.Education.values.reshape(-1,1).astype(np.float32))
Y=torch.from_numpy(df.Income.values.reshape(-1,1).astype(np.float32))
w = torch.randn(1,requires_grad=True)
b = torch.zeros(1,requires_grad=True)
learning_rate = 0.001
for i in range(5000):
for x,y in zip(X,Y):
y_pred = torch.matmul(x,w) + b
loss=(y-y_pred).pow(2).mean()
if w.grad is not None:
w.grad.data.zero_()
if b.grad is not None:
b.grad.data.zero_()
loss.backward()
with torch.no_grad():
w.data -= w.grad.data * learning_rate
b.data -= b.grad.data * learning_rate
plt.scatter(df.Education, df.Income)
plt.xlabel = "x"
plt.ylabel = "y"
plt.plot(X.numpy(), (torch.matmul(X,w) + b).data.numpy(),c='r')
plt.show()