不能相乘的部分
loss = K.sum(tf.matmul(loss,y_mask))/K.sum(y_mask))
这里相乘的时候会产生报错,因为loss的类型为tf.float32类型,而y_mask的类型为tf.int32类型。
所以这里此时在做乘法之前,需要将对应的类型进行转换一下:
y_mask = tf.cast(y_mask,dtype=tf.float32)
这里转换的部位需要注意,如果是在外面进行转换的话可能会发生报错问题
常规的模型调用内容如下:
batch_size = 5
max_seq_len = 128
bertmodel = Bert(maxlen=max_seq_len,batch_size=batch_size,with_mlm=True,mode='unilm',
solution='seq2seq')
input_ids = [keras.layers.Input(shape=(max_seq_len,),dtype='int32',name="token_ids"),
keras.layers.Input(shape=(max_seq_len,),dtype='int32',name="segment_ids")]
output = bertmodel(input_ids)
output = CrossEntropy()([input_ids,output])
model = keras.models.Model(input_ids,output)
model.compile(optimizer=keras.optimizers.Adam())
在
output = bertmodel(input_ids)
和
output = CrossEntropy()([input_ids,output])
之间如果加入对应的类型转换
input_ids[0] = tf.cast(input_ids[0],dtype=tf.float32)
此时这里会发生报错:
Graph disconnected: cannot obtain value for tensor KerasTensor
(type_spec=TensorSpec(shape=(None, 128), dtype=tf.int32, name='token_ids'),
name='token_ids', description="created by layer 'token_ids'")
at layer "tf.cast". The following previous layers were accessed without issue: []
所以这里我们进行变换思路,在计算前对数据类型进行转变
loss = K.sparse_categorical_crossentropy(y_true,y_pred)
#下面为转换语句
y_mask = tf.cast(y_mask,dtype=tf.float32)
loss = K.sum(tf.matmul(loss,y_mask))/K.sum(y_mask)