一小时学会TensorFlow2之自定义层
概述
通过自定义网络, 我们可以自己创建网络并和现有的网络串联起来, 从而实现各种各样的网络结构.
sequential
sequential 是 keras 的一个网络容器. 可以帮助我们将多层网络封装在一起.
通过 sequential 我们可以把现有的层已经我们自己的层实现结合, 一次前向传播就可以实现数据从第一层到最后一层的计算.
格式:
tf.keras.sequential( layers=none, name=none )
例子:
# 5层网络模型 model = tf.keras.sequential([ tf.keras.layers.dense(256, activation=tf.nn.relu), tf.keras.layers.dense(128, activation=tf.nn.relu), tf.keras.layers.dense(64, activation=tf.nn.relu), tf.keras.layers.dense(32, activation=tf.nn.relu), tf.keras.layers.dense(10) ])
model & layer
通过 model 和 layer 的__init__
和call()
我们可以自定义层和模型.
model:
class my_model(tf.keras.model): # 继承model def __init__(self): """ 初始化 """ super(my_model, self).__init__() self.fc1 = my_dense(784, 256) # 第一层 self.fc2 = my_dense(256, 128) # 第二层 self.fc3 = my_dense(128, 64) # 第三层 self.fc4 = my_dense(64, 32) # 第四层 self.fc5 = my_dense(32, 10) # 第五层 def call(self, inputs, training=none): """ 在model被调用的时候执行 :param inputs: 输入 :param training: 默认为none :return: 返回输出 """ x = self.fc1(inputs) x = tf.nn.relu(x) x = self.fc2(x) x = tf.nn.relu(x) x = self.fc3(x) x = tf.nn.relu(x) x = self.fc4(x) x = tf.nn.relu(x) x = self.fc5(x) return x
layer:
class my_dense(tf.keras.layers.layer): # 继承layer def __init__(self, input_dim, output_dim): """ 初始化 :param input_dim: :param output_dim: """ super(my_dense, self).__init__() # 添加变量 self.kernel = self.add_variable("w", [input_dim, output_dim]) # 权重 self.bias = self.add_variable("b", [output_dim]) # 偏置 def call(self, inputs, training=none): """ 在layer被调用的时候执行, 计算结果 :param inputs: 输入 :param training: 默认为none :return: 返回计算结果 """ # y = w * x + b out = inputs @ self.kernel + self.bias return out
案例
数据集介绍
cifar-10 是由 10 类不同的物品组成的 6 万张彩色图片的数据集. 其中 5 万张为训练集, 1 万张为测试集.
完整代码
import tensorflow as tf def pre_process(x, y): # 转换x x = 2 * tf.cast(x, dtype=tf.float32) / 255 - 1 # 转换为-1~1的形式 x = tf.reshape(x, [-1, 32 * 32 * 3]) # 把x铺平 # 转换y y = tf.convert_to_tensor(y) # 转换为0~1的形式 y = tf.one_hot(y, depth=10) # 转成one_hot编码 # 返回x, y return x, y def get_data(): """ 获取数据 :return: """ # 获取数据 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() # 调试输出维度 print(x_train.shape) # (50000, 32, 32, 3) print(y_train.shape) # (50000, 1) # squeeze y_train = tf.squeeze(y_train) # (50000, 1) => (50000,) y_test = tf.squeeze(y_test) # (10000, 1) => (10000,) # 分割训练集 train_db = tf.data.dataset.from_tensor_slices((x_train, y_train)).shuffle(10000, seed=0) train_db = train_db.batch(batch_size).map(pre_process).repeat(iteration_num) # 迭代20次 # 分割测试集 test_db = tf.data.dataset.from_tensor_slices((x_test, y_test)).shuffle(10000, seed=0) test_db = test_db.batch(batch_size).map(pre_process) return train_db, test_db class my_dense(tf.keras.layers.layer): # 继承layer def __init__(self, input_dim, output_dim): """ 初始化 :param input_dim: :param output_dim: """ super(my_dense, self).__init__() # 添加变量 self.kernel = self.add_weight("w", [input_dim, output_dim]) # 权重 self.bias = self.add_weight("b", [output_dim]) # 偏置 def call(self, inputs, training=none): """ 在layer被调用的时候执行, 计算结果 :param inputs: 输入 :param training: 默认为none :return: 返回计算结果 """ # y = w * x + b out = inputs @ self.kernel + self.bias return out class my_model(tf.keras.model): # 继承model def __init__(self): """ 初始化 """ super(my_model, self).__init__() self.fc1 = my_dense(32 * 32 * 3, 256) # 第一层 self.fc2 = my_dense(256, 128) # 第二层 self.fc3 = my_dense(128, 64) # 第三层 self.fc4 = my_dense(64, 32) # 第四层 self.fc5 = my_dense(32, 10) # 第五层 def call(self, inputs, training=none): """ 在model被调用的时候执行 :param inputs: 输入 :param training: 默认为none :return: 返回输出 """ x = self.fc1(inputs) x = tf.nn.relu(x) x = self.fc2(x) x = tf.nn.relu(x) x = self.fc3(x) x = tf.nn.relu(x) x = self.fc4(x) x = tf.nn.relu(x) x = self.fc5(x) return x # 定义超参数 batch_size = 256 # 一次训练的样本数目 learning_rate = 0.001 # 学习率 iteration_num = 20 # 迭代次数 optimizer = tf.keras.optimizers.adam(learning_rate=learning_rate) # 优化器 loss = tf.losses.categoricalcrossentropy(from_logits=true) # 损失 network = my_model() # 实例化网络 # 调试输出summary network.build(input_shape=[none, 32 * 32 * 3]) print(network.summary()) # 组合 network.compile(optimizer=optimizer, loss=loss, metrics=["accuracy"]) if __name__ == "__main__": # 获取分割的数据集 train_db, test_db = get_data() # 拟合 network.fit(train_db, epochs=5, validation_data=test_db, validation_freq=1)
输出结果:
model: "my__model"
_________________________________________________________________
layer (type) output shape param #
=================================================================
my__dense (my_dense) multiple 786688
_________________________________________________________________
my__dense_1 (my_dense) multiple 32896
_________________________________________________________________
my__dense_2 (my_dense) multiple 8256
_________________________________________________________________
my__dense_3 (my_dense) multiple 2080
_________________________________________________________________
my__dense_4 (my_dense) multiple 330
=================================================================
total params: 830,250
trainable params: 830,250
non-trainable params: 0
_________________________________________________________________
none
(50000, 32, 32, 3)
(50000, 1)
2021-06-15 14:35:26.600766: i tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:176] none of the mlir optimization passes are enabled (registered 2)
epoch 1/5
3920/3920 [==============================] - 39s 10ms/step - loss: 0.9676 - accuracy: 0.6595 - val_loss: 1.8961 - val_accuracy: 0.5220
epoch 2/5
3920/3920 [==============================] - 41s 10ms/step - loss: 0.3338 - accuracy: 0.8831 - val_loss: 3.3207 - val_accuracy: 0.5141
epoch 3/5
3920/3920 [==============================] - 41s 10ms/step - loss: 0.1713 - accuracy: 0.9410 - val_loss: 4.2247 - val_accuracy: 0.5122
epoch 4/5
3920/3920 [==============================] - 41s 10ms/step - loss: 0.1237 - accuracy: 0.9581 - val_loss: 4.9458 - val_accuracy: 0.5050
epoch 5/5
3920/3920 [==============================] - 42s 11ms/step - loss: 0.1003 - accuracy: 0.9666 - val_loss: 5.2425 - val_accuracy: 0.5097
到此这篇关于一小时学会tensorflow2之自定义层的文章就介绍到这了,更多相关tensorflow2自定义层内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!