Keras 快速通关
官方网址:https://keras-zh.readthedocs.io/
快速开始
搭建模型框架
from keras.models import Sequential#导入模块
model = Sequential()
使用.add()来堆叠模型
from keras.layers import Dense
model.add(Dense(units=64, activation='relu', input_dim=100))#添加全连接层(设置输出为64/激活函数为relu/输入为100)
model.add(Dense(units=10, activation='softmax'))#添加全连接层(设置输出为10,激活函数为softmax‘分类常用输出层激活函数’)
配置学习方式
#简单的配置方式
model.compile(loss='categorical_crossentropy',#配置损失函数
optimizer='sgd',#配置优化器
metrics=['accuracy'])#
#必要的时候可以采用以下方式设置参数
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True))
开始训练
# x_train 和 y_train 是 Numpy 数组 -- 就像在 Scikit-Learn API 中一样。
#批量训练
model.fit(x_train, y_train, epochs=5, batch_size=32)#开始训练(训练数据/标签/训练几遍/每一次训练多少数据)
#你可以手动地将批次的数据提供给模型
model.train_on_batch(x_batch, y_batch)
评估模型
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128) #评估模型(测试数据/标签/每一次训练几个数据)
对新数据生成预测
classes = model.predict(x_test, batch_size=128)#生成预测(数据集,每一次训练几个数据)
进阶的函数结构
和之前一样只不过语法变了一下而已
引入模组
from keras.models import Model
基本模式
from keras.models import Model
from keras.layers import Input, Dense
inputs = Input(shape=(784,))
output_1 = Dense(64, activation='relu')(inputs)
output_2 = Dense(64, activation='relu')(output_1)
predictions = Dense(10, activation='softmax')(output_2)
# 这部分创建了一个包含输入层和三个全连接层的模型
model = Model(inputs=inputs, outputs=predictions)
构建多输入多输出模型
连接不同的输入
#在这里是将两个完全不同的神经网络的最后输出层连接起来,作为输入输入x层
x = keras.layers.concatenate([lstm_out, auxiliary_input])
定义模型
#此时传入数据时数据必须一一对应
model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output])
训练模型
model.compile(optimizer='rmsprop',
loss={'main_output': 'binary_crossentropy', 'aux_output': 'binary_crossentropy'},
loss_weights={'main_output': 1., 'aux_output': 0.2})
# 然后使用以下方式训练:
model.fit({'main_input': headline_data, 'aux_input': additional_data},
{'main_output': headline_labels, 'aux_output': additional_labels},
epochs=50, batch_size=32)
#或者采用这种进行训练
model.fit([headline_data, additional_data], [headline_labels, additional_labels],
epochs=50, batch_size=32)#此时数据必须一一对应
推理数据
model.predict({'main_input': headline_data, 'aux_input': additional_data})
#或者
pred = model.predict([headline_data, additional_data])
保存网络
model.save('my_model.h5') # 保存网络并命名,但你需要pyh5这个组件
读取网络
model = load_model('my_model.h5') #读取网络