vgg16网络搭建可运行代码

目录

1.我搭建的是这一个

2.方法一,用一个sequential配置

2 方法二,用cfg进行配置


1.我搭建的是这一个

2.方法一,用一个sequential配置

import torch
from torch import nn
from torchinfo import summary

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.layer=nn.Sequential(
            nn.Conv2d(3,64,3,1,1),
            nn.Conv2d(64,64,3,1,1),
            nn.MaxPool2d(2),
            nn.Conv2d(64,128,3,1,1),
            nn.Conv2d(128,128,3,1,1),
            nn.MaxPool2d(2),
            nn.Conv2d(128,256,3,1,1),
            nn.Conv2d(256,256,3,1,1),
            nn.Conv2d(256,256,3,1,1),
            nn.MaxPool2d(2),
            nn.Conv2d(256,512,3,1,1),
            nn.Conv2d(512,512,3,1,1),
            nn.Conv2d(512,512,3,1,1),
            nn.MaxPool2d(2),
            nn.Conv2d(512, 512, 3, 1, 1),
            nn.Conv2d(512, 512, 3, 1, 1),
            nn.Conv2d(512, 512, 3, 1, 1),
            nn.MaxPool2d(2),

        )
        self.linear=nn.Sequential(
            nn.Flatten(1),
            nn.Linear(512 * 7 * 7, 4096),
            nn.Linear(4096, 4096),
            nn.Linear(4096, 1000),
            nn.Softmax(dim=1)
        )
    def forward(self,x):
        x=self.layer(x)
        x=self.linear(x)
        return x
if __name__ == '__main__':
    x=torch.randn(1,3,224,224)
    net=Net()
    out=net(x)
    print(out.shape)
    summary(net,(1,3,224,224))

summary是打印网络结构信息

2 方法二,用cfg进行配置


import cv2
import torch
from torch import nn
from torchinfo import summary
cfg={
    'vgg':[
        64,64,'M',
        128,128,'M',
        256,256,256,'M',
        512,512,512,'M',
        512,512,512,'M'
    ]
}
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        layer=[]
        out_ch=3
        for in_ch in cfg['vgg']:
            if in_ch=='M':
                layer+=[nn.MaxPool2d(2)]
            else:
                layer+=[nn.Conv2d(out_ch,in_ch,3,1,1)]
                out_ch=in_ch#容易出错
        self.layer=nn.Sequential(*layer)
        self.linear=nn.Sequential(
            nn.Flatten(),
            nn.Linear(512*7*7,4096),
            nn.Linear(4096,4096),
            nn.Linear(4096,1000)
        )
    def forward(self,x):
        x=self.layer(x)
        x=self.linear(x)
        return x
if __name__ == '__main__':
    x=torch.randn(1,3,224,224)
    net=Net()
    out=net(x)
    print(out.shape)

 

