Tensorflow tensor 数学运算和逻辑运算方式

一、arthmetic 算术操作(+,-,*,/,Mod)

(1)tensor-tensor操作(element-wise)

#两个tensor 运算
#运算规则:element-wise。即c[i,j,..,k]=a[i,j,..,k] op b[i,j,..,k]
ts1=tf.constant(1.0,shape=[2,2])
ts2=tf.Variable(tf.random_normal([2,2]))
sess.run(tf.global_variables_initializer())
#以ts1和ts2为例:

#(1)加法+
ts_add1=tf.add(ts1,ts2,name=None)
ts_add2=ts1+ts2    #二者等价
#(2)减法-
ts_sub1=tf.subtract(ts1,ts2,name=None)
ts_sub2=ts1-ts2    #二者等价
#(3)乘法*
ts_mul1=tf.multiply(ts1,ts2,name=None)
ts_mul2=ts1*ts2
#(4)除法/
ts_div1=tf.divide(ts1,ts2,name=None)
ts_div2=tf.div(ts1,ts2,name=None)  #div 支持 broadcasting(即shape可不同)
ts_div3=ts1/ts2
#另外还有truediv(x,y) x,y类型必须一致,floor_div等。
#(5)取模Mod(估计基本用不到)

(2)tensor-scalar操作

#scalar-tensor操作。
#对tensor中所有element执行同样的操作(+,-,*,/)
#加法
ts_add=ts1+2
#减法
ts_sub=ts1-2
#乘法
ts_mul=ts1*2
#除法
ts_div=ts1/2

二、基本数学函数

#以下x,y均代表tensor

tf.add_n(inputs, name=None) #inputs:tensor数组,所有tensor相加
tf.abs(x, name=None)     #绝对值
tf.negative(x, name=None)  #取反
tf.sign(x, name=None)    #取符号(y = sign(x) = -1 if x < 0; 0 if x == 0; 1 if x > 0.)
tf.square(x, name=None)   #y=x*x
tf.round(x, name=None)    #Rounds the values of a tensor to the nearest integer, element-wise.
tf.sqrt(x, name=None)    #sqrt
tf.pow(x, y, name=None)   #x,y均为tensor,element-wise求pow
tf.exp(x, name=None)     #y=e^x
tf.log(x, name=None)     #y=log(x)
tf.ceil(x, name=None)    #ceil
tf.floor(x, name=None)    #floor
tf.maximum(x, y, name=None) #z=max(x,y)
tf.minimum(x, y, name=None)
tf.cos(x, name=None)     #三角函数,sin,cos,tan,acos,asin,atan
tf.sin(x, name=None)
tf.tan(x, name=None)
tf.acos(x, name=None)
tf.asin(x, name=None)
tf.atan(x, name=None)
#...
#等等一些函数。

三、Matrix矩阵操作

tf.diag(diagonal, name=None)     #得到以diagonal为对角的tensor
tf.diag_part(input, name=None)    #tf.diag 逆操作,得到input的对角矩阵
tf.transpose(a, perm=None,name=None) #转置矩阵,y[i,j]=x[j,i]
#矩阵乘法
tf.matmul(a, b,
 transpose_a=False, transpose_b=False, #
 adjoint_a=False, adjoint_b=False,   #共轭
 a_is_sparse=False, b_is_sparse=False, #矩阵是否稀疏
 name=None)

四、Reduction 归约操作

#(1)tf.reduce_sum
#当keep_dims=False。rank of tensor会降维度。
tf.reduce_sum(input_tensor,
  axis=None,        #要归约的dimention。值为None或一个数字或者数组。如0,1,[0,3,4]
  keep_dims=False,     #if true, retains reduced dimensions with length 1.
  name=None,
  reduction_indices=None)

#(2)tf.reduce_min / tf.reduce_max / tf.reduce_mean
#参数与tf.reduce_sum一致。
#tf.reduce_min : 被归约的数取最小值;
#tf.reduce_max : 被归约的数取最大值;
#tf.reduce_mean: 被归约的数取平均值。

#(3)逻辑操作
# tf.reduce_all:logical and operation
# tf.reduce_any: logical or operation

#(4)自定义操作函数
tf.einsum(equation, *inputs)
#例子:
tf.einsum('ij,jk->ik', ts1,ts2) #矩阵乘法
tf.einsum('ij->ji',ts1)     #矩阵转置

五、tensor大小 比较

#(1)相等equal (element-wise)
tf.equal(x, y, name=None) #Returns the truth value of (x == y) element-wise.

#(2)不等not_equal
tf.not_equal(x, y, name=None)

#(3)其他比较
tf.less(x, y, name=None)
tf.less_equal(x, y, name=None)
tf.greater(x, y, name=None)
tf.greater_equal(x, y, name=None)

六、恒等映射

#恒等映射

tf.identity(input, name=None) #Return a tensor with the same shape and contents as the input tensor or value.

七、类型转化

tf.cast(x, dtype, name=None)
#Casts a tensor to a new type.

#For example:
# tensor `a` is [1.8, 2.2], dtype=tf.float
#tf.cast(a, tf.int32) ==> [1, 2] dtype=tf.int32

