본문 바로가기
목차
Python

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

by ds31x 2024. 3. 15.
728x90
반응형

Tensor를 추상화하는 Class들

Python에서

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

  • NumPy의 ndarray: numpy.array
  • PyTorch의 torch.Tensor : torch.tensor()로 생성.
  • Tensorflow의 tf.Tensor : tf.constant(), tf.convert_to_tensor(), tf.Variable 등으로 생성.

https://dsaint31.tistory.com/891

 

[ML] Tensor: Scalar, Vector, Matrix.

Tensor 종류1. Scalar (0차원 tensor)하나의 숫자로 표현되는 가장 기본적인 형태.크기(magnitude)만을 가지며 방향은 없음.예시: 온도(25°C), 나이(20), 가격(1000원)# 파이썬/NumPy에서의 표현scalar = 5.02. Vector (

dsaint31.tistory.com


대표 Attributes

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

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

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

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

예제

import numpy as np
import tensorflow as tf
import torch

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

# ---------------------
# NumPy ndarray
# ---------------------
print(a.ndim)       # 배열의 차원(rank). 여기서는 1D → 출력: 1
print(a.shape)      # 배열의 형태(shape). (6,)
print(a.itemsize)   # 각 element가 차지하는 byte 수. int64이면 일반적으로 8 bytes
print(a.size)       # 전체 element의 개수. 6
print(a.dtype)      # 배열의 데이터 타입. 기본적으로 int64 (플랫폼마다 다름)

# ---------------------
# TensorFlow Tensor
# ---------------------
tensor = tf.constant(t)

print(tf.rank(tensor))   # 텐서의 rank(차원 수). 1D → 출력: 1 (TensorFlow op)
print(tensor.ndim)       # 파이썬 property로 제공되는 텐서의 rank. 동일하게 1
print(tensor.shape)      # 텐서의 shape. (6,)
# TensorFlow의 tf.Tensor는 NumPy처럼 itemsize/size 제공하지 않음
# print(tensor.itemsize)  # 지원되지 않음 → AttributeError
# print(tensor.size)      # 지원되지 않음 → AttributeError
print(tensor.dtype)      # 텐서의 dtype. 기본적으로 int32 (TensorFlow는 기본 정수가 int32)

# ---------------------
# PyTorch Tensor
# ---------------------
p = torch.tensor(t)

print(p.ndim)        # 텐서의 차원 수(rank). 1D → 출력: 1
print(p.shape)       # 텐서의 shape. torch.Size([6])
print(p.itemsize)    # 각 element의 byte 수. PyTorch int64 기본 → 8 bytes
print(p.size())      # 전체 element 개수 반환하는 메서드. tensor.size() → 6
print(p.dtype)       # 텐서의 dtype. PyTorch는 기본 정수가 int64

https://gist.github.com/dsaint31x/0ae43fbd9979f93d1a20b83e0198c4d0

 

dl_tensor_attributes.ipynb

dl_tensor_attributes.ipynb. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com


같이 보면 좋은 자료들

2025.03.13 - [Python] - [PyTorch] tensor 생성 및 초기화, 기본 조작

 

[PyTorch] tensor 생성 및 초기화, 기본 조작

NumPy에 대한 것은 다음을 참고:2024.09.09 - [Python] - [NumPy] 생성 및 초기화, 기본 조작 (1) [NumPy] 생성 및 초기화, 기본 조작 (1)1. ndarray 생성하기 (=tensor생성하기)np.array ( seq [,dtype])list 나 tuple 등의 sequen

ds31x.tistory.com

 

728x90