본문 바로가기
Python

[DL] Tensor 객체의 attributes: ndim, shape, dtype

by ds31x 2024. 3. 15.

Python에서

Tensor 를 추상화하는 대표적인 class는 다음과 같음.

  • numpy의 ndarray
  • pytorch의 tensor
  • tensorflow의 constant

이들의 대표적인 attributes는 다음과 같음.

  • dtype: the datatype of element
  • ndim: the number of dimension (차원의 수로, rank라고도 불림)
  • shape: ndim의 객수로 구성된 sequencty type의 인스턴스로 각 축의 크기를 나타냄.

다음은 Tensorflow에서는 지원하지 않으나, torch와 numpy에선 지원하는 것들임.

  • itemsize: element 하나가 차지하는 bytes 크기.
  • size or size(): numpy는 그냥 attribute로, pytorch에선 method로 전체 element의 수를 반환.

예제

t = (1,2,3,4,5,6)
a = np.array(t)

print(a.ndim)
print(a.shape)
print(a.itemsize) #bytes
print(a.size)
print(a.dtype)

tensor = tf.constant(t)
print(tf.rank(tensor))
print(tensor.ndim)
print(tensor.shape)
# print(tensor.itemsize)  #error. not supported
# print(tensor.size)      #error. not supported
print(tensor.dtype)

p = torch.tensor(t)
print(p.ndim)
print(p.shape)
print(p.itemsize)
print(p.size())    # not attribute but method
print(p.dtype)
728x90