AI - TensorFlow - 张量(Tensor)
张量(Tensor)
在Tensorflow中,变量统一称作张量(Tensor)。
张量(Tensor)是任意维度的数组。
- 0阶张量:纯量或标量 (scalar), 也就是一个数值,例如,\'Howdy\' 或 5
- 1阶张量:向量 (vector)或矢量,也就是一维数组(一组有序排列的数),例如,[2, 3, 5, 7, 11] 或 [5]
- 2阶张量:矩阵 (matrix),也就是二维数组(有序排列的向量),例如,[[3.1, 8.2, 5.9][4.3, -2.7, 6.5]]
- 3阶张量:三维的矩阵,也就是把矩阵有序地叠加起来,成为一个“立方体”
- 以此类推,等等。
在大多数情况下,只会使用一个或多个低维张量(2阶及以下)。
典型 TensorFlow 程序中的大多数代码行都是指令,张量也是计算图中的一种指令。
张量可以作为常量或变量存储在图中。
- 常量是始终会返回同一张量值的指令,存储的是值不会发生更改的张量。
- 变量是会返回分配给它的任何张量的指令,存储的是值会发生更改的张量。
TensorFlow指南:
张量的定义
1 # coding=utf-8
2 import tensorflow as tf
3 import os
4
5 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
6
7 x = tf.constant([5.6], name="x_const") # tf.constant定义标量整数常量并传入值
8 y = tf.Variable([0], name="y_Variable") # tf.Variable定义变量并传入默认值
9 y = y.assign([3]) # 分配一个值
10
11 with tf.Session() as sess: # 图必须在会话中运行,会话存储了它所运行的图的状态
12 initialization = tf.global_variables_initializer() # 使用tf.Variable时,必须在会话开始时明确初始化变量
13 print("x: {}".format(sess.run(x)))
14 print("y: {}".format(sess.run(y)))
运行结果:
x: [5.6]
y: [3]
常量相加
1 # coding=utf-8
2 import tensorflow as tf
3 import os
4
5 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
6
7 g = tf.Graph() # 创建图,虽然TensorFlow提供一个默认图,仍建议创建自己的Graph,以便跟踪状态
8
9 with g.as_default(): # 将定义的图作为默认
10 x = tf.constant(8, name="x_const") # tf.constant定义标量整数常量并传入值
11 y = tf.constant(5, name="y_const")
12 z = tf.constant(4, name="z_const")
13 sum1 = tf.add(x, y, name="x_y_sum") # tf.add相加
14 sum2 = tf.add(z, sum1, name="x_y_z_sum")
15 with tf.Session() as sess: # 图必须在会话中运行
16 print("sum1: {}".format(sum1.eval()))
17 print("sum2: {}".format(sum2.eval()))
运行结果:
sum1: 13
sum2: 17
矢量相加、张量形状与广播
# coding=utf-8
import tensorflow as tf
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '' try:
tf.contrib.eager.enable_eager_execution()
print("# TF imported with eager execution!")
except ValueError:
print("# TF already imported with eager execution!") # ### 矢量(一维张量)加法
primes = tf.constant([2, 3, 5, 7, 11, 13], dtype=tf.int32) # 包含质数的primes矢量
ones = tf.ones([6], dtype=tf.int32) # 值全为1的ones矢量
just_beyond_primes = tf.add(primes, ones) # 通过对前两个矢量执行元素级加法而创建的矢量
twos = tf.constant([2, 2, 2, 2, 2, 2], dtype=tf.int32)
primes_doubled = primes * twos # 通过将primes矢量中的元素翻倍而创建的矢量
print("primes: ", primes)
print("ones: ", ones)
print("just_beyond_primes: ", just_beyond_primes)
print("primes_doubled: ", primes_doubled) some_matrix = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32)
print("some_matrix: ", some_matrix) # 输出张量将返回其值、形状以及存储在张量中的值的类型
print("value of some_matrix is:\n", some_matrix.numpy()) # 调用张量的numpy方法会返回该张量的值(以NumPy数组形式) # ### 张量形状
scalar = tf.zeros([]) # 标量
vector = tf.zeros([3]) # 值全为0的矢量
matrix = tf.zeros([2, 3]) # 值全为0的2行3列矩阵
print('scalar has shape:', scalar.get_shape(), 'and value:\n', scalar.numpy())
print('vector has shape:', vector.get_shape(), 'and value:\n', vector.numpy())
print('matrix has shape:', matrix.get_shape(), 'and value:\n', matrix.numpy()) # ### 广播
primes2 = tf.constant([2, 3, 5, 7, 11, 13], dtype=tf.int32)
ones2 = tf.ones(1, dtype=tf.int32) # 使用的是标量值(不是全包含1矢量)和广播
just_beyond_primes2 = tf.add(primes2, ones2)
twos2 = tf.constant(2, dtype=tf.int32) # 使用的是标量值(不是全包含 2 的矢量)和广播
primes_doubled2 = primes2 * twos2
print("primes2: ", primes2)
print("ones2: ", ones2)
print("just_beyond_primes2: ", just_beyond_primes2)
print("primes_doubled2: ", primes_doubled2) # ### 矢量加法
# 可以对张量执行很多典型数学运算:https://www.tensorflow.org/api_docs/python/tf/math;
# 输出张量将返回其值、形状以及存储在张量中的值的类型;
# 调用张量的numpy方法会返回该张量的值(以NumPy数组形式);
#
# ### 张量形状(shape)
# 形状(shape)用于描述张量维度的大小和数量;
# 张量的形状表示为list,其中第i个元素表示维度i的大小;
# 列表的长度表示张量的阶(即维数);
#
# ### 广播
# TensorFlow支持广播(一种借鉴自NumPy的概念);
# 利用广播,元素级运算中的较小数组会增大到与较大数组具有相同的形状;
运行结果:
# TF imported with eager execution!
primes: tf.Tensor([ 2 3 5 7 11 13], shape=(6,), dtype=int32)
ones: tf.Tensor([1 1 1 1 1 1], shape=(6,), dtype=int32)
just_beyond_primes: tf.Tensor([ 3 4 6 8 12 14], shape=(6,), dtype=int32)
primes_doubled: tf.Tensor([ 4 6 10 14 22 26], shape=(6,), dtype=int32)
some_matrix: tf.Tensor(
[[1 2 3]
[4 5 6]], shape=(2, 3), dtype=int32)
value of some_matrix is:
[[1 2 3]
[4 5 6]]
scalar has shape: () and value:
0.0
vector has shape: (3,) and value:
[0. 0. 0.]
matrix has shape: (2, 3) and value:
[[0. 0. 0.]
[0. 0. 0.]]
primes2: tf.Tensor([ 2 3 5 7 11 13], shape=(6,), dtype=int32)
ones2: tf.Tensor([1], shape=(1,), dtype=int32)
just_beyond_primes2: tf.Tensor([ 3 4 6 8 12 14], shape=(6,), dtype=int32)
primes_doubled2: tf.Tensor([ 4 6 10 14 22 26], shape=(6,), dtype=int32)
矩阵相乘、张量变形
# coding=utf-8
import tensorflow as tf
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '' try:
tf.contrib.eager.enable_eager_execution()
print("# TF imported with eager execution!")
except ValueError:
print("# TF already imported with eager execution!") # ### 矩阵相乘
x = tf.constant([[5, 2, 4, 3], [5, 1, 6, -2], [-1, 3, -1, -2]], dtype=tf.int32) # 3行4列矩阵
y = tf.constant([[2, 2], [3, 5], [4, 5], [1, 6]], dtype=tf.int32) # 4行2列矩阵
matrix_multiply_result = tf.matmul(x, y) # 矩阵相乘的结果是3行2列矩阵
print("matrix_multiply_result: ", matrix_multiply_result) # ### 张量变形
matrix = tf.constant([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=tf.int32) # 4行2列的矩阵
reshaped_2x4_matrix = tf.reshape(matrix, [2, 4]) # 将4x2张量变形为2x4张量
reshaped_1x8_matrix = tf.reshape(matrix, [1, 8])
reshaped_2x2x2_tensor = tf.reshape(matrix, [2, 2, 2]) # 将4x2张量变形为三维2x2x2张量
one_dimensional_vector = tf.reshape(matrix, [8]) # 将4x2张量变形为一维8元素张量
print("Original matrix (4x2):\n", matrix.numpy())
print("Reshaped matrix (2x4):\n", reshaped_2x4_matrix.numpy())
print("Reshaped matrix (1x8):\n", reshaped_1x8_matrix.numpy())
print("reshaped_2x2x2_tensor:\n", reshaped_2x2x2_tensor.numpy())
print("one_dimensional_vector:\n", one_dimensional_vector.numpy()) # ### 矩阵相乘
# 在线性代数中,当两个矩阵相乘时,第一个矩阵的列数必须等于第二个矩阵的行数,否则是无效的;
#
# ### 张量变形
# 可以使用tf.reshape方法改变张量的形状和维数(“阶”);
# 例如,可以将4x2张量变形为2x4张量;
# 例如,可以将4x2张量变形为三维2x2x2张量或一维8元素张量;
运行结果:
# TF imported with eager execution!
matrix_multiply_result: tf.Tensor(
[[35 58]
[35 33]
[ 1 -4]], shape=(3, 2), dtype=int32)
Original matrix (4x2):
[[1 2]
[3 4]
[5 6]
[7 8]]
Reshaped matrix (2x4):
[[1 2 3 4]
[5 6 7 8]]
Reshaped matrix (1x8):
[[1 2 3 4 5 6 7 8]]
reshaped_2x2x2_tensor:
[[[1 2]
[3 4]] [[5 6]
[7 8]]]
one_dimensional_vector:
[1 2 3 4 5 6 7 8]
变量、初始化和赋值
# coding=utf-8
import tensorflow as tf
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '' try:
tf.contrib.eager.enable_eager_execution()
print("# TF imported with eager execution!")
except ValueError:
print("# TF already imported with eager execution!") v1 = tf.contrib.eager.Variable([3]) # 创建一个初始值为3的标量变量
v2 = tf.contrib.eager.Variable(
tf.random_normal(shape=[1, 4], # 形状为1行4列,必选项
mean=1.0, # 正态分布的均值,默认为0
stddev=0.35, # 正态分布的标准差,默认为1.0
dtype=tf.float64, # 输出的类型,默认为tf.float32
seed=1, # 每次产生的随机数结果是否相同,如果固定seed值为一个整数则相同,默认为None(不相同)
name="test") # 操作的名称
) # 创建一个初始值为正态分布的1*4矢量变量
tf.assign(v1, [7]) # 使用assign更改变量的值 print("v1:", v1.numpy())
print("v2:", v2.numpy()) # ### 变量、初始化和赋值
# 在TensorFlow中可以定义Variable对象(变量),其值可以更改;
# 创建变量时,可以明确设置一个初始值,也可以使用初始化程序(例如分布);
# 使用assign更改变量的值,向变量赋予新值时,其形状必须和之前的形状一致;
#
# ### tf.random_normal()函数
# 用于从服从指定正太分布的数值中取出指定个数的值;
运行结果:
# TF imported with eager execution!
v1: [7]
v2: [[1.08498964 0.87645062 0.70722227 0.91475084]]
AI - TensorFlow - 张量(Tensor)的更多相关文章
- tensorflow中张量(tensor)的属性——维数(阶)、形状和数据类型
tensorflow的命名来源于本身的运行原理,tensor(张量)意味着N维数组,flow(流)意味着基于数据流图的计算,所以tensorflow字面理解为张量从流图的一端流动到另一端的计算过程. ...
- AI - TensorFlow - 起步(Start)
01 - 基本的神经网络结构 输入端--->神经网络(黑盒)--->输出端 输入层:负责接收信息 隐藏层:对输入信息的加工处理 输出层:计算机对这个输入信息的认知 每一层点开都有它相应的内 ...
- 机器学习-Tensorflow之Tensor和Dataset学习
好了,咱们今天终于进入了现阶段机器学习领域内最流行的一个框架啦——TensorFlow.对的,这款由谷歌开发的机器学习框架非常的简单易用并且得到了几乎所有主流的认可,谷歌为了推广它的这个框架甚至单独开 ...
- 8 tensorflow修改tensor张量矩阵的某一列
1.tensorflow的数据流图限制了它的tensor是只读属性,因此对于一个Tensor(张量)形式的矩阵,想修改特定位置的元素,比较困难. 2.我要做的是将所有的操作定义为符号形式的操作.也就是 ...
- tensorflow 张量的阶、形状、数据类型及None在tensor中表示的意思。
x = tf.placeholder(tf.float32, [None, 784]) x isn't a specific value. It's a placeholder, a value th ...
- 2、介绍在TensorFlow当中使用不同的方式创建张量tensor
import tensorflow as tf from tensorflow.python.framework import ops ops.reset_default_graph() #开始一个计 ...
- Tensorflow张量
张量常规解释 张量(tensor)理论是数学的一个分支学科,在力学中有重要应用.张量这一术语起源于力学,它最初是用来表示弹性介质中各点应力状态的,后来张量理论发展成为力学和物理学的一个有力的数学工具. ...
- tensorflow四维tensor的形状以及函数tf.argmax( )的笔记
关于tensorflow里多维数组(主要是四维)的组织形式之前一直没弄懂,最近遇到相关问题,算是搞清楚了一些东西,特别记下来,免得自己又遗忘了. 三维形式能很简单的脑补出来三维的形状,不再赘述. 之前 ...
- tensorflow中tensor的静态维度和动态维度
tf中使用张量(tensor)这种数据结构来表示所有的数据,可以把张量看成是一个具有n个维度的数组或列表,张量会在各个节点之间流动,参与计算. 张量具有静态维度和动态维度. 在图构建过程中定义的张量拥 ...
随机推荐
- 让站点支持MarkDown语法~(转)
Markdown是一种可以使用普通文本编辑器编写的标记语言,通过类似HTML的标记语法,它可以使普通文本内容具有一定的格式.Markdown的语法简洁明了.学习容易,而且功能比纯文本更强,因此有很多人 ...
- B20J_2243_[SDOI2011]染色_树链剖分+线段树
B20J_2243_[SDOI2011]染色_树链剖分+线段树 一下午净调这题了,争取晚上多做几道. 题意: 给定一棵有n个节点的无根树和m个操作,操作有2类: 1.将节点a到节点b路径上所有点都染成 ...
- linux文件的基本属性
Linux 文件基本属性 Linux系统是一种典型的多用户系统,不同的用户处于不同的地位,拥有不同的权限.为了保护系统的安全性,Linux系统对不同的用户访问同一文件(包括目录文件)的权限做了不同的规 ...
- create react app 项目部署在Spring(Tomcat)项目中
网上看了许多,大多数都是nginx做成静态项目,但是这样局限性太多,与Web项目相比许多服务端想做的验证都很麻烦,于是开始了艰难的探索之路,终于在不经意间试出来了,一把辛酸... 正常的打包就不说了. ...
- C语言——输入输出函数
0.getchar().putchar() 输入缓冲区,键盘输入是"行缓冲"遇到一个换行符的时候清空缓冲区. 标准流,stdin和stdout,是标准的输入输出流,键盘输入就是用的 ...
- Uiautomator--出现报错“urllib3.exceptions.ProtocolError:<'Connection aborted.',error<10054,''>>”的解决方式!
在运行uiautomator时,出现报错"urllib3.exceptions.ProtocolError:<'Connection aborted.',error<10054, ...
- vue+axios访问本地json数据踩坑点
当我们想在vue项目中模拟后台接口访问json数据时,我们发现无论如何也访问不到本地的json数据. 注意:1.在vue-cli项目中,我们静态资源只能放在static文件夹中,axios使用get请 ...
- vue笔记 递归组件的使用
递归组件 什么是递归组件? 组件自身去调用组件自身. 代码示例 DetailList.vue(子组件-递归组件) <template> <div> <div class= ...
- JS的 try catch使用心得
try{ //正常执行 }catch(e/*你感觉会出错的 错误类型*/){ // 可能出现的意外 eg:用户自己操作失误 或者 函数少条件 不影响下面的函数执行 // 有时也会用在 比如 focus ...
- 浅析一款扫描dom-xss的浏览器插件
目录 0x00 前言 0x01 浅析 0x00 前言 这款插件的名字叫 ra2-dom-xss-scanner,其作者刚好也是jsprime的开发者,后续有可能会继续跟进一下jsprime.这个ra2 ...