Resnet for Fashion_Mnist(二)

Resnet for Fashion_Mnist(二)

模型定义

下面给出Resnet的模型定义代码,包含了resnet18。想写其他restnet模型,可以在此基础上扩展。

import torch
import torch.nn as nn
import utils
import math
from torch.autograd import Variable


__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152']


def conv3x3(in_planes, out_planes, stride=1):
    "3x3 convolution with padding"
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d
好的,我可以为您提供代码实现。在这里,我将使用Keras中的ResNet50预训练模型,并使用Fashion-MNIST数据集对十种服装进行分类。首先,我们需要安装一些必要的库: ``` !pip install tensorflow !pip install keras !pip install matplotlib ``` 接下来,我们将加载数据集并进行预处理: ```python import numpy as np import keras from keras.datasets import fashion_mnist from keras.preprocessing.image import ImageDataGenerator # 数据集路径 (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() # 将图像转换为RGB格式 x_train = np.repeat(x_train[..., np.newaxis], 3, -1) x_test = np.repeat(x_test[..., np.newaxis], 3, -1) # 批量大小 batch_size = 32 # 数据增强 train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) # 没有数据增强的验证数据生成器 val_datagen = ImageDataGenerator(rescale=1./255) # 训练集生成器 train_generator = train_datagen.flow( x_train, keras.utils.to_categorical(y_train), batch_size=batch_size) # 验证集生成器 val_generator = val_datagen.flow( x_test, keras.utils.to_categorical(y_test), batch_size=batch_size) ``` 接下来,我们将加载ResNet50模型,并对其进行微调,以适应我们的数据集: ```python from keras.applications.resnet50 import ResNet50 from keras.layers import Dense, GlobalAveragePooling2D from keras.models import Model # 加载ResNet50模型,不包括顶层(全连接层) base_model = ResNet50(weights='imagenet', include_top=False) # 添加全局平均池化层 x = base_model.output x = GlobalAveragePooling2D()(x) # 添加全连接层,输出为十个类别 predictions = Dense(10, activation='softmax')(x) # 构建我们需要训练的完整模型 model = Model(inputs=base_model.input, outputs=predictions) # 冻结ResNet50的所有层,以便在训练过程中不更新它们的权重 for layer in base_model.layers: layer.trainable = False ``` 现在,我们可以开始训练模型了: ```python from keras.optimizers import SGD # 编译模型,指定损失函数、优化器和评价指标 model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.001), metrics=['accuracy']) # 训练模型 history = model.fit_generator( train_generator, steps_per_epoch=x_train.shape[0] // batch_size, epochs=10, validation_data=val_generator, validation_steps=x_test.shape[0] // batch_size) ``` 最后,我们可以使用matplotlib库绘制训练和验证的准确率和损失曲线: ```python import matplotlib.pyplot as plt # 绘制训练和验证的准确率曲线 plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Val'], loc='upper left') plt.show() # 绘制训练和验证的损失曲线 plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Val'], loc='upper left') plt.show() ``` 现在您应该可以使用这些代码实现您的需求了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值