TensorFlow学习笔记:4、TensorFlow简单运算
文件 add.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tensorflow as tf
# 基本常量操作
# 构造函数返回的值就是常量节点(Constant op)的输出.
a = tf.constant(2)
b = tf.constant(3)
# 启动TensorFlow会话
ss = tf.Session()
# 运行
print(ss.run(a+b))
# 需要关闭Session
ss.close()
print("-----------------")
# 使用变量(variable)作为计算图的输入
# tensorflow里对于暂时不进行赋值的元素有一个称呼叫占位符
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)
# 定义一些操作
add = tf.add(a, b)
mul = tf.multiply(a, b)
# 启动默认会话
with tf.Session() as sess:
# 把运行每一个操作,把变量输入进去
# feed_dict就是用来赋值的,格式为字典型
print("变量相加: %i" % sess.run(add, feed_dict={a: 2, b: 3}))
print("变量相乘: %i" % sess.run(mul, feed_dict={a: 2, b: 3})) sess.close()
以上程序在Spyder中执行结果如下
Python 3.7.1 | packaged by conda-forge | (default, Mar 13 2019, 13:32:59) [MSC v.1900 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.
IPython 7.3.0 -- An enhanced Interactive Python.
runfile('C:/Users/hadron/Downloads/tensorflow-multiply.py', wdir='C:/Users/hadron/Downloads')
5
-----------------
变量相加: 5
变量相乘: 6
还没有评论,来说两句吧...