在 Keras 中有两类主要的模型:Sequential 顺序模型 和 使用函数式 API 的 Model 类模型。
Sequential 模型 API
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential(name='my_sequential')
model.add(keras.Input(shape=(250, 250, 3), name='input')) # 250x250 RGB images
model.add(layers.Conv2D(32, 5, strides=2, activation="relu"))
model.add(layers.Conv2D(32, 3, activation="relu"))
model.summary() # Note that the Input object is not displayed as part of model.layers, since it isn't a layer
model.add(layers.MaxPooling2D(3))
model.summary()
Model 类(函数式 API)
from keras.models import Model
from keras.layers import Input, Dense
a = Input(shape=(32,))
b = Dense(32)(a)
model = Model(inputs=a, outputs=b)
完整示例,多层感知机:
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt
def show_train_history(train_history, train, validation):
plt.plot(train_history.history[train])
plt.plot(train_history.history[validation])
plt.title('Train History')
plt.ylabel(train)
plt.xlabel('Epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
(x_train_image, y_train_label), (x_test_image, y_test_label) = mnist.load_data()
x_Train = x_train_image.reshape(-1, 784).astype('float32') / 255
x_Test = x_test_image.reshape(-1, 784).astype('float32') / 255
y_Train_label_onehot = np.eye(10)[y_train_label]
y_Test_label_onehot = np.eye(10)[y_test_label]
model = keras.Sequential(name='MLP')
model.add(keras.Input(shape=(28*28, ), name='input')) # 28x28
model.add(layers.Dense(1000, activation="relu", use_bias=True, kernel_initializer='normal'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(1000, activation="relu", use_bias=True, kernel_initializer='normal'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(10, activation='softmax'))
model.summary()
print((len(model.weights)))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
train_history= model.fit(x=x_Train, y=y_Train_label_onehot, epochs=10, batch_size=200, verbose=2, validation_split=0.2)
show_train_history(train_history, 'accuracy', 'val_accuracy')
show_train_history(train_history, 'loss', 'val_loss')
scores = model.evaluate(x_Test, y_Test_label_onehot)
print('accuracy=', scores[1])
prediction=model.predict_classes(x_Test)
print('done')
完整示例,卷积神经网络:
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt
def show_train_history(train_history, train, validation):
plt.plot(train_history.history[train])
plt.plot(train_history.history[validation])
plt.title('Train History')
plt.ylabel(train)
plt.xlabel('Epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
(x_train_image, y_train_label), (x_test_image, y_test_label) = mnist.load_data()
x_train = x_train_image.astype('float32') / 255
x_test = x_test_image.astype('float32') / 255
y_train_label = np.eye(10)[y_train_label]
y_test_label = np.eye(10)[y_test_label]
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
model = keras.Sequential()
model.add(keras.Input(shape=(28, 28, 1), name='input'))
model.add(layers.Conv2D(256, [3, 3], 1, activation='relu', name='conv1'))
model.add(layers.MaxPool2D([3, 3], strides=2, name='pool1'))
model.add(layers.Conv2D(128, [3, 3], 1, activation='relu', name='conv2'))
model.add(layers.MaxPool2D([3, 3], 2, name='pool2'))
model.add(layers.Flatten(name='flatten'))
model.add(layers.Dense(10, activation='softmax', name='dense'))
model.summary()
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
train_history = model.fit(x=x_train, y=y_train_label, batch_size=None, epochs=10, verbose=2, validation_split=0.1)
show_train_history(train_history, 'accuracy', 'val_accuracy')
show_train_history(train_history, 'loss', 'val_loss')
scores = model.evaluate(x_test, y_test_label)
print('accuracy=', scores[1])
Reference
https://keras-zh.readthedocs.io/