pytorch实现一个简单的CNN

python 复制代码
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms

# Define the CNN model
class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, padding=1)
        self.relu1 = nn.ReLU()
        self.pool1 = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(32, 64, 3, padding=1)
        self.relu2 = nn.ReLU()
        self.pool2 = nn.MaxPool2d(2, 2)
        self.conv3 = nn.Conv2d(64, 64, 3, padding=1)
        self.relu3 = nn.ReLU()
        self.flatten = nn.Flatten()
        self.fc1 = nn.Linear(64 * 7 * 7, 64)
        self.relu4 = nn.ReLU()
        self.fc2 = nn.Linear(64, 10)

    def forward(self, x):
        x = self.pool1(self.relu1(self.conv1(x)))
        x = self.pool2(self.relu2(self.conv2(x)))
        x = self.relu3(self.conv3(x))
        x = self.flatten(x)
        x = self.relu4(self.fc1(x))
        x = self.fc2(x)
        return x

# Load Fashion MNIST dataset
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
train_dataset = torchvision.datasets.FashionMNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = torchvision.datasets.FashionMNIST(root='./data', train=False, download=True, transform=transform)

train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)

# Initialize the CNN model
model = CNN()

# Define loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

# Train the model
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)

epochs = 5
for epoch in range(epochs):
    running_loss = 0.0
    for i, data in enumerate(train_loader, 0):
        inputs, labels = data[0].to(device), data[1].to(device)

        optimizer.zero_grad()

        outputs = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()

    print(f'Epoch {epoch + 1}, Loss: {running_loss / len(train_loader)}')

print("Training finished!")

# Evaluate the model
correct = 0
total = 0
with torch.no_grad():
    for data in test_loader:
        images, labels = data[0].to(device), data[1].to(device)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print(f"Accuracy on the test set: {100 * correct / total}%")
相关推荐
LingYi_06 分钟前
语义分割-yolo26seg
人工智能·深度学习
AI街潜水的八角16 分钟前
YOLO26手语识别项目实战1-三十五种手语实时检测系统数据集说明(含下载链接)
python·深度学习
春日见17 分钟前
从底层思维3分钟彻底弄清卷积神经网络CNN
人工智能·深度学习·神经网络·计算机视觉·docker·cnn·计算机外设
报错小能手21 分钟前
初识transformer《Attention Is All You Need》论文解析
人工智能·深度学习·transformer
Learn Beyond Limits33 分钟前
RNN的多样化用途|The diverse applications of RNN
人工智能·深度学习·神经网络·机器学习·ai·语言模型·自然语言处理
木心术11 小时前
卷积神经网络(CNN)与AI编程的深度整合指南
人工智能·cnn·ai编程
junior_Xin1 小时前
机器学习深度学习beginning4
深度学习·机器学习
智算菩萨1 小时前
GPT-5.4 进阶思考模式全面解析:从推理等级到实战提示词,代码、论文、数据处理一站通
人工智能·gpt·深度学习·机器学习·语言模型·自然语言处理·chatgpt
枫叶林FYL1 小时前
【自然语言处理 NLP】 大语言模型(LLM)系统工程(Large Language Model Engineering)5.1.2 ZeRO与显存优化技术
人工智能·深度学习·机器学习
龙文浩_2 小时前
AI机器学习中NumPy随机种子的应用
人工智能·python·深度学习·神经网络·机器学习