Pytorch English 공식 문서 연구 노트(1. Tensors)

텐서는 배열 및 행렬과 매우 유사한 데이터 구조이고, 텐서는 배열 및 행렬과 매우 유사한 데이터 구조입니다.텐서 배열 및 행렬과 매우 유사한 데이터 구조입니다 .
PyTorch에서는 텐서를 사용하여 모델의 입력과 출력은 물론 모델의 매개변수도 인코딩 합니다 .

1. 텐서 초기화
torch.tensor(data, dtype=None, device=None, requires_grad=False, pin_memory=False) → Tensor

·데이터: 데이터의 데이터 유형은 목록, 튜플, numpy 배열 ndarray, 스칼라(스칼라라고도 함) 및 기타 데이터 유형일 수 있습니다.
·dtype: 이 매개변수는 선택사항이며 기본값은 None입니다. 설정하지 않으면 생성된 Tensor 데이터 유형은 data에 전달된 매개변수의 데이터 유형을 복사합니다. 예를 들어 data의 데이터 유형이 float인 경우 데이터 유형은 다음과 같습니다. 기본적으로 생성됩니다. torch.FloatTensor에 대한 Tensor입니다.
·device: 이 매개변수는 선택사항이며 기본값은 None입니다. 설정하지 않으면 현재 장치에 생성된 Tensor에 메모리가 할당됩니다.
·requires_grad: 선택사항이며 기본값은 False이며, False인 경우 생성된 Tensor는 기울기 연산을 수행할 수 없으며, True로 변경하면 기울기를 계산할 수 있습니다.
·pin_memory: 이 매개변수는 선택사항이며 기본값은 False입니다. True로 설정하면 현재 Tensor가 고정 메모리에 할당되지만 CPU의 Tensor에만 적용됩니다.


设置require_grad参数的函数
Tensor.requires_grad_(requires_grad=True) → Tensor
autograd가 이 텐서에 대한 작업을 기록해야 하는지 여부를 변경합니다. 이 텐서의 require_grad 속성을 제자리에 설정합니다. 이 텐서를 반환합니다.

torch.no_grad의 역할

이 모듈에서는 계산된 모든 텐서의 요구 사항_grad가 자동으로 False로 설정되어 비디오 메모리를 크게 절약할 수 있습니다.
torch.no_grad로 계산된 텐서(x라는) require_grad = True인 경우에도 x require_grad에서 얻은 새 텐서(w라는)는 False이고 grad_fn도 None입니다. 즉, w는 구별되지 않습니다. 예가 아래에 나와 있습니다.

x = torch.rand(10, 5, requires_grad = True)
y = torch.rand(10, 5, requires_grad = True)
with torch.no_grad():
    w = x + y
    print(w.requires_grad)
    print(w.grad_fn)
#False
#None


1. 데이터 초기화 방법을 직접 사용
data=[[1,2],[3,4]]
x_data=torch.tensor(data)

2. Numpy 배열에서 변환

np_array=np.array(data)
x_np=torch.from_numpy(np_array)

t = torch.ones(5)
print(f"t: {
      
      t}")
n = t.numpy()#反之Numpy array也可以由tensor转化而来
print(f"n: {
      
      n}")
#t: tensor([1., 1., 1., 1., 1.])
#n: [1. 1. 1. 1. 1.]
t.add_(1)
print(f"t: {
      
      t}")
print(f"n: {
      
      n}")
#t: tensor([2., 2., 2., 2., 2.])
#n: [2. 2. 2. 2. 2.]
#CPU上的张量和NumPy数组可以共享它们的底层内存位置,所以改变一个的同时可以改变另一个。

3. 다른 텐서의 형태로 변환

x_ones = torch.ones_like(x_data)
print(f"Ones Tensor: \n {
      
      x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float)
print(f"Random Tensor: \n {
      
      x_rand} \n")
#Ones Tensor:
# tensor([[1, 1],
#        [1, 1]])

#Random Tensor:
# tensor([[0.5900, 0.9701],
#        [0.3483, 0.4137]])

4. 임의의 값이나 상수 및 모양 튜플을 사용하여 텐서를 정의합니다.

shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
print(f"Random Tensor: \n {
      
      rand_tensor} \n")
print(f"Ones Tensor: \n {
      
      ones_tensor} \n")
