Tìm hiểu sâu hơn về nạp dữ liệu

Nhập môn Deep Learning với PyTorch

Jasmin Ludolf

Senior Data Science Content Developer, DataCamp

Bộ dữ liệu động vật của chúng ta

import pandas as pd
animals = pd.read_csv('animal_dataset.csv')
animal_name hair feathers eggs milk predator legs tail type
sparrow 0 1 1 0 0 2 1 0
eagle 0 1 1 0 1 2 1 0
cat 1 0 0 1 1 4 1 1
dog 1 0 0 1 0 4 1 1
lizard 0 0 1 0 1 4 1 2

Loại: bird (0), mammal (1), reptile (2)

Nhập môn Deep Learning với PyTorch

Bộ dữ liệu động vật: xác định đặc trưng

import numpy as np

# Xác định đặc trưng đầu vào
features = animals.iloc[:, 1:-1]


X = features.to_numpy() print(X)
[[0 1 1 0 0 2 1]
 [0 1 1 0 1 2 1]
 [1 0 0 1 1 4 1]
 [1 0 0 1 0 4 1]
 [0 0 1 0 1 4 1]]
Nhập môn Deep Learning với PyTorch

Quay lại bộ dữ liệu: xác định nhãn mục tiêu

# Xác định giá trị mục tiêu (nhãn gốc)
target = animals.iloc[:, -1]
y = target.to_numpy()
print(y)
[0 0 1 1 2]
Nhập môn Deep Learning với PyTorch

TensorDataset

import torch
from torch.utils.data import TensorDataset


# Khởi tạo lớp dataset dataset = TensorDataset(torch.tensor(X), torch.tensor(y))
# Truy cập một mẫu đơn lẻ input_sample, label_sample = dataset[0] print('input sample:', input_sample) print('label sample:', label_sample)
input sample: tensor([0, 1, 1, 0, 0, 2, 1])
label sample: tensor(0)
Nhập môn Deep Learning với PyTorch

DataLoader

from torch.utils.data import DataLoader


batch_size = 2
shuffle = True
# Tạo DataLoader dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle)

$$

  • Epoch: một lượt duyệt đầy đủ qua dataloader huấn luyện
  • Khả năng khái quát hóa: mô hình hoạt động tốt trên dữ liệu chưa thấy
Nhập môn Deep Learning với PyTorch

DataLoader

# Lặp qua dataloader
for batch_inputs, batch_labels in dataloader:
    print('batch_inputs:', batch_inputs)
    print('batch_labels:', batch_labels)
batch_inputs: tensor([[1, 0, 0, 1, 1, 4, 1],
        [1, 0, 0, 1, 0, 4, 1]])
batch_labels: tensor([1, 1])

batch_inputs: tensor([[0, 1, 1, 0, 1, 2, 1], [0, 0, 1, 0, 1, 4, 1]]) batch_labels: tensor([0, 2])
batch_inputs: tensor([[0, 1, 1, 0, 0, 2, 1]]) batch_labels: tensor([0])
Nhập môn Deep Learning với PyTorch

Ayo berlatih!

Nhập môn Deep Learning với PyTorch

Preparing Video For Download...