用iris.csv数据构建神经网络预测花的种类:将所有数据 随机分为训练集和测试集,分别计算测试集上总的准确率和不同类的准确率。torch
时间: 2023-12-06 12:45:43 浏览: 32
首先,我们需要导入必要的库和数据集:
```python
import torch
import torch.nn as nn
import pandas as pd
from sklearn.model_selection import train_test_split
# 读取数据集
iris_df = pd.read_csv('iris.csv')
# 将类别转换为数字
iris_df['species'] = pd.Categorical(iris_df['species']).codes
# 将特征和标签分开
X = iris_df.iloc[:, :-1].values
y = iris_df.iloc[:, -1].values
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
接下来,我们可以定义一个简单的神经网络模型,包括一个输入层、一个隐藏层和一个输出层:
```python
class Net(nn.Module):
def __init__(self):
super(Net, 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
```
然后,我们可以使用该模型对数据进行训练和测试:
```python
# 定义模型、损失函数和优化器
model = Net()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# 训练模型
num_epochs = 1000
for epoch in range(num_epochs):
inputs = torch.tensor(X_train, dtype=torch.float32)
labels = torch.tensor(y_train, dtype=torch.long)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if epoch % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 测试模型
with torch.no_grad():
inputs = torch.tensor(X_test, dtype=torch.float32)
labels = torch.tensor(y_test, dtype=torch.long)
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total = labels.size(0)
correct = (predicted == labels).sum().item()
accuracy = correct / total
print('Accuracy of the model on the test set: {:.2f}%'.format(accuracy * 100))
class_correct = [0 for _ in range(3)]
class_total = [0 for _ in range(3)]
for i in range(len(labels)):
label = labels[i]
prediction = predicted[i]
if prediction == label:
class_correct[label] += 1
class_total[label] += 1
for i in range(3):
print('Accuracy of {} : {:.2f}%'.format(i, 100 * class_correct[i] / class_total[i]))
```
在上述代码中,我们使用交叉熵损失函数和随机梯度下降优化器进行训练。在测试模型时,我们计算了总的准确率和每个类别的准确率。