Tensorflow는 머신러닝 및 딥러닝을 유용하게 수행할 수 있는 라이브러리이다. Numpy와 유사한 부분이 다수 존재한다.
Tensorflow는 구글이 개발한 머신러닝 및 딥러닝 프레임워크로, 대규모 연산과 신경망 모델 학습을 지원한다.
import tensorflow as tf
상수 텐서를 생성하는 방법을 설명한다.
상수 텐서: tf.constant(value, dtype=None, shape=None, name='Const')
tf.constant([1., 2., 3.])
# <tf.Tensor: shape=(3,), dtype=float32, numpy=array([1., 2., 3.], dtype=float32)>
0으로 채워진 텐서: tf.zeros(shape, dtype=tf.dtypes.float32, name=None, layout=None)
tf.zeros((3, 4))
# <tf.Tensor: shape=(3, 4), dtype=float32, numpy=
# array([[0., 0., 0., 0.],
# [0., 0., 0., 0.],
# [0., 0., 0., 0.]], dtype=float32)>
1로 채워진 텐서: tf.ones(shape, dtype=tf.dtypes.float32, name=None, layout=None)
tf.ones((2, 2))
# <tf.Tensor: shape=(2, 2), dtype=float32, numpy=
# array([[1., 1.],
# [1., 1.]], dtype=float32)>
정규분포 난수 텐서: tf.random.normal(shape, mean=0.0, stddev=1.0, dtype=tf.dtypes.float32, seed=None, name=None)
tf.random.normal((3, 3), mean=0.0, stddev=1.0)
# <tf.Tensor: shape=(3, 3), dtype=float32, numpy=
# array([[-0.97255796, -1.5671692 , 0.07179262],
# [-1.2181268 , 0.104133 , -2.20482 ],
# [-1.3041384 , -0.22525507, 0.39505556]], dtype=float32)>
균등분포 난수 텐서: tf.random.uniform(shape, minval=0, maxval=None, dtype=tf.dtypes.float32, seed=None, name=None)
tf.random.uniform((3, 3), minval=0, maxval=1)
# <tf.Tensor: shape=(3, 3), dtype=float32, numpy=
# array([[0.03841484, 0.8136203 , 0.20101428],
# [0.79671586, 0.87854755, 0.36359763],
# [0.69892585, 0.49602473, 0.3701707 ]], dtype=float32)>
범위 텐서 생성: tf.range(start, limit, delta=1, dtype=None)
tf.range(0, 10, 2)
# <tf.Tensor: shape=(5,), dtype=int32, numpy=array([0, 2, 4, 6, 8], dtype=int32)>
균등 간격 생성: tf.linspace(start, stop, num)
tf.linspace(-5, 5, 1000)
# <tf.Tensor: shape=(1000,), dtype=float64, numpy=
# array([-5. , -4.98998999, -4.97997998, -4.96996997, -4.95995996,
# ...
# 4.95995996, 4.96996997, 4.97997998, 4.98998999, 5. ])>
변수 텐서 생성: tf.Variable(initial_value=None, trainable=None, name=None, dtype=None, shape=None)
var = tf.Variable([0., 0., 0.])
# <tf.Variable 'Variable:0' shape=(3,) dtype=float32, numpy=array([0., 0., 0.], dtype=float32)>
값 할당: tf.Variable.assign(value, use_locking=False, name=None, read_value=True)
var.assign([1, 2, 3])
# <tf.Variable 'UnreadVariable' shape=(3,) dtype=float32, numpy=array([1., 2., 3.], dtype=float32)>
값 더하기: tf.Variable.assign_add(delta, use_locking=False, name=None, read_value=True)
var.assign_add([3, 3, 3])
# <tf.Variable 'UnreadVariable' shape=(3,) dtype=float32, numpy=array([4., 5., 6.], dtype=float32)>
값 빼기: tf.Variable.assign_sub(delta, use_locking=False, name=None, read_value=True)
var.assign_sub([4, 5, 6])
# <tf.Variable 'UnreadVariable' shape=(3,) dtype=float32, numpy=array([0., 0., 0.], dtype=float32)>