Intro TensorFlow 2.0

Perbedaan yang jelas antara TensorFlow 2.0 dengan versi sebelumnya adalah kemudahan mengakses variables dan constant.

Pada TensorFlow 2.0, tidak diperlukan session untuk mengakses constant dan variables. Sangat mudah memanipulasi data tensor baik menggunakan operasi aritmetik atau numpy function.

import tensorflow as tf
import numpy as np

tf2_const = tf.constant([[1, 2], [3, 4]])

TensorFlow Constant

tf2_const
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[1, 2],
       [3, 4]], dtype=int32)>
tf2_const.shape
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
TensorShape([2, 2])
#mengakses nilai constant tidak memerlukan session.
tf2_const.numpy()
array([[1, 2],
       [3, 4]], dtype=int32)
#inisialisasi constant dari numpy array
numpy_tensor = np.array([[20,  4], [10, 6]])
tf2_const_numpy = tf.constant(numpy_tensor)

tf2_const_numpy
<tf.Tensor: shape=(2, 2), dtype=int64, numpy=
array([[20,  4],
       [10,  6]])>

TensorFlow Variables

tf2_var = tf.Variable([[1., 2., 3.], [4., 5., 6.]])
tf2_var
<tf.Variable 'Variable:0' shape=(2, 3) dtype=float32, numpy=
array([[1., 2., 3.],
       [4., 5., 6.]], dtype=float32)>
#mengambil nilai variable menggunakan numpy
tf2_var.numpy()
array([[1., 2., 3.],
       [4., 5., 6.]], dtype=float32)
tf2_var[0, 2].assign(100)
tf2_var
<tf.Variable 'Variable:0' shape=(2, 3) dtype=float32, numpy=
array([[  1.,   2., 100.],
       [  4.,   5.,   6.]], dtype=float32)>

Operasi Tensor

tensor_const = tf.constant([[1, 2], [3, 4]])
tensor_const
<tf
tensor_const = tf.constant([[1, 2], [3, 4]])
tensor_const
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[1, 2],
       [3, 4]], dtype=int32)>
#operasi tambah tensor dengan skalar
tensor_const + 2
<tf
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[3, 4],
       [5, 6]], dtype=int32)>
#operasi perkalian tensor dengan skalar
tensor_const * 3
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[ 3,  6],
       [ 9, 12]], dtype=int32)>
#menggunakan fungsi numpy
np.square(tensor_const)
np.sqrt(tensor_const)
np.dot(tensor_const, tf2_const)
array([[ 7, 10],
       [15, 22]], dtype=int32)

TensorFlow String

tf_string = tf.constant("TensorFlow")
tf_string
array([[ 7, 10],
<tf.Tensor: shape=(), dtype=string, numpy=b'TensorFlow'>
#fungsi string length
tf.strings.length(tf_string)
<tf.Tensor: shape=(), dtype=int32, numpy=10>
#fungsi string decode
tf.strings.unicode_decode(tf_string, "UTF8")
<tf.Tensor: shape=(10,), dtype=int32, numpy=array([ 84, 101, 110, 115, 111, 114,  70, 108, 111, 119], dtype=int32)>
tf_string_array = tf.constant(["TensorFlow", "Deep Learning", "AI"])

#iterasi TensorFlow string array
for string in tf_string_array:
  print(string)
tf.Tensor(b'TensorFlow', shape=(), dtype=string)
tf.Tensor(b'Deep Learning', shape=(), dtype=string)
tf.Tensor(b'AI', shape=(), dtype=string)

File colab dapat diakses di https://colab.research.google.com/drive/1aDLz-CauTC_yZkYwcfSnvAFAshpaTGXD?usp=sharing

Sharing is caring:

Leave a Comment