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.先训练此类模型是,可以指定不同的输出使用不同的优化器和损失函数