TensorFlow (Google) framework học máy mã nguồn mở, tối ưu NumPy/tensor, scalable, GPU, nhiều dataset, tài liệu tốt.
Cài đặt: pip install tensorflow
Tensor: mảng đa chiều với Rank, Type, Shape.
IMDB dataset: >50.000 review phim, dùng cho NLP.
Chạy trên Google Colab (Python trên trình duyệt, GPU miễn phí).
Ví dụ
import matplotlib.pyplot as plt
import os, re, shutil, string
import tensorflow as tf
from tensorflow.keras import layers, losses, preprocessing
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
print("Phiên bản TensorFlow:", tf.__version__)
url = "https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz"
dataset = tf.keras.utils.get_file("aclImdb_v1.tar.gz", url, untar=True, cache_dir='.', cache_subdir='')
print("Đang tải dataset...")
dataset_dir = os.path.join(os.path.dirname(dataset), 'aclImdb')
print("Thư mục trong dataset:", os.listdir(dataset_dir))
train_dir = os.path.join(dataset_dir, 'train')
print("Train dir:", os.listdir(train_dir))
print("Mẫu dữ liệu:")
sample_file = os.path.join(train_dir, 'pos/1181_9.txt')
with open(sample_file) as f:
print(f.read())
remove_dir = os.path.join(train_dir, 'unsup')
shutil.rmtree(remove_dir)
batch_size = 32
seed = 42
print("Batch size:", batch_size)
raw_train_ds = tf.keras.preprocessing.text_dataset_from_directory(
'aclImdb/train', batch_size=batch_size, validation_split=0.2, subset='training', seed=seed)
for text_batch, label_batch in raw_train_ds.take(1):
for i in range(3):
print("Review:", text_batch.numpy()[i])
print("Label:", label_batch.numpy()[i])
print("Label 0 →", raw_train_ds.class_names[0])
print("Label 1 →", raw_train_ds.class_names[1])
raw_val_ds = tf.keras.preprocessing.text_dataset_from_directory(
'aclImdb/train', batch_size=batch_size, validation_split=0.2, subset='validation', seed=seed)
raw_test_ds = tf.keras.preprocessing.text_dataset_from_directory(
'aclImdb/test', batch_size=batch_size)
Nguồn mã: TensorFlow Text Classification
Đầu ra
Phiên bản TensorFlow: 2.4.0 Đang tải dataset... Thư mục trong dataset: ... Mẫu dữ liệu: Rachel Griffiths writes and directs this award winning short film... Batch size: 32 Found 25000 files belonging to 2 classes. Using 20000 files for training. Review b'"Pandemonium" is a horror movie spoof...' Label 0 Review b"David Mamet is a very interesting..." Label 0 Review b'Great documentary about the lives of NY firefighters...' Label 1 Label 0 corresponds to neg Label 1 corresponds to pos Found 25000 files belonging to 2 classes. Using 5000 files for validation. Found 25000 files belonging to 2 classes.
Giải thích
- Import package và alias.
- Tải IMDB data từ Stanford, lưu để Colab truy cập.
- Hiển thị mẫu review gốc.
- Chia train/validation/test; loại bỏ thư mục unsup.
- Phân loại binary: negative (0) hoặc positive (1).