原地操作符的使用(可以使用其他变量接收也可以使用自身变量来接收)

>>> a
tensor([2., 4., 6., 8.])
>>> c = a.resize_(2,2)
>>> a
tensor([[2., 4.],
[6., 8.]])
>>> c
tensor([[2., 4.],
[6., 8.]])
>>> a = a.resize_(4)
>>> a
tensor([2., 4., 6., 8.])

>>> c
tensor([2., 4., 6., 8.])

 

除了有resize_(),,,,,add_() ,,,,等操作符实现原地操作。。。。

在pytorch中是tensor的共享内存,,

 1,Tensor初始化另一个Tensor

  2,add_()等原地操做符

 3,Tensor与Numpy的转化

 

>>> c
tensor([2., 4., 6., 8.])
>>> b = c
>>> c = c.resize_(2,2)
>>> c
tensor([[2., 4.],
[6., 8.]])
>>> b
tensor([[2., 4.],
[6., 8.]])

 

 

Tensor和Numpy的相会转化

import numpy as np
# data = np.ones(2)
# print(type(data))
# a = torch.from_numpy(data)
# print(a,type(a)) #numpy和tensor的相互转换

>>> a = torch.randn(1,2)
>>> a
tensor([[ 0.2295, -1.4333]])
>>> import numpy as np


>>> b = a.numpy()
>>> b
array([[ 0.22947219, -1.433332 ]], dtype=float32)
>>> b = torch.from_numpy(b)
>>> b
tensor([[ 0.2295, -1.4333]])

>>> b = a.tolist()
>>> b
[[0.22947219014167786, -1.4333319664001465]]

posted @ 2021-01-19 20:50  _八级大狂风  阅读(107)  评论(0编辑  收藏  举报