·利用pytorch构建合适的神经网络,实现鸢尾花的分类(PS:应当包含以下内容,数据载入、数据处理、构建模型、训练模型、测试模型)
时间: 2023-12-21 21:03:13 浏览: 62
好的,以下是一个简单的代码示例:
```python
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)
# 数据处理
X_train = torch.from_numpy(X_train).float()
X_test = torch.from_numpy(X_test).float()
y_train = torch.from_numpy(y_train).long()
y_test = torch.from_numpy(y_test).long()
# 构建模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(4, 16)
self.fc2 = nn.Linear(16, 3)
self.relu = nn.ReLU()
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
net = Net()
# 训练模型
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=0.01)
for epoch in range(1000):
optimizer.zero_grad()
outputs = net(X_train)
loss = criterion(outputs, y_train)
loss.backward()
optimizer.step()
if epoch % 100 == 0:
print('Epoch {}, Loss: {}'.format(epoch, loss.item()))
# 测试模型
with torch.no_grad():
outputs = net(X_test)
_, predicted = torch.max(outputs.data, 1)
accuracy = (predicted == y_test).sum().item() / y_test.size(0)
print('Test Accuracy: {}'.format(accuracy))
```
这个示例中,我们使用了PyTorch构建了一个简单的神经网络模型,用于对鸢尾花进行分类。我们首先载入了数据,然后进行了数据处理,将其转换成了PyTorch的张量。接着,我们构建了一个包含两个全连接层的神经网络,并使用交叉熵损失作为损失函数,使用Adam优化器进行模型训练。最后,我们测试了模型的准确率。
阅读全文