print(f"Zeros Tensor: \n {
      
      zeros_tensor}")
#Random Tensor:
# tensor([[0.8330, 0.5998, 0.8980],
#        [0.6941, 0.3293, 0.7102]])
#
#Ones Tensor:
# tensor([[1., 1., 1.],
#        [1., 1., 1.]])
#
#Zeros Tensor:
# tensor([[0., 0., 0.],
#        [0., 0., 0.]])



torch.Tensor(data): 입력 데이터를 torch.FloatTensor()로 변환합니다.
torch.Tensor()는 빈 FloatTensor를 생성할 수 있지만 torch.tensor()를 사용할 때 오류가 보고됩니다.

a=torch.tensor(1)
print(a)
print(a.type())
a=torch.Tensor(1)
print(a)
print(a.type())
#tensor(1)
#torch.LongTensor
#tensor([1.0010e-38])
#torch.FloatTensor
2. 텐서의 속성

Tensor.shape[i]는 i번째 차원의 값을 나타냅니다.

tensor = torch.rand(3,4)
print(f"Shape of tensor: {
      
      tensor.shape}")
print(f"Shape of tensor: {
      
      tensor.shape[0]}")
print(f"Shape of tensor: {
      
      tensor.shape[1]}")
print(f"Datatype of tensor: {
      
      tensor.dtype}")
print(f"Device tensor is stored on: {
      
      tensor.device}")
print(tensor.requires_grad) #表示autograd时是否需要计算此tensor的梯度,默认False
print(tensor.grad) #存储梯度的值,初始为None
print(tensor.grad_fn) #反向传播时,用来计算梯度的函数
print(tensor.is_leaf) #该张量节点在计算图中是否为叶子节点
'''
当这个 tensor 是用户创建的时候,它是一个叶子节点,
当这个 tensor 是由其他运算操作产生的时候,它就不是一个叶子节点
'''
print(f"mean of tensor: {
      
      Tensor.mean(tensor)}")
print(f"variance of tensor: {
      
      Tensor.var(tensor)}")
#Shape of tensor: torch.Size([3, 4])
#Shape of tensor: 3
#Shape of tensor: 4
#Datatype of tensor: torch.float32
#Device tensor is stored on: cpu
#False
#None
#None
#True

require_grad: 텐서에 대한 기울기를 계산해야 하면 True이고, 그렇지 않으면 False입니다. 텐서를 생성할 때 require_grad를 True로 지정할 수 있습니다(기본값은 False).

grad_fn: grad_fn은 기울기 계산을 용이하게 하기 위해 변수가 어떻게 나오는지 기록하는 데 사용됩니다. y = x*3, y.grad_fn은 x에서 y를 계산하는 과정을 기록합니다. grad_fn=None을 사용하여 리프 노드를 직접 생성합니다.

grad:backward()를 실행한 후 x.grad를 통해 x의 기울기 값을 확인합니다.

require_grad, grad, grad_fn 및 is_leaf에 대한 자세한 내용은 이 문서를 참조하세요.


3. 텐서의 연산

1. 텐서는 기본적으로 CPU에서 생성됩니다. 텐서를 명시적으로 GPU로 이동하려면 .to 메서드를 사용해야 합니다(GPU 사용 가능 여부를 확인한 후).

if torch.cuda.is_available():
    tensor = tensor.to("cuda")


2 인덱싱, 슬라이싱, 전치(순열, 전치) 작업

tensor = torch.ones(4, 4)
print(f"First row: {
      
      tensor[0]}")
print(f"First column: {
      
      tensor[:, 0]}")
print(f"Last column: {
      
      tensor[..., -1]}")#此处用:或...都行
tensor[:,1] = 2
print(tensor)
#First row: tensor([1., 1., 1., 1.])
#First column: tensor([1., 1., 1., 1.])
#Last column: tensor([1., 1., 1., 1.])
#tensor([[1., 2., 1., 1.],
#        [1., 2., 1., 1.],
#        [1., 2., 1., 1.],
#        [1., 2., 1., 1.]])

'''
def transpose(self, dim0, dim1): -> Tensor
def permute(self, *dims): -> Tensor
transpose:只能选择tensor中两个维度进行转置
permute:可以让tensor按照任意指定维度顺序进行转置
'''
tensor1=tensor.transpose(0,1)#例原本坐标为(0,1,1,0)的点就会变成(1,0,1,0)
tensor2=tensor.permute(1,0,3,2)#例原本坐标为(0,1,1,0)的点就会变成(1,0,0,1)

