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

相关文章

ubuntu 18.04 安装opencv3.4.5的教程(图解)

ubuntu 18.04 安装opencv3.4.5的教程(图解)

【写在前面】 这真的是太那个什么了 不管怎么说 做过的东西做个笔记总是好的 花一点点时间做笔记 不然如果哪一天要重新做了 或者哪一天要汇报工作 都不知道该从哪里入手 又要重新来...

详解python之多进程和进程池(Processing库)

详解python之多进程和进程池(Processing库)

环境:win7+python2.7 一直想学习多进程或多线程,但之前只是单纯看一点基础知识还有简单的介绍,无法理解怎么去应用,直到前段时间看了github的一个爬虫项目涉及到多进程,多线...

python 模拟贷款卡号生成规则过程解析

前言 笔者在测试某web系统的过程中,需要用到“贷款卡号”,且此贷款卡号仅能使用一次,保存过后下一次无法再次使用相同的卡号。 遂决定依据它的生成规则,自己写一段代码来实现。 同时为了方便...

python lambda表达式在sort函数中的使用详解

1.lambda表达式一般用法 语法: lamda argument:expression example: add = lambda x, y: x+y print(add(10,...

Python操作MySQL数据库的方法

pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。 下载安装 pip3 install pymysql 使用操作 1、执行SQL i...