【keras】函数式(Functional)模型学习构建全连接神经网络(一)

Keras函数式模型接口是用户定义多输出模型非循环有向模型具有共享层的模型等复杂模型的途径。一句话,只要你的模型不是类似VGG一样一条路走到黑的模型,或者你的模型需要多于一个的输出,那么你总应该选择函数式模型。函数式模型是最广泛的一类模型,序贯模型(Sequential)只是它的一种特殊情况

通过function模型构建全连接神经网络:

# -*- coding: utf-8 -*-
"""
Created on Thu Jan 11 23:53:26 2018
函数式function模型
@author: BruceWong
"""
import keras
from keras.layers import Input, Dense
from keras.models import Model
import numpy as np
# generate data生成数据
x_train = np.random.random((1000,10))
y_train = keras.utils.to_categorical(np.random.randint(10,size = (1000,1)), num_classes=10)
#设定模型,用input设定传入张量tensor的维度;
# This returns a tensor
inputs = Input(shape=(10,))
#所有的模型都是可调用的,就像层一样
# a layer instance is callable on a tensor, and returns a tensor
x = Dense(64, activation='relu')(inputs)
x = Dense(64, activation='relu')(x)
#得到输出的张量prediction
predictions = Dense(10, activation='softmax')(x)
# This creates a model that includes
# the Input layer and three Dense layers
#用model生成模型
model = Model(inputs=inputs, outputs=predictions)
#编译模型,指定优化参数、损失函数、效用评估函数
model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
#传入数据进行训练
model.fit(x_train, y_train,epochs = 10,batch_size = 128)  # starts training

所有的模型都是可调用的,就像层一样

利用函数式模型的接口,我们可以很容易的重用已经训练好的模型:可以把模型当作一个层一样,通过提供一个tensor来调用它。注意当你调用一个模型时,不仅仅重用了它的结构,也重用了它的权重。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值