使用iris.csv数据构建神经网络预测花的种类:将所有数据随机分为训练集和测试集,分别计算测试集上总的准确率和不同类的准确率,要求用到torch来完成代码
时间: 2024-02-03 21:13:53 浏览: 20
首先,需要导入相关的库,读取并处理数据:
```python
import torch
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
# 读取数据
data = pd.read_csv("iris.csv")
# 将类别数据进行编码
le = LabelEncoder()
data['species'] = le.fit_transform(data['species'])
# 将数据进行归一化处理
sc = StandardScaler()
data.iloc[:, :-1] = sc.fit_transform(data.iloc[:, :-1])
# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(data.iloc[:, :-1], data['species'], test_size=0.2, random_state=42)
```
接着,可以使用 PyTorch 搭建神经网络模型:
```python
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = torch.nn.Linear(4, 10)
self.fc2 = torch.nn.Linear(10, 10)
self.fc3 = torch.nn.Linear(10, 3)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
```
在训练模型之前,需要定义损失函数和优化器:
```python
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.01)
```
接下来,可以开始训练模型了:
```python
for epoch in range(1000):
inputs = torch.tensor(X_train.values, dtype=torch.float32)
labels = torch.tensor(y_train.values, dtype=torch.long)
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if epoch % 100 == 0:
print("epoch {} loss: {}".format(epoch, loss.item()))
```
最后,可以在测试集上进行预测并计算准确率:
```python
with torch.no_grad():
inputs = torch.tensor(X_test.values, dtype=torch.float32)
labels = torch.tensor(y_test.values, dtype=torch.long)
outputs = net(inputs)
_, predicted = torch.max(outputs.data, 1)
total = labels.size(0)
correct = (predicted == labels).sum().item()
accuracy = correct / total
print("Accuracy: {}".format(accuracy))
```
同时,还可以分别计算不同类别的准确率:
```python
for i in range(3):
with torch.no_grad():
inputs = torch.tensor(X_test[y_test == i].values, dtype=torch.float32)
labels = torch.tensor(y_test[y_test == i].values, dtype=torch.long)
outputs = net(inputs)
_, predicted = torch.max(outputs.data, 1)
total = labels.size(0)
correct = (predicted == labels).sum().item()
accuracy = correct / total
print("Class {} Accuracy: {}".format(i, accuracy))
```