Tensorflow入门笔记(一)张量

在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]]]
nn阶张量

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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值