keras关于model的小总结

进来看了看keras, 比tf友好的多啊,总结下: Keras有两种类型的模型,顺序模型(Sequential)和泛型模型(Model) 首先比较简单的顺序型

Sequential模型接口

代码示例

model = Sequential()
model.add(Dense(32, input_shape=(500,)))
model.add(Dense(10, activation=softmax))
model.compile(optimizer=rmsprop,
      loss=categorical_crossentropy,
      metrics=[accuracy])
model.fit( x, y, batch_size=32, nb_epoch=10, verbose=1, callbacks=[], validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None)
score = model.evaluate(x_test, y_test, batch_size=32)
model.predict(x, batch_size=32, verbose=0)
model.predict_classes( x, batch_size=32, verbose=1)
model.predict_proba(x, batch_size=32, verbose=1)
Sequential() 代表类的初始化;
Dense() 代表全连接层,参数32表示本层有32个神经元,然后接relu激活层,由于是第一层,计算机不知道应该是以多少维增加,因此,后面添加输入维度数100。这一层需要训练100*32+32个参数。
model.add() 相当于把模型一层层拼接起来。
model.compile()函数中输入优化器,损失函数等信息
model.fit()中传入需要训练的数据x,y以及训练的批次等信息,开始训练
model.evaluate()用来评估模型的误差函数的返回值是预测值的numpy array
model.predict_classes:本函数按batch产生输入数据的类别预测结果;
model.predict_proba:本函数按batch产生输入数据属于各个类别的概率

model模型接口

函数式模型基本属性与训练流程 一般需要: 1、model.layers,添加层信息; 2、model.compile,模型训练的BP模式设置; 3、model.fit,模型训练参数设置 + 训练; 4、evaluate,模型评估; 5、predict 模型预测

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

a = Input(shape=(32,))
b = Dense(32)(a)
model = Model(input=a, output=b)
model.compile(optimizer, loss, metrics=[], loss_weights=None, sample_weight_mode=None)
model.fit(x, y, batch_size=32, nb_epoch=10, verbose=1, callbacks=[], validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None)
model.evaluate(x, y, batch_size=32, verbose=1, sample_weight=None)
model.predict(x, batch_size=32, verbose=0)

例子

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

# This returns a tensor
inputs = Input(shape=(784,))

# a layer instance is callable on a tensor, and returns a tensor
x = Dense(64, activation=relu)(inputs)
# 输入inputs,输出x
# (inputs)代表输入
x = Dense(64, activation=relu)(x)
# 输入x,输出x
predictions = Dense(10, activation=softmax)(x)
# 输入x,输出分类

# This creates a model that includes
# the Input layer and three Dense layers
model = Model(inputs=inputs, outputs=predictions)
model.compile(optimizer=rmsprop,
              loss=categorical_crossentropy,
              metrics=[accuracy])
model.fit(data, labels)  # starts training
经验分享 程序员 微信小程序 职场和发展