Einführung in Deep Learning mit PyTorch
Jasmin Ludolf
Senior Data Science Content Developer, DataCamp
import pandas as pd
animals = pd.read_csv('animal_dataset.csv')
tier_name | Haare | Federn | Eier | Milch | Raubtier | Beine | Schwanz | Art |
---|---|---|---|---|---|---|---|---|
Sperling | 0 | 1 | 1 | 0 | 0 | 2 | 1 | 0 |
Adler | 0 | 1 | 1 | 0 | 1 | 2 | 1 | 0 |
Katze | 1 | 0 | 0 | 1 | 1 | 4 | 1 | 1 |
Hund | 1 | 0 | 0 | 1 | 0 | 4 | 1 | 1 |
Eidechse | 0 | 0 | 1 | 0 | 1 | 4 | 1 | 2 |
Artenkategorien: Vogel (0), Säugetier (1), Reptil (2)
import numpy as np # Define input features 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]]
# Define target values (ground truth)
target = animals.iloc[:, -1]
y = target.to_numpy()
print(y)
[0 0 1 1 2]
import torch from torch.utils.data import TensorDataset
# Instantiate dataset class dataset = TensorDataset(torch.tensor(X), torch.tensor(y))
# Access an individual sample 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)
from torch.utils.data import DataLoader
batch_size = 2
shuffle = True
# Create a DataLoader dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle)
$$
# Iterate over the 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])
Einführung in Deep Learning mit PyTorch