Conv2d不接受张量作为输入,说它不是张量

时间:2019-05-31 07:10:11

标签: conv-neural-network typeerror pytorch

我想让张量通过卷积2层。即使将numpy数组转换为张量,我也遇到类型错误,因此我无法执行它。

我尝试使用tf.convert_to_tensor()解决此问题。没用

import numpy as np
import tensorflow as tf

class Generator():

  def __init__(self):

    self.conv1 = nn.Conv2d(1, 28, kernel_size=3, stride=1, padding=1)
    self.pool1 = nn.MaxPool2d(kernel_size=3, stride=0, padding=1)

    self.fc1 = nn.Linear(100, 10)
    self.fc2 = nn.Linear(10, 5)

  def forward_pass(self, x):                                                                       #Why do we pass the object itself in every method?

    x = self.conv1(x)
    print(x)
    x = self.pool1(x)
    print(x)

    x = self.fc1(x)
    print(x)
    x = self.fc2(x)
    print(x)

    return x

arr = tf.convert_to_tensor(np.random.random((3,28,28)))

gen = Generator()
gen.forward_pass(arr)


错误消息-

TypeError                                 Traceback (most recent call last)

<ipython-input-31-9fa8e764dcdb> in <module>()
      1 gen = Generator()
----> 2 gen.forward_pass(arr)

2 frames

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/conv.py in forward(self, input)
    336                             _pair(0), self.dilation, self.groups)
    337         return F.conv2d(input, self.weight, self.bias, self.stride,
--> 338                         self.padding, self.dilation, self.groups)
    339 
    340 

TypeError: conv2d(): argument 'input' (position 1) must be Tensor, not Tensor

1 个答案:

答案 0 :(得分:0)

您正试图将TensorFlow张量传递给PyTorch函数。 TensorFlow和PyTorch是具有不同数据结构的单独项目,通常不能以这种方式互换使用。

要将NumPy数组转换为PyTorch张量,可以使用:

if decAge > 0.5 :
  age = int(age) + 1
else:
  age = int(age)