TensorFlow中什么是Tensor?

版权声明:如有转载复制请注明出处,博主QQ715608270,欢迎沟通交流! https://blog.csdn.net/qq_41000891/article/details/84326557

一、Tensor概念

Tensor意思为张量,张量是什么?张量具有维度,或者可有称作为他的秩:Rank/Order

我们以数组为对比,展示张量维度的概念:

 在上图中,当在零维的时候,称为标量;

当在一维的时候,就是我们经常提的向量;

当在二维的时候,就是我们经常提的矩阵;即Matrix

在多维的时候,就可以称作n维的张量。

张量的概念是相对与标量,向量,矩阵这一系类概念的拓展

 二、Tensor的属性

Tensor和Pyhton中的Numpy包有很多相似的属性和用法:

 还有很多如device,name,graph等等。

三、常见的Tensor

1.Constant(常量)

Constant是值不能改变的一种Tensor

下面试引用的方法,要注意的是,我们要想输出const,必须以创建session回话的方式,而不能直接打印

import tensorflow as tf

const = tf.constant(3)

下面是对constant的属性设置:

constant(
    value,
    dtpye = None,
    shape = None,
    name = 'Const',
    verify_shape = False
)

2.Variable(变量) 

下面是对Variable的使用:

import tensorflow as tf

const = tf.variable

下面是Variable的构造函数

__init__(
    initial_value = None,
    trainable =True,
    collections = None,
    validate_shape = True,
    caching_device = None,
    name = None,
    variable_def = None,
    dtype = None,
    expected_shape = None,
    import_scope = None,
    constraint = None
)

3.placeholder(占位符)

先占住一个固定的位置,等着你之后往里面添加值的一种Tensor

import tensorflow as tf

const = tf.placeholder

属性如下:

placeholder(
    dtype
    shape = None,
    name = None
)

官网代码实例如下:

x = tf.placeholder(tf.float32, shape=(1024, 1024))
y = tf.matmul(x, x)

with tf.Session() as sess:
  print(sess.run(y))  # ERROR: will fail because x was not fed.

  rand_array = np.random.rand(1024, 1024)
  print(sess.run(y, feed_dict={x: rand_array}))  # Will succeed.

通过tf.float32指定数据类型,shape指定了1024*1024的矩阵;

使用feed_dict进行字典传参。

4.SparseTensor(稀疏张量)

可以类比稀疏矩阵,稀疏矩阵的概念是:在矩阵中,若数值为0的元素数目远远多于非0元素的数目,并且非0元素分布没有规律时,则称该矩阵稀疏矩阵;与之相反,若非0元素数目占大多数时,则称该矩阵为稠密矩阵。定义非零元素的总数比上矩阵所有元素的总数为矩阵的稠密度。

ensorFlow表示一个稀疏张量,作为三个独立的稠密张量:indices,values和dense_shape。在Python中,三个张量被集合到一个SparseTensor类中,以方便使用。如果你有单独的indices,values和dense_shape张量,SparseTensor在传递给下面的操作之前,将它们包装在一个对象中。 

具体来说,该稀疏张量SparseTensor(indices, values, dense_shape)包括以下组件,其中N和ndims分别是在SparseTensor中的值的数目和维度的数量:

  • indices:density_shape[N, ndims]的2-D int64张量,指定稀疏张量中包含非零值(元素为零索引)的元素的索引。例如,indices=[[1,3], [2,4]]指定索引为[1,3]和[2,4]的元素具有非零值。
  • values:任何类型和dense_shape [N]的一维张量,它提供了indices中的每个元素的值。例如,给定indices=[[1,3], [2,4]]的参数values=[18, 3.6]指定稀疏张量的元素[1,3]的值为18,张量的元素[2,4]的值为3.6。
  • dense_shape:density_shape[ndims]的一个1-D int64张量,指定稀疏张量的dense_shape。获取一个列表,指出每个维度中元素的数量。例如,dense_shape=[3,6]指定二维3x6张量,dense_shape=[2,3,4]指定三维2x3x4张量,并且dense_shape=[9]指定具有9个元素的一维张量。
SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])

[[1, 0, 0, 0]
 [0, 0, 2, 0]
 [0, 0, 0, 0]]

init方法:

__init__(
    indices,
    values,
    dense_shape
)

猜你喜欢

转载自blog.csdn.net/qq_41000891/article/details/84326557