"Torch"의 두 판 사이의 차이

ph
이동: 둘러보기, 검색
잔글 (→‎storage)
71번째 줄: 71번째 줄:
 
  0  1  0  0
 
  0  1  0  0
 
[torch.ByteTensor of size 5x4] </pre>
 
[torch.ByteTensor of size 5x4] </pre>
 +
===slicing===
 +
<pre>x = torch.Tensor(5, 6):zero()
 +
x[{ 1,3 }] = 1 -- sets element at (i=1,j=3) to 1
 +
x[{ 2,{2,4} }] = 2  -- sets a slice of 3 elements to 2
 +
x[{ {},4 }] = -1 -- sets the full 4th column to -1
 +
x[{ {},2 }] = torch.range(1,5) -- copy a 1D tensor to a slice of x
 +
x[torch.lt(x,0)] = -2 -- sets all negative elements to -2 via a mask
 +
--final result
 +
> x
 +
0  1  1 -2  0  0
 +
0  2  2 -2  0  0
 +
0  3  0 -2  0  0
 +
0  4  0 -2  0  0
 +
0  5  0 -2  0  0
 +
[torch.DoubleTensor of dimension 5x6]</pre>

2017년 7월 12일 (수) 17:41 판

links

iTorch

https://github.com/facebook/iTorch
ipython같이 쓸 수 있음.

etc

storage

Tensor is a particular way of viewing a Storage. storage로 접근하면 내부 배열에 순차적으로 접근 가능. matlab에서 2차원 이상 배열을 1차원배열 index로 접근하는 것과 동일.

x = torch.Tensor(4,5)
s = x:storage()
for i=1,s:size() do -- fill up the Storage
  s[i] = i
end

apply

x:apply(function(x)
  return x
end)

narrow, sub

:narrow(dim, offset, length)

행렬의 slice를 가져옴. dim=1은 row, 2는 column, 3이상도 가능.(row가 먼저임에 주의. torch 자체가 MATLAB과는 달리 항상 row먼저. 예를들어 1 2 3 4 5 6벡터를 (2,3)으로 reshape하면 첫 행이 1,2,3이 된다.) 이래서 torch가 안되는거야
offset=1이면 첫줄부터 가져옴. 즉 start index라고 보면 된다.
length는 해당 dimension의 vector몇개를 가져올지 지정. 즉 length=3이라고 해서 숫자 세개가 오는 것이 아니다. 5\(\times\)4 행렬에서 narrow(1,3,2)하면, 다음 색칠한 두줄을 반환한다. sub(3,4)[1]와 같다. (sub는 index에 -1을 허용한다. bound를 뜻함). 직관적인 sub권장

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

초기화

x = torch.Tensor(5):zero()
x = torch.Tensor(5):fill(1)
x:zero()
-- creates a storage with 10 elements
s = torch.Storage(10):fill(1)
torch.Tensor({{1,2,3,4}, {5,6,7,8}})

contiguous

메모리상에서 연속이면 그 자체를 반환하고 아니면 clone해서 준다.
x:isContiguous()로 알아볼 수도 있음.

type

th> torch.Tensor():type()
torch.DoubleTensor
-- type casting
y = x:type('torch.IntTensor')
-- is equivalent to calling int()
> x:int()

Querying the size and structure

x:nDimension()
x:dim() -- same as above
x:size()
x:size(2) -- gets the number of columns

Querying elements

> x[2][3] -- returns row 2, column 3
> x[{2,3}] -- another way to return row 2, column 3
> x[torch.le(x,3)] -- torch.le returns a ByteTensor that acts as a mask
> torch.le(x,3)
 1  0  0  1
 1  0  1  0
 1  1  1  0
 1  0  0  0
 0  1  0  0
[torch.ByteTensor of size 5x4] 

slicing

x = torch.Tensor(5, 6):zero()
x[{ 1,3 }] = 1 -- sets element at (i=1,j=3) to 1
x[{ 2,{2,4} }] = 2  -- sets a slice of 3 elements to 2
x[{ {},4 }] = -1 -- sets the full 4th column to -1
x[{ {},2 }] = torch.range(1,5) -- copy a 1D tensor to a slice of x
x[torch.lt(x,0)] = -2 -- sets all negative elements to -2 via a mask
--final result
> x
 0  1  1 -2  0  0
 0  2  2 -2  0  0
 0  3  0 -2  0  0
 0  4  0 -2  0  0
 0  5  0 -2  0  0
[torch.DoubleTensor of dimension 5x6]