PyTorch의 중량 생성 방법

25466 단어 PyTorch

장량의 개념


Tensor는 PyTorch의 기본 데이터 구조입니다.수학 개념에서 장량은 다차원 수조로 표량, 벡터, 행렬의 고차원 확장이다.
torch.Tensor의 속성:
  • 데이터: 포장된 Tensor
  • grad:데이터의 경계
  • grad_fn: Tensor의 Function을 만듭니다. 예를 들어 덧셈, 곱셈 등은 구도 과정에서 사용되기 때문에 기록해야 합니다.
  • requires_grad: 사다리 계산이 필요한지 표시
  • is_leaf: 잎 결점 여부를 표시합니다
  • dtype: 장량의 데이터 형식, 예를 들어torch.FloatTensor, torch.cuda.FloatTensor
  • shape: 장량의 형상, 예를 들어(64,3,224,224)
  • device: 장량이 있는 장치, GPU/CPU, GUP에서만 GUP로 가속 연산 가능
  • Data Type
    dtype
    CPU tensor
    GPU tensor
    32-bit floating point
    torch.float32 or torch.float
    torch.FloatTensor
    torch.cuda.FloatTensor
    64-bit floating point
    torch.float64 or torch.double
    torch.DoubleTensor
    torch.cuda.DoubleTensor
    16-bit floating point
    torch.float16 or torch.half
    torch.HalfTensor
    torch.cuda.HalfTensor
    8-bit integer(unsigned)
    torch.uint8
    torch.ByteTensor
    torch.cuda.ByteTensor
    8-bit integer(signed)
    torch.int8
    torch.CharTensor
    torch.cuda.CharTensor
    16-bit integer(signed)
    torch.int16 or torch.short
    torch.ShortTensor
    torch.cuda.ShortTensor
    32-bit integer(signed)
    torch.int32 or torch.int
    torch.IntTensor
    torch.cuda.IntTensor
    64-bit integer(signed)
    torch.int64 or torch.long
    torch.LongTensor
    torch.cuda.LongTensor
    Boolean
    torch.bool
    torch.BoolTensor
    torch.cuda.BoolTensor
    GPU tensor는 GPU에 데이터를 배치합니다.torch.float32가 가장 많이 사용되고, 권적층의 값과 그림을 미리 처리한 후, 기본값은float32입니다.torch.long 다음으로 이미지 라벨은 보통 긴 정형으로 표시됩니다.

    장량의 생성


    직접 생성


    torch.tensor()

    torch.tensor(data, 
                 dtype=None, 
                 device=None, 
                 requires_grad=False, 
                 pin_memory=False)
    

    기능:데이터에서 tensor 만들기
  • 데이터: 데이터,list,ndarray
  • 가능
  • dtype: 데이터 형식, 기본값은 데이터와 일치
  • device: 소재 장치,cuda/cpu
  • requires_grad: 계단식 계산이 필요한지 여부
  • pin_memory: 잠금 페이지 메모리에 저장되는지 여부는 전환 효율과 관련이 있으며 대개 False
  • arr = np.ones((3, 3))
    print("ndarray :", arr.dtype)
    t1 = torch.tensor(arr)
    t2 = torch.tensor(arr, device='cuda')
    print(t1)
    print(t2)
    
    ndarray : float64
    tensor([[1., 1., 1.],
            [1., 1., 1.],
            [1., 1., 1.]], dtype=torch.float64)
    tensor([[1., 1., 1.],
            [1., 1., 1.],
            [1., 1., 1.]], device='cuda:0', dtype=torch.float64)
    

    torch.from_numpy()

    torch.from_numpy(ndarray) 
    

    기능:numpy에서 tensor 주의사항 만들기:torch.from_numpy에서 만든 tensor는 원ndarray와 메모리를 공유합니다. 그 중 하나를 수정하면 다른 것도 변경됩니다.
    arr = np.array([[1, 2, 3], [4, 5, 6]])
    t = torch.from_numpy(arr)
    print(arr)
    print(t)
    
    print("
    arr"
    ) arr[0, 0] = 0 print(arr) print(t) print("
    tensor"
    ) t[0, 0] = -1 print(arr) print(t)
    [[1 2 3]
     [4 5 6]]
    tensor([[1, 2, 3],
            [4, 5, 6]], dtype=torch.int32)
    
     arr
    [[0 2 3]
     [4 5 6]]
    tensor([[0, 2, 3],
            [4, 5, 6]], dtype=torch.int32)
    
     tensor
    [[-1  2  3]
     [ 4  5  6]]
    tensor([[-1,  2,  3],
            [ 4,  5,  6]], dtype=torch.int32)
    

    수치에 따라 생성


    torch.zeros()

    torch.zeros(size, 
                out=None, 
                dtype=None, 
                layout=torch.strided, 
                device=None, 
                requires_grad=False)
    

    기능:size에 따라 전체 0장 만들기
  • size: 장량의 형상, 예를 들어(3,3),(3,224224)
  • out: 출력된 장량, 생성된 tensor를 out에 부여하고 공유 메모리
  • dtype: 데이터 유형
  • layout: 메모리의 레이아웃 형식,strided,sparsecoo(희소장량 사용) 등
  • device: 소재 장치,cuda/cpu
  • requires_grad: 계단식 계산이 필요한지 여부
  • out_t = torch.tensor([1])
    print(out_t)
    t = torch.zeros((3, 3), out=out_t)
    print(t)
    print(out_t)
    print(id(t), id(out_t), id(t) == id(out_t))
    
    tensor([1])
    tensor([[0, 0, 0],
            [0, 0, 0],
            [0, 0, 0]])
    tensor([[0, 0, 0],
            [0, 0, 0],
            [0, 0, 0]])
    1752193781416 1752193781416 True
    

    torch.zeros_like()

    torch.zeros_like(input, 
                     dtype=None, 
                     layout=None, 
                     device=None, 
                     requires_grad=False)
    

    기능: input 모양으로 전체 0 장 만들기
  • intput: input와 같은 모양의 전체 0장 만들기
  • dtype: 데이터 유형
  • layout: 메모리의 레이아웃 형식,strided,sparsecoo(희소장량 사용) 등
  • device: 소재 장치,cuda/cpu
  • requires_grad: 계단식 계산이 필요한지 여부
  • t1 = torch.tensor([1, 1, 1])
    t2 = torch.zeros_like(t1)
    print(t1)
    print(t2)
    
    tensor([1, 1, 1])
    tensor([0, 0, 0])
    

    torch.ones ()와 torch.ones_like()

    torch.ones(size, 
               out=None, 
               dtype=None, 
               layout=torch.strided, 
               device=None, 
               requires_grad=False
               
    torch.ones_like(input, 
                    dtype=None, 
                    layout=None, 
                    device=None, 
                    requires_grad=False)
    

    기능: 전체 1장 크기를 만듭니다. 제로와 같은 용도로 사용합니다.

    torch.full () 및 torch.full_like()

    torch.full(size, 
               fill_value, 
               out=None, 
               dtype=None, 
               layout=torch.strided, 
               device=None, 
               requires_grad=False)
               
    torch.full_like(input, 
                    fill_value, 
                    dtype=None, 
                    layout=None, 
                    device=None, 
                    requires_grad=False)
    

    기능: 사용자 정의 수치의 장량을 만듭니다.zero와 같은 용도로 사용합니다
  • fill_value: 충전 장량의 값
  • t1 = torch.full((3, 3), 9)
    print(t1)
    t2 = torch.full_like(t1, 8)
    print(t2)
    
    tensor([[9., 9., 9.],
            [9., 9., 9.],
            [9., 9., 9.]])
    tensor([[8., 8., 8.],
            [8., 8., 8.],
            [8., 8., 8.]])
    

    torch.arange()

    torch.arange(start=0, 
                 end, 
                 step=1, 
                 out=None, 
                 dtype=None, 
                 layout=torch.strided, 
                 device=None, 
                 requires_grad=False)
    

    기능: 등차의 1차원 장량 주의사항 만들기: 수치 구간은 [start,end),end를 찾을 수 없습니다
  • start: 수열 시작값
  • end: 수열 끝값
  • step: 수열 공차, 기본 1
  • t = torch.arange(2, 10, 2)
    print(t)
    
    tensor([2, 4, 6, 8])
    

    torch.linspace()

    torch.linspace(start, 
                   end, 
                   steps=100, 
                   out=None, 
                   dtype=None, 
                   layout=torch.strided, 
                   device=None, 
                   requires_grad=False) 
    

    기능: 균일한 1차원 장량 주의사항 만들기: 수치 구간은 [start,end]이고 end를 포함합니다
  • start: 수열 시작값
  • end: 수열 끝값
  • steps: 수열 길이
  • t1 = torch.linspace(2, 10, 5)
    t2 = torch.linspace(2, 10, 6)
    print(t1)
    print(t2)
    
    tensor([ 2.,  4.,  6.,  8., 10.])
    tensor([ 2.0000,  3.6000,  5.2000,  6.8000,  8.4000, 10.0000])
    

    torch.logspace()

    torch.logspace(start, 
                   end, 
                   steps=100, 
                   base=10.0, 
                   out=None, 
                   dtype=None, 
                   layout=torch.strided, 
                   device=None, 
                   requires_grad=False)
    

    기능: 베이스의 start 차멱에서 베이스의 end 차멱까지의 등비 1차원 장량 주의사항 만들기: 수치 구간은 [start,end]이고 end를 포함합니다
  • start: 수열 시작 幂次
  • end: 수열 끝 幂次
  • steps: 수열 길이
  • base: 수열 공비, 기본값 10
  • t = torch.logspace(0, 4, 5, 3)
    print(t)
    
    tensor([ 1.,  3.,  9., 27., 81.])
    

    torch.eye()

    torch.eye(n, 
              m=None, 
              out=None, 
              dtype=None, 
              layout=torch.strided, 
              device=None, 
              requires_grad=False) 
    

    기능: 단위 대각 행렬 만들기(2차원 장량) 주의사항: 기본적으로 방진
  • n: 행렬 행수
  • m: 매트릭스 열수
  • t1 = torch.eye(3)
    t2 = torch.eye(3, 5)
    print(t1)
    print(t2)
    
    tensor([[1., 0., 0.],
            [0., 1., 0.],
            [0., 0., 1.]])
    tensor([[1., 0., 0., 0., 0.],
            [0., 1., 0., 0., 0.],
            [0., 0., 1., 0., 0.]])
    

    확률 분포에 따라 장량 생성


    torch.normal()

    torch.normal(mean, 
                 std, 
                 size, 
                 out=None)
    

    기능: 주어진 매개 변수의 이산 정적 분포(고스 분포)에서 무작위 수를 추출하여 장량 만들기
    주의사항: 모두 네 가지 모드가 있는데, 2와 3은broadcast 메커니즘을 응용하여 표량을 동형 장량으로 확장한다.
  • mean은 표량,std는 표량
  • mean은 표량,std는 장량
  • mean은 장량,std는 표량
  • mean은 장량,std는 장량
  • mean: 평균치
  • std: 표준차
  • size:mean과 std가 모두 표량일 때만 사용하며 창설 장량의 모양
  • 을 표시합니다
    # mean ,std 
    t1 = torch.normal(0, 1, (4,))
    print(t1, "
    "
    ) # mean ,std , mean std , mean = torch.arange(1, 5, dtype=torch.float) std = torch.arange(1, 5, dtype=torch.float) t = torch.normal(mean, std) print("mean:{}
    std:{}
    {}"
    .format(mean, std, t))
    tensor([-0.0209,  1.2597, -0.7261,  0.8786]) 
    
    mean:tensor([1., 2., 3., 4.])
    std:tensor([1., 2., 3., 4.])
    tensor([ 0.0653,  3.8435, -2.2774,  8.5908])
    

    torch.randn () 및 torch.randn_like()

    torch.randn(size, 
                out=None, 
                dtype=None, 
                layout=torch.strided, 
                device=None, 
                requires_grad=False)
    
    torch.randn_like(input, 
                     dtype=None, 
                     layout=None, 
                     device=None, 
                     requires_grad=False)
    

    기능: 표준 정적 분포(균일치 0, 표준 차이 1)에서 무작위 수를 추출하여 장량 만들기

    torch.rand () 및 torch.rand_like()

     torch.rand(size, 
                out=None, 
                dtype=None, 
                layout=torch.strided, 
                device=None, 
                requires_grad=False) 
    
    torch.rand_like(input,
    			    dtype=None, 
                    layout=torch.strided, 
                	device=None, 
                	requires_grad=False) 
    

    기능: [0,1)의 고른 분포에서 무작위 수를 추출하여 장량 만들기

    torch.randint () 및 torch.randint_like()

    torch.randint(low=0, 
                  high, 
                  size, 
                  out=None, 
                  dtype=None, 
                  layout=torch.strided, 
                  device=None, 
                  requires_grad=False)
    
    torch.randint_like(input,
    				   dtype=None, 
                  	   layout=torch.strided, 
                       device=None, 
                       requires_grad=False)
    

    기능:[low,high)의 정수에서 무작위 수를 추출하여 장량 만들기

    torch.randperm()

     torch.randperm(n, 
                    out=None, 
                    dtype=torch.int64, 
                    layout=torch.strided, 
                    device=None, 
                    requires_grad=False)
    

    기능: 0에서 n-1까지의 무작위 배열을 생성하여 난잡한 색인을 생성할 수 있습니다
  • n: 장량의 길이
  • torch.bernoulli()

    torch.bernoulli(input, 
                    generator=None, 
                    out=None)
    

    기능: 베누리 분포에서 이원 랜덤수(0 또는 1)를 추출하고 입력 중의 모든 값은 [0, 1] 구간에 있어야 하며 출력 장량의 i번째 원소값은 입력 장량의 i번째 확률값에 따라 1과 같다.
  • input: 확률치
  • t1 = torch.rand((4,))
    t = torch.bernoulli(t1)
    print(t1)
    print(t)
    
    tensor([0.5793, 0.7866, 0.6888, 0.2221])
    tensor([0., 1., 0., 0.])
    

    초기화되지 않은 크기 만들기


    torch.empty()

    torch.empty(size, 
                out=None, 
                dtype=None, 
                layout=torch.strided, 
                device=None, 
                requires_grad=False)
    

    기능: 초기화되지 않은 수치의 tensor를 만듭니다. tensor의 크기는size에 의해 결정됩니다
    t1 = torch.tensor([1, 2, 3])
    print(t1)
    t2 = torch.empty(size=[2, 3], out=t1)
    print(t2)
    
    tensor([1, 2, 3])
    tensor([[                1,                 2,                 3],
            [30962681235898419, 31525592536121462, 32088624093986937]])
    

    설명: t2와 t1이 메모리 주소를 공유하는데 t2가 초기화되지 않았기 때문에 표시되는 앞의 3개 요소는 t1의 값이고 뒤의 요소는 부호화입니다.t2가 초기화되면 인쇄 t1과 t2는 t2의 값을 표시합니다.

    좋은 웹페이지 즐겨찾기