Keras学习笔记----三(编译 训练 例子)

来源:互联网 发布:linux查询端口命令 编辑:程序博客网 时间:2024/06/06 14:22

Keras学习笔记----三(编译 训练 例子)

编译

在训练模型之前,我们需要通过compile来对学习过程进行配置。compile接收三个参数:


1 优化器optimizer:该参数可指定为已预定义的优化器名,如rmsprop、adagrad,或一个optimizers类的对象,详情见optimizers

2 损失函数loss:该参数为模型试图最小化的目标函数,它可为预定义的损失函数名,如categorical_crossentropy、mse,也可以为一个损失函数。详情见objectives

3 指标列表metrics:对分类问题,我们一般将该列表设置为metrics=['accuracy']。指标可以是一个预定义指标的名字,也可以是一个用户定制的函数.指标函数应该返回单个张量,或一个完成- > metric_valuemetric_name映射的字典.

# for a multi-class classification problemmodel.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy']) # for a binary classification problemmodel.compile(optimizer='rmsprop',loss='binary_crossentropy',metrics=['accuracy']) # for a mean squared error regression problemmodel.compile(optimizer='rmsprop',loss='mse')# for custom metricsimport keras.backend as Kdef mean_pred(y_true, y_pred):       return K.mean(y_pred)def false_rates(y_true, y_pred):       false_neg = ...       false_pos = ...       return {                     'false_neg': false_neg,                     'false_pos': false_pos,                    }model.compile(optimizer='rmsprop',                       loss='binary_crossentropy',                        metrics=['accuracy', mean_pred, false_rates])

训练

Keras以Numpy数组作为输入数据和标签的数据类型。训练模型一般使用fit函数,下面是一些例子。

# for a single-input model with 2 classes (binary):model = Sequential()model.add(Dense(1, input_dim=784, activation='sigmoid'))model.compile(optimizer='rmsprop',                            loss='binary_crossentropy',                            metrics=['accuracy'])# generate dummy dataimport numpy as npdata = np.random.random((1000, 784))labels = np.random.randint(2, size=(1000, 1))# train the model, iterating on the data in batches# of 32 samplesmodel.fit(data, labels, nb_epoch=10, batch_size=32)###########################################################3 # for a multi-input model with 10 classes:left_branch = Sequential()left_branch.add(Dense(32, input_dim=784))right_branch = Sequential()right_branch.add(Dense(32, input_dim=784))merged = Merge([left_branch, right_branch], mode='concat')model = Sequential()model.add(merged)model.add(Dense(10, activation='softmax'))model.compile(optimizer='rmsprop',                           loss='categorical_crossentropy',                           metrics=['accuracy']) # generate dummy dataimport numpy as npfrom keras.utils.np_utils import to_categoricaldata_1 = np.random.random((1000, 784))data_2 = np.random.random((1000, 784))# these are integers between 0 and 9labels = np.random.randint(10, size=(1000, 1))# we convert the labels to a binary matrix of size (1000, 10)# for use with categorical_crossentropylabels = to_categorical(labels, 10)# train the model# note that we are passing a list of Numpy arrays as training data# since the model has 2 inputsmodel.fit([data_1, data_2], labels, nb_epoch=10, batch_size=32)

例子

在 Keras 代码包的 examples 文件夹中,可以找到使用真实数据的示例模型:

1  CIFAR10 小图片分类:使用CNN和实时数据提升
2  IMDB 电影评论观点分类:使用LSTM处理成序列的词语
3  Reuters(路透社)新闻主题分类:使用多层感知器(MLP)
4  MNIST手写数字识别:使用多层感知器和CNN
5  字符级文本生成:使用LSTM...

原创粉丝点击