【Keras】Keras中的两种模型:Sequential和Model

在Keras中有两种深度学习的模型:序列模型(Sequential)和通用模型(Model)。差异在于不同的拓扑结构。

序列模型 Sequential

序列模型各层之间是依次顺序的线性关系,模型结构通过一个列表来制定。

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)

或者逐层添加网络结构

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'))

通用模型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)
  • 26
    点赞
  • 120
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值