【发布时间】:2018-02-27 08:29:45
【问题描述】:
我是 Pytorch 的新手,我试图编写我的培训课程,但我遇到了这个错误
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import torch.optim as optim
import tqdm
class MLPNet(nn.Module):
def __init__(self):
super(MLPNet, self).__init__()
self.first_fully_connected = nn.Linear(8*8, 100)
self.last_fully_connected = nn.Linear(100, 10)
def forward(self, x):
x = x.view(-1, 8*8) # reshape input tensor to the size (batch_size, 8*8)
x = F.sigmoid(self.first_fully_connected(x))
x = F.sigmoid(self.last_fully_connected(x))
return x
def training(mlp, X, y, epochs=1, lr=.2, batch_size=101):
# solver
# loss
solver = torch.optim.SGD(mlp.parameters(), lr=lr, momentum=0.9)
loss = nn.CrossEntropyLoss() # nn.NLLLoss()
n_batches = (len(X) + batch_size - 1) // batch_size
for epoch in tqdm.tqdm(range(epochs)):
for i in range(n_batches):
slice_ = np.s_[i::n_batches]
X_batch = Variable(torch.from_numpy(X[slice_])).float()
y_batch = Variable(torch.from_numpy(y[slice_, np.newaxis])).float()
# X_batch = Variable(torch.from_numpy(X[slice_])).long()
# y_batch = Variable(torch.from_numpy(y[slice_, np.newaxis])).long()
print(type(X_batch.data))
print(type(y_batch.data))
### BEGIN: your optim step here. do not forget to reset gradients
# Clear gradients w.r.t. parameters
solver.zero_grad()
prediction = mlp(X_batch)
# Forward pass to get output/logits
#outputs = mlp(X_batch)
# Calculate Loss: softmax --> cross entropy loss
#loss = criterion(outputs, y_batch)
loss_f = loss(prediction, y_batch)
# Getting gradients w.r.t. parameters
loss_f.backward()
# Updating parameters
solver.step()
### END
return mlp
mlp = nn.Sequential(
#### Your net here
nn.Linear(2, 64),
nn.ReLU(),
nn.Linear(64, 2)
)
model_mlp = training(mlp, X_std, y_std)
但我得到了这个错误, 我尝试更改类型,但仍然遇到该错误。 我也尝试了更改损失函数,但仍然出现错误。
RuntimeError Traceback(最近一次调用最后一次) 在 () ----> 1 model_mlp = fit(mlp, X_std, y_std)
RuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.LongTensor] for argument #1 'mat1'
非常感谢您提供的任何帮助。 非常感谢
【问题讨论】:
标签: python neural-network deep-learning pytorch