[Chatgpt提效实战]基于ResNet50的MNIST手写数字识别

prompt

请你帮我写一个pytorch框架下的图像分类模型的训练代码,使用pytorch中的resnet50预训练模型作为模型主体,使用pytorch中的mnist数据集作为训练数据,使用crossentropy作为loss函数,并且用acc作为评价指标。请将batchsize设置为32,epoch数设置为10,使用adam优化器进行优化。最后请画出训练过程的acc曲线以及loss曲线。用tqdm显示每个epoch中的iterations进度,并且在gpu上进行训练。并且在transformer中请注意对图像特征图深度的适配。

支持21、22年,期间发行的pytorch版本。但是准确率只能到0.8多。
matplotlib如果报错可以百度解决,最近可能会有更新。

import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
from tqdm import tqdm

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
# Define transformations for the dataset
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Lambda(lambda x: torch.cat([x, x, x], 0)), # 将灰度图像转换为三通道图像
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

# Load the MNIST dataset
trainset = torchvision.datasets.MNIST(root='./data', train=True,
                                        download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=32,
                                          shuffle=True, num_workers=0)

# Load the pre-trained ResNet50 model
model = torchvision.models.resnet50(pretrained=True)

# Freeze all the layers except the final fully-connected layer
for param in model.parameters():
    param.requires_grad = False
model.fc.requires_grad = True

# Replace the final fully-connected layer with a new one that outputs 10 classes
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 10)


model = model.to(device)
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.fc.parameters(), lr=0.01)

# Train the model
num_epochs = 10
train_loss = []
train_acc = []
for epoch in range(num_epochs):
    running_loss = 0.0
    running_corrects = 0
    with tqdm(total=len(trainloader), desc=f'Epoch {epoch + 1}/{num_epochs}', unit='batch', dynamic_ncols=True) as t:
        for i, data in enumerate(trainloader, 0):
            # Get the inputs
            inputs, labels = data[0].to(device), data[1].to(device)

            # Zero the parameter gradients
            optimizer.zero_grad()

            # Forward pass
            outputs = model(inputs)
            loss = criterion(outputs, labels)

            # Backward pass and optimize
            loss.backward()
            optimizer.step()

            # Update statistics
            _, preds = torch.max(outputs, 1)
            running_loss += loss.item() * inputs.size(0)
            running_corrects += torch.sum(preds == labels.data)

            # Update tqdm
            t.update()

    # Calculate statistics for the epoch
    epoch_loss = running_loss / len(trainset)
    epoch_acc = (running_corrects.double() / len(trainset)).cpu()

    # Print statistics for the epoch
    print('Epoch [{}/{}], Loss: {:.4f}, Acc: {:.4f}'
          .format(epoch+1, num_epochs, epoch_loss, epoch_acc))

    # Save statistics for the epoch
    train_loss.append(epoch_loss)
    train_acc.append(epoch_acc)

# Plot the training loss and accuracy curves
plt.figure()
plt.plot(train_loss)
plt.title('Training Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.savefig('train_loss.png')

plt.figure()
plt.plot(train_acc)
plt.title('Training Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.savefig('train_acc.png')

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用ResNet网络模型实现MNIST手写数字识别的代码示例: ```python import tensorflow as tf from tensorflow.keras.datasets import mnist from tensorflow.keras.layers import Input, Conv2D, BatchNormalization, ReLU, Add, GlobalAveragePooling2D, Dense from tensorflow.keras.models import Model # 加载MNIST数据集 (x_train, y_train), (x_test, y_test) = mnist.load_data() # 数据预处理:将像素值缩放到0到1之间,并增加一维通道数 x_train = x_train.astype('float32') / 255.0 x_train = x_train.reshape(x_train.shape[0], 28, 28, 1) x_test = x_test.astype('float32') / 255.0 x_test = x_test.reshape(x_test.shape[0], 28, 28, 1) # 定义ResNet网络模型 def residual_block(inputs, filters, strides=1): shortcut = inputs # 第一个卷积层 x = Conv2D(filters, kernel_size=3, strides=strides, padding='same')(inputs) x = BatchNormalization()(x) x = ReLU()(x) # 第二个卷积层 x = Conv2D(filters, kernel_size=3, strides=1, padding='same')(x) x = BatchNormalization()(x) # 如果输入和输出的维度不同,则使用1x1卷积调整维度 if shortcut.shape[-1] != filters: shortcut = Conv2D(filters, kernel_size=1, strides=strides, padding='same')(shortcut) shortcut = BatchNormalization()(shortcut) # 将残差块的输出与输入相加,构成下一层的输入 x = Add()([x, shortcut]) x = ReLU()(x) return x def ResNet(input_shape=(28, 28, 1), num_classes=10): inputs = Input(shape=input_shape) # 第一层卷积 x = Conv2D(64, kernel_size=3, strides=1, padding='same')(inputs) x = BatchNormalization()(x) x = ReLU()(x) # 残差块组1 x = residual_block(x, filters=64, strides=1) x = residual_block(x, filters=64, strides=1) x = residual_block(x, filters=64, strides=1) # 残差块组2 x = residual_block(x, filters=128, strides=2) x = residual_block(x, filters=128, strides=1) x = residual_block(x, filters=128, strides=1) # 残差块组3 x = residual_block(x, filters=256, strides=2) x = residual_block(x, filters=256, strides=1) x = residual_block(x, filters=256, strides=1) # 残差块组4 x = residual_block(x, filters=512, strides=2) x = residual_block(x, filters=512, strides=1) x = residual_block(x, filters=512, strides=1) # 全局平均池化 x = GlobalAveragePooling2D()(x) # 全连接层 x = Dense(num_classes, activation='softmax')(x) model = Model(inputs=inputs, outputs=x) return model # 创建ResNet模型 model = ResNet(num_classes=10) # 编译模型 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # 训练模型 model.fit(x_train, y_train, batch_size=128, epochs=10, validation_data=(x_test, y_test)) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值