• Tensorflow2.0:CNN、ResNet实现MNIST分类识别


    以下仅是个人的学习笔记 ,内容可能是错误

    CNN: 

    1. import tensorflow as tf
    2. from tensorflow import keras
    3. from tensorflow.keras import layers
    4. # 导入数据
    5. (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
    6. # 数据预处理
    7. x_train = x_train.reshape(-1, 28, 28, 1) / 255.0
    8. x_test = x_test.reshape(-1, 28, 28, 1) / 255.0
    9. # 构建模型
    10. model = keras.Sequential([
    11. layers.Conv2D(filters=32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)),
    12. layers.MaxPooling2D(pool_size=(2, 2)),
    13. layers.Flatten(),
    14. layers.Dense(10, activation='softmax')
    15. ])
    16. # 编译模型
    17. model.compile(optimizer='adam',
    18. loss='sparse_categorical_crossentropy',
    19. metrics=['accuracy'])
    20. # 训练模型
    21. model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))
    22. # 评估模型
    23. test_loss, test_acc = model.evaluate(x_test, y_test)
    24. print('Test accuracy:', test_acc)

    ResNet18: 

    1. import tensorflow as tf
    2. from keras import layers, models, datasets
    3. import os
    4. # 定义gpu
    5. os.environ['CUDA_VISIBLE_DEVICES'] = '0' # 指定GPU编号
    6. gpus = tf.config.experimental.list_physical_devices('GPU')
    7. if gpus:
    8. try:
    9. tf.config.experimental.set_memory_growth(gpus[0], True) # 动态申请显存
    10. except RuntimeError as e:
    11. print(e)
    12. # 加载数据集
    13. (train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
    14. # 数据预处理
    15. train_images, test_images = train_images / 255.0, test_images / 255.0
    16. # 搭建残差模块
    17. def resnet_block(inputs, num_filters=16, kernel_size=3, strides=1, activation='relu'):
    18. x = layers.Conv2D(num_filters, kernel_size=kernel_size, strides=strides, padding='same')(inputs)
    19. x = layers.BatchNormalization()(x)
    20. if activation:
    21. x = layers.Activation(activation)(x)
    22. return x
    23. # 定义resnet
    24. def resnet18():
    25. inputs = layers.Input(shape=(32, 32, 3))
    26. num_filters = 64
    27. t = layers.BatchNormalization()(inputs)
    28. t = resnet_block(t, num_filters=num_filters)
    29. for i in range(2):
    30. t = resnet_block(t, num_filters=num_filters, activation=None)
    31. t = layers.Add()([t, layers.Activation('relu')(t)])
    32. t = resnet_block(t, num_filters=num_filters * 2, strides=2, activation=None)
    33. t = layers.Add()([t, resnet_block(t, num_filters=num_filters * 2)])
    34. num_filters *= 2
    35. for i in range(2):
    36. t = resnet_block(t, num_filters=num_filters, activation=None)
    37. t = layers.Add()([t, layers.Activation('relu')(t)])
    38. t = resnet_block(t, num_filters=num_filters * 2, strides=2, activation=None)
    39. t = layers.Add()([t, resnet_block(t, num_filters=num_filters * 2)])
    40. num_filters *= 2
    41. for i in range(2):
    42. t = resnet_block(t, num_filters=num_filters, activation=None)
    43. t = layers.Add()([t, layers.Activation('relu')(t)])
    44. t = layers.AveragePooling2D()(t)
    45. outputs = layers.Dense(10, activation='softmax')(layers.Flatten()(t))
    46. model = models.Model(inputs, outputs)
    47. return model
    48. # 定义模型
    49. model = resnet18()
    50. model.compile(optimizer='adam',
    51. loss='sparse_categorical_crossentropy',
    52. metrics=['accuracy'])
    53. # 训练 CPU
    54. # history = model.fit(train_images, train_labels, epochs=10,
    55. # validation_data=(test_images, test_labels))
    56. with tf.device('GPU:0'): # 指定使用GPU
    57. history = model.fit(train_images, train_labels, epochs=10,
    58. validation_data=(test_images, test_labels))

     

  • 相关阅读:
    FLStudio21汉化破解激活版下载,Fl Studio 2024中文破解版激活补丁
    获取店铺的所有商品API 返回值说明
    K8S安装过程一:Linux升级内核
    一分钟学一个 Linux 命令 - tar
    54. 螺旋矩阵
    能带你起飞的【数据结构】成王第十篇:二叉树4
    Hive简介及核心概念
    Python: 初识Python
    C#学习 - 方法的定义、调用、调试
    白水三佳电脑ERP部署
  • 原文地址:https://blog.csdn.net/m0_72675651/article/details/134455828