自定义损失函数
之前使用的损失函数
def customized_mse(y_true, y_pred):
return tf.reduce_mean(tf.square(y_pred - y_true))
model = keras.models.Sequential([
keras.layers.Dense(30, activation='relu',
input_shape=x_train.shape[1:]),
keras.layers.Dense(1),
])
model.summary()
# 用上面的自定义函数 loss参数
model.compile(loss=customized_mse, optimizer="sgd",
# 其他指标
metrics=["mean_squared_error"])
callbacks = [keras.callbacks.EarlyStopping(
patience=5, min_delta=1e-2)]
进行训练
可以发现自定义的loss和指标的loss是一样的
自定义层次
# Dense layers定义 这个全连接层有一百个神经单元
layer = tf.keras.layers.Dense(100)
# 指定input shape 输出是一个None * 100 的矩阵
layer = tf.keras.layers.Dense(100, input_shape=(None, 5))
# 输入是一个 10*5 的矩阵 输出是一个 10 * 100 的矩阵
layer(tf.zeros([10, 5]))
# 打印layer的变量
# layer.variables
# x * w + b
# 可训练的变量
layer.trainable_variables
x的值
b的值
可以使用 help(layer)查看其它方法
自定义dense layer
# customized dense layer.
class CustomizedDenseLayer(keras.layers.Layer):
# 重载初始化函数
def __init__(self, units, activation=None, **kwargs):
# 这一层的单元数目
self.units = units
# 激活函数
self.activation = keras.layers.Activation(activation)
super(CustomizedDenseLayer, self).__init__(**kwargs)
def build(self, input_shape):
"""构建所需要的参数"""
# x * w + b. input_shape:[None, a] w:[a,b]output_shape: [None, b]
self.kernel = self.add_weight(name = 'kernel',
#input shanpe的第二个值 和后面的单元值
shape = (input_shape[1], self.units),
# 如何初始化参数矩阵 使用uniform均匀分布的随机化方法
initializer = 'uniform',
# 这个参数是可被训练的
trainable = True)
self.bias = self.add_weight(name = 'bias',
shape = (self.units, ),
# 偏置一般用zeros初始化
initializer = 'zeros',
trainable = True)
super(CustomizedDenseLayer, self).build(input_shape)
def call(self, x):
"""完成正向计算"""
# x * w + b.
return self.activation(x @ self.kernel + self.bias)
model = keras.models.Sequential([
#调用自定义程序构建模型
CustomizedDenseLayer(30, activation='relu',
input_shape=x_train.shape[1:]),
CustomizedDenseLayer(1),
# 添加激活函数层
customized_softplus,
# 与下面两行代码是等价的
# keras.layers.Dense(1, activation="softplus"),
# keras.layers.Dense(1), keras.layers.Activation('softplus'),
])
model.summary()
model.compile(loss="mean_squared_error", optimizer="sgd")
callbacks = [keras.callbacks.EarlyStopping(
patience=5, min_delta=1e-2)]
#平滑版的relu
# tf.nn.softplus : log(1+e^x)
# 对于一个输入的x 输出为softplus(x)
customized_softplus = keras.layers.Lambda(lambda x : tf.nn.softplus(x))
print(customized_softplus([-10., -5., 0., 5., 10.]))
训练
学习曲线
测试