首页 文章

使用PyTorch实现自定义数据集

提问于
浏览
1

我正在尝试修改从https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/01-basics/feedforward_neural_network/main.py获取的此前馈网络以使用我自己的数据集 .

我将两个1 dim数组的自定义数据集定义为输入,将两个标量定义为相应的输出:

x = torch.tensor([[5.5, 3,3,4] , [1 , 2,3,4], [9 , 2,3,4]])
print(x)

y = torch.tensor([1,2,3])
print(y)

import torch.utils.data as data_utils

my_train = data_utils.TensorDataset(x, y)
my_train_loader = data_utils.DataLoader(my_train, batch_size=50, shuffle=True)

我已经更新了超参数以匹配新的input_size(2)和num_classes(3) .

我也将 images = images.reshape(-1, 28*28).to(device) 更改为 images = images.reshape(-1, 4).to(device)

由于训练集很小,我已将batch_size更改为1 .

在进行这些修改时,我在尝试训练时收到错误:

()中的RuntimeError Traceback(最近一次调用)51 52#Forward pass ---> 53 outputs = model(images)54 loss = criterion(outputs,labels)55 /home/.local/lib/python3.6/调用中的site-packages / torch / nn / modules / module.py(self,* input,** kwargs)489 result = self._slow_forward(* input,** kwargs)490 else: - > 491 result = self . forward(* input,** kwargs)492 for hook in self._forward_hooks.values():493 hook_result = hook(self,input,result)in forward(self,x)31 32 def forward(self,x): - - > 33 out = self.fc1(x)34 out = self.relu(out)35 out = self.fc2(out)/home/.local/lib/python3.6/site-packages/torch/nn/ modules / module.py in call(self,* input,** kwargs)489 result = self._slow_forward(* input,** kwargs)490 else: - > 491 result = self.forward(* input,** kwargs )492 for hook in self._forward_hooks.values():493 hook_result = hook(self,input,result)/home/.local/lib/python3.6/site-packages/torch/nn/modules/linear.py in向前(自我,输入)53 54向前(自我,输入):---> 55 ret urn F.linear(input,self.weight,self.bias)56 57 def extra_repr(self):/ home /.local/lib/python3.6/site-packages/torch/nn/functional.py in linear(输入,权重,偏差)990如果input.dim()== 2且偏差不是无:991#fused op略快 - > 992 return torch.addmm(bias,input,weight.t())993 994输出= input.matmul(weight.t())运行时错误:大小不匹配,m1:[3 x 4],m2:[2 x 3] at /pytorch/aten/src/THC/generic/THCTensorMathBlas.cu:249

如何修改代码以匹配预期的维度?我不确定要更改的代码,因为我已经更改了所有需要更新的参数?

更改前的来源:

import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms


# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Hyper-parameters 
input_size = 784
hidden_size = 500
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001

# MNIST dataset 
train_dataset = torchvision.datasets.MNIST(root='../../data', 
                                           train=True, 
                                           transform=transforms.ToTensor(),  
                                           download=True)

test_dataset = torchvision.datasets.MNIST(root='../../data', 
                                          train=False, 
                                          transform=transforms.ToTensor())

# Data loader
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, 
                                           batch_size=batch_size, 
                                           shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset=test_dataset, 
                                          batch_size=batch_size, 
                                          shuffle=False)

# Fully connected neural network with one hidden layer
class NeuralNet(nn.Module):
    def __init__(self, input_size, hidden_size, num_classes):
        super(NeuralNet, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden_size) 
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_size, num_classes)  

    def forward(self, x):
        out = self.fc1(x)
        out = self.relu(out)
        out = self.fc2(out)
        return out

model = NeuralNet(input_size, hidden_size, num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)  

# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):  
        # Move tensors to the configured device
        images = images.reshape(-1, 28*28).to(device)
        labels = labels.to(device)

        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)

        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i+1) % 100 == 0:
            print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' 
                   .format(epoch+1, num_epochs, i+1, total_step, loss.item()))

# Test the model
# In test phase, we don't need to compute gradients (for memory efficiency)
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.reshape(-1, 28*28).to(device)
        labels = labels.to(device)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Accuracy of the network on the 10000 test images: {} %'.format(100 * correct / total))

# Save the model checkpoint
torch.save(model.state_dict(), 'model.ckpt')

来源帖子更改:

x = torch.tensor([[5.5, 3,3,4] , [1 , 2,3,4], [9 , 2,3,4]])
print(x)

y = torch.tensor([1,2,3])
print(y)

import torch.utils.data as data_utils

my_train = data_utils.TensorDataset(x, y)
my_train_loader = data_utils.DataLoader(my_train, batch_size=50, shuffle=True)

print(my_train)

print(my_train_loader)

import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms


# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Hyper-parameters 
input_size = 2
hidden_size = 3
num_classes = 3
num_epochs = 5
batch_size = 1
learning_rate = 0.001

# MNIST dataset 
train_dataset = my_train

# Data loader
train_loader = my_train_loader

# Fully connected neural network with one hidden layer
class NeuralNet(nn.Module):
    def __init__(self, input_size, hidden_size, num_classes):
        super(NeuralNet, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden_size) 
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_size, num_classes)  

    def forward(self, x):
        out = self.fc1(x)
        out = self.relu(out)
        out = self.fc2(out)
        return out

model = NeuralNet(input_size, hidden_size, num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)  

# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):  
        # Move tensors to the configured device
        images = images.reshape(-1, 4).to(device)
        labels = labels.to(device)

        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)

        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i+1) % 100 == 0:
            print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' 
                   .format(epoch+1, num_epochs, i+1, total_step, loss.item()))

# Test the model
# In test phase, we don't need to compute gradients (for memory efficiency)
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.reshape(-1, 4).to(device)
        labels = labels.to(device)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Accuracy of the network on the 10000 test images: {} %'.format(100 * correct / total))

# Save the model checkpoint
torch.save(model.state_dict(), 'model.ckpt')

1 回答

  • 2

    您需要将 input_size 更改为4(2 * 2),而不是更改代码当前显示的2 .
    如果将它与原始MNIST示例进行比较,您会看到 input_size 设置为784(28 * 28)而不仅仅是28 .

相关问题