在TensorFlow 中,张量是数据流图上的数据载体。
张量与常见数据实体的关系
阶 | 数据实体 | Pythony样例 |
---|---|---|
0 | 标量 | scalar = 1 |
1 | 向量 | vector = [1, 2, 3] |
2 | 矩阵(数据表) | matrix = [[1,2,3],[4,5,6],[7,8,9]] |
3 | 数据立方 | tensor = [[[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,14,15],[16,17,18]]] |
… | … | … |
n | n阶张量 | … |
1、创建张量
##创建常量用constant
import tensorflow as tf
a = tf.constant(1.0)
b = tf.constant(2.0)
c = tf.add(a,b)
print([a,b,c])
##输出
[<tf.Tensor 'Const:0' shape=() dtype=float32>,
<tf.Tensor 'Const_1:0' shape=() dtype=float32>,
<tf.Tensor 'Add:0' shape=() dtype=float32>]
2、求解
如果要进行求解,必须进行会话,执行张量的eval(张量的值)或者会话的run方法(操作)
with tf.Session() as sess:
print(c.eval())
print(sess.run([a,b,c]))
输出
3.0
[1.0, 2.0, 3.0]
3、稀疏张量
Tensorflow提供了专门用于处理高维稀疏数据的SparseTensor类。该类以键值对的形式表示高维稀疏数据。
SparseTensor包含3个属性,indices、value、dense_shape indices是一个形状为[N, ndims]的Tensor实例,N表示非零元素的个数,ndims是张量的阶数,values是一个形状为[N]的Tensor对象,用于保存indices中指定的非零元素,dense_shape是一个形状为[ndims]的tensor实例,表示该稀疏张量对应的稠密张量的形状。
sp = tf.SparseTensor(indices=[[0,2],[1,3]],
values=[1,2],dense_shape=[3,4])
这个稀疏张量sp的键值对形式为:
[0, 2]: 1
[1, 3]: 2
等价于形状为[3, 4]的2阶稠密张量:
[[0, 0, 1, 0]
[0, 0, 0, 2]
[0, 0, 0, 0]]
with tf.Session() as sess:
print(sp.eval())
输出
SparseTensorValue(indices=array([[0, 2],
[1, 3]], dtype=int64), values=array([1, 2]), dense_shape=array([3, 4], dtype=int64))