참고: 하지만 numpy의 def transpose(self, *axes): 이 방법은 numpy.array()가 지정된 차원 순서로 전치되도록 하는 것입니다.


3. 압축 및 압축 해제 작업으로 차원을 줄이고 차원을 높입니다.

토치. unsqueeze ( input , 희미 ) → T ensor \text torch.unsqueeze(input, 희미) → Tensort 오크 h . u n s q u eeze ( in p u t ,디임 ) _텐서 _ _ _

지정된 위치에 삽입된 크기 1의 차원을 가진 새 텐서를 반환합니다.
반환된 텐서는 이 텐서와 동일한 기본 데이터를 공유합니다.
[-input.dim() - 1, input.dim() + 1) 범위 내의 희미한 값을 사용할 수 있습니다.음수 Dim은 Dim = Dim + input.dim() + 1에 적용된 unsqueeze()에 해당합니다.

>>> x = torch.tensor([1, 2, 3, 4])#shape为4
>>> torch.unsqueeze(x, 0)#shape变为1×4
tensor([[ 1,  2,  3,  4]])
>>> torch.unsqueeze(x, 1)#shape变为4×1
tensor([[ 1],
        [ 2],
        [ 3],
        [ 4]])

토치. squeeze(input,dim=None) → Tensor \text torch.squeeze(input,dim=None) → Tensort 오크 h . s q u eeze ( in p u t ,나는 _=없음 ) _ _ _텐서 _ _ _

크기의 입력 차원이 모두 제거된 텐서를 반환합니다.
예를 들어, 입력의 형태가 다음과 같다면: ( A × 1 × B × C × 1 × D ) (A \times 1 \times B \times C \times 1 \times D)( _×1×××1×D ) 그러면 출력 텐서는 다음과 같은 모양이 됩니다.( A × B × C × D ) (A \times B \times C \times D)( _×××D )
dim이 주어지면 주어진 차원에서만 스퀴즈 작업이 수행됩니다. 입력의 모양이 다음과 같은 경우:( A × 1 × B ) (A \times 1 \times B)( _×1×) ,squeeze(input, 0)은 텐서를 변경하지 않고 그대로 둡니다., 그러나 squeeze(input, 1)은 텐서를 ( A × B ) (A \times B) 모양으로 압축합니다.( _×)

>>> x = torch.zeros(2, 1, 2, 1, 2)
>>> x.size()
torch.Size([2, 1, 2, 1, 2])

>>> y = torch.squeeze(x)
>>> y.size()
torch.Size([2, 2, 2])

>>> y = torch.squeeze(x, 0)#leaves the tensor unchanged
>>> y.size()
torch.Size([2, 1, 2, 1, 2])

>>> y = torch.squeeze(x, 1)
>>> y.size()
torch.Size([2, 2, 1, 2])


4. 산술 연산 torch.matmul, ±*/

기본 4가지 산술 연산
a + b는 torch.add()와 동일합니다.
a - b는 torch.sub()와 동일합니다.
a * b는 torch.mul()과 동일합니다.
a / b는 torch.div()와 동일합니다.
직접 덧셈, 뺄셈, 곱셈, 나눗셈, 지수화 , 제곱근 torch.sqrt

a=10000**(torch.arange(0, 256, 2).float() / 256)

* 메소드 연산은 mul 이고 , / 메소드 연산도 유사하며 다음과 같이 분류됩니다.

(1) Tensor*scalar k의 결과는 Tensor의 각 요소에 k를 곱한 값입니다.

>>> a = torch.ones(3,4)
>>> a
tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])
>>> a * 2
tensor([[2., 2., 2., 2.],
        [2., 2., 2., 2.],
        [2., 2., 2., 2.]])

(2)Tensor* 1차원 텐서
Tensor* 행 벡터의 결과는 각 열에 행 벡터의 해당 열 값을 곱한 결과이고,
Tensor*와 열 벡터의 결과는 각 행에 곱한 결과입니다. 열 벡터의 해당 행 값으로 계산됩니다.