### 回答1: 好的,下面是使用 TensorFlow (Keras) 搭建 VGG 卷积神经网络进行手写数字识别的代码: ``` import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers # 加载 MNIST 数据集 (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() # 数据预处理 x_train = x_train.reshape(-1, 28, 28, 1).astype("float32") / 255.0 x_test = x_test.reshape(-1, 28, 28, 1).astype("float32") / 255.0 # 构建 VGG 网络 model = keras.Sequential( [ layers.Conv2D(64, kernel_size=(3, 3), activation="relu", input_shape=(28, 28, 1)), layers.Conv2D(64, kernel_size=(3, 3), activation="relu"), layers.MaxPooling2D(pool_size=(2, 2)), layers.Conv2D(128, kernel_size=(3, 3), activation="relu"), layers.Conv2D(128, kernel_size=(3, 3), activation="relu"), layers.MaxPooling2D(pool_size=(2, 2)), layers.Conv2D(256, kernel_size=(3, 3), activation="relu"), layers.Conv2D(256, kernel_size=(3, 3), activation="relu"), layers.Conv2D(256, kernel_size=(3, 3), activation="relu"), layers.MaxPooling2D(pool_size=(2, 2)), layers.Conv2D(512, kernel_size=(3, 3), activation="relu"), layers.Conv2D(512, kernel_size=(3, 3), activation="relu"), layers.Conv2D(512, kernel_size=(3, 3), activation="relu"), layers.MaxPooling2D(pool_size=(2, 2)), layers.Flatten(), layers.Dense(256, activation="relu"), layers.Dense(10, activation="softmax"), ] ) # 编译模型 model.compile(loss="sparse_categorical_crossentropy", optimizer="adam", metrics=["accuracy"]) # 训练模型 model.fit(x_train, y_train, batch_size=128, epochs=10, validation_split=0.1) # 评估模型 model.evaluate(x_test, y_test, batch_size=128) ``` 在上面的代码中,我们首先加载了 MNIST 数据集,并对数据进行了预处理。接着,我们构建了一个 VGG 网络,包含了多个卷积层、池化层和全连接层。最后,我们编译了模型并进行了训练和评估。 运行上述代码,即可训练出一个能够识别手写数字的卷积神经网络。 ### 回答2: 使用TensorFlow(Keras)搭建卷积神经网络(VGG)可以实现手写数字识别。手写数字识别是一个常见的机器学习问题,可以通过卷积神经网络(VGG)来解决。 首先,我们需要导入相关的库和数据集。如下所示: ``` import tensorflow as tf from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense # 加载MNIST数据集 (x_train, y_train), (x_test, y_test) = mnist.load_data() ``` 数据集包含了60000个训练样本和10000个测试样本,每个样本都是一个28x28像素的手写数字图像。 接下来,我们需要对数据进行预处理。将图像转换为多维数组,并将每个像素值归一化到0-1范围内。还需要对标签进行独热编码处理。 ``` # 对图像数据进行预处理 x_train = x_train.reshape(-1, 28, 28, 1) x_train = x_train / 255.0 x_test = x_test.reshape(-1, 28, 28, 1) x_test = x_test / 255.0 # 对标签进行独热编码 y_train = tf.keras.utils.to_categorical(y_train, num_classes=10) y_test = tf.keras.utils.to_categorical(y_test, num_classes=10) ``` 接下来,我们开始构建VGG模型。 ``` model = Sequential() model.add(Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(28, 28, 1))) model.add(Conv2D(64, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(128, (3, 3), activation='relu', padding='same')) model.add(Conv2D(128, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(256, (3, 3), activation='relu', padding='same')) model.add(Conv2D(256, (3, 3), activation='relu', padding='same')) model.add(Conv2D(256, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(512, (3, 3), activation='relu', padding='same')) model.add(Conv2D(512, (3, 3), activation='relu', padding='same')) model.add(Conv2D(512, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(512, (3, 3), activation='relu', padding='same')) model.add(Conv2D(512, (3, 3), activation='relu', padding='same')) model.add(Conv2D(512, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(4096, activation='relu')) model.add(Dense(4096, activation='relu')) model.add(Dense(10, activation='softmax')) ``` 将模型编译后,我们可以对模型进行训练和评估。 ``` model.compile(optimizer=tf.keras.optimizers.SGD(), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, batch_size=64, epochs=10, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test) print('Test loss:', score[0]) print('Test accuracy:', score[1]) ``` 通过以上步骤,我们就可以使用TensorFlow(Keras)搭建VGG卷积神经网络,并实现手写数字识别。 ### 回答3: 使用TensorFlow(Keras)搭建卷积神经网络VGG模型,并实现手写数字识别的步骤如下: 1. 数据准备:收集手写数字数据集,例如MNIST数据集,包含60000张训练图像和10000张测试图像。 2. 导入相关库:使用TensorFlow和Keras库进行模型构建和训练。 3. 数据预处理:对训练和测试数据进行预处理,包括将像素值标准化至0到1之间,将标签进行独热编码等。 4. 构建模型:使用Keras中的Sequential模型,按照VGG网络的结构顺序添加卷积层、池化层和全连接层。VGG网络通常由多个卷积层和全连接层组成,其中每个卷积层均由两个连续的卷积层和一个池化层组成。 5. 编译模型:设置模型的损失函数、优化器和评估指标。常用的损失函数是交叉熵损失函数,优化器可以选择Adam或SGD,评估指标可以选择准确率。 6. 模型训练:使用模型的fit()方法进行模型训练,设定训练的批次大小、训练轮数等参数。 7. 模型评估:使用测试集评估模型的准确率和损失值。 8. 手写数字识别:使用训练好的模型对新的手写数字图像进行识别。首先对输入图像进行预处理,然后使用模型的predict()方法预测图像的类别,并输出相应的数字。 以上是使用TensorFlow(Keras)搭建卷积神经网络VGG模型,实现手写数字识别的基本步骤。详细代码实现可以参考TensorFlow和Keras的官方文档以及相关教程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西柚与蓝莓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值