Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Trực quan hóa dữ liệu TensorFlow với matplotlib Python

Hiển thị batch hình ảnh từ dataset TensorFlow bằng matplotlib.

Mã ví dụ

print("Trực quan hóa dataset...")
import matplotlib.pyplot as plt

plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
    for i in range(6):
        ax = plt.subplot(3, 3, i + 1)
        plt.imshow(images[i].numpy().astype("uint8"))
        plt.title(class_names[labels[i]])
        plt.axis("off")

for image_batch, labels_batch in train_ds:
    print("Image batch shape:", image_batch.shape)
    print("Labels batch shape:", labels_batch.shape)
    break

Kết quả

Trực quan hóa dataset
(32, 180, 180, 3)
(32,)

Trực quan hóa dữ liệu TensorFlow với matplotlib Python

Giải thích

  • train_ds.take(1): Lấy 1 batch đầu tiên.
  • images[i].numpy().astype("uint8"): Chuyển tensor → numpy array uint8 để imshow hiển thị đúng màu.
  • class_names[labels[i]]: Lấy tên class từ index label.
  • image_batch.shape = (32, 180, 180, 3): Batch 32 ảnh, size 180x180, 3 kênh RGB.
  • labels_batch.shape = (32,): 32 nhãn integer.