>>> a = torch.ones(3,4)
>>> a
tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])
>>> b = torch.Tensor([1,2,3,4])
>>> b
tensor([1., 2., 3., 4.])
>>> a * b
tensor([[1., 2., 3., 4.],
        [1., 2., 3., 4.],
        [1., 2., 3., 4.]])

>>> b = torch.Tensor([1,2,3]).reshape((3,1))
>>> b
tensor([[1.],
        [2.],
        [3.]])
>>> a * b
tensor([[1., 1., 1., 1.],
        [2., 2., 2., 2.],
        [3., 3., 3., 3.]])

(3)Tensor1*Tensor2
곱하려는 두 텐서의 차원이 일치하지 않지만 Tensor2의 차원이 Tensor1의 후자 차원과 같을 경우 곱셈이 가능합니다.
곱셈을 하면 Tensor2는 반복적으로 Tensor1의 모양으로 확장됩니다.

Tensor1과 Tensor2의 차원이 동일할 경우 해당 차원의 값도 동일해야 하며, 해당 차원의 값이 다를 경우 둘 중 하나는 1이어야 하며, 그렇지 않으면 오류가 보고됩니다. .

+ 메소드 연산은 add 이고 , - 메소드 연산도 유사하여 다음과 같이 분류됩니다.
(1) (2) 상황은 위와 동일합니다
(3) Tensor1+Tensor2
추가된 두 텐서의 차원이 일치하지 않지만, Tensor2의 차원은 Tensor1의 후자 차원과 동일합니다. 해당 값이 동일하면 추가할 수 있습니다.
추가하면 Tensor2는 반복적으로 Tensor1의 모양으로 확장됩니다.

a = torch.ones([8, 4, 5, 6])
b = torch.ones([5, 6])
c = a+b
print(c.shape)#(8, 4, 5, 6)


Tensor1과 Tensor2의 차원이 동일한 경우 해당 축의 값은 동일하거나 1이어야 합니다.
a = torch.ones([8, 4, 5, 6])
b = torch.ones([8, 1, 5, 6])
c = torch.ones([8, 2, 5, 6])
a+b可以。相加过程也是先将b重复扩充为与a相同shape
a+c报错

Matmul 작업

y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)#类似矩阵乘法

y3 = torch.rand_like(y1)
torch.matmul(tensor, tensor.T, out=y3)
#y1,y2,y3是相同的

z1 = tensor * tensor
z2 = tensor.mul(tensor)#两个tensor的对应位置相乘

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
#z1,z2,z3是相同的
#tensor([[1., 4., 1., 1.],
#       [1., 4., 1., 1.],
#       [1., 4., 1., 1.],
#       [1., 4., 1., 1.]])


5、torch.reshape(입력, 모양) → Tensor

'''
Parameters
input (Tensor) – the tensor to be reshaped
shape (tuple of python:ints) – the new shape
A single dimension may be -1, in which case it’s inferred from the remaining dimensions and
 the number of elements in input.
 一个单一的维度可能是-1,在这种情况下,它是由其余的维度和输入的元素数量推断出来的。
'''
应用举例:假设当我们的dataloader的batch_size设置为64。并且经过卷积(out_channels=6)之后,
我们需要使用tensorboard可视化,而彩色图片的writer.add.images(output)的彩色图片是in_channels=3的。
那么则需要对卷积后的图片进行reshape,Torch.size(64,6,30,30)---->torch.size(-1,3,30,30)-1的意思为最后自动计算其batch_size。
输出通道由6变成了3,从而每一个通道的数量增加,因而结果为torch.size(128,3,30,30)


6. Tensor.view(*shape) → Tensor, 사용하기 전에 contiguous() 메소드를 추가해야 하는 경우가 있음

자체 텐서와 동일한 데이터를 갖지만 모양이 다른 새 텐서를 반환합니다.

x = torch.randn(4, 4)
x.size()#torch.Size([4, 4])
y = x.view(16)
y.size()#torch.Size([16])
z = x.view(-1, 8)  # the size -1 is inferred from other dimensions
z.size()#torch.Size([2, 8])


