1.导入必要的库
2.准备数据
3.定义数据集类(可选)
4.加载数据
5.定义模型
6.定义损失函数和优化器
7.训练模型
8.评估模型
9.保存和加载模型
10.使用模型进行推理
import torch.nn.functional as F
import torch.nn as nn
import torch
from torchvision import datasets,transforms
import os
import torch.optim as optim
device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
#有GPU版
# 定义模型
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc1 = nn.Linear(10, 32)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(32, 1)
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
# 创建模型实例
model = SimpleModel().to(device)
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 生成一些数据
inputs = torch.randn(64, 10).to(device)
targets = torch.randn(64, 1).to(device)
# 训练循环
for epoch in range(100):
# 前向传播
outputs = model(inputs)
loss = criterion(outputs, targets)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch + 1) % 10 == 0:
print(f'Epoch [{epoch + 1}/100], Loss: {loss.item():.4f}')
Epoch [10/100], Loss: 0.9730
Epoch [20/100], Loss: 0.9241
Epoch [30/100], Loss: 0.8880
Epoch [40/100], Loss: 0.8533
Epoch [50/100], Loss: 0.8202
Epoch [60/100], Loss: 0.7875
Epoch [70/100], Loss: 0.7552
Epoch [80/100], Loss: 0.7235
Epoch [90/100], Loss: 0.6912
Epoch [100/100], Loss: 0.6584
#GPU版
# 定义模型
class SimpleModel_cpu(nn.Module):
def __init__(self):
super(SimpleModel_cpu, self).__init__()
self.fc1 = nn.Linear(10, 32)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(32, 1)
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
# 创建模型实例
model_cpu= SimpleModel_cpu()
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 生成一些数据
inputs = torch.randn(64, 10)
targets = torch.randn(64, 1)
# 训练循环
for epoch in range(100):
# 前向传播
outputs = model_cpu(inputs)
loss = criterion(outputs, targets)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch + 1) % 10 == 0:
print(f'Epoch [{epoch + 1}/100], Loss: {loss.item():.4f}')
Epoch [10/100], Loss: 0.8705
Epoch [20/100], Loss: 0.8705
Epoch [30/100], Loss: 0.8705
Epoch [40/100], Loss: 0.8705
Epoch [50/100], Loss: 0.8705
Epoch [60/100], Loss: 0.8705
Epoch [70/100], Loss: 0.8705
Epoch [80/100], Loss: 0.8705
Epoch [90/100], Loss: 0.8705
Epoch [100/100], Loss: 0.8705
torch.save(model.state_dict(),"samplenn.pth")
model=SimpleModel()
model.load_state_dict(torch.load("./samplenn.pth"))
model.eval()
SimpleModel(
(fc1): Linear(in_features=10, out_features=32, bias=True)
(relu): ReLU()
(fc2): Linear(in_features=32, out_features=1, bias=True)
)