Untitled
user_5426888
plain_text
a year ago
4.0 kB
11
Indexable
Để sử dụng tập dữ liệu F-MNIST trong Python, bạn có thể dùng thư viện `TensorFlow` hoặc `PyTorch`. Dưới đây là hướng dẫn cơ bản cho cả hai thư viện:
### Sử dụng với TensorFlow
1. **Cài đặt TensorFlow** (nếu chưa cài):
```bash
pip install tensorflow
```
2. **Tải và sử dụng F-MNIST trong TensorFlow**:
```python
import tensorflow as tf
# Tải dữ liệu F-MNIST
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.fashion_mnist.load_data()
# Chuẩn hóa dữ liệu (giá trị pixel từ 0-255 sang 0-1)
train_images = train_images / 255.0
test_images = test_images / 255.0
# Xây dựng mô hình cơ bản
model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)), # Chuyển từ 2D thành 1D
tf.keras.layers.Dense(128, activation='relu'), # Lớp ẩn với 128 nút
tf.keras.layers.Dense(10, activation='softmax') # Lớp đầu ra với 10 lớp (10 loại sản phẩm)
])
# Compile mô hình
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Huấn luyện mô hình
model.fit(train_images, train_labels, epochs=5)
# Đánh giá mô hình
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f'Độ chính xác của mô hình trên tập test: {test_acc}')
```
### Sử dụng với PyTorch
1. **Cài đặt PyTorch** (nếu chưa cài):
```bash
pip install torch torchvision
```
2. **Tải và sử dụng F-MNIST trong PyTorch**:
```python
import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
# Chuyển đổi dữ liệu (chuẩn hóa)
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
# Tải dữ liệu
trainset = datasets.FashionMNIST(root='./data', train=True, download=True, transform=transform)
testset = datasets.FashionMNIST(root='./data', train=False, download=True, transform=transform)
# Tạo DataLoader
trainloader = DataLoader(trainset, batch_size=64, shuffle=True)
testloader = DataLoader(testset, batch_size=64, shuffle=False)
# Xây dựng mô hình đơn giản
from torch import nn, optim
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.fc1 = nn.Linear(28*28, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.Linear(64, 10)
def forward(self, x):
x = x.view(x.shape[0], -1) # Chuyển đổi từ 2D thành 1D
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = torch.log_softmax(self.fc3(x), dim=1)
return x
model = Model()
# Khởi tạo hàm mất mát và bộ tối ưu
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.parameters(), lr=0.003)
# Huấn luyện mô hình
epochs = 5
for epoch in range(epochs):
running_loss = 0
for images, labels in trainloader:
optimizer.zero_grad()
output = model(images)
loss = criterion(output, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Loss tại epoch {epoch+1}: {running_loss/len(trainloader)}")
# Đánh giá mô hình
correct = 0
total = 0
with torch.no_grad():
for images, labels in testloader:
output = model(images)
_, predicted = torch.max(output.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f'Độ chính xác của mô hình trên tập test: {100 * correct / total:.2f}%')
```
Cả hai ví dụ trên đều minh họa cách tải và huấn luyện mô hình cơ bản với tập dữ liệu Fashion MNIST, sử dụng `TensorFlow` và `PyTorch`.Editor is loading...
Leave a Comment