Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

๐Ÿ“š The CoCalc Library - books, templates and other resources

132927 views
License: OTHER
1
""" Example to demonstrate the use of feed_dict
2
Author: Chip Huyen
3
Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"
4
cs20si.stanford.edu
5
"""
6
import os
7
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
8
9
import tensorflow as tf
10
11
# Example 1: feed_dict with placeholder
12
# create a placeholder of type float 32-bit, value is a vector of 3 elements
13
a = tf.placeholder(tf.float32, shape=[3])
14
15
# create a constant of type float 32-bit, value is a vector of 3 elements
16
b = tf.constant([5, 5, 5], tf.float32)
17
18
# use the placeholder as you would a constant
19
c = a + b # short for tf.add(a, b)
20
21
with tf.Session() as sess:
22
# print(sess.run(c)) # InvalidArgumentError because a doesnโ€™t have any value
23
24
# feed [1, 2, 3] to placeholder a via the dict {a: [1, 2, 3]}
25
# fetch value of c
26
print(sess.run(c, {a: [1, 2, 3]})) # >> [6. 7. 8.]
27
28
29
# Example 2: feed_dict with variables
30
a = tf.add(2, 5)
31
b = tf.multiply(a, 3)
32
33
with tf.Session() as sess:
34
# define a dictionary that says to replace the value of 'a' with 15
35
replace_dict = {a: 15}
36
37
# Run the session, passing in 'replace_dict' as the value to 'feed_dict'
38
print(sess.run(b, feed_dict=replace_dict)) # >> 45
39