1. 查看版本
torch.__version__
2. pandas 读取数据
import pandas as pd
data = pd.read_csv('./....csv')
data.head
data.info
3. 画散点图
import matplotlib.pyplot as plt
plt.scatter(data.Education, data.Income)
plt.xlabel('Education')
plt.ylabel('Income')
4. 基本步骤:
a. 数据预处理
b. 设计模型 优化器 损失函数
c. 训练
d. 测试
记录样本和标签
data.Education.values
X = data.Education.values.reshape(-1,1)
Y = data.Income.values.reshape(-1,1)
X = torch.from_numpy(X) #numpy --> tensor
Y = torch.from_numpy(Y)
X = X.type(torch.FloatTensor)
Y = Y.type(torch.FloatTensor)
模型创建:
from torch import nn
class EIModel(nn.Module):
def __init__(self):
super(EIMdoel, self).__init__()
self.linear = nn.Linear(in_features = 1 , out_features = 1)
def forward(self, inputs):
logits = self.linear(inputs)
return logits
损失函数 + 优化器
# 损失函数 均方误差
loss_fn = nn.MSELoss()
# 优化函数 随机梯度下降
# 模型参数 + 学习率
opt = torch.optim.SGD(model.parameters(), lr = 0.0001)
train 过程
for epoch in range(5000):
for x,y in zip(X,Y):
# 预测
y_pred = model(x)
# 计算损失
loss = loss_fn(y_pred, y)
# 梯度清零
opt.zero_grad()
# 反向传播
loss.backward()
# 更新参数
opt.step()
list(model.parameters()) 查看参数
model.linear.weight
查看拟合图像
plt.scatter(data.Education, data.Income)
plt.xlabel('Education')
plt.ylabel('Income')
plt.plot(X.model(X).detach().numpy() , c = 'r')
5. tensor 与 numpy 转换
tensor 2 numpy
t.numpy()
numpy 2 tenosr
torch.from_numpy()
参考b站 pytorch 教学