TensorFlow 的计算需要事先定义一个 computation graph(计算图),该图是一个抽象的结构,只有在评估(evaluate)时,才有数值解,这点和 numpy 不同。这张图由一组节点构成。
>> a = tf.ones((2, 2))
>> tf.reduce_sum(a, reduction_indices=1)
<tf.Tensor 'Sum_2:0' shape=(2,) dtype=float32>
>> tf.reduce_sum(a, reduction_indices=1).eval()
array([ 2., 2.], dtype=float32)
0. 一个计算图实例
relu = tf.nn.relu(tf.matmul(w, x) + b)
1. TensorFlow 的计算机制
TensorFlow 程序一般可划分为两个流程:
- construction phase,构建过程,会构建出一个图(graph),即所谓的计算图(computation graph)
- evaluation phase,执行过程,使用 session 执行构建过程中生成的图中的操作;
2. placeholders:数据的读入
tf.convert_to_tenso() 接口可将 numpy 下的多维数组转化为 tensor,但该函数接收的数据不可规模化。
tf.placeholder() 提供了向计算图(computation graph)读入数据的入口点。
feed_dict
关键字参数,类型为 Python 的字典类型,实现了 tf.placeholder() 变量向数据(numpy arrays)的映射。
>> input1 = tf.placeholder(tf.float32)
>> input2 = tf.placeholder(tf.float32)
>> output = tf.mul(input1, input2)
>> with tf.Session() as sess:
print(sess.run([output], feed_dict={input1: [7.], input2: [2.]}))
3. tf.Graph() 图对象下的成员
get_operations():
graph = tf.Graph() names = [op.name for op in model.graph.get_operations() if op.type=='Conv2D']
tensor = tf.get_default_graph().get_tensor_by_name(tensor_name)
- Get the tensor with this name.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步