본문 바로가기
Python

[NumPy] 생성 및 초기화, 기본 조작 (1)

by ds31x 2024. 9. 9.

1. ndarray 생성하기 (=tensor생성하기)

np.array ( seq [,dtype])
  • listtuple 등의 sequence 객체로부터 ndarray 생성.
  • dtype : data type of element.
    • float64 : default type in the numpy. *
    • uint8 : unsigned int (8bit), the most commonly used for image processing
    • int8 : signed int (8bit)
    • float32 : float (32bit)

예제는 다음과 같음.

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

 

결과는

<class 'tuple'>
<class 'numpy.ndarray'>

 

https://ds31x.tistory.com/34

 

[Python] list (sequence type) : summary

list (Sequence Type) : Summary list는 ordered mutable collection으로, collection을 위한 python data type들 중 가장 많이 사용된다. C에서의 array와 같이 가장 기본적인 collection임. 단, heterogeneous item을 가질 수 있으며,

ds31x.tistory.com


2. ndarray의 대표적인 attributes

print(a.ndim)     # num of dimensions
print(a.shape)    # 각 축의 요소의 수를 가진 tuple반환.
print(a.itemsize) # 각 요소의 bytes 크기
print(a.size)     # 총 요소의 수.
print(a.dtype)    # 각 요소의 data type

 

결과는

1
(6,)
8
6
int64

3. 기본 dtype

numpy 의 경우, float64int64 가 기본적인 data type임.

  • tensorflow 의 경우, float32int32
  • torch 의 경우, float32int64

https://dsaint31.tistory.com/456

 

[Programming] Primitive Data Type : C, C++, NumPy, Torch

Primitive Data Type이(Unboxed type)란?C, C++, NumPy, Torch, TensorFlow 등에서 사용되는 numeric data type들은보통 unboxed type이라고도 불리는 primitive data type들이다.unboxed type에서는할당된 메모리 bit들이 해당 numeric

dsaint31.tistory.com

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

 

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

Python에서 Tensor 를 추상화하는 대표적인 class는 다음과 같음. numpy의 ndarray pytorch의 tensor tensorflow의 constant 이들의 대표적인 attributes는 다음과 같음. dtype: the datatype of element ndim: the number of dimension (

ds31x.tistory.com

 


4. Multi-dimensional Array

# nested lists result in multi-dimensional arrays
a = np.array([range(i, i + 3) for i in [2, 4, 6]])
print(a.ndim)
print(a.shape)
print(a.itemsize) #bytes
print(a.size)
print(a.dtype)
a

 

결과는

2
(3, 3)
8
9
int64
array([[2, 3, 4],
       [4, 5, 6],
       [6, 7, 8]])

5. ndarray를 특정 값으로 초기화하기

zeros,ones, and full (or fill: tf)

5.1 zeros: 0으로 초기화

a = np.zeros((3,2)) # default dtype = float64
# a = np.zeros(shape=(4,4),dtype=np.uint8)
print(a.dtype)
a

결과는

<dtype: 'float32'>
<tf.Tensor: shape=(3, 2), dtype=float32, numpy=
array([[0., 0.],
       [0., 0.],
       [0., 0.]], dtype=float32)>

5.2 ones: 1로 초기화

a = np.ones((4,2,3))
print(a.dtype)
a

 

결과는

float64
array([[[1., 1., 1.],
        [1., 1., 1.]],

       [[1., 1., 1.],
        [1., 1., 1.]],

       [[1., 1., 1.],
        [1., 1., 1.]],

       [[1., 1., 1.],
        [1., 1., 1.]]])

5.3 full: 특정값을 지정하여 초기화

a = np.full((1,3),255)
print(a.dtype)
a

결과는

int64
array([[255, 255, 255]])

6. 기존 ndarray객체와 shape를 같게 초기화.

  • 기존의 ndarray 와 같은 shape를 가지는 ndarray생성 (torchtensor도 유사.)
    • zeros_like, ones_like, and full_like
  • tf 의 경우는 다음과 같음.
    • zeors_like, ones_like, and fill

6.1 zeros_like

s = np.array([[1,2,3],[4,5,6]])
print(s.shape, a.dtype)

a = np.zeros_like(s)
print(a.shape, a.dtype)
a

 

결과는

(2, 3) int64
(2, 3) int64
array([[0, 0, 0],
       [0, 0, 0]])

6.2 ones_like

a = np.ones_like(s)
print(a.shape, a.dtype)
a

 

결과는

(2, 3) int64
array([[1, 1, 1],
       [1, 1, 1]])

6.3 full_like

a = np.full_like(s,3.0)
print(a.dtype)
a

 

결과는

int64
array([[3, 3, 3],
       [3, 3, 3]])

7. 기타

7.1 arange

range의 float 버전.

print(range(0,10,1)) # only integer
print(np.arange(0,1,0.1))

 

결과는

range(0, 10)
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]

 

 dtype도 지정가능.


