最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
TensorFlow如何实现矩阵维度扩展 TensorFlow实现矩阵维度扩展代码
时间:2020-05-22 编辑:袖梨 来源:一聚教程网
TensorFlow如何实现矩阵维度扩展?本篇文章小编给大家分享一下TensorFlow实现矩阵维度扩展代码,代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
一般TensorFlow中扩展维度可以使用tf.expand_dims()。近来发现另一种可以直接运用取数据操作符[]就能扩展维度的方法。
用法很简单,在要扩展的维度上加上tf.newaxis就行了。
foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) print(foo[tf.newaxis, :, :].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]] print(foo[:, tf.newaxis, :].eval()) # => [[[1,2,3]], [[4,5,6]], [[7,8,9]]] print(foo[:, :, tf.newaxis].eval()) # => [[[1],[2],[3]], [[4],[5],[6]],[[7],[8],[9]]]
参考:
https://tensorflow.google.cn/api_docs/python/tf/Tensor?hl=en#__getitem__
补充知识:tensorflow 利用expand_dims和squeeze扩展和压缩tensor维度
在利用tensorflow进行文本挖掘工作的时候,经常涉及到维度扩展和压缩工作。比如对文本进行embedding操作完成之后,若要进行卷积操作,就需要对embedded的向量扩展维度,将[batch_size, embedding_dims]扩展成为[batch_size, embedding_dims, 1],利用tf.expand_dims(input, -1)就可实现,反过来用squeeze(input, -1)或者tf.squeeze(input)也可以把最第三维去掉。
tf.expand_dims()
tf.squeeze()
tf.expand_dims()
tf.expand_dims(input, axis=None, name=None, dim=None)
在第axis位置增加一个维度.
给定张量输入,此操作在输入形状的维度索引轴处插入1的尺寸。 尺寸索引轴从零开始; 如果您指定轴的负数,则从最后向后计数。
如果要将批量维度添加到单个元素,则此操作非常有用。
例如,如果您有一个单一的形状[height,width,channels],您可以使用expand_dims(image,0)使其成为1个图像,这将使形状[1,高度,宽度,通道]。
例子
# 't' is a tensor of shape [2] shape(expand_dims(t, 0)) ==> [1, 2] shape(expand_dims(t, 1)) ==> [2, 1] shape(expand_dims(t, -1)) ==> [2, 1] # 't2' is a tensor of shape [2, 3, 5] shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5] shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5] shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]
tf.squeeze()
tf.squeeze(input, axis=None, name=None, squeeze_dims=None)
直接上例子
# 't' is a tensor of shape [1, 2, 1, 3, 1, 1] shape(squeeze(t)) ==> [2, 3] # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] shape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1]
相关文章
- Golang ProtoBuf的基本语法详解 10-20
- Python识别MySQL中的冗余索引解析 10-20
- Python+Pygame绘制小球代码展示 10-18
- Python中的数据精度问题介绍 10-18
- Python随机值生成的常用方法介绍 10-18
- python3解压缩.gz文件分析 09-27