ซึ่งจะมีลักษณะการใช้งานหรือตัวอย่างการใช้งานดังต่อไปนี้
1. Constant การประกาศตัวแปลแบบค่าคงที ไม่สามารถเปลี่ยนแปลงค่าได้
โค้ด: เลือกทั้งหมด
tf.constant(value, dtype=None, shape=None, name='Const', verify_shape=False)
โค้ด: เลือกทั้งหมด
import tensorflow as tf
# create graph
a = tf.constant("hello world")
# launch the graph in a session
with tf.Session() as sess:
print(sess.run(a))
โค้ด: เลือกทั้งหมด
hello world
ตัวอย่างที่ 2 ประกาศตัวแปลเเบบ matrix
โค้ด: เลือกทั้งหมด
import tensorflow as tf
m = tf.constant([[1, 2], [3, 4]], name='matrix')
# launch the graph in a session
with tf.Session() as sess:
print(sess.run(m))
2.Variable สิ่งที่ใช้เพื่อเก็บข้อมูลเเละสามารถเปลี่ยนเเปลงค่าได้ ตัวแปลนี้ในระหว่าง Training model สามารถปรับปรุง สามารถเก็บค่ามาใช้งานภายหลังได้
ในการประกาศตัวแปลนี้ จะต้องมีการ initializer ก่อน
โค้ด: เลือกทั้งหมด
# Create a variable.
w = tf.Variable(<initial-value>, name=<optional-name>)
โค้ด: เลือกทั้งหมด
import tensorflow as tf
x = tf.Variable(35, name='x')
y = tf.Variable(x + 5, name='y')
model = tf.global_variables_initializer()
with tf.Session() as session:
session.run(model)
print(session.run(y))
โค้ด: เลือกทั้งหมด
40
หรือ
ผลลัพท์ ที่ได้
โค้ด: เลือกทั้งหมด
import tensorflow as tf
x = tf.Variable(35, name='x')
model_x = tf.variables_initializer([x])
y = tf.Variable(x + 5, name='y')
model_y = tf.variables_initializer([y])
with tf.Session() as session:
session.run(model_x)
session.run(model_y)
print(session.run(y))
โค้ด: เลือกทั้งหมด
40
ตัวอย่าง
โค้ด: เลือกทั้งหมด
import tensorflow as tf
# create graph
a = tf.get_variable(name="A", initializer=tf.constant(2))
b = tf.get_variable(name="B", initializer=tf.constant(3))
c = tf.add(a, b, name="Add")
# add an Op to initialize global variables
init_op = tf.global_variables_initializer()
# launch the graph in a session
with tf.Session() as sess:
# run the variable initializer operation
sess.run(init_op)
# now let's evaluate their value
print(sess.run(a))
print(sess.run(b))
print(sess.run(c))
โค้ด: เลือกทั้งหมด
2
3
5
ถ้าต้องการประกาศเเบบ matrix สามารถทำได้เเบบนี้
โค้ด: เลือกทั้งหมด
tf.zeros(
shape,
dtype=tf.dtypes.float32,
name=None
)
4.placeholder เป็นตัวที่สำคัญในการ input ค่าเพื่อ trainging model โดยมันจะ feed ใน ตัวแปล placeholder
โค้ด: เลือกทั้งหมด
import tensorflow as tf
a = tf.constant([5, 5, 5], tf.float32, name='A')
b = tf.placeholder(tf.float32, shape=[3], name='B')
c = tf.add(a, b, name="Add")
with tf.Session() as sess:
# create a dictionary:
d = {b: [1, 2, 3]}
# feed it to the placeholder
print(sess.run(c, feed_dict=d))
โค้ด: เลือกทั้งหมด
[6. 7. 8.]
อ้างอิง
-https://www.tensorflow.org/versions/r1. ... _variables
-https://www.tensorflow.org/versions/r1. ... s/constant
-https://www.datacamp.com/community/tuto ... low-python