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

yipeiwu_com6年前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设计】。

相关文章

window环境pip切换国内源(pip安装异常缓慢的问题)

在使用pip默认的安装源时,安装速度通常会比较缓慢。通过切换为国内的安装源通常会解决这个问题,以下是解决步骤: 在如下目录新增一个pip文件 \Users\Administrato...

Flask框架Jinjia模板常用语法总结

Flask框架Jinjia模板常用语法总结

本文实例总结了Flask框架Jinjia模板常用语法。分享给大家供大家参考,具体如下: 1. 变量表示 {{ argv }} 2. 赋值操作 {% set links =...

Python实现FTP文件传输的实例

Python实现FTP文件传输的实例

FTP一般流程 FTP对应PASV和PORT两种访问方式,分别为被动和主动,是针对FTP服务器端进行区分的,正常传输过程中21号端口用于指令传输,数据传输端口使用其他端口。 PASV:...

50行代码实现贪吃蛇(具体思路及代码)

50行代码实现贪吃蛇(具体思路及代码)

最近一直在准备用来面试的几个小demo,为了能展现自己,所以都是亲自设计并实现的,其中一个就是在50行代码内来实现一个贪吃蛇,为了说明鄙人自己练习编程的一种方式--把代码写短,为了理解语...

python3实现斐波那契数列(4种方法)

基础版(list方法) # 比较占内存 w = int(input("输入一个数字还你一个斐波那契数列:")) list_res = [] def list_n(n): if...