Keras 是一个广为流行的高级神经网络 API,简单、快速而不失灵活性,现已得到 TensorFlow 的官方内置和全面支持。
层将各种计算流程和变量进行了封装(例如基本的全连接层,CNN 的卷积层、池化层等),而模型则将各种层进行组织和连接,并封装成一个整体,描述了如何将输入数据通过各种层以及运算而得到输出。
import tensorflow as tf
层将各种计算流程和变量进行了封装,包含了神经网络层全连接层,CNN的卷积层、池化层等。
全连接层
Arguments:
Input shape:
Output shape:
activation激活函数
tf.keras.activations.sigmoid(x)
tf.keras.activations.softmax(x)
tf.keras.activations.relu(x)
tf.keras.layers.Dense(units=100,input_shape(2,), activation=tf.nn.relu)
tf.keras.layers.Dense(units=100, activation=tf.nn.relu)
tf.keras.layers.Dense(units=100, activation="sigmoid")
卷积层
tf.keras.layers.Conv2D()
tf.keras.layers.Conv1D()
循环神经网络层
tf.keras.layers.SimpleRNN()
tf.keras.layers.LSTM()
tf.keras.layers.GRU()
一般步骤:
顺序式模型的编程特点:
将神经网络层按按特定顺序叠加起来
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(100,input_shape=(2,),activation="relu"))
model.add(tf.keras.layers.Dense(10,activation="softmax"))
查看模型结构
model.summary()
Model: "sequential_2"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_2 (Dense) (None, 100) 300
_________________________________________________________________
dense_3 (Dense) (None, 10) 1010
=================================================================
Total params: 1,310
Trainable params: 1,310
Non-trainable params: 0
_________________________________________________________________
model = tf.keras.Sequential([
tf.keras.layers.Dense(100,input_shape=(2,),activation="relu"),
tf.keras.layers.Dense(10,activation="softmax")
])
model.summary()
Model: "sequential_3"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_4 (Dense) (None, 100) 300
_________________________________________________________________
dense_5 (Dense) (None, 10) 1010
=================================================================
Total params: 1,310
Trainable params: 1,310
Non-trainable params: 0
_________________________________________________________________
顺序式模型这种层叠结构并不能表示任意的神经网络结构。为此,Keras 提供了 Functional API,帮助我们建立更为复杂的模型,例如多输入 / 输出或存在参数共享的模型。其使用方法是将层作为可调用的对象并返回张量,并将输入向量和输出向量提供给 tf.keras.Model 的 inputs 和 outputs 参数,示例如下:
inputs = tf.keras.Input(shape=(2,))
x = tf.keras.layers.Dense(units=100, activation=tf.nn.relu)(inputs)
x = tf.keras.layers.Dense(units=10)(x)
outputs = tf.keras.layers.Softmax()(x)
model = tf.keras.Model(inputs=inputs, outputs=x)
model.summary()
Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 2)] 0
_________________________________________________________________
dense_6 (Dense) (None, 100) 300
_________________________________________________________________
dense_7 (Dense) (None, 10) 1010
=================================================================
Total params: 1,310
Trainable params: 1,310
Non-trainable params: 0
_________________________________________________________________
tf.keras.Model.compile 接受 3 个重要的参数:
categorical_crossentropy和sparse_categorical_crossentropy的区别:
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
loss=tf.keras.losses.sparse_categorical_crossentropy,
# loss = tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=[tf.keras.metrics.sparse_categorical_accuracy]
)
或者
model.compile(optimizer = "adam",
loss = "sparse_categorical_crossentropy",
metrics=["sparse_categorical_accuracy"])
tf.keras.Model.fit 接受 6 个重要的参数:
model.fit(x=train_data,y=train_label, epochs=num_epochs, batch_size=batch_size)
model.evaluate(x=test_data, y=test_label,epochs=num_epochs)
model.predict(x=pred_data)
x = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
y = tf.constant([5.0,6.0,7.0,8.0,9.0,10.0])
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(1,input_shape=(1,)))
model.summary()
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_1 (Dense) (None, 1) 2
=================================================================
Total params: 2
Trainable params: 2
Non-trainable params: 0
_________________________________________________________________
# 定义训练参数
model.compile(
optimizer=tf.keras.optimizers.SGD(learning_rate=0.05), # 指定优化器
# loss=tf.keras.losses.MSE, # 指定损失函数
loss = 'mse'
)
查看模型变量值
model.variables # 模型所有的变量
# model.layers[0].variables 模型第一层变量值
[,
]
model.fit(x,y, epochs=10,verbose=2)
Train on 6 samples
Epoch 1/10
6/6 - 0s - loss: 6.5611
Epoch 2/10
6/6 - 0s - loss: 4.1146
Epoch 3/10
6/6 - 0s - loss: 3.1746
Epoch 4/10
6/6 - 0s - loss: 2.7765
Epoch 5/10
6/6 - 0s - loss: 2.5747
Epoch 6/10
6/6 - 0s - loss: 2.4452
Epoch 7/10
6/6 - 0s - loss: 2.3438
Epoch 8/10
6/6 - 0s - loss: 2.2544
Epoch 9/10
6/6 - 0s - loss: 2.1712
Epoch 10/10
6/6 - 0s - loss: 2.0921
model.evaluate(x=x, y=y,verbose=0)
2.0162193775177
model.predict(x)
array([[ 2.5158374],
[ 4.269158 ],
[ 6.0224786],
[ 7.7757993],
[ 9.52912 ],
[11.282441 ]], dtype=float32)