#텐서 생성
import torch
print(torch.tensor([[1,2],[3,4]])) #2차원형태 텐서
print(torch.tensor([[1,2],[3,4]], device="cuda:0")) # gpu에 텐서 생성
print(torch.tensor([[1,2],[3,4]], dtype=torch.float64)) #dtype 을 이용하여 텐서 생성
tensor([[1, 2],
[3, 4]])
tensor([[1, 2],
[3, 4]], device='cuda:0')
tensor([[1., 2.],
[3., 4.]], dtype=torch.float64)
----
#텐서를 ndarray 로 변환
temp = torch.tensor([[1,2],[3,4]])
print(temp.numpy())
[[1 2]
[3 4]]
----
#gpu 상의 텐서를 cpu 의 텐서로 변환한 후 ndarray 로 변환
temp = torch.tensor([[1,2],[3,4]],device="cuda:0")
print(temp.to("cpu").numpy())
[[1 2]
[3 4]]
----
----
#tensor 의 인덱스 조작
# torch.FloatTensor : 32비트 부동 소수점
# torch.DoubleTensor : 64비트의 부동 소수점
# torch.LongTensor : 64비트의 부호가 있는 정수
temp = torch.FloatTensor([1,2,3,4,5,6,7]) #파이토치로 1차원벡터 생성
print(temp)
print(temp[0],temp[1],temp[-1])
print("---------")
print(temp[2:5],temp[4:-1])
tensor([1., 2., 3., 4., 5., 6., 7.])
tensor(1.) tensor(2.) tensor(7.)
---------
tensor([3., 4., 5.]) tensor([5., 6.])
----
#텐서의 차원 조작
# view 를 이용하는 것이 대표적 : 넘파이의 reshape 과 유사
# 텐서를 결함하는 cat, stack : 다른 길이의 텐서를 하나로 병합할때
# 차원을 교환하는 t, transpose 도 사용 : 행렬의 전치 외에도 차원의 순서를 변경할 때
temp = torch.tensor([[1,2],[3,4]]) # 2*2 행렬 생성
print(temp.shape)
print('---------------')
print(temp.view(4,1)) # 2*2 행렬을 4*1 로 변형
print('---------------')
print(temp.view(-1)) # 1차원 벡터로 변형
print('---------------')
print(temp.view(1,-1)) # -1 은 1*자동으로 라는 의미. 반대도 마찬가지이다. 여기서는 1*4가 된다.
torch.Size([2, 2])
---------------
tensor([[1],
[2],
[3],
[4]])
---------------
tensor([1, 2, 3, 4])
---------------
tensor([[1, 2, 3, 4]])

| Ubuntu 22.04에서 기본 터미널 프로그램을 Hyper로 변경하기 (0) | 2023.05.06 |
|---|---|
| CMake를 이용한 Eigen3과 OpenCV 라이브러리 포함하기 (0) | 2023.05.06 |
| Install Nvidia graphic driver, Cuda Toolkit & Cudnn in Ubuntu 22.04 (0) | 2023.05.04 |
| Anaconda 사용법 - 설치부터 가상환경 생성 및 제거까지 (1) | 2023.04.10 |
| 우분투 yolo v4 설치 및 실행 방법 (0) | 2022.05.18 |
댓글 영역