这里写代码片
import torch as th
a=th.FloatTensor(3,5)
a=th.randn(3,5)
inplace方法有 _,out没有
fill_,没有out方法,narrow没有inplace方法。
a.fill_(3.5)# do not have an out-place version
a.add_(1.0)
a.add()
a.narrow(dim,start,length)#dont exit inplace version
索引从0开始
索引方法和numpy相同,支持切片
b=a[0,3]
b=a[:,(0,1)]
b=a[:,1:3]
没有骆驼拼写了
例如 indexAdd( ) 现在为 index_add_( )
Args:
dim (int): Dimension along which to index
index (LongTensor): Indices to select from tensor
tensor (Tensor): Tensor containing values to add
Example:
x = torch.Tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
t = torch.Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
index = torch.LongTensor([0, 2, 1])
x.index_add_(0, index, t)
x
2 3 4
8 9 10
5 6 7
[torch.FloatTensor of size 3x3]
Tensor和numpy可以相互转换,但是它们的根本内存是一样的,所以改变一个另一个也会改变。
a=torch.ones(5)
b=a.numpy()
b
Out[20]: array([ 1., 1., 1., 1., 1.], dtype=float32)
内存共享,inplace 方法会同时改变
In [22]: a.add_(1)
Out[22]:
2
2
2
2
2
[torch.FloatTensor of size 5]
In [23]: a
Out[23]:
2
2
2
2
2
[torch.FloatTensor of size 5]
In [24]: b
Out[24]: array([ 2., 2., 2., 2., 2.], dtype=float32)
b=torch.from_numpy(a)
numpy 的类似的inplace方法
np.add(a,1,out=a)
Out[50]: array([ 7., 7., 7., 7., 7.])
这样,改变了a所在内存的内容,所以a和b同时改变,但是以下
a=a+1
会为a重新分配内存,a,b不再共享内存,b不变,a变。
In [52]: torch.cuda.is_available()
Out[52]: True
判断cuda是否可用。
b=a.cuda()
a=b.cpu()
注意转换后a,b内存不一样了