python 训练鸢尾花损失函数代码
时间: 2023-10-17 09:08:20 浏览: 89
鸢尾花数据集训练.py
以下是使用PyTorch库训练鸢尾花数据集的代码示例,包括定义损失函数和训练过程中的代码:
```python
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import numpy as np
# Load Iris dataset
iris = load_iris()
X = iris.data
y = iris.target
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Define custom dataset
class IrisDataset(Dataset):
def __init__(self, X, y):
self.X = torch.tensor(X, dtype=torch.float32)
self.y = torch.tensor(y, dtype=torch.long)
def __len__(self):
return len(self.X)
def __getitem__(self, idx):
return self.X[idx], self.y[idx]
# Initialize dataset and dataloader
iris_train = IrisDataset(X_train, y_train)
train_loader = DataLoader(iris_train, batch_size=16, shuffle=True)
# Define model architecture
class IrisNet(nn.Module):
def __init__(self):
super(IrisNet, self).__init__()
self.fc1 = nn.Linear(4, 16)
self.fc2 = nn.Linear(16, 3)
def forward(self, x):
x = self.fc1(x)
x = nn.functional.relu(x)
x = self.fc2(x)
return x
# Initialize model and optimizer
model = IrisNet()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Define loss function
criterion = nn.CrossEntropyLoss()
# Train model
num_epochs = 50
for epoch in range(num_epochs):
for i, (inputs, labels) in enumerate(train_loader):
# Forward pass
outputs = model(inputs)
loss = criterion(outputs, labels)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Print training loss after each epoch
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
```
在上述代码中,我们使用了PyTorch库来定义模型、损失函数和优化器,以及进行训练。我们还使用了sklearn库来加载鸢尾花数据集并将其拆分为训练和测试集。损失函数使用交叉熵损失函数。在训练过程中,我们通过迭代训练数据集中的每个批次来更新模型的权重,并在每个epoch结束后打印训练损失。
阅读全文