Tensorflow初识


1. 初识tensorflow

  • tensorflow中需要明白的几点:
    • 使用tensor表示数据
    • 使用图来表示计算任务
    • 在会话中执行图

  • tensorflow中的程序分成了构建阶段和执行阶段,构建阶段,在图中定义OP。执行阶段,在会话中执行图中的OP。
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
node1 = tf.constant(3.9)
node2 = tf.constant(4.0)print(node1, node2)
print(node1, node2)

并没有显示node1和node2的值,输出的结果为

Tensor("Const_2:0", shape=(), dtype=float32) 
Tensor("Const_3:0", shape=(), dtype=float32)

Tensorflow Python库中有一个默认的图,op构造器可以为图中添加节点。

matrix1 = tf.constant([[3, 3]])
matrix2 = tf.constant([[2],[2]])
c = tf.matmul(matrix1, matrix2)
print(tf.get_default_graph(), matrix1.graph, matrix2.graph)

输出结果为:


  

在会话中启动图

创建一个Session()对象,调用Session的run()方法来执行图中的op

sess = tf.Session()
result = sess.run(c)
print(result)
sess.close()

输出的结果为,两个矩阵相乘的结果:

[[12]]

feed操作

  • 在程序执行的时候,不确定输入的是什么,提前“占个坑”。比如,在训练神经网络的时,具体的权重参数不确定,就可以用feed操作。
  • 标记方法:tf.placeholder()
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.add(input1, input2)
with tf.Session() as sess:
    print(sess.run([output], feed_dict={input1:10.0, input2:20.0}))

输出结果为:

[30.0]

tensorflow实现一个加法

# 定义tensor
a = tf.constant(5.0)
b = tf.constant(6.0)
sum1 = tf.add(a, b)
# 开启上下文管理器,避免了关闭sess.close()的操作
with tf.Session() as sess:
    print(sess.run(sum1))

你可能感兴趣的:(Tensorflow初识)