Keras学习笔记(函数式API)

Keras学习笔记(函数式API)

1.函数式API可以用来设计很复杂的模型,如下图模型结构:
在这里插入图片描述
存在三个输入以及两个输出,在够贱的时候我们可以把layer当做堆积木一样,一块一块堆积,合并的方法现在有:
layers.concatenate: 合并,叠加效果
layers.average: 相加求平均
layers.add: 相加
等…
条件就是除数据的最后一个维度外,其余维度必须相同(不同的应该也可以使用广播的方法进行层的合并),下面献上代码:

from keras.models import Model
from keras.layers import LSTM, Bidirectional, Input, Dense
import keras
import matplotlib.pyplot as plt
from keras import layers
import numpy as np
import os
os.environ["PATH"] += os.pathsep + 'E:\Graphviz2.38\\bin\\'


# 多输入、多输出
num_tags = 12
num_words = 10000
num_departments = 4

title_input = Input(shape=(None, ), name='title_input')
body_input = Input(shape=(None, ), name='body_input')
tags_input = Input(shape=(num_tags, ), name='tags_input')
title_features = layers.Embedding(num_words, 64)(title_input)
body_features = layers.Embedding(num_words, 64)(body_input)
title_features = LSTM(128)(title_features)
body_features = LSTM(32)(body_features)
x = layers.concatenate([title_features, body_features, tags_input])
priority_pred = Dense(1, activation='sigmoid', name='priority')(x)
department_pred = Dense(num_departments, activation='softmax', name='department')(x)
model = Model(inputs=[title_input, body_input, tags_input], outputs=[priority_pred, department_pred])
# model.summary()
keras.utils.plot_model(model, 'test.png', show_shapes=True)
model.compile(
    optimizer=keras.optimizers.RMSprop(1e-3),
    loss={
        'priority': 'binary_crossentropy',
        'department': 'categorical_crossentropy',
    },
    loss_weights={'priority': 1.0, 'department': 0.2},
    metrics=['accuracy']
)


title_data = np.random.randint(num_words, size=(1000, 10))
body_data = np.random.randint(num_words, size=(1000, 100))
tags_data = np.random.randint(2, size=(1000, num_tags))
# tags_data = np.random.randint(num_tags, size=(1000, 1))
# tags_data = keras.utils.to_categorical(tags_data, num_classes=num_tags)

priority_data = np.random.random(size=(1000, 1))
department_data = np.random.randint(num_departments, size=(1000, 1))
department_data = keras.utils.to_categorical(department_data, num_classes=num_departments)

epochs = 10
history = model.fit(
    x=[title_data, body_data, tags_data],
    y=[priority_data, department_data],
    epochs=epochs,
    batch_size=250,
    validation_split=0.25
)
x = np.arange(epochs)
print(history.history)
plt.plot(x, history.history['loss'])
plt.plot(x, history.history['department_acc'])
plt.show()

2.在构建模型的时候,也可以将模型本身看作是一个layer来使用
3.共享层:像embedding层可以用来做共享层
4.先训练此类模型是,可以指定不同的输出使用不同的优化器和损失函数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值