← 보드GPU와 Colab · 5/8
GPU Tensor를 NumPy로 바꾸기
NumPy 배열은 CPU 메모리에만 있어요. GPU에 있는 Tensor를 바로 NumPy로 바꿀 수 없고, 먼저 CPU로 옮긴 뒤 바꿔요. 기울기를 추적 중인 Tensor(requires_grad=True)는 detach()로 추적을 끊고 바꿔요(Autograd 장에서 배워요).
| 목적 | 방법 |
|---|---|
| CPU → GPU | x = x.to('cuda') |
| GPU → CPU | x = x.to('cpu') |
| GPU Tensor → NumPy | x.to('cpu').numpy() (CPU로 먼저) |
| 기울기 추적 중인 Tensor → NumPy | x.detach().to('cpu').numpy() |
t = torch.randn(3, requires_grad=True)
print(t.detach().to('cpu').numpy().shape)
(3,)
기울기를 추적하는 Tensor에 detach() 없이 .numpy()를 하면 "requires grad인 Tensor에는 numpy()를 쓸 수 없고 detach().numpy()를 쓰라"는 에러가 나요.
시험엔 이렇게 써요 — 이렇게 고르세요
NumPy 배열은 CPU 메모리에만 저장되므로 GPU Tensor는 .to('cpu').numpy()로 CPU로 옮긴 뒤 변환한다. requires_grad=True인 Tensor는 detach()로 계산 그래프에서 분리한 뒤 변환한다. 순서는 "(필요하면 detach) → CPU → numpy"예요.
잠깐 확인 — GPU에 있는 Tensor g를 NumPy로 바꾸는 올바른 한 줄은?
g.to('cpu').numpy()예요. CPU로 먼저 옮겨야 해요.
다음 카드 → 내 컴퓨터에 GPU가 없다면 — Google Colab에서 GPU 켜기 ★
자료: 2주차(+1·3주차) · Week02_Tensor_and_GPU, 구글 Colab GPU 환경 사용법.pdf · 빅분01(1주차)·빅분02(2주차)·빅데이터03(3주차) 녹취