Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีใช้ TensorFlow Iterate ผ่าน Dataset และแสดงตัวอย่างข้อมูล StackOverflow ใน Python

บทนำ

TensorFlow ใช้ text_dataset_from_directory โหลดข้อมูลข้อความจากโฟลเดอร์ สร้าง Label อัตโนมัติจากชื่อโฟลเดอร์ย่อย

การติดตั้ง

pip install tensorflow

ตัวอย่างโค้ด

batch_size = 32
seed = 42

raw_train_ds = preprocessing.text_dataset_from_directory(
    train_dir,
    batch_size=batch_size,
    validation_split=0.25,
    subset='training',
    seed=seed
)

for text_batch, label_batch in raw_train_ds.take(1):
    for i in range(10):
        print("Question:", text_batch.numpy()[i][:100], '...')
        print("Label:", label_batch.numpy()[i])

# Validation & Test dataset
raw_val_ds = preprocessing.text_dataset_from_directory(
    train_dir, batch_size=batch_size, validation_split=0.25, subset='validation', seed=seed
)
test_dir = dataset_dir / 'test'
raw_test_ds = preprocessing.text_dataset_from_directory(test_dir, batch_size=batch_size)

ผลลัพธ์

Iterating through the training data
Label 0 maps to csharp
Label 1 maps to java
Label 2 maps to javascript
Label 3 maps to python
Found 8000 files belonging to 4 classes. Using 6000 files for training.
Found 8000 files belonging to 4 classes. Using 2000 files for validation.
The test dataset is being prepared
Found 8000 files belonging to 4 classes.

คำอธิบาย

  • โหลด Training/Validation/Test split อัตโนมัติ

  • Label: 0=csharp, 1=java, 2=javascript, 3=python

  • ใช้ take(1) ดึง batch แรกเพื่อตรวจสอบ