八、例子

(1)RELU实现

import tensorflow as tf
def relu(x):    #要构造一个和x shape一样的Tensor。源码中应该不会用效率这么低的写法。
 y=tf.constant(0.0,shape=x.get_shape())
 return tf.where(tf.greater(x,y),x,y)

sess=tf.Session()
x=tf.Variable(tf.random_normal(shape=[10],stddev=10))
sess.run(tf.global_variables_initializer())
x_relu=relu(x)
data_x,data_x_relu=sess.run((x,x_relu))
for i in range(0,len(data_x)):
 print("%.5f --relu--> %.5f" %(data_x[i],data_x_relu[i]))

补充知识:tensorflow 复合逻辑‘且'和‘或'的实现

我就废话不多说了,大家还是直接看代码吧~

import tensorflow as tf

n1 = tf.constant(2)
n2 = tf.constant(3)

n3 = tf.constant(4)
n4 = tf.constant(5)

def true_fn1():
 return tf.constant(11)

def false_fn1():
 return tf.constant(22)

def true_fn():
  return tf.cond(n3<n4,true_fn1,false_fn1)

def false_fn():
  return tf.constant(33)

r = tf.cond(n1<n2,true_fn,false_fn)

sess = tf.Session()

print(sess.run(r))

print结果11

相当于实现了if n1<n2 and n3<n4:

后来发现,用 & 和 | 就行了

import tensorflow as tf

n1 = tf.constant(True,tf.bool)
n2 = tf.constant(False,tf.bool)

r1 = n1 | n2
r2 = n1 & n2

sess = tf.Session()

print(sess.run(r1))
print(sess.run(r2))
import tensorflow as tf

n1 = tf.constant(1)>tf.constant(0)
n2 = tf.constant(1)<tf.constant(0)

r1 = n1 | n2
r2 = n1 & n2

sess = tf.Session()

print(sess.run(r1))
print(sess.run(r2))

