您的位置:首页 > 其它

关于tensorflow的基本语法知识

2017-09-12 00:12 274 查看
最近开始学习tensorflow,那么在这里把我学习过程中的感受讲讲。

首先是tensorflow的基本操作

在这里我只贴上一小部分代码,附上中文的解释,我觉得了解这些之后再去看官方文档应该知道怎么入手了。

第一个当然是用tensorflow写的 hello world啦。。。

import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# 使用TensorFlow输出Hello

# 创建一个常量操作( Constant op )
# 这个 op 会被作为一个节点( node )添加到默认计算图上.
#
# 该构造函数返回的值就是常量节点(Constant op)的输出.
hello = tf.constant('Hello, TensorFlow!')

# 启动TensorFlow会话
sess = tf.Session()

# 运行 hello 节点
print(sess.run(hello))


'''
TensorFlow library 的基本操作.
'''
import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# 基本常量操作
# T构造函数返回的值就是常量节点(Constant op)的输出.
a = tf.constant(2)
b = tf.constant(3)

# 启动默认的计算图
with tf.Session() as sess:
print("a=2, b=3")
print("常量节点相加: %i" % sess.run(a+b))
print("常量节点相乘: %i" % sess.run(a*b))

# 使用变量(variable)作为计算图的输入
# 构造函数返回的值代表了Variable op的输出 (session运行的时候,为session提供输入)
# tf Graph input
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:
# 把运行每一个操作,把变量输入进去
print("变量相加: %i" % sess.run(add, feed_dict={a: 2, b: 3}))
print("变量相乘: %i" % sess.run(mul, feed_dict={a: 2, b: 3}))

# 矩阵相乘(Matrix Multiplication)
# 创建一个 Constant op ,产生 1x2 matrix.
# 该op会作为一个节点被加入到默认的计算图
# 构造器返回的值 代表了Constant op的输出
matrix1 = tf.constant([[3., 3.]])
# 创建另一个 Constant op 产生  2x1 矩阵.
matrix2 = tf.constant([[2.],[2.]])
# 创建一个 Matmul op 以 'matrix1' 和 'matrix2' 作为输入.
# 返回的值, 'product', 表达了矩阵相乘的结果
product = tf.matmul(matrix1, matrix2)
# 为了运行 matmul op 我们调用 session 的 'run()' 方法, 传入 'product'
# ‘product’表达了 matmul op的输出. 这表明我们想要取回(fetch back)matmul op的输出
# op 需要的所有输入都会由session自动运行. 某些过程可以自动并行执行
#
# 调用 'run(product)' 就会引起计算图上三个节点的执行:2个 constants 和一个 matmul.
# ‘product’op 的输出会返回到 'result':一个 numpy `ndarray` 对象.
with tf.Session() as sess:
result = sess.run(product)
print('矩阵相乘的结果:', result)
# ==> [[ 12.]]

#保存计算图
writer = tf.summary.FileWriter(logdir='logs', graph=tf.get_default_graph())
writer.flush()





当然更多的关于tensorflow的基本操作我就没写了,大家可以看看tensorflow官方教程里面关于基本操作的介绍

当然这里有一篇挺好博文:对于tensorflow入门基本知识讲的还是挺全的:http://blog.csdn.net/lenbow/article/details/52152766

好啦,关于tensorflow的基础知识就介绍到这里了,祝大家学习生活愉快。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  tensorflow入门