本文主要是介绍【深度学习】复习温故而知新1,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
数据集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() # 下一次
总的来说
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import matplotlib.pyplot as pltdata = 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")
分解写法
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) + bloss=(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_rateb.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()
这篇关于【深度学习】复习温故而知新1的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!