您好,欢迎来到锐游网。
搜索
您的当前位置:首页Tensorflow中Tensor和Graph的理解

Tensorflow中Tensor和Graph的理解

来源:锐游网

对Tensor的理解

wiki对Tensor的定义:

  • Tensor是用于描述向量、标量和其它Tensor之间线性关系的集合对象。线性关系的简单例子包括点乘、叉乘和线性映射。向量和标量本身也是Tensor。
Tensor和矩阵的区别:
矩阵是一种数据结构,可以在特定坐标系下表示Tensor。
Tensor是一类多重线性函数,处理一系列线性可分的向量变量。在预定义好Tensor的情况下,数据传入时就会开始实际运算。



对Graph的理解
一个运算图(computational graph)是用图节点描述的一系列TensorFlow操作

import tensorflow as tf
#简单的常数乘法 a = 2 b = 3 mul = a*b
print ("The multiplication produces:::", mul)
The multiplication produces::: 6
# 改写成Tensorflow的常量形式 at = tf.constant(3) bt = tf.constant(4)
mult = tf.mul(at, bt)
print ("The multiplication produces:::", mult)
The multiplication produces::: Tensor("Mul:0", shape=(), dtype=int32)
每个节点输入0或多个Tensor,输出1个Tensor。一类节点被称为常量节点,它没有输入,只输出它存储的常量。
上述运算中的at和bt在传至节点前必须被赋值,如果不赋值会出现TypeError

目前的graph包括at和bt两个Tensor以及mult运算。为了处理mult运算,运算图需要开启一个session:


print ("The actual multiplication result:::", sess.run(mult))
The actual multiplication result::: 12
除了常量constant,还可以用变量variables和占位符Placeholders来给图传值
变量存储于内存缓冲区中,它们必须被显性初始化并可以在训练中和训练后保存到硬盘中。一般在调用模型前用一个函数实现所有变量的初始化。
占位符描述的量一般不会再创建运算图时被赋值,而是在运算过程中得到其值
# Variable

var1 = tf.Variable(2, name="var1") var2
= tf.Variable(3, name="var2")
mulv = tf.mul(var1, var2)
print (mulv)

Tensor("Mul_2:0", shape=(), dtype=int32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) # always need to initialize the variable
print ("The variable var1 is:::", sess.run(var1))
print ("The variable var2 is:::", sess.run(var2))
print ("The computational result is:::", sess.run(mulv))

The variable var1 is::: 2
The variable var2 is::: 3
The computational result is::: 6

# Placeholder

pl = tf.placeholder(tf.float32, name="p")
pi = tf.constant(3.) c = tf.add(pl, pi)
print (c)

Tensor("Add_1:0", dtype=float32)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) # always need to initialize the var iables
writer = tf.train.SummaryWriter("output", sess.graph)
#print("The placeholder value passed:::", sess.run(pl, {pl:3}))
print("The calculation result is:::", sess.run(c, {pl:3}))
writer.close()
WARNING:tensorflow:From <ipython‐input‐15‐4c5578691c20>:3 in <module>.: SummaryWriter.__init__ (from tensorflow.python.training.summary_io) is deprecated and will be
removed after 2016‐11‐30.
Instructions for updating:
Please switch to tf.summary.FileWriter. The interface and behavior is the same; thi s is just a rename.
The calculation result is::: 6.0


因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- ryyc.cn 版权所有 湘ICP备2023022495号-3

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务