- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
您好,我正在训练 PyTorch 模型并发生此错误:
----> 5 代表 i,枚举中的数据(trainloader, 0):
类型错误:“torch.Size”对象无法解释为整数
不确定这个错误意味着什么。
您可以在这里找到我的代码:
model.train()
for epoch in range(10):
running_loss = 0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if i % 2000 == 0:
print (loss.item())
running_loss += loss.item()
if i % 1000 == 0:
print ('[%d, %5d] loss: %.3f' % (epoch, i, running_loss/ 1000))
running_loss = 0
torch.save(model, 'FeatureNet.pkl')
<小时/>
这是 DataLoader 的代码块。我正在使用自定义的数据加载器和数据集,其中 x
是大小为 (1025, 16) 的图片,y
是用于分类的 one-hot 编码向量。
x_train.shape
= (1100, 1025, 16)
y_train.shape
= (1100, 10)
clean_dir = '/home/tk/Documents/clean/'
mix_dir = '/home/tk/Documents/mix/'
clean_label_dir = '/home/tk/Documents/clean_labels/'
mix_label_dir = '/home/tk/Documents/mix_labels/'
class MSourceDataSet(Dataset):
def __init__(self, clean_dir, mix_dir, clean_label_dir, mix_label_dir):
with open(clean_dir + 'clean0.json') as f:
clean0 = torch.Tensor(json.load(f))
with open(mix_dir + 'mix0.json') as f:
mix0 = torch.Tensor(json.load(f))
with open(clean_label_dir + 'clean_label0.json') as f:
clean_label0 = torch.Tensor(json.load(f))
with open(mix_label_dir + 'mix_label0.json') as f:
mix_label0 = torch.Tensor(json.load(f))
self.spec = torch.cat([clean0, mix0], 0)
self.label = torch.cat([clean_label0, mix_label0], 0)
def __len__(self):
return self.spec.shape
def __getitem__(self, index):
spec = self.spec[index]
label = self.label[index]
return spec, label
a, b = trainset.__getitem__(1000)
print (a.shape)
print (b.shape)
a.shape = torch.Size([1025, 16])
;b.shape = torch.Size([10])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-3bd71e5c00e1> in <module>()
3 running_loss = 0
4
----> 5 for i, data in enumerate(trainloader, 0):
6
7 inputs, labels = data
~/anaconda3/lib/python3.7/site-packages/torch/utils/data/dataloader.py in __next__(self)
311 def __next__(self):
312 if self.num_workers == 0: # same-process loading
--> 313 indices = next(self.sample_iter) # may raise StopIteration
314 batch = self.collate_fn([self.dataset[i] for i in indices])
315 if self.pin_memory:
~/anaconda3/lib/python3.7/site-packages/torch/utils/data/sampler.py in __iter__(self)
136 def __iter__(self):
137 batch = []
--> 138 for idx in self.sampler:
139 batch.append(idx)
140 if len(batch) == self.batch_size:
~/anaconda3/lib/python3.7/site-packages/torch/utils/data/sampler.py in __iter__(self)
32
33 def __iter__(self):
---> 34 return iter(range(len(self.data_source)))
35
36 def __len__(self):
TypeError: 'torch.Size' object cannot be interpreted as an integer
最佳答案
您的问题是 __len__
函数。您不能使用shape
作为返回值。
下面是一个示例:
import torch
class Foo:
def __init__(self, data):
self.data = data
def __len__(self):
return self.data.shape
myFoo = Foo(data=torch.rand(10, 20))
print(len(myFoo))
会引发完全相同的错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-285-e97aace2f622> in <module>
7
8 myFoo = Foo(data=torch.rand(10, 20))
----> 9 print(len(myFoo))
TypeError: 'torch.Size' object cannot be interpreted as an integer
由于 shape 代表一个 torch.Size
元组:
print(myFoo.data.shape)
输出:
torch.Size([10, 20])
所以你必须决定要将哪个维度交给__len__
,例如第一个维度:
import torch
class Foo:
def __init__(self, data):
self.data = data
def __len__(self):
return self.data.shape[0] # choosing first dimension for len
myFoo = Foo(data=torch.rand(10, 20))
print(len(myFoo))
# prints 10
工作正常并返回10
。当然,您也可以选择输入的任何其他维度,但您必须选择一个。
因此,在您的 MSourceDataSet
代码中,您必须将 __len__
函数更改为:
def __len__(self):
return self.spec.shape[0] # as said of course you can also choose other dimensions
这应该可以解决您的问题。
关于python - Pytorch-类型错误 : 'torch.Size' object cannot be interpreted as an integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53588623/
我正在尝试执行 JavaPairRDD 和 JavaPairRDD 的 leftOuterJoin> 并且函数签名返回类型是 JavaPairRDD>>> 这里可选的是 com.google.comm
我正在尝试按元素的频率对元素进行排序 import java.io.BufferedReader; import java.io.IOException; import java.io.InputSt
这个问题已经有答案了: Is List a subclass of List? Why are Java generics not implicitly polymorphic? (19 个回答) 已
编辑:问题已解决:请参阅 Karim SNOUSSI 的答案和我在下面的评论。 这是我在堆栈溢出时遇到的第一个问题,所以我可能不会一开始就把所有事情都做对。对此感到抱歉。此外,我对 Java 和一般
#include #include using namespace std; class Integer { public: int i; Integer (int ll
我不明白: ArrayList list = new ArrayList(); Collection list1 = new ArrayList(); 类 ArrayList扩展实现接口(interf
我编写了:。它成功了。我不知道为什么?
我编写了:。它成功了。我不知道为什么
我编写了:。它成功了。我不知道为什么?
Collectors.counting()返回 long此方法中每个键的值: private static Map countDuplicates(HashSet cards) { retur
我正在尝试通过搜索旧元素并将其替换为新元素来更新节点的元素。但是有一个我不明白的错误。是什么导致我的代码出现该错误,我该如何解决?错误; The method update(Integer, Inte
我有一个称为 client 的表,其中有一列称为created_time ,所以实际上我想绘制一个 map ,以便我可以知道在哪一年和哪一个月添加了多少客户?现在的要求是假设在 2018 年 11 月
这个问题已经有答案了: Is Java "pass-by-reference" or "pass-by-value"? (91 个回答) 已关闭 8 年前。 我对 ArrayList Collecti
我意识到下面的代码是正确的 Integer.MIN_VALUE == -Integer.MIN_VALUE == Math.abs(Integer.MIN_VALUE) 这是因为当我们取反-21474
我有以下类 AccountWebappGridRow,它扩展了 AccountGridRow: public class AccountWebappGridRow extends AccountGri
我正在学习 Haskell 并看到了函数组合。 尝试复合 map和 foldl mapd = (map.foldl) 比 test = (mapd (\x y -> x + y ) [1,2,3,4]
我有两个相同大小的数组和两个方法。 public class Client { private static int[] ints; private static final int
我喜欢 Java 8 中的 Streams 概念。现在我想借助 Java Streams 将 Java 中的 Map 转换为排序列表。我只想显示列表而不将其存储在任何地方。我希望在结果列表中有这个输出
我有一个数据库表,其中包含电视节目类型列表和关联的 ARGB 颜色值,用于在显示电视指南时突出显示 Android ListView 中的电视节目。流派表看起来像这样... id genre
我有一个 Integer 类,它应该模拟一个整数 mod n。因此,它具有如下构造函数: Integer::Integer(int x) : m(x), n(0) { } Integer::I
我是一名优秀的程序员,十分优秀!