import tensorflow as tf x = tf.constant(100, name='x') y = tf.Variable(x + 50, name='y') print(y)
<tf.Variable 'y:0' shape=() dtype=int32_ref>
init_node = tf.global_variables_initializer() with tf.Session() as session: session.run(init_node) print(session.run(y))
150
data = np.random.normal(loc=10.0, scale=2.0, size=[3,3]) # mean 10, std dev 2 print(data)
[[ 8.4245312 10.74940182 14.22705451]
[ 9.76979594 9.03838597 10.29252576]
[ 10.60165571 12.10778192 6.57955182]]
# all nodes get added to default graph (unless we specify otherwise) # we can reset the default graph -- so it's not cluttered up: tf.reset_default_graph() x = tf.constant(data, name='x') y = tf.Variable(x * 10, name='y') init_node = tf.global_variables_initializer() with tf.Session() as session: session.run(init_node) print(session.run(y))
[[ 84.245312 107.49401822 142.27054512]
[ 97.69795937 90.38385973 102.92525764]
[ 106.01655709 121.07781918 65.79551821]]
with tf.Session() as session: for i in range(3): x = x + 1 print(session.run(x)) print("----------------------------------------------")
[[ 9.4245312 11.74940182 15.22705451]
[ 10.76979594 10.03838597 11.29252576]
[ 11.60165571 13.10778192 7.57955182]]
----------------------------------------------
[[ 10.4245312 12.74940182 16.22705451]
[ 11.76979594 11.03838597 12.29252576]
[ 12.60165571 14.10778192 8.57955182]]
----------------------------------------------
[[ 11.4245312 13.74940182 17.22705451]
[ 12.76979594 12.03838597 13.29252576]
[ 13.60165571 15.10778192 9.57955182]]
----------------------------------------------
x = tf.placeholder("float") y = tf.placeholder("float") m = tf.Variable([1.0], name="m-slope-coefficient") # initial values ... for now they don't matter much b = tf.Variable([1.0], name="b-intercept") y_model = tf.multiply(x, m) + b error = tf.square(y - y_model) train_op = tf.train.GradientDescentOptimizer(0.01).minimize(error) model = tf.global_variables_initializer() with tf.Session() as session: session.run(model) for i in range(10): x_value = np.random.rand() y_value = x_value * 2 + 6 # we know these params, but we're making TF learn them session.run(train_op, feed_dict={x: x_value, y: y_value}) out = session.run([m, b]) print(out) print("Model: {r:.3f}x + {s:.3f}".format(r=out[0][0], s=out[1][0]))
[array([ 1.41145968], dtype=float32), array([ 1.97268069], dtype=float32)]
Model: 1.411x + 1.973
SDS-2.2, Scalable Data Science
This is used in a non-profit educational setting with kind permission of Adam Breindel. This is not licensed by Adam for use in a for-profit setting. Please contact Adam directly at
adbreind@gmail.com
to request or report such use cases or abuses. A few minor modifications and additional mathematical statistical pointers have been added by Raazesh Sainudiin when teaching PhD students in Uppsala University.Last refresh: Never