주요 예: 3 × 4차원 텐서 → t에 대해 reshape(t, (4, 3)) 및 t = t, transpose(− 1, − 2)를 수행합니다. 얻은 새 차원은 일관성이 있지만 그 중 해당 위치의 값이 일치하지 않습니다. reshape 및 view는 단순히 새 차원에 따라 값을 채우기만 하면 됩니다. 전치(transpose)는 행렬\color{red}를 전치하는 데 핵심입니다. 예: 3×4의 경우 차원 텐서→t, reshape(t, (4,3)) 및 t=t.transpose(-1,-2), 얻은 새 차원은 일관성이 있지만 해당 위치의 값은 일관성이 없습니다. reshape 및 view는 새로운 차원에 따라 값을 채우고 Transpose는 Transpose 행렬입니다.주요 예: 3×4 차원 텐서 _ _ _t , 결과 e ( t , _( 4 ,3 )) 그리고 t=t . t r an s p ose ( 1 ,2 ) , 얻은 새 치수 일치하지만 해당 위치의 값은 일치하지 않습니다. reshape view e w 단순히 치수에 따라 값을 채우고 t r an s p ose는 행렬을 전치하는 것입니다.

7、토치.캣、토치.분할

torch.cat(tensors,dim=0, *, out=None) → Tensor
주어진 차원에서 주어진 seq 텐서 시퀀스를 연결합니다. 모든 텐서는 동일한 모양(연결 차원 제외)을 가지거나 비어 있어야 합니다.

매개변수:
텐서(텐서 시퀀스) – 동일한 유형의 텐서로 구성된 모든 Python 시퀀스. 제공된 비어 있지 않은 텐서는 고양이 차원을 제외하고 동일한 모양을 가져야 합니다.
희미한 (int, 선택 사항) – 텐서가 연결되는 차원
Dim=-1은 마지막 차원의 첫 번째 차원을 의미합니다.

>>> x = torch.randn(2, 3)
>>> x
tensor([[ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497]])
>>> torch.cat((x, x, x), 0)#shape是6×3
tensor([[ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497],
        [ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497],
        [ 0.6580, -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497]])
>>> torch.cat((x, x, x), 1)#shape是2×9
tensor([[ 0.6580, -1.0969, -0.4614,  0.6580, -1.0969, -0.4614,  0.6580,
         -1.0969, -0.4614],
        [-0.1034, -0.5790,  0.1497, -0.1034, -0.5790,  0.1497, -0.1034,
         -0.5790,  0.1497]])


8、torch.clamp(input, min=None, max=None, *, out=None) → 텐서

입력의 모든 요소를 ​​[ min, max ] 범위로 고정합니다. min_value 및 max_value를 각각 min 및 max로 설정하면 다음이 반환됩니다.

합산 공식 : yi = min ⁡ ( max ⁡ ( xi , min_value i ) , max_value i ) 합산 공식 : y_i = \min(\max(x_i, \text{min\_value}_i), \text{max\_value} _i)계산식: y=최소 ( 최대 ( x,최소값) ,최대_값)은
min, max 범위 밖의 숫자는 min 또는 max로 제한되고, 범위 내의 숫자는 변경되지 않음을 의미합니다.

min이 None이면 하한이 없습니다. 또는 max가 None이면 상한이 없습니다.

>>> a = torch.randn(4)
>>> a
tensor([-1.7120,  0.1734, -0.0478, -0.0922])
>>> torch.clamp(a, min=-0.5, max=0.5)
tensor([-0.5000,  0.1734, -0.0478, -0.0922])

>>> min = torch.linspace(-1, 1, steps=4)
>>> torch.clamp(a, min=min)
tensor([-1.0000,  0.1734,  0.3333,  1.0000])


9、torch.linspace(시작, 끝, 단계, *, out=None, dtype=None, 레이아웃=torch.strided, device=None, require_grad=False) → Tensor

값이 처음부터 끝까지 균등한 간격을 갖는 크기 단계의 1차원 텐서를 생성합니다. 즉, 값은 다음과 같습니다.

( start , start + end − 시작 단계 − 1 , … , start + ( 단계 − 2 ) ✽ end − 시작 단계 − 1 , end ) (\text{start}, \text{start} + \frac{\text{ 끝} - \text{시작}}{\text{단계} - 1}, \ldots, \text{시작} + (\text{단계} - 2) * \frac{\text{end} - \text{ 시작}}{\text{단계} - 1}, \text{end})( 시작 ,시작+단계 - 1 - 시작,,시작+( 단계-2 )*단계 - 1 - 시작, )

