Matplotlib 기억하기 구체적인 예

6169 단어 파이썬matplotlib

이미지를 타일 형식으로 플롯



cifar-10, 무작위로 선택한 100장, 제목 포함



코드
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()

print('# Image shapes')
print(x_train.shape, y_train.shape)
print(x_test.shape, y_test.shape)

CLASSES = np.array([
    'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog',
    'frog', 'horse', 'ship', 'truck'
])

# 100個のアイテムをランダムに選びだす
idxs = np.random.randint(low=0, high=x_train.shape[0], size=100)
imgs, labels = x_train[idxs], y_train[idxs]

# ラベル(0~9整数)をクラス名に変更
labels = [CLASSES[x] for x in labels.flatten()]

# 10x10のタイルにする
fig, axs = plt.subplots(nrows=10, ncols=10, figsize=(12, 12))
# .flatで一次元アクセスできるイテレータができる
for ax, img, label in zip(axs.flat, imgs, labels):
    ax.imshow(img)
    ax.set_title(label)
    ax.set_axis_off()

# tight_layoutしないとタイトルと画像が被る
plt.tight_layout()
plt.savefig('image.png')
plt.show()

출력
# Image shapes
(50000, 32, 32, 3) (50000, 1)
(10000, 32, 32, 3) (10000, 1)

좋은 웹페이지 즐겨찾기