我正在尝试修改来自https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/01-basics/feedforward_neural_network/main.py的此前馈网络 利用我自己的数据集。
我定义了一个自定义数据集,其中包含两个1个暗淡数组作为输入,两个标量分别对应于输出:
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跟踪(最近的调用) 最后)在() 51 52#前传 ---> 53个输出=模型(图像) 54损失=标准(输出,标签) 55
呼叫中的/home/.local/lib/python3.6/site-packages/torch/nn/modules/module.py(自身,*输入,** kwargs) 489结果= self._slow_forward(* input,** kwargs) 490其他: -> 491结果= self.forward(* input,** kwargs) 492 for self._forward_hooks.values()的钩子: 493 hook_result =钩子(自身,输入,结果)
向前(自己,x) 31 32 def forward(自我,x): -> 33出= self.fc1(x) 34出= self.relu(出) 35 out = self.fc2(out)
呼叫中的/home/.local/lib/python3.6/site-packages/torch/nn/modules/module.py(自身,*输入,** kwargs) 489结果= self._slow_forward(* input,** kwargs) 490其他: -> 491结果= self.forward(* input,** kwargs) 492 for self._forward_hooks.values()的钩子: 493 hook_result =钩子(自身,输入,结果)
/home/.local/lib/python3.6/site-packages/torch/nn/modules/linear.py向前(自己,输入) 53 54 def forward(自己,输入): ---> 55 return F.linear(input,self.weight,self.bias) 56 57 def extra_repr(self):
/home/.local/lib/python3.6/site-packages/torch/nn/functional.py 线性(输入,重量,偏差) 990如果input.dim()== 2并且bias不是None: 991#融合操作速度稍快 -> 992返回torch.addmm(bias,input,weight.t()) 993 994输出= input.matmul(weight.t())
RuntimeError:大小不匹配,m1:[3 x 4],m2:[2 x 3],位于 /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')
答案 0 :(得分:2)
您需要将input_size
更改为4(2 * 2),而不是更改为当前显示的代码2。
如果将其与原始MNIST示例进行比较,您会发现input_size
设置为784(28 * 28),而不仅仅是28。