6.图和会话

import tensorflow as tf

# 之前也说过,直接打印,只能得到状态,是得不到值的
c = tf.constant([[1,2],[2,3]],name='const_1',dtype=tf.int64)
print(c)  # Tensor("const_1:0", shape=(2, 2), dtype=int64)

# 必须创建会话,然后执行
with tf.Session() as sess:
    print(sess.run(c))
    '''
    [[1 2]
    [2 3]]
    '''

# 之前说过,tensor和operation组成graph,交给session执行
# 在这里我们并没有显式地创建graph,为什么可以执行呢?
# 因为TensorFlow默认帮我们创建一张图,可以通过tf.get_default_graph()查看
print(c.graph is tf.get_default_graph())  # True
const1 = tf.constant([[2, 2]])
const2 = tf.constant([[4], [4]])

# matmul -->matrix,multiple,矩阵间的相乘,相当于np.dot()
multiple = tf.matmul(const1, const2)
print(multiple)  # Tensor("MatMul:0", shape=(1, 1), dtype=int32)

with tf.Session() as sess:
    print(sess.run(multiple))  # [[16]]

  

猜你喜欢

转载自www.cnblogs.com/traditional/p/9339386.html