python人脸识别:从入门到精通(5.3)Keras使用方法

第5章 深度学习与Keras工程实践

5.3 Keras使用方法

5.3.2 Keras神经网络堆叠的两种方式

1.线性模型

from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(units=4, activation='relu', input_dim=100))
model.add(Dense(units=5, activation='softmax'))
model.compile(loss='categorical_crossentropy',
              optimizer='sgd',
              metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5, batch_size=32)
classes = model.predict(x_test, batch_size=128)

2.函数式API

from keras.layers import Input, Dense
from keras.models import Model

#创建一个输入层, 输入样本的维度是100, 返回一个张量
inputs = Input(shape=(100,))
X = Dense(4, activation='relu')(inputs)
predictions = Dense(5, activation='softmax')(X)
model = Model(inputs=inputs, outputs=predictions)
model.compile(loss='categorical_crossentropy',
               optimizer='sgd',
               metrics=['accuracy'])
model.fit(data, labels)  #开始训练

复杂网络样例

from keras.layers import Input, Dense, Embedding, LSTM
from keras.models import Model
from tensorflow import keras
#接收一个含有100个整数的序列, 每个整数在1到10000之间
main_input = Input(shape=(100,), dtype='int32', name='main_input')

#添加一个Embedding层, 将输入序列编码为一个稠密向量序列, 每个向量维度为512
X = Embedding(output_dim=521,
              input_dim=10000,
              input_length=100)(main_input)
lstm_out = LSTM(32)(X)
auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out)
auxiliary_input = Input(shape=(5,), name='aux_input')
x = keras.layers.concatenate([lstm_out, auxiliary_input])

x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)

main_output = Dense(1, activation='sigmoid', name='main_output')(x)
model = Model(inputs=[main_input, auxiliary_input],
              outputs=[main_output, auxiliary_output])

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              loss_weights=[1, 0.2]
)
model.fit([headline_data, additional_data],
          [labels, labels],
          epoches=50,
          batch_size=32)

在这里插入图片描述

©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页