import warnings
warnings.simplefilter(action='ignore')
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
print('x_train data:', len(x_train))
print('x_test data:', len(x_test))
x_train data: 50000 x_test data: 10000
print('x_train shape:', x_train.shape)
print('y_train shape:', y_train.shape)
print('x_test shape:', x_test.shape)
print('y_test shape:', y_test.shape)
x_train shape: (50000, 32, 32, 3) y_train shape: (50000, 1) x_test shape: (10000, 32, 32, 3) y_test shape: (10000, 1)
x_test[0]
array([[[158, 112, 49], [159, 111, 47], [165, 116, 51], ..., [137, 95, 36], [126, 91, 36], [116, 85, 33]], [[152, 112, 51], [151, 110, 40], [159, 114, 45], ..., [136, 95, 31], [125, 91, 32], [119, 88, 34]], [[151, 110, 47], [151, 109, 33], [158, 111, 36], ..., [139, 98, 34], [130, 95, 34], [120, 89, 33]], ..., [[ 68, 124, 177], [ 42, 100, 148], [ 31, 88, 137], ..., [ 38, 97, 146], [ 13, 64, 108], [ 40, 85, 127]], [[ 61, 116, 168], [ 49, 102, 148], [ 35, 85, 132], ..., [ 26, 82, 130], [ 29, 82, 126], [ 20, 64, 107]], [[ 54, 107, 160], [ 56, 105, 149], [ 45, 89, 132], ..., [ 24, 77, 124], [ 34, 84, 129], [ 21, 67, 110]]], dtype=uint8)
label_dict = {
0: 'airplane',
1: 'automobile',
2: 'bird',
3: 'cat',
4: 'deer',
5: 'dog',
6: 'frog',
7: 'horse',
8: 'ship',
9: 'truck'
}
def plot_images_labels_prediction(images, labels, predictions, idx, num=10):
"""
images: 图像数组
labels: 真实值数组, 其实每个元素的数字代表一种图像类别的名称
predictions: 预测结果数据
idx: 开始显示的数据index
num: 要显示的数据项数, 默认为10, 不超过25
"""
fig = plt.gcf()
fig.set_size_inches(12, 14)
if num > 25:
num = 25
for i in range(0, num):
ax = plt.subplot(5, 5, i+1)
ax.imshow(images[idx], cmap='binary')
title = str(labels[idx][0]) + ',' + label_dict[labels[idx][0]]
if len(predictions) > 0:
title += '=>' + label_dict[predictions[idx]]
ax.set_title(title, fontsize=10)
ax.set_xticks([])
ax.set_yticks([])
idx += 1
plt.show()
plot_images_labels_prediction(x_train, y_train, [], 0, 10)
plot_images_labels_prediction(x_test, y_test, [], 0, 10)
x_train[0][0][0]
array([59, 62, 63], dtype=uint8)
x_train_normalize = x_train / 255.0
x_test_normalize = x_test / 255.0
x_train_normalize[0][0][0]
array([0.23137255, 0.24313725, 0.24705882])
y_train.shape
(50000, 1)
y_train[:5]
array([[6], [9], [9], [4], [1]], dtype=uint8)
y_train_one_hot = tf.keras.utils.to_categorical(y_train)
y_test_one_hot = tf.keras.utils.to_categorical(y_test)
y_train_one_hot[:5]
array([[0., 0., 0., 0., 0., 0., 1., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.], [0., 1., 0., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32)