TensorFlow学习笔记:4、TensorFlow简单运算

向右看齐 2022-03-02 14:24 375阅读 0赞

文件 add.py

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import tensorflow as tf
  4. # 基本常量操作
  5. # 构造函数返回的值就是常量节点(Constant op)的输出.
  6. a = tf.constant(2)
  7. b = tf.constant(3)
  8. # 启动TensorFlow会话
  9. ss = tf.Session()
  10. # 运行
  11. print(ss.run(a+b))
  12. # 需要关闭Session
  13. ss.close()
  14. print("-----------------")
  15. # 使用变量(variable)作为计算图的输入
  16. # tensorflow里对于暂时不进行赋值的元素有一个称呼叫占位符
  17. a = tf.placeholder(tf.int16)
  18. b = tf.placeholder(tf.int16)
  19. # 定义一些操作
  20. add = tf.add(a, b)
  21. mul = tf.multiply(a, b)
  22. # 启动默认会话
  23. with tf.Session() as sess:
  24. # 把运行每一个操作,把变量输入进去
  25. # feed_dict就是用来赋值的,格式为字典型
  26. print("变量相加: %i" % sess.run(add, feed_dict={a: 2, b: 3}))
  27. print("变量相乘: %i" % sess.run(mul, feed_dict={a: 2, b: 3})) sess.close()

以上程序在Spyder中执行结果如下

  1. Python 3.7.1 | packaged by conda-forge | (default, Mar 13 2019, 13:32:59) [MSC v.1900 64 bit (AMD64)]
  2. Type "copyright", "credits" or "license" for more information.
  3. IPython 7.3.0 -- An enhanced Interactive Python.
  4. runfile('C:/Users/hadron/Downloads/tensorflow-multiply.py', wdir='C:/Users/hadron/Downloads')
  5. 5
  6. -----------------
  7. 变量相加: 5
  8. 变量相乘: 6

发表评论

表情:
评论列表 (有 0 条评论,375人围观)

还没有评论,来说两句吧...

相关阅读

    相关 TensorFlow:矩阵运算

    矩阵的加法和乘法,具体的算法在这里不做过多的展开,有需要的同学可以自行搜索一下线性代数相关的内容,这主要讲解矩阵在TensorFlow中的运算。 tf.matmul()