Load Packages
1 2
   | import numpy as np import tensorflow as tf
   | 
 
 Tensor 생성
list -> Tensor
1 2 3 4
   | tf.constant([1, 2, 3])
 
  <tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 2, 3])>
   | 
 
tuple -> Tensor
1 2 3 4 5 6
   | tf.constant(((1, 2, 3), (1, 2, 3)))
 
  <tf.Tensor: shape=(2, 3), dtype=int32, numpy= array([[1, 2, 3],        [1, 2, 3]])>
   | 
 
Array -> Tensor
1 2 3 4 5
   | arr = np.array([1, 2, 3]) tf.constant(arr)
 
  <tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 2, 3])>
   | 
 
 Tensor에 담긴 정보 확인
shape 확인
1 2 3 4 5
   | tensor = tf.constant(arr) tensor.shape
 
  TensorShape([3])
   | 
 
Data Type 확인
- 주의: Tensor를 생성 할 때 Data Type을 정해주지 않기 때문에 혼동이 올 수 있다.
 
- Data Type에 따라 모델의 무게나 성능 차이에 영향을 줄 수 있다.
 
Data Type 정의
1 2 3 4
   | tf.constant([1, 2, 3], dtype=tf.uint8)
 
  <tf.Tensor: shape=(3,), dtype=uint8, numpy=array([1, 2, 3], dtype=uint8)>
   | 
 
Data Type 변환
1 2 3 4
   | tf.cast(tensor, dtype=tf.uint8)
 
  <tf.Tensor: shape=(3,), dtype=uint8, numpy=array([1, 2, 3], dtype=uint8)>
   | 
 
Tensor에서 Numpy 불러오기
1 2 3 4
   | tensor.numpy()
 
  array([1, 2, 3])
   | 
 
Numpy로 변환된 것 확인
1 2 3 4
   | type(tensor.numpy())
 
  numpy.ndarray
   | 
 
 난수 생성
Numpy에서는 난수 생성 시 기본적으로 Normal Distribution을 생성한다.
- Normal Distribution은 중심 극한 이론에 의한 연속적인 모양
 
- Uniform Distribution은 중심 극한 이론과는 무관하며 불연속적이며 일정한 분포
 
Numpy에서 사용법
1 2 3 4 5
   | np.random.randn(9)
 
  array([ 0.53020669,  0.65508422, -0.59177912,  1.16459962, -1.05122869,         0.08080872,  0.17245994,  0.08721459, -0.69788519])
   | 
 
TensorFlow에서 사용법
1 2 3 4 5 6 7
   | tf.random.normal([3, 3])
 
  <tf.Tensor: shape=(3, 3), dtype=float32, numpy= array([[ 0.46394104, -0.8973731 , -0.1977468 ],        [-1.6685097 , -0.8181516 , -1.8963411 ],        [ 0.5654544 ,  0.13616897, -1.7370273 ]], dtype=float32)>
   | 
 
1 2 3 4 5 6 7
   | tf.random.uniform([3, 3])
 
  <tf.Tensor: shape=(3, 3), dtype=float32, numpy= array([[0.7996844 , 0.05048668, 0.7060809 ],        [0.9390234 , 0.29056323, 0.33341527],        [0.4387114 , 0.13688791, 0.12659645]], dtype=float32)>
   |