import tensorflow as f
from tensorflow.keras import layers, losses
class OneLayer(layers.Layer):
def __init__(self):
super(OneLayer, self).__init__()
# def call(self, inputs, **kwargs):
# def call(self, inputs, **kwargs):
#
# if kwargs.get("training", False):
# inputs = inputs + 1
# tf.print("加11111111111111111111111111111111")
# else:
# inputs = inputs - 1
# tf.print("减11111111111111111111111111111111")
#
# return inputs
#
def call(self, inputs, training=None, mask=None, **kwargs):
if training:
inputs = inputs + 1
tf.print("加11111111111111111111111111111111")
else:
inputs = inputs - 1
tf.print("减11111111111111111111111111111111")
return inputs
inputs = layers.Input((1, ))
embedding = layers.Dense(64)(inputs)
embedding = OneLayer()(embedding)
embedding = tf.multiply(embedding, 2.0)
output = layers.Dense(1)(embedding)
model = tf.keras.Model(inputs, output)
model.summary()
import numpy as np
x = np.arange(64).reshape((64, 1)) * 1.0
y = np.arange(64).reshape((64, 1)) * 1.0 + 1
model.compile("adam", loss=losses.MeanSquaredError(), metrics=["mse"])
model.fit(x, y, batch_size=16, epochs=100)
print("----------------------------")
print(model.predict(x[:2]))
tf.keras 中training的使用
最新推荐文章于 2022-04-04 11:11:30 发布
这篇博客展示了如何在TensorFlow中创建一个自定义层`OneLayer`,该层在训练期间对输入加1,在评估期间减1。通过将这个自定义层整合到模型中,并使用Mean Squared Error损失函数进行训练,博主演示了模型的构建和训练过程。最后,他们展示了模型的预测结果。
摘要由CSDN通过智能技术生成