以上这篇Tensorflow tensor 数学运算和逻辑运算方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 详解用TensorFlow实现逻辑回归算法

    本文将实现逻辑回归算法,预测低出生体重的概率. # Logistic Regression # 逻辑回归 #---------------------------------- # # This function shows how to use TensorFlow to # solve logistic regression. # y = sigmoid(Ax + b) # # We will use the low birth weight data, specifically: # y

  • Tensorflow轻松实现XOR运算的方式

    对于"XOR"大家应该都不陌生,我们在各种课程中都会遇到,它是一个数学逻辑运算符号,在计算机中表示为"XOR",在数学中表示为"",学名为"异或",其来源细节就不详细表明了,说白了就是两个a.b两个值做异或运算,若a=b则结果为0,反之为1,即"相同为0,不同为1". 在计算机早期发展中,逻辑运算广泛应用于电子管中,这一点如果大家学习过微机原理应该会比较熟悉,那么在神经网络中如何实现它呢,早先我们使用的是感

  • tensorflow: 查看 tensor详细数值方法

    问题 tensor详细数值 不能直接print打印: import tensorflow as tf x = tf.constant(1) print x 输出: Tensor("Const:0", shape=(), dtype=int32) 原因: print只能打印输出shape的信息,而要打印输出tensor的值,需要借助 tf.Session,tf.InteractiveSession. 因为我们在建立graph的时候,只建立 tensor 的 结构形状信息 ,并没有 执行

  • tensorflow指定CPU与GPU运算的方法实现

    1.指定GPU运算 如果安装的是GPU版本,在运行的过程中TensorFlow能够自动检测.如果检测到GPU,TensorFlow会尽可能的利用找到的第一个GPU来执行操作. 如果机器上有超过一个可用的GPU,除了第一个之外的其他的GPU默认是不参与计算的.为了让TensorFlow使用这些GPU,必须将OP明确指派给他们执行.with......device语句能够用来指派特定的CPU或者GPU执行操作: import tensorflow as tf import numpy as np w

  • Tensorflow矩阵运算实例(矩阵相乘,点乘,行/列累加)

    Tensorflow二维.三维.四维矩阵运算(矩阵相乘,点乘,行/列累加) 1. 矩阵相乘 根据矩阵相乘的匹配原则,左乘矩阵的列数要等于右乘矩阵的行数. 在多维(三维.四维)矩阵的相乘中,需要最后两维满足匹配原则. 可以将多维矩阵理解成:(矩阵排列,矩阵),即后两维为矩阵,前面的维度为矩阵的排列. 比如对于(2,2,4)来说,视为2个(2,4)矩阵. 对于(2,2,2,4)来说,视为2*2个(2,4)矩阵. import tensorflow as tf a_2d = tf.constant([

  • Tensorflow tensor 数学运算和逻辑运算方式

    一.arthmetic 算术操作(+,-,*,/,Mod) (1)tensor-tensor操作(element-wise) #两个tensor 运算 #运算规则:element-wise.即c[i,j,..,k]=a[i,j,..,k] op b[i,j,..,k] ts1=tf.constant(1.0,shape=[2,2]) ts2=tf.Variable(tf.random_normal([2,2])) sess.run(tf.global_variables_initializer(

  • 通过shell进行数学运算的多种方式

    在Bash中, bash的数学运算有点别扭,很难适应和记住, 只好写个博文, 方便以后翻翻看. 有四种方式可以进行数学运算: 一.let命令 复制代码 代码如下: #/bin/bashnum1=13num2=14let sum=$num1+$num2 echo $sum #自增let sum++ #自减let sum-- #简写形式let sum+=1let sum-=2 #顺便吐槽下,let sum=(1+3)*(2+2)居然不行, 果然很烂有没有! 二. $[]形式 复制代码 代码如下: #

  • TensorFLow 数学运算的示例代码

    一.Tensor 之间的运算规则 相同大小 Tensor 之间的任何算术运算都会将运算应用到元素级 不同大小 Tensor(要求dimension 0 必须相同) 之间的运算叫做广播(broadcasting) Tensor 与 Scalar(0维 tensor) 间的算术运算会将那个标量值传播到各个元素 Note: TensorFLow 在进行数学运算时,一定要求各个 Tensor 数据类型一致 二.常用操作符和基本数学函数 大多数运算符都进行了重载操作,使我们可以快速使用 (+ - * /)

  • Pytorch Tensor基本数学运算详解

    1. 加法运算 示例代码: import torch # 这两个Tensor加减乘除会对b自动进行Broadcasting a = torch.rand(3, 4) b = torch.rand(4) c1 = a + b c2 = torch.add(a, b) print(c1.shape, c2.shape) print(torch.all(torch.eq(c1, c2))) 输出结果: torch.Size([3, 4]) torch.Size([3, 4]) tensor(1, dt

  • PHP 的比较运算与逻辑运算详解

    1.以下值用 empty() 被判断为true: 未赋值变量.未声明变量.0."0"."".false.null.空数组 array() .对象的魔术方法 __get() 返回的值 在低于 PHP5.0 的版本中,没有任何属性的对象也被 empty 判断为 true 注意:empty() 只接受变量或变量的索引值或属性值,不能直接传入常量,也不能传入运算表达式,PHP 5.5 之后支持表达式 2.被 isset() 判断为 false 的值:未赋值变量.未声明变量.

  • 利用Tensorflow的队列多线程读取数据方式

    在tensorflow中,有三种方式输入数据 1. 利用feed_dict送入numpy数组 2. 利用队列从文件中直接读取数据 3. 预加载数据 其中第一种方式很常用,在tensorflow的MNIST训练源码中可以看到,通过feed_dict={},可以将任意数据送入tensor中. 第二种方式相比于第一种,速度更快,可以利用多线程的优势把数据送入队列,再以batch的方式出队,并且在这个过程中可以很方便地对图像进行随机裁剪.翻转.改变对比度等预处理,同时可以选择是否对数据随机打乱,可以说是

  • 从零开始学习Node.js系列教程之基于connect和express框架的多页面实现数学运算示例

    本文实例讲述了Node.js基于connect和express框架的多页面实现数学运算.分享给大家供大家参考,具体如下: 1.使用connect框架 .use方法用于绑定中间件到connect服务器,它会配置一系列在接到请求时调用的中间件模块,此例中我们要配置的中间件有favicon logger static router app.get/post/put        写法:app.requestName('path', function(req, res, next){}); app-co

  • PHP数学运算函数大汇总(经典值得收藏)

    本文汇总分析了PHP数学运算函数.分享给大家供大家参考,具体如下: 一.常用函数说明: Abs: 取得绝对值. Acos: 取得反余弦值. Asin: 取得反正弦值. Atan: 取得反正切值. Atan2: 计算二数的反正切值. base_convert: 转换数字的进位方式. BinDec: 二进位转成十进位. Ceil: 计算大于指定数的最小整数. Cos: 余弦计算. DecBin: 十进位转二进位. DecHex: 十进位转十六进位. DecOct: 十进位转八进位. Exp: 自然对

  • Python中的数学运算操作符使用进阶

    Python中对象的行为是由它的类型 (Type) 决定的.所谓类型就是支持某些特定的操作.数字对象在任何编程语言中都是基础元素,支持加.减.乘.除等数学操作. Python的数字对象有整数和浮点数,支持各种数学操作,比如+, -,*, /等. 没有这些操作符,程序中只能使用函数调用的方式进行数学运算,比如add(2, 3), sub(5, 2). 程序中操作符的作用与普通数学操作的用法是一致的,使用中更加简便直观.Python中,这些操作符实现是通过定义一些object的特殊方法实现的,比如o

  • 第四章 php数学运算

    一.数值数据类型 数字或数值数据在PHP中一般就两种double和int. PHP是一种松散类型的脚本语言,要注意类型转换的方式. 复制代码 代码如下: <?php $a = '5'; //数字的字符串也是数字,参与数学运算当数字处理 echo is_numeric ( $a ); //1 echo '<br/>'; echo 7 + $a; //12 echo '<br/>'; echo '7' + $a; //12 echo '<br/>'; //用.连接后就

随机推荐