类型转换

时间:2018-12-20 16:42:07

标签: python numpy scikit-learn pytorch

我对pytorch还是很陌生,所以我不确定这是错误还是仅仅是错误。

我正在尝试在sklearn的make_classification数据集上构建一个简单的LogisticRegression模块,但是由于某种原因,我一直在获取它。

  

RuntimeError:标量类型为Double的预期对象,但参数#2'mat2'的标量类型为Float

我试图将X和y变量都转换为double,但由于某种原因,它似乎仍然认为它是浮动的。

这是我的代码:

X, y = make_classification(n_samples=60000,n_features=10, n_redundant=0, n_informative=2)

X_train,y_train, X_test, y_test = train_test_split(X, y, stratify=y, random_state=42)

X_train = Variable(torch.from_numpy(X_train)).double()
y_train = Variable(torch.from_numpy(y_train)).double()
X_test = Variable(torch.from_numpy(X_test)).double()
y_test = Variable(torch.from_numpy(y_test)).double()

这是网络

input_dim = 40000
output_dim = 2
criterion = nn.CrossEntropyLoss()
learning_rate = 0.001
batch_size = 100
n_iters = 3000
num_epochs = int(n_iters / (len(X_train) / batch_size))

model = SingleLayeredNetwork(input_dim, output_dim)
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

class SingleLayeredNetwork(nn.Module):
    def __init__(self, input_dimension, output_dimension):
        super(SingleLayeredNetwork, self).__init__()
        self.layer = nn.Linear(input_dimension, output_dimension)

    def forward(self, x):
        out = self.layer(x)
        return out

这是训练循环

iter = 0
for epoch in range(num_epochs):
for train, test in zip(X_train, y_train):
    train = train.double()
    print(train)
    print(train.dtype)
    print(torch.typename(train))
    optimizer.zero_grad()

    outputs = model(train)
    loss = criterion(outputs, test)

    loss.backward()

    # Updating parameters
    optimizer.step()

    iter += 1

    if iter % 500 == 0:
        # Calculate Accuracy         
        correct = 0
        total = 0
        # Iterate through test dataset
        for tra, tes in zip(X_test, y_test):
            # Load images to a Torch Variable
            tra = tra

            # Forward pass only to get logits/output
            outputs = model(tra)

            # Get predictions from the maximum value
            # 100 x 1
            _, predicted = torch.max(train, 1)

            # Total number of labels
            total += labels.size(0)

            # Total correct predictions
            correct += (predicted == test).sum()

        accuracy = 100 * correct.item() / total

        # Print Loss
        print('Iteration: {}. Loss: {}. Accuracy: {}'.format(iter, loss.item(), accuracy))

这是我不断收到的错误


  

RuntimeError跟踪(最近的调用)   最后)        10 Optimizer.zero_grad()        11   -> 12个输出=模型(火车)        13损耗=标准(输出,测试)        14

     

〜/ miniconda3 / envs / mlbook / lib / python3.6 / site-packages / torch / nn / modules / module.py   在通话中((自己,*输入,** kwargs)       487 result = self._slow_forward(* input,** kwargs)       488其他:   -> 489结果= self.forward(* input,** kwargs)       490 for self._forward_hooks.values()的钩子:       491 hook_result = hook(自己,输入,结果)

     

向前(自己,x)         5         6 def前进(自己,x):   ----> 7出= self.layer(x)         8退出

     

〜/ miniconda3 / envs / mlbook / lib / python3.6 / site-packages / torch / nn / modules / module.py   在通话中((自己,*输入,** kwargs)       487 result = self._slow_forward(* input,** kwargs)       488其他:   -> 489结果= self.forward(* input,** kwargs)       490 for self._forward_hooks.values()的钩子:       491 hook_result = hook(自己,输入,结果)

     

〜/ miniconda3 / envs / mlbook / lib / python3.6 / site-packages / torch / nn / modules / linear.py   向前(自己,输入)        65 @weak_script_method        66 def forward(自己,输入):   ---> 67 return F.linear(输入,self.weight,self.bias)        68        69 def extra_repr(self):

     

〜/ miniconda3 / envs / mlbook / lib / python3.6 / site-packages / torch / nn / functional.py   线性(输入,重量,偏置)1352 ret =   torch.addmm(torch.jit._unwrap_optional(bias),input,weight.t())
  1353其他:   -> 1354输出= input.matmul(weight.t())1355如果没有偏置,则无:1356输出+ =   torch.jit._unwrap_optional(bias)

     

RuntimeError:标量类型为Double的预期对象,但得到了标量   为参数#2'mat2'输入Float

我想念什么?

0 个答案:

没有答案