TensorFlow用expand_dim()来增加维度的方法

yipeiwu_com5年前Python基础

TensorFlow中,想要维度增加一维,可以使用tf.expand_dims(input, dim, name=None)函数。当然,我们常用tf.reshape(input, shape=[])也可以达到相同效果,但是有些时候在构建图的过程中,placeholder没有被feed具体的值,这时就会包下面的错误:TypeError: Expected binary or unicode string, got 1

在这种情况下,我们就可以考虑使用expand_dims来将维度加1。比如我自己代码中遇到的情况,在对图像维度降到二维做特定操作后,要还原成四维[batch, height, width, channels],前后各增加一维。如果用reshape,则因为上述原因报错

one_img2 = tf.reshape(one_img, shape=[1, one_img.get_shape()[0].value, one_img.get_shape()[1].value, 1])

用下面的方法可以实现:

one_img = tf.expand_dims(one_img, 0)
one_img = tf.expand_dims(one_img, -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]

Args:

input: A Tensor.
dim: A Tensor. Must be one of the following types: int32, int64. 0-D (scalar). Specifies the dimension index at which to expand the shape of input.
name: A name for the operation (optional).

Returns:

A Tensor. Has the same type as input. Contains the same data as input, but its shape has an additional dimension of size 1 added.

以上这篇TensorFlow用expand_dim()来增加维度的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

django认证系统实现自定义权限管理的方法

本文记录使用django自带的认证系统实现自定义的权限管理系统,包含组权限、用户权限等实现。 0x01. django认证系统 django自带的认证系统能够很好的实现如登录、登出、创建...

Python交互环境下实现输入代码

Python交互环境下实现输入代码

Iamlaosong文 Python交互环境的提示符是“>>>”,命令行模式下输入python命令就可以进入这个交互环境进行交互会话。 在windows中,除了在she...

对python中数组的del,remove,pop区别详解

以a=[1,2,3] 为例,似乎使用del, remove, pop一个元素2 之后 a都是为 [1,3], 如下: >>> a=[1,2,3] >>...

Python字符串中删除特定字符的方法

Python字符串中删除特定字符的方法

分析 在Python中,字符串是不可变的。所以无法直接删除字符串之间的特定字符。 所以想对字符串中字符进行操作的时候,需要将字符串转变为列表,列表是可变的,这样就可以实现对字符串中特定字...

python编写暴力破解zip文档程序的实例讲解

python编写暴力破解zip文档程序的实例讲解

编写暴力破解Zip文件要从学习zipfile库的使用方法入手,首先打开Python解释器,用help('zipfile')命令来了解这个库并重点看一下ZipFile类中的extracta...