【tensorflow2.0】张量的数学运算

张量的操作主要包括张量的结构操作和张量的数学运算。

张量结构操作诸如:张量创建,索引切片,维度变换,合并分割。

张量数学运算主要有:标量运算,向量运算,矩阵运算。另外我们会介绍张量运算的广播机制。

本篇我们介绍张量的数学运算。

一,标量运算

张量的数学运算符可以分为标量运算符、向量运算符、以及矩阵运算符。

加减乘除乘方,以及三角函数,指数,对数等常见函数,逻辑比较运算符等都是标量运算符。

标量运算符的特点是对张量实施逐元素运算。

有些标量运算符对常用的数学运算符进行了重载。并且支持类似numpy的广播特性。

许多标量运算符都在 tf.math模块下。

import tensorflow as tf 
import numpy  np 
a = tf.constant([[1.0,2],[-3,1)">4.0]])
b = tf.constant([[5.0,1)">6],[7.0,1)">8.0]])
a+b  #运算符重载
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[ 6.,  8.],
       [ 4., 12.]], dtype=float32)>
a-b 
<tf.Tensor: shape=(2, numpy=
array([[ -4.,  -4.],
       [-10.,  -4.]], dtype=float32)>
a*b 
<tf.Tensor: shape=(2, numpy=
array([[  5.,  12.],
       [-21.,  32.]], dtype=float32)>
a/b
<tf.Tensor: shape=(2, numpy=
array([[ 0.2       ,  0.33333334],
       [-0.42857143,  0.5       ]], dtype=float32)>
a**2
<tf.Tensor: shape=(2, numpy=
array([[ 1.,  4.],
       [ 9., 16.]], dtype=float32)>
a**(0.5)
<tf.Tensor: shape=(2, numpy=
array([[1.       , 1.4142135],
       [      nan, 2.       ]], dtype=float32)>
a%3 #mod的运算符重载,等价于m = tf.math.mod(a,3)
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 2, 0], dtype=int32)>
a//3  地板除法
<tf.Tensor: shape=(2, numpy=
array([[ 0.,  0.],
       [-1.,  1.]], dtype=float32)>
(a>=2)
<tf.Tensor: shape=(2, dtype=bool, numpy=
array([[False,  True],
       [False,  True]])>
(a>=2)&(a<=3)
<tf.Tensor: shape=(2, False]])>
(a>=2)|(a<=3)
<tf.Tensor: shape=(2, numpy=
array([[ True,
       [ True,  True]])>
a==5 tf.equal(a,5)
<tf.Tensor: shape=(3, numpy=array([False, False, False])>
tf.sqrt(a)
<tf.Tensor: shape=(2, dtype=float32)>
a = tf.constant([1.0,8.0])
b = tf.constant([5.0,6.0])
c = tf.constant([6.0,7.0])
tf.add_n([a,b,c])
<tf.Tensor: shape=(2, numpy=array([12., 21.], dtype=float32)>
tf.print(tf.maximum(a,b))
[5 8]
tf.print(tf.minimum(a,b))
[1 6]

二,向量运算

向量运算符只在一个特定轴上运算,将一个向量映射到一个标量或者另外一个向量。 许多向量运算符都以reduce开头。

 向量reduce
a = tf.range(1,10)
tf.print(tf.reduce_sum(a))
tf.(tf.reduce_mean(a))
tf.(tf.reduce_max(a))
tf.(tf.reduce_min(a))
tf.print(tf.reduce_prod(a))
45
5
9
1
362880
 张量指定维度进行reduce
b = tf.reshape(a,(3,3))
tf.print(tf.reduce_sum(b,axis=1,keepdims=True))
tf.[[6]
 [15]
 [24]]
[[12 15 18]]
 bool类型的reduce
p = tf.constant([True,False,False])
q = tf.constant([False,True])
tf.(tf.reduce_all(p))
tf.print(tf.reduce_any(q))
0
1
 利用tf.foldr实现tf.reduce_sum
s = tf.foldr(lambda a,b:a+b,tf.range(10)) 
tf.print(s)
45
 cum扫描累积
a = tf.range(1,1)">(tf.math.cumsum(a))
tf.print(tf.math.cumprod(a))
[1 3 6 ... 28 36 45]
[1 2 6 ... 5040 40320 362880]
 arg最大最小值索引
a = tf.range(1,1)">(tf.argmax(a))
tf.print(tf.argmin(a))
8
0
 tf.math.top_k可以用于对张量排序
a = tf.constant([1,3,7,5,4,8])
 
values,indices = tf.math.top_k(a,sorted=True)
tf.(values)
tf.(indices)
 
 利用tf.math.top_k可以在TensorFlow中实现KNN算法
[8 7 5]
[5 2 3]

三,矩阵运算

矩阵必须是二维的。类似tf.constant([1,2,3])这样的不是矩阵。

矩阵运算包括:矩阵乘法,矩阵转置,矩阵逆,矩阵求迹,矩阵范数,矩阵行列式,矩阵求特征值,矩阵分解等运算。

除了一些常用的运算外,大部分和矩阵有关的运算都在tf.linalg子包中。

 矩阵乘法
a = tf.constant([[1,2],[3,4]])
b = tf.constant([[2,0],[0,2]])
a@b  等价于tf.matmul(a,b)
<tf.Tensor: shape=(2, numpy=
array([[2, 4],
       [6, 8]], dtype=int32)>
 矩阵转置
a = tf.constant([[1.0,1)">]])
tf.transpose(a)
<tf.Tensor: shape=(2, numpy=
array([[1., 3.],
       [2., 4.]], dtype=float32)>
 矩阵逆,必须为tf.float32或tf.double类型
a = tf.constant([[1.0,[3.0,4]],dtype = tf.float32)
tf.linalg.inv(a)
<tf.Tensor: shape=(2, numpy=
array([[-2.0000002 ,  1.0000001 ],
       [ 1.5000001 , -0.50000006]], dtype=float32)>
 矩阵求trace
a = tf.constant([[1.0,1)">]])
tf.linalg.trace(a)
<tf.Tensor: shape=(), numpy=5.0>
 矩阵求范数
a = tf.constant([[1.0,1)">]])
tf.linalg.norm(a)
<tf.Tensor: shape=(), numpy=5.477226>
 矩阵行列式
a = tf.constant([[1.0,1)">]])
tf.linalg.det(a)
<tf.Tensor: shape=(), numpy=-2.0>
 矩阵特征值
tf.linalg.eigvalsh(a)
<tf.Tensor: shape=(2, numpy=array([-0.8541021,  5.854102 ], dtype=float32)>
 矩阵qr分解
a  = tf.constant([[1.0,2.0],4.0]],1)"> tf.float32)
q,r = tf.linalg.qr(a)
tf.(q)
tf.(r)
tf.print(q@r)
[[-0.316227794 -0.948683321]
 [-0.948683321 0.316227734]]
[[-3.1622777 -4.4271884]
 [0 -0.632455349]]
[[1.00000012 1.99999976]
 [3 4]]
 矩阵svd分解
a  = tf.constant([[1.0,1)"> tf.float32)
v,s,d = tf.linalg.svd(a)
tf.matmul(tf.matmul(s,tf.linalg.diag(v)),d)
 
 利用svd分解可以在TensorFlow中实现主成分分析降维
<tf.Tensor: shape=(2, numpy=
array([[0.9999996, 1.9999996],
       [2.9999998, 4.       ]], dtype=float32)>

四,广播机制

TensorFlow的广播规则和numpy是一样的:

  • 1、如果张量的维度不同,将维度较小的张量进行扩展,直到两个张量的维度都一样。
  • 2、如果两个张量在某个维度上的长度是相同的,或者其中一个张量在该维度上的长度为1,那么我们就说这两个张量在该维度上是相容的。
  • 3、如果两个张量在所有维度上都是相容的,它们就能使用广播。
  • 4、广播之后,每个维度的长度将取两个张量在该维度长度的较大值。
  • 5、在任何一个维度上,如果一个张量的长度为1,另一个张量长度大于1,那么在该维度上,就好像是对第一个张量进行了复制。

tf.broadcast_to 以显式的方式按照广播机制扩展张量的维度。

 利用svd分解可以在TensorFlow中实现主成分分析降维
<tf.Tensor: shape=(3, 3), numpy=
array([[1, 3],
       [2, 3,
       [3, 4, 5]], dtype=int32)>
tf.broadcast_to(a,b.shape)
<tf.Tensor: shape=(3,
       [1, 3]], dtype=int32)>
 计算广播后计算结果的形状,静态形状,TensorShape类型参数
tf.broadcast_static_shape(a.shape,b.shape)
TensorShape([3, 3])
 计算广播后计算结果的形状,动态形状,Tensor类型参数
c = tf.constant([1,1)">])
d = tf.constant([[1],[2],[3]])
tf.broadcast_dynamic_shape(tf.shape(c),tf.shape(d))
<tf.Tensor: shape=(2, numpy=array([3, dtype=int32)>
 广播效果
c+d 等价于 tf.broadcast_to(c,3]) + tf.broadcast_to(d,3])
<tf.Tensor: shape=(2, numpy=
array([[6.5760484, 7.8174157],
       [6.8174157, 6.4239516]], dtype=float32)>

 

参考:

开源电子书地址:https://lyhue1991.github.io/eat_tensorflow2_in_30_days/

GitHub 项目地址:https://github.com/lyhue1991/eat_tensorflow2_in_30_days

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


MNIST数据集可以说是深度学习的入门,但是使用模型预测单张MNIST图片得到数字识别结果的文章不多,所以本人查找资料,把代码写下,希望可以帮到大家~1#BudingyourfirstimageclassificationmodelwithMNISTdataset2importtensorflowastf3importnumpyasnp4impor
1、新建tensorflow环境(1)打开anacondaprompt,输入命令行condacreate-ntensorflowpython=3.6注意:尽量不要更起名字,不然环境容易出错在选择是否安装时输入“y”(即为“yes”)。其中tensorflow为新建的虚拟环境名称,可以按喜好自由选择。python=3.6为指定python版本为3
这篇文章主要介绍“张量tensor是什么”,在日常操作中,相信很多人在张量tensor是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大...
tensorflow中model.fit()用法model.fit()方法用于执行训练过程model.fit(训练集的输入特征,训练集的标签,batch_size,#每一个batch的大小epochs,#迭代次数validation_data=(测试集的输入特征,
https://blog.csdn.net/To_be_little/article/details/124438800 目录1、查看GPU的数量2、设置GPU加速3、单GPU模拟多GPU环境1、查看GPU的数量importtensorflowastf#查看gpu和cpu的数量gpus=tf.config.experimental.list_physical_devices(device_type='GPU')cpus=tf.c
根据身高推测体重const$=require('jquery');consttf=require('@tensorflowfjs');consttfvis=require('@tensorflowfjs-vis');/*根据身高推测体重*///把数据处理成符合模型要求的格式functiongetData(){//学习数据constheights=[150,151,160,161,16
#!/usr/bin/envpython2#-*-coding:utf-8-*-"""CreatedonThuSep610:16:372018@author:myhaspl@email:myhaspl@myhaspl.com二分法求解一元多次方程"""importtensorflowastfdeff(x):y=pow(x,3)*3+pow(x,2)*2-19return
 继续上篇的pyspark集成后,我们再来看看当今热的不得了的tensorflow是如何继承进pycharm环境的参考:http://blog.csdn.net/include1224/article/details/53452824思路其实很简单,说下要点吧1.python必须要3.564位版本(上一篇直接装的是64位版本的Anaconda)2.激活3.5版本的
首先要下载python3.6:https://www.python.org/downloadselease/python-361/接着下载:numpy-1.13.0-cp36-none-win_amd64.whl 安装这两个:安装python3.6成功,接着安装numpy.接着安装tensorflow: 最后测试一下: python3.6+tensorflow安装完毕,高深的AI就等着你去
参考书《TensorFlow:实战Google深度学习框架》(第2版)以下TensorFlow程序完成了从图像片段截取,到图像大小调整再到图像翻转及色彩调整的整个图像预处理过程。#!/usr/bin/envpython#-*-coding:UTF-8-*-#coding=utf-8"""@author:LiTian@contact:694317828@qq.com
参考:TensorFlow在windows上安装与简单示例写在开头:刚开始安装的时候,由于自己的Python版本是3.7,安装了好几次都失败了,后来发现原来是tensorflow不支持3.7版本的python,所以后来换成了Python3.6,就成功了。。。。。anconda:5.3.2python版本:3.6.8tensorflow版本:1.12.0安装Anconda
实验介绍数据采用CriteoDisplayAds。这个数据一共11G,有13个integerfeatures,26个categoricalfeatures。Spark由于数据比较大,且只在一个txt文件,处理前用split-l400000train.txt对数据进行切分。连续型数据利用log进行变换,因为从实时训练的角度上来判断,一般的标准化方式,
 1)登录需要一个 invitationcode,申请完等邮件吧,大概要3-5个小时;2)界面3)配置数据集,在右边列设置 
模型文件的保存tensorflow将模型保持到本地会生成4个文件:meta文件:保存了网络的图结构,包含变量、op、集合等信息ckpt文件:二进制文件,保存了网络中所有权重、偏置等变量数值,分为两个文件,一个是.data-00000-of-00001文件,一个是.index文件checkpoint文件:文本文件,记录了最新保持
原文地址:https://blog.csdn.net/jesmine_gu/article/details/81093686这里只是做个收藏,防止原链接失效importosimportnumpyasnpfromPILimportImageimporttensorflowastfimportmatplotlib.pyplotaspltangry=[]label_angry=[]disgusted=[]label_d
 首先声明参考博客:https://blog.csdn.net/beyond_xnsx/article/details/79771690?tdsourcetag=s_pcqq_aiomsg实践过程主线参考这篇博客,相应地方进行了变通。接下来记载我的实践过程。  一、GPU版的TensorFlow的安装准备工作:笔者电脑是Windows10企业版操作系统,在这之前已
1.tensorflow安装  进入AnacondaPrompt(windows10下按windows键可找到)a.切换到创建好的tensorflow36环境下:activatetensorflow36    b.安装tensorflow:pipinstlltensorflow    c.测试环境是否安装好       看到已经打印出了"h
必须走如下步骤:sess=tf.Session()sess.run(result)sess.close()才能执行运算。Withtf.Session()assess:Sess.run()通过会话计算结果:withsess.as_default():print(result.eval())表示输出result的值生成一个权重矩阵:tf.Variable(tf.random_normal([2,3]
tf.zeros函数tf.zeros(shape,dtype=tf.float32,name=None)定义在:tensorflow/python/ops/array_ops.py.创建一个所有元素都设置为零的张量. 该操作返回一个带有形状shape的类型为dtype张量,并且所有元素都设为零.例如:tf.zeros([3,4],tf.int32)#[[0,0,
一、Tensorflow基本概念1、使用图(graphs)来表示计算任务,用于搭建神经网络的计算过程,但其只搭建网络,不计算2、在被称之为会话(Session)的上下文(context)中执行图3、使用张量(tensor)表示数据,用“阶”表示张量的维度。关于这一点需要展开一下       0阶张量称