2018-07-01
keras
, learn
官方教程,记录以便查阅!
以下代码运行环境为 —— keras[2.2.4], tensorflow[1.11.0]
# The core data structure of Keras is a model, a way to organize layers.
# The simplest type of model is the `Sequential` model, a linear stack of layers.
# For more complex architectures, you should use the Keras functional API,
# which allows to build arbitrary graphs of layers.
from keras.models import Sequential
model = Sequential()
# Stacking layers is as easy as .add()
from keras.layers import Dense
model.add(Dense(units=64, activation='relu', input_dim=784))
model.add(Dense(units=10, activation='softmax'))
# Once your model looks good, configure its learning process with .compile()
model.compile(loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
# If you need to, you can further configure your optimizer.
# A core principle of Keras is to make things reasonably simple,
# while allowing the user to be fully in control when they need to
import keras
model.compile(loss=keras.losses.categorical_crossentropy,
metrics=['accuracy'],
optimizer=keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True))
from keras import backend as K
from keras.datasets import mnist
batch_size = 128
num_classes = 10
epochs = 12
# input image dimensions
img_rows, img_cols = 28, 28
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# if K.image_data_format() == 'channels_first':
# x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
# x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
# input_shape = (1, img_rows, img_cols)
# else:
# x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
# x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
# input_shape = (img_rows, img_cols, 1)
x_train = x_train.reshape(x_train.shape[0], -1)
x_test = x_test.reshape(x_test.shape[0], -1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
# You can now iterate on your training data in batches
# x_train and y_train are Numpy arrays --just like in the Scikit-Learn API.
model.fit(x_train, y_train, epochs=5, batch_size=32)
# Alternatively, you can feed batches to your model manually:
model.train_on_batch(x_train[:1000], y_train[:1000])
# Evaluate your performance in one line
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128)
loss_and_metrics
model.metrics_names
# Or generate predictions on new data
classes = model.predict(x_test, batch_size=128)
classes
model.predict(x_test[:1])