Tensorflow初识

2019-05-16  本文已影响0人  Daily_Note

1. 初识tensorflow

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)

输出结果为:

<tensorflow.python.framework.ops.Graph object at 0x0000000004B72748>
 <tensorflow.python.framework.ops.Graph object at 0x0000000004B72748> 
<tensorflow.python.framework.ops.Graph object at 0x0000000004B72748>

在会话中启动图

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

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

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

[[12]]

feed操作

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))
上一篇 下一篇

猜你喜欢

热点阅读