【keras】序贯Sequential模型实例之基于多层感知器的softmax多分类

基于多层感知器的softmax多分类:

# -*- coding: utf-8 -*-
"""
Created on Tue Jan  9 00:11:20 2018

@author: BruceWong
"""
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD

# Generate dummy data
#此处运用 keras.utils.to_categorical生成one_hot编码
import numpy as np
x_train = np.random.random((10000, 20))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(10000, 1)), num_classes=10)
x_test = np.random.random((100, 20))
y_test = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)
#设计模型
model = Sequential()
# Dense(64) is a fully-connected layer with 64 hidden units.
# in the first layer, you must specify the expected input data shape:
# here, 20-dimensional vectors.
model.add(Dense(128, activation='relu', input_dim=20))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
#定义随机梯度下降中的参数
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
#编译模型
model.compile(loss='categorical_crossentropy',
              #optimizer=sgd,
              optimizer= 'rmsprop',
              metrics=['accuracy'])
#训练模型
model.fit(x_train, y_train,
          epochs=10,
          batch_size=128)
#评估模型
score = model.evaluate(x_test, y_test, batch_size=128)
print(score)

你可能感兴趣的:(深度学习,Keras)