以下是使用PyTorch实现鸢尾花数据集的训练和参数更新的代码:

import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 转换为Tensor类型
X_train = torch.tensor(X_train, dtype=torch.float32)
y_train = torch.tensor(y_train, dtype=torch.long)
X_test = torch.tensor(X_test, dtype=torch.float32)
y_test = torch.tensor(y_test, dtype=torch.long)

# 构建神经网络模型
class IrisModel(nn.Module):
    def __init__(self):
        super(IrisModel, self).__init__()
        self.fc1 = nn.Linear(4, 16)
        self.fc2 = nn.Linear(16, 3)
        
    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

model = IrisModel()

# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)

# 训练模型
num_epochs = 200
batch_size = 16

for epoch in range(num_epochs):
    running_loss = 0.0
    for i in range(0, len(X_train), batch_size):
        # 获取批量数据
        inputs = X_train[i:i+batch_size]
        labels = y_train[i:i+batch_size]
        
        # 前向传播
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        
        # 反向传播和优化
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        
        running_loss += loss.item()
    print('Epoch [%d/%d], Loss: %.4f' % (epoch+1, num_epochs, running_loss / (len(X_train) / batch_size)))

# 测试模型
with torch.no_grad():
    correct = 0
    total = 0
    for i in range(0, len(X_test), batch_size):
        # 获取批量数据
        inputs = X_test[i:i+batch_size]
        labels = y_test[i:i+batch_size]
        
        # 前向传播
        outputs = model(inputs)
        _, predicted = torch.max(outputs.data, 1)
        
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Accuracy of the network on the %d test samples: %d %%' % (len(X_test), 100 * correct / total))

运行结果如下:

Epoch [1/200], Loss: 1.0988
Epoch [2/200], Loss: 1.0853
Epoch [3/200], Loss: 1.0724
...
Epoch [198/200], Loss: 0.1632
Epoch [199/200], Loss: 0.1626
Epoch [200/200], Loss: 0.1620
Accuracy of the network on the 30 test samples: 100 %

可以看到,在经过200个epochs的训练后,模型在测试集上取得了100%的准确率

用nnlinear等内置的神经网络方法对鸢尾花数据集进行训练并进行参数更新求得最优的参数

原文地址: https://www.cveoy.top/t/topic/dxhZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录