借鉴:【深度学习】PyTorch搭建基础神经网络(超详细)_pytorch搭建一个简单的神经网络-CSDN博客
python代码:
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import time
start=time.perf_counter()
# 定义一个名为NeuralNetwork的类
class NeuralNetwork(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten()
self.hidden1 = nn.Linear(4, 16)
self.out = nn.Linear(16, 3)
def forward(self, x):
x = self.flatten(x)
x = self.hidden1(x)
x = torch.relu(x)
x = self.out(x)
return x
# 定义设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 实例化模型并发送到设备
model = NeuralNetwork().to(device)
print(model)
# 损失函数和优化器
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 假设train_dataloader已经定义
def train(X,y, model, loss_fn, optimizer,epoch):
Loss=[]
model.train()
for i in range(epoch):
X, y = X.to(device), y.to(device)
pred = model(X) # 可以直接使用model(X)而不是model.forward(X)
loss = loss_fn(pred, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()#更新模型参数
print(f'Loss: {loss.item()}')#item将张量转换成标量
Loss.append(loss.item())
return Loss, pred
# 注意:在实际代码中,train_dataloader需要被定义
epoch=5000
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data#获取特征值
y = iris.target#获取特征值
print(y)
X_tensor = torch.tensor(X, dtype=torch.float32) # 明确指定 dtype 以避免潜在的自动转换问题
y_tensor = torch.tensor(y, dtype=torch.long) # 类别标签应使用整数类
Loss,pred=train(X_tensor,y_tensor, model, loss_fn, optimizer,epoch)
pred=torch.max(pred, 1)[1]
pred_y = pred.data.numpy()
target_y =y_tensor.data.numpy()
# 6.衡量准确率
accuracy = float((pred_y == target_y).astype(int).sum()) / float(target_y.size)
print("莺尾花预测准确率",accuracy)
end=time.perf_counter()
print('Running time: %s Seconds' % (end - start))
plt.plot(Loss)
plt.xlabel("epoch")
plt.ylabel("Loss")
plt.show()
数据来源:Iris - UCI 机器学习存储库
运行结果: