Keras大法(6)——实现LeNet5模型

Keras大法(6)——实现LeNet5模型


在这里插入图片描述

(1)模型结构

模型结构如下:
在这里插入图片描述

(2)模型代码

import tensorflow as tf
from tensorflow import keras

import os
os.environ["CUDA_VISIBLE_DEVICES"] = "2"

# 使用tf.data进行数据馈送,此为参考示例
def parse_function(example_proto):
    features = {
        'label' : tf.FixedLenFeature([], tf.int64),
        'img_raw' : tf.FixedLenFeature([], tf.string)
    }
    parsed_features = tf.parse_single_example(example_proto, features)
    img = tf.decode_raw(parsed_features['img_raw'], tf.uint8)
    img = tf.reshape(img, [224, 224, 3])
    img = tf.cast(img, tf.float32) / 255
    label = tf.one_hot(parsed_features['label'], depth= 2)
    #label = to_categorical(parsed_features['label'], num_classes= 8)
    return img, label
dataset = tf.data.TFRecordDataset(r"C:\Users\12394\PycharmProjects\Chest X-Ray Automatic Identification\dataset\train.tfrecords")
dataset = dataset.map(parse_function)
dataset = dataset.repeat()
dataset = dataset.shuffle(buffer_size= 5).batch(4)

# Define the input layer
inputs = keras.Input(shape = [224, 224, 3])
# Define the converlutional layer 1
conv1 = keras.layers.Conv2D(filters= 6, kernel_size= [5, 5], strides= (1, 1), padding= 'same',activation= keras.activations.relu,use_bias=True)(inputs)
# Define the pooling layer 1
pooling1 = keras.layers.MaxPooling2D(pool_size= (2, 2), strides= (2, 2), padding= 'same')(conv1)
# Define the converlutional layer 2
conv2 = keras.layers.Conv2D(filters= 16, kernel_size= (5, 5), strides= (1, 1), padding= 'same', activation= keras.activations.relu, use_bias=True)(pooling1)
# Define the pooling layer 2
pooling2 = keras.layers.MaxPooling2D(pool_size= (2, 2), strides= (2, 2), padding= 'valid')(conv2)
# Define the converlutional layer 3
conv3 = keras.layers.Conv2D(filters= 120, kernel_size= (5, 5), strides= (1, 1), padding= 'same', activation= keras.activations.relu, use_bias=True)(pooling2)
# Define the fully connected layer

flatten = keras.layers.Flatten()(conv3)
connected = keras.layers.Dense(80, activation= keras.activations.relu, use_bias=True)(flatten)

predictions = keras.layers.Dense(2, activation= 'softmax', use_bias=True)(connected)

# 基于Model方法实现模型
model = keras.Model(inputs= inputs, outputs = predictions)
# 编译模型
model.compile(optimizer= tf.train.AdamOptimizer(0.01),
              loss= keras.losses.categorical_crossentropy,
              metrics= ['accuracy'])
# 训练配置,仅供参考
model.fit(dataset, epochs = 5, steps_per_epoch= 4442)
model.save('模型文件地址')

(3)总 结

在这一节中我们使用Keras实现了LeNet5模型,有任何的疑问请在评论区留言,我会尽快回复,谢谢支持!

发布了80 篇原创文章 · 获赞 74 · 访问量 32万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 黑客帝国 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览