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

相关文章

Python3.5 Pandas模块之Series用法实例分析

Python3.5 Pandas模块之Series用法实例分析

本文实例讲述了Python3.5 Pandas模块之Series用法。分享给大家供大家参考,具体如下: 1、Pandas模块引入与基本数据结构 2、Series的创建...

python 用lambda函数替换for循环的方法

场景如下: 现在有一个dataframe,其中一列为score,值从0-100, df: score 98 88 37 68 86 33 现在需要增加一列level,给这些分数分类,90...

简单总结Python中序列与字典的相同和不同之处

共同点: 1.它们都是python的核心类型,是python语言自身的一部分 核心类型与非核心类型 多数核心类型可通过特定语法来生成其对象,比如"dave"就是创建字符串类型的对象的...

简介Python中用于处理字符串的center()方法

 center()方法返回集中在长度宽度的字符串。填充是通过使用specifiedfillchar。默认填充字符是一个空格。 语法 以下是center()方法的语法: st...

讲解Python中fileno()方法的使用

 fileno()方法返回所使用的底层实现,要求从操作系统I/O操作的整数文件描述符。 语法 以下是fileno()方法的语法: fileObject.fileno();...