- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我收到错误,
Input type (torch.cuda.ByteTensor) and weight type (torch.cuda.FloatTensor) should be the same
以下是我的代码,
device = torch.device('cuda:0')
trainData = torchvision.datasets.FashionMNIST('/content/', train=True, transform=None, target_transform=None, download=True)
testData = torchvision.datasets.FashionMNIST('/content/', train=False, transform=None, target_transform=None, download=True)
class Net(nn.Module):
def __init__(self):
super().__init__()
'''
Network Structure:
input >
(1)Conv2D > (2)MaxPool2D >
(3)Conv2D > (4)MaxPool2D >
(5)Conv2D > (6)MaxPool2D >
(7)Linear > (8)LinearOut
'''
# Creating the convulutional Layers
self.conv1 = nn.Conv2d(in_channels=CHANNELS, out_channels=32, kernel_size=3)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3)
self.conv3 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3)
self.flatten = None
# Creating a Random dummy sample to get the Flattened Dimensions
x = torch.randn(CHANNELS, DIM, DIM).view(-1, CHANNELS, DIM, DIM)
x = self.convs(x)
# Creating the Linear Layers
self.fc1 = nn.Linear(self.flatten, 512)
self.fc2 = nn.Linear(512, CLASSES)
def convs(self, x):
# Creating the MaxPooling Layers
x = F.max_pool2d(F.relu(self.conv1(x)), kernel_size=(2, 2))
x = F.max_pool2d(F.relu(self.conv2(x)), kernel_size=(2, 2))
x = F.max_pool2d(F.relu(self.conv3(x)), kernel_size=(2, 2))
if not self.flatten:
self.flatten = x[0].shape[0] * x[0].shape[1] * x[0].shape[2]
return x
# FORWARD PASS
def forward(self, x):
x = self.convs(x)
x = x.view(-1, self.flatten)
sm = F.relu(self.fc1(x))
x = F.softmax(self.fc2(sm), dim=1)
return x, sm
x_train, y_train = training_set
x_train, y_train = x_train.to(device), y_train.to(device)
optimizer = optim.Adam(net.parameters(), lr=LEARNING_RATE)
loss_func = nn.MSELoss()
loss_log = []
for epoch in range(EPOCHS):
for i in tqdm(range(0, len(x_train), BATCH_SIZE)):
x_batch = x_train[i:i+BATCH_SIZE].view(-1, CHANNELS, DIM, DIM).to(device)
y_batch = y_train[i:i+BATCH_SIZE].to(device)
net.zero_grad()
output, sm = net(x_batch)
loss = loss_func(output, y_batch.float())
loss.backward()
optimizer.step()
loss_log.append(loss)
# print(f"Epoch : {epoch} || Loss : {loss}")
return loss_log
train_set = (trainData.train_data, trainData.train_labels)
test_set = (testData.test_data, testData.test_labels)
EPOCHS = 5
LEARNING_RATE = 0.001
BATCH_SIZE = 32
net = Net().to(device)
loss_log = train(net, train_set, EPOCHS, LEARNING_RATE, BATCH_SIZE)
这是我遇到的错误,
RuntimeError Traceback (most recent call last)
<ipython-input-8-0db1a1b4e37d> in <module>()
5 net = Net().to(device)
6
----> 7 loss_log = train(net, train_set, EPOCHS, LEARNING_RATE, BATCH_SIZE)
6 frames
<ipython-input-6-7de4a78e3736> in train(net, training_set, EPOCHS, LEARNING_RATE, BATCH_SIZE)
13
14 net.zero_grad()
---> 15 output, sm = net(x_batch)
16 loss = loss_func(output, y_batch.float())
17 loss.backward()
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
539 result = self._slow_forward(*input, **kwargs)
540 else:
--> 541 result = self.forward(*input, **kwargs)
542 for hook in self._forward_hooks.values():
543 hook_result = hook(self, input, result)
<ipython-input-5-4fddc427892a> in forward(self, x)
41 # FORWARD PASS
42 def forward(self, x):
---> 43 x = self.convs(x)
44 x = x.view(-1, self.flatten)
45 sm = F.relu(self.fc1(x))
<ipython-input-5-4fddc427892a> in convs(self, x)
31
32 # Creating the MaxPooling Layers
---> 33 x = F.max_pool2d(F.relu(self.conv1(x)), kernel_size=(2, 2))
34 x = F.max_pool2d(F.relu(self.conv2(x)), kernel_size=(2, 2))
35 x = F.max_pool2d(F.relu(self.conv3(x)), kernel_size=(2, 2))
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
539 result = self._slow_forward(*input, **kwargs)
540 else:
--> 541 result = self.forward(*input, **kwargs)
542 for hook in self._forward_hooks.values():
543 hook_result = hook(self, input, result)
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/conv.py in forward(self, input)
343
344 def forward(self, input):
--> 345 return self.conv2d_forward(input, self.weight)
346
347 class Conv3d(_ConvNd):
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/conv.py in conv2d_forward(self, input, weight)
340 _pair(0), self.dilation, self.groups)
341 return F.conv2d(input, weight, self.bias, self.stride,
--> 342 self.padding, self.dilation, self.groups)
343
344 def forward(self, input):
RuntimeError: Input type (torch.cuda.ByteTensor) and weight type (torch.cuda.FloatTensor) should be the same
我仔细检查了我的神经网络和输入都在 GPU 中。我仍然收到此错误,但我不明白为什么!
有人请帮我摆脱这个错误。
最佳答案
将您的输入x_batch
转换为 float 。在将其传递到模型之前使用 x_batch = x_batch.float()
。
关于python - CNN Pytorch错误: Input type (torch. cuda.ByteTensor)和权重类型(torch.cuda.FloatTensor)应该相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59582663/
这个: device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) for data
首先,我使用类似“model.cuda()”的方法将模型和数据转换为 cuda。但是它仍然存在这样的问题。我调试模型的每一层,每个模块的权重都有 iscuda=True。那么有谁知道为什么会出现这样的
虽然此示例没有经过训练,但这是一个较大程序的改编部分,其中确实进行了训练。在这种情况下,我只是希望生成器网络生成随机图像: import torch from torch.autograd impor
我有 2 个 numpy 数组,我将它们转换为张量以使用 TensorDataset 对象。 import torch.utils.data as data_utils X = np.zeros((1
我正在尝试在运行 MacOS 12.4 的 Apple M1(第一代)上运行这个 notebook, 库卡住: >pip3 freeze anyio @ file:///private/tmp/jup
从我在网上看到的所有内容来看,FloatTensors 是 Pytorch 的默认值,当我创建一个张量传递给我的生成器模块时,它是一个 FloatTensor,但是当我尝试通过一个线性层运行它,它提示
我正在执行类似 MNIST 的任务,输入是 10 类图像,预期输出是图像的预测类。 但现在 output 类似于 [-2.3274, -2.2723, ...],其长度为 batch_size。而 t
我尝试像这样比较位于 GPU 上的两个 torch.FloatTensor(只有一个条目): if (FloatTensor_A > FloatTensor_B): do something 问题是,
我无法将 int64 分配给 torch 张量。我有以下张量 tempScale = torch.zeros((total, len(scale))).cuda() if useGpu else to
我想用 python 生成一些随机数,并用 pytorch 将其转换为张量。这是我生成随机数并将其转换为张量的代码。 import numpy as np import torch P = np.ra
我有一批来自 GRU 的输出隐藏向量。它的形状是[1,4,256] ( 0 ,.,.) = -0.9944 1.0000 0.0000 ... -1.0000 0.0000 -1.0000
我正在运行来自 the documentation 的这个极其简单的 PyTorch 示例 NN原样,没有任何改变。 我收到这个错误: Traceback (most recent call last
我的输入张量是 torch.DoubleTensor 类型。但我得到了下面的 RuntimeError: RuntimeError: Expected object of type torch.Dou
我收到错误, Input type (torch.cuda.ByteTensor) and weight type (torch.cuda.FloatTensor) should be the sam
Pytorch 0.4.0 引入了 Tensor 和 Variable 类的合并。 在此版本之前,当我想从一个 numpy 数组创建一个带有 autograd 的 Variable 时,我会执行以下操
我一直在尝试重新训练模型,但不幸的是,最近 2 天我不断遇到同样的错误。 你能帮忙解决一下这个问题吗? 初步工作: %matplotlib inline %config InlineBackend.f
为什么会出现这个错误。 我正在尝试编写一个自定义损失函数,它最终具有负对数似然。 根据我的理解,NLL 是在两个概率值之间计算的? >>> loss = F.nll_loss(sigm, trg_,
我在运行机器翻译代码时遇到了这个错误。 RuntimeError Traceback (most recent call last) in 5 decoder = Decoder(len(out_vo
我是一名优秀的程序员,十分优秀!