7.2 linspace

step 대신 points 갯수

a = np.linspace(1,5,6)
print(a.dtype)
print(a)

 

결과는

float64
[1.  1.8 2.6 3.4 4.2 5. ]

7.3 Identity Matrix

a = np.eye(5)
print(a.dtype)
print(a)

 

결과는

float64
[[1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 1.]]
<dtype: 'float32'>

7.4 초기화 없이 생성.

a = np.empty((4,2))
print(a.dtype)
print(a)

 

결과는

float64
[[4.86489613e-310 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000]]

8. 난수로 구성된 ndarray

2024.03.29 - [Python] - [DL] Tensor: Random Tensor 만들기 (NumPy, PyTorch)

 

[DL] Tensor: Random Tensor 만들기 (NumPy, PyTorch)

Random value를 얻는데 이용되는 Probability Distribution에 따라 크게 2가지로 나눌 수 있음. Uniform Distribution Normal Distribution Uniform Distribution Random Variable이 가질 수 있는 값들이 모두 같은 확률을 가짐. int

ds31x.tistory.com


9. dtype이나 shape변경하기.

2024.03.15 - [Python] - [DL] Tensor: dtype 변경(casting) 및 shape 변경.

 

[DL] Tensor: dtype 변경(casting) 및 shape 변경.

Tensor를 추상화하고 있는 class로는 numpy.array: numpy의 ndarray torch.tensor tensorflow.constant: (or tensorflow.Variable) 이 있음. 이들은 Python의 sequence types과 달리 일반적으로 다음과 같은 특징을 지님. 데이터들

ds31x.tistory.com

2024.09.09 - [Python] - [NumPy] ravel() 메서드 with flatten

 

[NumPy] ravel() 메서드 with flatten

NumPy의 ndarray.ravel() 메서드는 다차원 배열을 1차원 배열로 평탄화(flatten)하는 데 사용됨.기본적으로 이 메서드는 원본 배열의 데이터에 대한 뷰(view)를 반환: 즉 복사본을 생성하지 않고 메모리를

ds31x.tistory.com


 

같이 보면 좋은 URLs

2024.03.18 - [Python] - [DL] Tensor: Indexing <Simple, Slicing, Fancy, Boolean Mask>

 

[DL] Tensor: Indexing <Simple, Slicing, Fancy, Boolean Mask>

numpy나 pytorch, tensorflow의 텐서들도 파이썬의 list 또는 tubple 에서의 indexing과 slicing이 거의 그대로 사용됨. 2023.07.12 - [Python] - [Python] list (sequence type) : summary [Python] list (sequence type) : summary list는 ordere

ds31x.tistory.com

2024.03.16 - [Python] - [DL] Tensor: Transpose and Permute

 

[DL] Tensor: Transpose and Permute

Transpose Transpose(전치)의 linear algebra에서의 정의는 다음과 같음. Given an m x n matrix A, the transpose of A is the n x m matrix, denoted by AT whose columns are formed from the corresponding rows of A. 간단하게 말하면 행과 열

ds31x.tistory.com

2024.03.19 - [Python] - [Tensor] vectorized op. (or universal func)

 

[Tensor] vectorized op. (or universal func)

Numpy에서 제공하는 ufunc. (Universal Functions)은 homogeneous and contiguous tensor 에서 모든 elements에 같은 연산을 적용하여 기존의 반복 loop에 기반한 연산에 비해 압도적인 속도를 보이면서 간편한 연산자

ds31x.tistory.com

 

728x90