tf2.0为我们封装了很多的损失函数,不过常用的是均方差和交叉熵损失函数,关于这两个函数的具体计算过程和适用范围,点击这里
下边说一下自定义损失函数,自定义损失函数有两种实现方式,分别是:函数实现形式和类的实现形式,相比于自定义层,自定义函数要简单一点,不过要多注意python语法错误和公式的计算过程。我们可以通过自定义来设计自己的损失函数(大佬才能做的事情)。
#类的实现过程
class MeanSquaredError(tf.keras.losses.Loss):
def call(self, y_true, y_pred):
return tf.reduce_mean(tf.square(y_pred - y_true))
#函数的实现过程
def MeanSquaredError(y_true, y_pred):
return tf.reduce_mean(tf.square(y_pred - y_true))
#下边讲一下老师的代码
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model
import numpy as np
print(tf.__version__)
print(np.__version__)
mnist = np.load("mnist.npz")
x_train, y_train, x_test, y_test = mnist['x_train'],mnist['y_train'],mnist['x_test'],mnist['y_test']
#/255是对数据进行归一化,因为图片的颜色特征大小为0-255
x_train, x_test = x_train / 255.0, x_test / 255.0
y_train = np.int32(y_train)
y_test = np.int32(y_test)
# 增加一个新的维度
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]
y_train = tf.one_hot(y_train,depth=10)
y_test = tf.one_hot(y_test,depth=10)
#将数据打乱,提高模型的泛化能力
train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)).shuffle(10000).batch(32)
test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).shuffle(100).batch(32)
#定义一个函数式的网络结构
def MyModel():
inputs = tf.keras.Input(shape=(28,28,1), name='digits')
#第一层是卷积层,共有32个3*3的卷积核
x = tf.keras.layers.Conv2D(32, 3, activation='relu')(inputs)
#由于维度问题,我们要把x拉伸才能连接全连接层
x = tf.keras.layers.Flatten()(x)
x = tf.keras.layers.Dense(128, activation='relu')(x)
#这是一个10分类问题,所以最后一层输出10个节点,激活函数用softmax
outputs = tf.keras.layers.Dense(10,activation='softmax', name='predictions')(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
return model
#定义FocalLoss,这个可以结合上边的公式去看,这里我们用函数式定义
def FocalLoss(gamma=2.0,alpha=0.25):
def focal_loss_fixed(y_true, y_pred):
y_pred = tf.nn.softmax(y_pred,axis=-1)
epsilon = tf.keras.backend.epsilon()
y_pred = tf.clip_by_value(y_pred, epsilon, 1.0)
y_true = tf.cast(y_true,tf.float32)
loss = - y_true * tf.math.pow(1 - y_pred, gamma) * tf.math.log(y_pred)
loss = tf.math.reduce_sum(loss,axis=1)
return loss
return focal_loss_fixed
model = MyModel()
model.compile(optimizer = tf.keras.optimizers.Adam(0.001), #优化器
loss = FocalLoss(gamma=2.0,alpha=0.25), #损失函数
metrics = [tf.keras.metrics.CategoricalAccuracy()]
) #评估函数
model.fit(train_ds, epochs=5,validation_data=test_ds)