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

Cách tạo cặp (ảnh, nhãn) từ đường dẫn file với TensorFlow cho tập flower

Để tạo cặp (image, label) từ đường dẫn file:

  1. Chuyển đường dẫn thành danh sách thành phần (path components).
  2. Lấy thành phần倒数 thứ 2 (thư mục lớp) làm nhãn.
  3. Mã hóa nhãn thành số nguyên (integer encoding).
  4. Chuỗi nén (compressed string) chuyển thành tensor 3D int, resize về kích thước yêu cầu.

Mã ví dụ

print("Hàm chuyển file path -> (image,label) pair")
print("1. Path -> list path components")
print("2. Phần tử倒数 2 -> class directory")
print("3. Label integer encoded")
def get_label(file_path):
    parts = tf.strings.split(file_path, os.path.sep)
    one_hot = parts[-2] == class_names
    return tf.argmax(one_hot)

print("Chuỗi nén -> tensor 3D int")
print("Resize ảnh về kích thước yêu cầu")
def decode_img(img):
    img = tf.image.decode_jpeg(img, channels=3)
    return tf.image.resize(img, [img_height, img_width])

print("Load dữ liệu thô từ file dưới dạng string")
def process_path(file_path):
    label = get_label(file_path)
    img = tf.io.read_file(file_path)
    img = decode_img(img)
    return img, label

Nguồn mã: TensorFlow Images Tutorial

Đầu ra

Hàm chuyển file path -> (image,label) pair
1. Path -> list path components
2. Phần tử倒数 2 -> class directory
3. Label integer encoded
Chuỗi nén -> tensor 3D int
Resize ảnh về kích thước yêu cầu
Load dữ liệu thô từ file dưới dạng string

Giải thích

  • Hàm get_label: file path → (image,label) pair.
  • Path → list components bằng tf.strings.split.
  • Thành phần倒数 2 là tên thư mục lớp.
  • Label encode integer bằng tf.argmax trên one-hot.
  • Hàm decode_img: decode_jpeg → resize.
  • Hàm process_path: read_file (string) → decode → resize → return (img, label).