当前位置:   article > 正文

Keras框架

keras框架

Keras中有两种深度学习的模型:序列模型(Sequential)和通用模型(Model)。

序列模型 Sequential

1、序列模型各层之间是依次顺序的线性关系,模型结构通过一个列表来制定。
from keras.models import Sequential
from keras.layers import Dense, Activation
layers = [Dense(32, input_shape = (784,)),
   Activation('relu'),
   Dense(10),
   Activation('softmax')]
model = Sequential(layers)


2、或者逐层添加网络结构
from keras.models import Sequential
from keras.layers import Dense, Activation
model = Sequential()
model.add(Dense(32, input_shape = (784,)))
model.add(Activation('relu'))
model.add(Dense(10))
model.add(Activation('softmax'))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

通用模型Model

通用模型可以设计非常复杂、任意拓扑结构的神经网络,例如有向无环网络、共享层网络等。相比于序列模型只能依次线性逐层添加,通用模型能够比较灵活地构造网络结构,设定各层级的关系。

from keras.layers import Input, Dense
from keras.models import Model
# 定义输入层,确定输入维度
input = input(shape = (784, ))
# 2个隐含层,每个都有64个神经元,使用relu激活函数,且由上一层作为参数
x = Dense(64, activation='relu')(input)
x = Dense(64, activation='relu')(x)
# 输出层
y = Dense(10, activation='softmax')(x)
# 定义模型,指定输入输出
model = Model(input=input, output=y)
# 编译模型,指定优化器,损失函数,度量
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
# 模型拟合,即训练
model.fit(data, labels)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

保存模型的四种方式

model.save()
model.save_weights()
model.to_json()
model.to_yaml()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/47320
推荐阅读
相关标签
  

闽ICP备14008679号