Keras是用于构建和训练深度学习模型的高层API,可以使用TensorFlow,Theano或CNTK为后端,相当于在TensorFlow基础上再封装一层,也就是它的下层可以使用TensorFlow,Theano,CNTK之间自由切换。
Keras有如下特点:
- 用户友好:对常见的使用场景做了简单一致性的接口优化,并且对于错误提供了清晰和可操作性的错误反馈
- 模块化并且可以自由组合,没有什么限制
- 容易扩展,可以创建自己的神经网络层,损失函数,等
导入Keras
tf.keras是TensorFlow针对keras API 标准的实现,tf.keras的版本可能和最新的keras版本不一致,在使用的时候可以打印一下版本留意当前TensorFlow和keras版本号。
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import keras
print(tf.version.VERSION)
print(tf.keras.__version__)
print(keras.__version__)
1569199645770
训练简单模型
模型使用是为70000张灰度图片的10种类型的数据集。Fashion-mnist. 可以自行点开数据集看一下图片内容,每张图片都是28x28像素。
我们将会使用60000张图片用于训练模型,10000张图片用于评价模型训练的效果,即能否正确的对图片进行分类。
代码与步骤注释,已经整理如下。
from __future__ import absolute_import, division, print_function, unicode_literals
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
# 1. 下载fashion_mnist数据集,在TensorFlow中已经在代码中集成好了,直接调用即可下载图片
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
# 1.1 查看数据的形状,数据的label即数据的分类,测试图片的形状分类等,这里作为日志输出
print(train_images.shape)
print(train_labels)
print(test_images.shape)
print(len(test_labels))
# (60000, 28, 28)
# [9 0 0 ... 3 0 5] 图片的种类
# (10000, 28, 28)
# 10000 10000张测试图片,每一个坐标对应图片下标的种类
# 1.2 上面训练分类的标签对应的具体名称
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# 2. 预处理数据,将图片的点位值缩小到0~1的范围。方便神经网络处理
# print(train_images[0])
train_images = train_images / 255.0
test_images = test_images / 255.0
# 2.1 查看处理后的图片显示,这一步为可选,看到图片的内容即可
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()
# 3. 构建模型,需要配置要构建的神经网络模型,然后编译模型
# Flatten层只是将数据展平,原本为28*28的二维数组,变为784的一维数组,这一层不学习任何参数,只是对数据进行转换
# Dense层为全连接层,配合激活函数。第一个全连接层有128个节点(神经元),
# 第二个Dense层有10个神经元,然后使用softmax作为激活函数,使节点输出的每种种类的数值不会大于1.
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
# 3.1 编译模型
# 损失函数:测量我们模型预测值的精准度,损失函数的值越小越好
# 优化器:基于当前的数据和损失函数来更新
# Metrics:用于监控的。当前使用的是accuracy,查看图片是否被正确的分类
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 4. 训练模型,传入训练的图片和训练的标签(分类),指定5次迭代
model.fit(train_images, train_labels, epochs=5)
# 5. 使用测试集,评估我们模型训练的好坏
test_loss, test_acc = model.evaluate(test_images, test_labels)
# 打印模型训练的精度
print('Test accuracy:', test_acc)
# 6. 对图片做预测
# 6.1 预测多张图片,并绘画出多张图片的预测结果
# predictions = model.predict(test_images)
# print(predictions[0])
# print(np.argmax(predictions[0]))
# print(test_labels[0])
# num_rows = 5
# num_cols = 3
# num_images = num_rows*num_cols
# plt.figure(figsize=(2*2*num_cols, 2*num_rows))
# for i in range(num_images):
# plt.subplot(num_rows, 2*num_cols, 2*i+1)
# plot_image(i, predictions, test_labels, test_images)
# plt.subplot(num_rows, 2*num_cols, 2*i+2)
# plot_value_array(i, predictions, test_labels)
# plt.show()
# 6.2 预测单张图片的的分类
# img = test_images[0]
# img = (np.expand_dims(img,0))
# predictions_single = model.predict(img)
#
# print(predictions_single)
# plot_value_array(0, predictions_single, test_labels)
# plt.xticks(range(10), class_names, rotation=45)
# plt.show()
# 画图片
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100 * np.max(predictions_array),
class_names[true_label]),
color=color)
# 画预测精度的柱状图
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array[i], true_label[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
最后的测试精度为0.8794.
1569201378997
使用卷积神经网络进行训练
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow import keras
import keras.models as models
import keras.layers as layers
# Helper libraries
import numpy as np
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
train_images = train_images / 255.0
test_images = test_images / 255.0
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# model.summary()
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
model.summary()
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(test_acc)
测试集的精度为0.8989..
1569201642032
几种常见的卷积网络层
img
最后
这篇文章主要简单介绍下Keras及其与TensorFlow的关系,最后借助两个模型训练的案例,了解Keras如何使用。