当前位置: 代码迷 >> 综合 >> keras 函数式API
  详细解决方案

keras 函数式API

热度:103   发布时间:2023-11-23 11:41:42.0

一、函数式API基础

from keras import Input, layers
from keras.models import Modelinput_tensor = Input(shape=(64,))
#input_tensor值为<tf.Tensor 'input_5:0' shape=(?, 32) dtype=float32>
#其类型为tensorflow.python.framework.ops.Tensor
dense = layers.Dense(32, activation='relu')
#dense值为<keras.layers.core.Dense at 0x2be14f1d708>
#其类型为keras.layers.core.Dense,说明Dense类初始化时会返回一个层实例
output_tensor = dense(input_tensor)
#像层实例中输入一个tensor,会输出一个tensor#也可以联合起来写成下面这样子
input_tensor = Input(shape=(64,))
x = layers.Dense(32, activation='relu')(input_tensor)
x = layers.Dense(32, activation='relu')(x)
output_tensor = layers.Dense(10, activation='softmax')(x)#将Model 对象实例化只用了一个输入张量和 一个输出张量。
#Keras 会在后台检索从input_tensor 到 output_tensor 
#所包含的每一层, 并将这些层组合成一个类图的数据结构,即一个Model
model = Model(input_tensor, output_tensor)

二、多输入模型

> 函数式API 可用于构建具有多个输入的模型。通常情况下,这种模型会在某一时刻用一个
> 可以组合多个张量的层将不同的输入分支合并,张量组合方式可能是相加、连接等。
> 这通常利用 Keras的合并运算来实现,比如keras.layers.add、keras.layers.concatenate 等。```python
concatenated = layers.concatenate([encoded_text, encoded_question], axis=-1)
answer = layers.Dense(answer_vocabulary_size, activation='softmax')(concatenated)
model = Model([text_input, question_input], answer)
model.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['acc'])
model.fit([text, question], answers, epochs=10, batch_size=128)

三、多输出模型


> 训练这种模型需要能够对网络的各个头指定不同的损失函数,
> 例如,年龄预测 是标量回归任务,而性别预测是二分类任务,二者需要不同的训练过程。
> 但是,梯度下降要求 将一个标量最小化,所以为了能够训练模型,
> 我们必须将这些损失合并为单个标量。合并不同 损失最简单的方法就是对所有损失求和。
> 在Keras 中,你可以在编译时使用损失组成的列表或 字典来为不同输出指定不同损失,
> 然后将得到的损失值相加得到一个全局损失,并在训练过程中将这个损失最小化。```python
age_prediction = layers.Dense(1, name='age')(x)
income_prediction = layers.Dense(num_income_groups,activation='softmax',name='income')(x)
gender_prediction = layers.Dense(1, activation='sigmoid', name='gender')(x) 
model = Model(posts_input,[age_prediction, income_prediction, gender_prediction])
model.compile(optimizer='rmsprop',loss=['mse', 'categorical_crossentropy', 'binary_crossentropy']) 
model.compile(optimizer='rmsprop',loss={'age': 'mse','income': 'categorical_crossentropy', 'gender':'binary_crossentropy'})
'''
严重不平衡的损失贡献会导致模型表示针对单个损失值最大的任务优先进行优化,
而不考虑其他任务的优化。为了解决这个问题,我们可以为每个损失值对最终损失的
贡献分配 不同大小的重要性。如果不同的损失值具有不同的取值范围,那么这一方法尤其有用。
比如, 用于年龄回归任务的均方误差(MSE)损失值通常在3~5 左右,而用于性别
分类任务的交叉熵损失值可能低至0.1。在这种情况下,为了平衡不同损失的贡献,
我们可以让交叉熵损失的权重 取 10,而 MSE 损失的权重取 0.5。
'''
model.compile(optimizer='rmsprop',loss=['mse', 'categorical_crossentropy', 'binary_crossentropy'], loss_weights=[0.25,1., 10.]) model.fit(posts, [age_targets, income_targets, gender_targets],epochs=10,batch_size=64)

  相关解决方案