[torch for R] R에서 데이터프레임을 torch 텐서로 변환하는 방법

R 프로그래밍 문법이 더 익숙하다보니, pytorch 를 R로 한번 공부해보고 있다. 그 중, R 데이터프레임 자료형을 torch 텐서로의 변환하는 예시를 정리해본다.

Orange 데이터셋을 사용한다.

> Orange
   Tree  age circumference
1     1  118            30
2     1  484            58
3     1  664            87
4     1 1004           115
5     1 1231           120
6     1 1372           142
...

Orange 는 데이터프레임이고, class 함수로 확인 가능하다.

> Orange |> class()
[1] "nfnGroupedData" "nfGroupedData" 
[3] "groupedData"    "data.frame"    

단순히 torch_tensor로 변환이 되지 않는다.

> torch_tensor(Orange)
Error in torch_tensor(Orange) : could not find function "torch_tensor"

이유는, 데이터프레임(data.frame)형식으로는 변환이 되지 않기 때문인데, matrix 형식으로 변환해야 한다.

The problem here is the containing structure, the data.frame. We need to call as.matrix() on it first.

그런데, factor 컬럼이 존재하기 때문에, matrix 로 바로 변환하면 모두 string 으로 변환된다.

Due to the presence of the factor, though, this will result in a matrix of all strings, which is not what we want.

> as.matrix(Orange)
   Tree age    circumference
1  "1"  " 118" " 30"        
2  "1"  " 484" " 58"        
3  "1"  " 664" " 87"        
4  "1"  "1004" "115"        
5  "1"  "1231" "120"        
6  "1"  "1372" "142"   
...

그래서, factor 내부에 있는 정수형 인덱스를 추출해야 하고, 그 데이터로 변환해야 한다. dplyr::mutate 함수를 이용해서 변환했다.

Therefore, we first extract the underlying levels (integers) from the factor, and then convert the data.frame to a matrix.

> Orange |> 
  mutate(Tree = as.numeric(Tree)) |> 
  as.matrix()

   Tree  age circumference
1     2  118            30
2     2  484            58
3     2  664            87
4     2 1004           115
5     2 1231           120
6     2 1372           142
...
r  pytorch 

더 보면 좋을 글들