ค่าคงที่และตัวแปร

TensorFlow เบื้องต้นใน Python

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

TensorFlow คืออะไร?

  • ไลบรารีโอเพนซอร์สสำหรับการคำนวณเชิงตัวเลขแบบกราฟ
    • พัฒนาโดย Google Brain Team
  • API ระดับต่ำและระดับสูง
    • การบวก การคูณ การหาอนุพันธ์
    • โมเดล machine learning
  • การเปลี่ยนแปลงสำคัญใน TensorFlow 2.0
    • Eager execution เป็นค่าเริ่มต้น
    • สร้างโมเดลด้วย Keras และ Estimators
TensorFlow เบื้องต้นใน Python

tensor คืออะไร?

  • การขยายแนวคิดของเวกเตอร์และเมทริกซ์
  • ชุดของตัวเลข
  • มีรูปร่าง (shape) ที่กำหนดไว้
TensorFlow เบื้องต้นใน Python

tensor คืออะไร?

ภาพแสดงขนมปังแผ่นเดียว ขนมปังที่แบ่งเป็น 9 ชิ้น และก้อนขนมปังทั้งก้อน Source: Public Domain Vectors

TensorFlow เบื้องต้นใน Python

การกำหนด tensor ใน TensorFlow

import tensorflow as tf

# 0D Tensor
d0 = tf.ones((1,))
# 1D Tensor
d1 = tf.ones((2,))
# 2D Tensor
d2 = tf.ones((2, 2))
# 3D Tensor
d3 = tf.ones((2, 2, 2))
TensorFlow เบื้องต้นใน Python

การกำหนด tensor ใน TensorFlow

# Print the 3D tensor
print(d3.numpy())
[[[1. 1.]
  [1. 1.]]

 [[1. 1.]
  [1. 1.]]]
TensorFlow เบื้องต้นใน Python

การกำหนดค่าคงที่ใน TensorFlow

  • ค่าคงที่คือ tensor ประเภทพื้นฐานที่สุด
    • ไม่สามารถฝึก (train) ได้
    • กำหนดได้ทุกมิติ
from tensorflow import constant

# Define a 2x3 constant.
a = constant(3, shape=[2, 3])
# Define a 2x2 constant.
b = constant([1, 2, 3, 4], shape=[2, 2])
TensorFlow เบื้องต้นใน Python

ฟังก์ชันสำเร็จรูปสำหรับกำหนดค่าคงที่

การดำเนินการ ตัวอย่าง
tf.constant() constant([1, 2, 3])
tf.zeros() zeros([2, 2])
tf.zeros_like() zeros_like(input_tensor)
tf.ones() ones([2, 2])
tf.ones_like() ones_like(input_tensor)
tf.fill() fill([3, 3], 7)
TensorFlow เบื้องต้นใน Python

การกำหนดและกำหนดค่าเริ่มต้นให้ตัวแปร

import tensorflow as tf

# Define a variable
a0 = tf.Variable([1, 2, 3, 4, 5, 6], dtype=tf.float32)
a1 = tf.Variable([1, 2, 3, 4, 5, 6], dtype=tf.int16)
# Define a constant
b = tf.constant(2, tf.float32)
# Compute their product
c0 = tf.multiply(a0, b)
c1 = a0*b
TensorFlow เบื้องต้นใน Python

มาฝึกกันเถอะ!

TensorFlow เบื้องต้นใน Python

Preparing Video For Download...