[深度学习笔记]TensorFlow-操作

版权声明:未经博主允许不得转载(https://github.com/ai-word) https://blog.csdn.net/BaiHuaXiu123/article/details/89162986

导入 tensorflow:

import tensorflow as tf

创建两个常量 op:

m1 = tf.constant([[3, 3]])
m2 = tf.constant([[2], [3]])

创建一个矩阵乘法 op,把 m1 和 m2 传入:

product = tf.matmul(m1, m2)
print(product)

打印 product 结果如下:

Tensor("MatMul:0", shape=(1, 1), dtype=int32)

可见,直接运行 tenserflow 中常量算术操作的得到的结果是一个张量。

接下来创建一个会话,启动默认图:

sess = tf.Session()

调用 sess 的 run 方法来执行矩阵乘法 op,run(product)触发了图中 3 个 op:

result = sess.run(product)
print(result)
sess.close()

打印结果如下:

[[15]]

可见,真正要进行运算还需要使用会话操作。

PS:Session 最后需要关闭 sess.close(),以释放相关的资源。当然也可以使用with模块,session 在with模块中自动会关闭:

with tf.Session() as sess:
    result = sess.run(product)
    print(result)

同样的打印结果如下:

[[15]]

资源下载
资源下载
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/BaiHuaXiu123/article/details/89162986