import torch def AddDataToTorch(oriData, newData, addDim): if (oriData.numel() != 0): if (len(oriData.shape) > addDim) and (len(newData.shape) > addDim): return torch.cat((oriData.view(-1, 1), newData.view(-1, 1)), dim = addDim) else: return torch.cat((oriData.view(-1, 1), newData.view(-1, 1)), dim = 0) mergeData = torch.Tensor() tmpData = torch.randn(3) for i in range(1, 10): mergeData = AddDataToTorch(mergeData, tmpData, 1) 这段代码为什么提示AttributeError: 'NoneType' object has no attribute 'numel'
时间: 2023-06-26 18:09:02 浏览: 179
torch(git clone https://github.com/torch/distro.git ~/torch --recursive)
这是因为在第一次调用`AddDataToTorch`时,`oriData`是空的,即为`NoneType`,没有`numel()`属性。你可以在调用`AddDataToTorch`之前添加一个判断语句,在`oriData`为空时进行特殊处理,如返回`newData`本身或创建一个大小为`newData`的新张量。例如:
```
import torch
def AddDataToTorch(oriData, newData, addDim):
if oriData is None:
return newData
elif (len(oriData.shape) > addDim) and (len(newData.shape) > addDim):
return torch.cat((oriData.view(-1, 1), newData.view(-1, 1)), dim=addDim)
else:
return torch.cat((oriData.view(-1, 1), newData.view(-1, 1)), dim=0)
mergeData = None
tmpData = torch.randn(3)
for i in range(1, 10):
mergeData = AddDataToTorch(mergeData, tmpData, 1)
```
这样就可以避免该错误。
阅读全文