>>> torch.linspace(3, 10, steps=5)
tensor([  3.0000,   4.7500,   6.5000,   8.2500,  10.0000])
>>> torch.linspace(-10, 10, steps=5)
tensor([-10.,  -5.,   0.,   5.,  10.])
>>> torch.linspace(start=-10, end=10, steps=5)
tensor([-10.,  -5.,   0.,   5.,  10.])
>>> torch.linspace(start=-10, end=10, steps=1)
tensor([-10.])


10. 반복 및 확장

* Tensor.repeat( size) → Tensor
지정된 차원을 따라 이 텐서를 반복합니다.

>>> x = torch.tensor([1, 2, 3])
>>> x.repeat(4, 2)#把x看作1×3了,然后1乘4,3乘2
tensor([[ 1,  2,  3,  1,  2,  3],
        [ 1,  2,  3,  1,  2,  3],
        [ 1,  2,  3,  1,  2,  3],
        [ 1,  2,  3,  1,  2,  3]])
>>> x.repeat(4, 2, 1).size()#把x看作1×1×3了,然后1乘4,1乘2,3乘1
torch.Size([4, 2, 3])

* Tensor.expand( sizes) → Tensor
싱글톤 차원이 더 큰 크기로 확장된 셀프 텐서의 새로운 뷰를 반환합니다.
차원의 크기로 -1을 전달하면 해당 차원의 크기가 변경되지 않는다는 의미입니다.

Tensor는 더 많은 차원으로 확장될 수도 있으며, 새로운 차원이 앞에 추가됩니다. 새 치수의 경우 크기를 -1로 설정할 수 없습니다.

>>> x = torch.tensor([[1], [2], [3]])
>>> x.size()
torch.Size([3, 1])
>>> x.expand(3, 4)
tensor([[ 1,  1,  1,  1],
        [ 2,  2,  2,  2],
        [ 3,  3,  3,  3]])
>>> x.expand(-1, 4)   # -1 means not changing the size of that dimension
tensor([[ 1,  1,  1,  1],
        [ 2,  2,  2,  2],
        [ 3,  3,  3,  3]])


11、torch.sum(입력, 희미함, keepdim=False, *, dtype=없음)

주어진 차원 치수에 있는 입력 텐서의 각 행의 합을 반환합니다. Dim이 차원 목록인 경우줄이다그들 모두 위에.
매개변수:
·input(Tensor) - 입력 텐서.
·dim (int 또는 int의 튜플, 선택 사항) - 줄일 차원입니다. 없음인 경우 모든 차원이 축소됩니다.
·keepdim (bool) – 출력 텐서의 희미한 유지 여부.

키워드 인수:
·dtype (torch.dtype, 선택 사항) – 반환된 텐서의 원하는 데이터 유형. 지정된 경우 입력 텐서는 작업이 수행되기 전에 dtype으로 캐스팅됩니다. 이는 데이터 유형 오버플로를 방지하는 데 유용합니다. 기본값: 없음.

>>>a=torch.arange(3*2*2).view(2,2,3)
>>>print(a)
tensor([[[ 0,  1,  2],
         [ 3,  4,  5]],

        [[ 6,  7,  8],
         [ 9, 10, 11]]])
>>>b=torch.sum(a,(1,2))
>#把(0,0,0)、(0,0,1)、(0,0,2)、(0,1,0)、(0,1,1)、(0,1,2)的相加,以此类推
>>>print(b)
tensor([15, 51])

>>>c=torch.sum(a,0)#即把坐标为(0,0,0)和(1,0,0)的相加,以此类推
>>>print(c)
tensor([[ 6,  8, 10],
        [12, 14, 16]])


12, 토치.cumprod

>>>a=torch.Tensor([[0.1,0.2],[0.3,0.4]])
>>>b=torch.cumprod(a,dim=0)#第0维所以就是坐标为(0,0)和(1,0)的进行相乘
tensor([[0.1000, 0.2000],
		[0.0300, 0.0800]])
>>>b=torch.cumprod(a,dim=1)
tensor([[0.1000, 0.0200],
		[0.3000, 0.1200]])

13. torch.flaten(n), n번째 차원부터 차원을 평면화합니다.

agg = tensor.sum().item()
print(agg, type(agg))
tensor.add_(5)
#In-place operations:Operations that store the result into the operand are called in-place. 
They are denoted by a _ suffix.

추천

출처blog.csdn.net/m0_50364811/article/details/126650237