常量与会话
import tensorflow as tf
a = tf.constant([1.0, 2.0], name="a")
b = tf.constant([2.0, 3.0], name="b")
print(a)
print(b)
result = a + b
print(result)
sess = tf.Session()
r = sess.run(result)
print(r, "\n", type(r))
sess.close()
with tf.Session() as sess:
print(sess.run(result * 2))
变量与正向传播
"""
变量的使用 与正向传播
"""
import tensorflow as tf
x = tf.constant([[1, 3], [4, 6], [8, 6], [9, 3]], name="x", dtype=tf.float32)
w0 = tf.Variable(
tf.random_normal((2, 4), stddev=0.35, mean=0, seed=7, name="w0"), dtype=tf.float32)
w1 = tf.Variable(
tf.random_normal((4, 1), stddev=0.35, mean=0, seed=7, name="w1"), dtype=tf.float32)
l1 = tf.matmul(x, w0)
l2 = tf.matmul(l1, w1)
init_op = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init_op)
r = sess.run(l2)
print(r)
占位符
"""
占位符
"""
import tensorflow as tf
x = tf.placeholder(tf.float32, shape=(None, 2))
print(x)
w0 = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=tf.float32)
w1 = tf.constant([[2], [3], [2], [1]], dtype=tf.float32)
print(x.shape, w0.shape, w1.shape)
l1 = tf.matmul(x, w0)
out = tf.matmul(l1, w1)
with tf.Session() as sess:
r = sess.run(out, feed_dict={
x: [[5.0, 6.0]]})
print(r)
r = sess.run(out, feed_dict={
x: [[6.0, 5.0]]})
print(r)
r = sess.run(out, feed_dict={
x: [[6.0, 5.0], [5.0, 6.0]]})
print(r)