Here's an example of using PyTorch to solve a classification problem:

First, we need to import the necessary PyTorch modules:

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader

Next, let's define our dataset. For this example, we'll use the famous Iris dataset:

from sklearn.datasets import load_iris

iris = load_iris()
X = iris.data
y = iris.target

Now, let's split the dataset into training and testing sets:

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

We'll use PyTorch's Dataset and DataLoader classes to load the data:

class IrisDataset(torch.utils.data.Dataset):
    def __init__(self, X, y):
        self.X = X
        self.y = y

    def __getitem__(self, idx):
        x = self.X[idx]
        y = self.y[idx]
        return x, y

    def __len__(self):
        return len(self.X)

train_dataset = IrisDataset(X_train, y_train)
test_dataset = IrisDataset(X_test, y_test)

train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=16, shuffle=False)

Now, let's define our neural network:

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 = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

model = IrisNet()

Finally, let's train the model:

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

for epoch in range(100):
    running_loss = 0.0
    for i, data in enumerate(train_loader, 0):
        inputs, labels = data
        optimizer.zero_grad()
        outputs = model(inputs.float())
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        running_loss += loss.item()

    if epoch % 10 == 9:
        print(f"[{epoch+1}/100] Loss: {running_loss/len(train_loader):.4f}")

print("Finished Training")

And finally, let's evaluate the model on the test set:

correct = 0
total = 0
with torch.no_grad():
    for data in test_loader:
        inputs, labels = data
        outputs = model(inputs.float())
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print(f"Accuracy: {100*correct/total:.2f}%")

In this example, we defined a simple neural network with one hidden layer and trained it on the Iris dataset. We achieved an accuracy of around 96% on the test set.

PyTorch Classification Example: Iris Dataset

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

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