AttributeError: 'torch.FloatTensor' object has no attribute 'item'
AttributeError: 'torch.FloatTensor' object has no attribute 'item'
代码如下:
from __future__ import print_function
from itertools import count
import torch
import torch.autograd
import torch.nn.functional as F
POLY_DEGREE = 4
W_target = torch.randn(POLY_DEGREE, 1) * 5
b_target = torch.randn(1) * 5
def make_features(x):
x = x.unsqueeze(1)
return torch.cat([x ** i for i in range(1, POLY_DEGREE+1)], 1)
def f(x):
return x.mm(W_target) + b_target.item()
这导致了以下错误消息:
AttributeError: 'torch.FloatTensor' object has no attribute 'item'
请问我该如何解决?
函数 item()
是 PyTorch 0.4.0
的新函数。使用早期版本的 PyTorch 时,您会收到此错误。
所以你可以升级你的 PyTorch 版本来解决这个问题。
编辑:
我又通过了你的例子。你想用 item()
存档什么?
在你的情况下 item()
应该只给你张量中的 (python) 浮点值。
你为什么要用这个?你可以省略 item()
.
所以:
def f(x):
return x.mm(W_target) + b_target
而不是:
def f(x):
return x.mm(W_target) + b_target.item()
这应该适合你,在 PyTorch 0.4.0 中没有区别。省略 item()
.
也更有效
代码如下:
from __future__ import print_function
from itertools import count
import torch
import torch.autograd
import torch.nn.functional as F
POLY_DEGREE = 4
W_target = torch.randn(POLY_DEGREE, 1) * 5
b_target = torch.randn(1) * 5
def make_features(x):
x = x.unsqueeze(1)
return torch.cat([x ** i for i in range(1, POLY_DEGREE+1)], 1)
def f(x):
return x.mm(W_target) + b_target.item()
这导致了以下错误消息:
AttributeError: 'torch.FloatTensor' object has no attribute 'item'
请问我该如何解决?
函数 item()
是 PyTorch 0.4.0
的新函数。使用早期版本的 PyTorch 时,您会收到此错误。
所以你可以升级你的 PyTorch 版本来解决这个问题。
编辑:
我又通过了你的例子。你想用 item()
存档什么?
在你的情况下 item()
应该只给你张量中的 (python) 浮点值。
你为什么要用这个?你可以省略 item()
.
所以:
def f(x):
return x.mm(W_target) + b_target
而不是:
def f(x):
return x.mm(W_target) + b_target.item()
这应该适合你,在 PyTorch 0.4.0 中没有区别。省略 item()
.