PyTorch의 중량 생성 방법
25466 단어 PyTorch
장량의 개념
Tensor는 PyTorch의 기본 데이터 구조입니다.수학 개념에서 장량은 다차원 수조로 표량, 벡터, 행렬의 고차원 확장이다.
torch.Tensor의 속성:
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 만들기
torch.tensor(data,
dtype=None,
device=None,
requires_grad=False,
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장 만들기
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 장 만들기
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와 같은 용도로 사용합니다
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를 찾을 수 없습니다
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를 포함합니다
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를 포함합니다
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차원 장량) 주의사항: 기본적으로 방진
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
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까지의 무작위 배열을 생성하여 난잡한 색인을 생성할 수 있습니다
torch.bernoulli()
torch.bernoulli(input,
generator=None,
out=None)
기능: 베누리 분포에서 이원 랜덤수(0 또는 1)를 추출하고 입력 중의 모든 값은 [0, 1] 구간에 있어야 하며 출력 장량의 i번째 원소값은 입력 장량의 i번째 확률값에 따라 1과 같다.
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의 값을 표시합니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
IceVision에서 형식별 데이터를 읽는 방법2021년에 가장 멋있는 물체 검출 프레임워크라고 해도 과언이 아닌 IceVision을 사용해, VOC format과 COCO format의 데이터 세트에 대해 Object Detection을 간단하게 실시하기 위한...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.