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

相关文章

Python Tkinter模块 GUI 可视化实例

我就废话不多说了,直接上代码: coding:utf-8 #自带的Tkinter模块 from Tkinter import * from ScrolledText impo...

跟老齐学Python之数据类型总结

下面的表格中列出了已经学习过的数据类型,也是python的核心数据类型之一部分,这些都被称之为内置对象。 对象,就是你面对的所有东西都是对象,看官要逐渐熟悉这个称呼。所有的数据类型,就是...

解决pandas使用read_csv()读取文件遇到的问题

如下: 数据文件: 上海机场 (sh600009) 24.11 3.58...

python 获取当天每个准点时间戳的实例

实例如下所示: import time,datetime def gettime(): for x in range(24): a = datetime.d...

如何利用python查找电脑文件

如何利用python查找电脑文件

利用python查找电脑里的文件非常方便 比如在我的电脑:D:\软件 文件夹里有非常非常多的软件。 我忘记某个软件叫什么名字了,只记得文件名称里有 now,而且后缀名是.zip 利用py...