tensorflow常用构造深度学习模型的两种方式

一、引言

  tensorflow常用构造模型的方式有两种:

  1、Sequential()方式
  2、函数式API

二、Sequtial()方式

  2.1 向Sequential()中传递layer列表

  示例一:

model = Sequential([Dense(64, input_shape=(784, ), activation='relu'),  # 添加第一层隐藏层,输入维度为(784, )
                    Dropout(0.2),
                    Dense(64, activation='relu'),                       # 添加第二层隐藏层
                    Dropout(0.2),
                    Dense(10, activation='softmax')                     # 添加输出层
                    ])

  示例二:

model = Sequential([Dense(64, input_shape=(784, )),   # 添加第一层隐藏层
                    Activation('relu'),
                    Dropout(0.2),
                    Dense(64),                        # 添加第二层隐藏层
                    Dropout(0.2),
                    Dense(10),                        # 添加第三层隐藏
                    Activation('softmax')])
  2.2 利用model.add()方法添加layer

  示例一:

model = Sequential()       # 实例化顺序模型
model.add(Dense(64, input_shape=(784, ), activation='relu'))   # 添加第一层隐藏层
model.add(Dropout(0.2))
model.add(Dense(64, activation='relu'))     # 添加第二层隐藏层
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))  # 添加输出层

  示例二:

model = Sequential()
model.add(Dense(64, input_shape=(784, )))  # 添加第一层隐藏层
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(64))
model.add(Activation('relu'))              # 添加第二层隐藏层
model.add(Dropout(0.2))
model.add(Dense(10))                       # 添加第三层隐藏层
model.add(Activation('softmax'))

三、函数式API

  示例一:

inputs = keras.Input(shape=(784,), name='mnist_input')
h1 = Dense(64, activation='relu')(inputs)     # 过第一个隐藏层
h1 = Dropout(0.2)(h1)
h1 = Dense(64, activation='relu')(h1)         # 过第二个隐藏层
h1 = Dropout(0.2)(h1)
outputs = Dense(10, activation='softmax')(h1) # 过第三个隐藏层
model = keras.Model(inputs, outputs)

  示例二:

inputs = keras.Input(shape=(784,), name='mnist_input')
h1 = Dense(64)(inputs)
h1 = Activation('relu')(h1)
h1 = Dropout(0.2)(h1)
h1 = Dense(64)(h1)
h1 = Activation('relu')(h1)
h1 = Dropout(0.2)(h1)
outputs = Dense(10)(h1)
outputs = Activation('softmax')(outputs)
model = keras.Model(inputs, outputs)

备注:采用函数式API可以将构建的模型封装为函数或者类

四、栗子-手写体数字识别

######################导入相应的模块###########################
from tensorflow import keras
from tensorflow.keras.layers import Dense, Activation, Dropout
from tensorflow.keras import Sequential
import matplotlib.pyplot as plt

##########################数据准备#############################
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()   #加载mnist数据集
x_train = x_train.reshape(60000, 784).astype('float32') /255    # 对图片像素做归一化处理
x_test = x_test.reshape(10000, 784).astype('float32') /255     # 对图片像素做归一化处理
x_val = x_train[-10000:]     # 划分训练集与校验集
y_val = y_train[-10000:]
x_train = x_train[:-10000]   # 划分训练集与校验集
y_train = y_train[:-10000]

######################模型构建###########################
# Sequential()方式
# model = Sequential()       # 实例化顺序模型
# model.add(Dense(64, input_shape=(784, ), activation='relu'))   # 添加第一层隐藏层
# model.add(Dropout(0.2))
# model.add(Dense(64, activation='relu'))     # 添加第二层隐藏层
# model.add(Dropout(0.2))
# model.add(Dense(10, activation='softmax'))  # 添加输出层

# 函数式API
inputs = keras.Input(shape=(784,), name='mnist_input')
h1 = Dense(64, activation='relu')(inputs)     # 过第一个隐藏层
h1 = Dropout(0.2)(h1)
h1 = Dense(64, activation='relu')(h1)         # 过第二个隐藏层
h1 = Dropout(0.2)(h1)
outputs = Dense(10, activation='softmax')(h1) # 过第三个隐藏层
model = keras.Model(inputs, outputs)

######################编译模型###########################
model.compile(optimizer=keras.optimizers.RMSprop(),
             loss=keras.losses.SparseCategoricalCrossentropy(),
             metrics=['accuracy'])

######################模型训练###########################
history = model.fit(x_train, 
					y_train, 
					batch_size=64, 
					epochs=3,
					validation_data=(x_val, y_val))

######################模型训练###########################
history = model.fit(x_train, y_train, batch_size=64, epochs=30,
         validation_data=(x_val, y_val))
         
######################模型评估###########################
result = model.evaluate(x_test, y_test, batch_size=128)

######################模型预测###########################
pred = model.predict(x_test[:2])

#######################损失可视化###########################
trian_loss = history.history['loss']
val_loss = history.history['val_loss']
plt.plot(trian_loss, label='train_loss')
plt.plot(val_loss, label='val_loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.legend()
plt.show()

损失可视化图形如下图所示:

五、总结

  • Sequential()方式实现方式简单,但是不够灵活可以用来实现逐层堆叠的模型
  • 函数式API类型可以完成大多数模型的构造,尤其是对于多输入的模型

六、参考文章

https://blog.csdn.net/weixin_42264234/article/details/103946960
https://www.cnblogs.com/xiximayou/p/12690353.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值