欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

tf.expand_dims()和tf.squeeze()的用法详解

发布时间:2024/3/13 编程问答 60 豆豆
生活随笔 收集整理的这篇文章主要介绍了 tf.expand_dims()和tf.squeeze()的用法详解 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

tf.expand_dims

tf.expand_dims(input, axis=None, name=None, dim=None )

给定的张量input,axis为需要在第几维度扩充,axis=0表示在原有的张量的第一维扩充,axis=1表示在原有的张量的第二维扩充,axis=-1表示在原有的张量的最后一维扩充

如果要将批次尺寸添加到单个元素,此操作很有用。例如,如果您有一个shape的图像[height, width, channels],则可以用制作一批1张图像expand_dims(image, 0),这将使shape成为[1, height, width, channels]。

示例:

增加一个维度

import numpy as np import tensorflow as tf from numpy import arraycurrent = np.array([[0, 7, 1, 2, 2],[1, 7, 3, 4, 3],[2, 7, 5, 6, 6],[3, 7, 7, 8, 7],[4, 7, 7, 8, 7],[5, 7, 7, 8, 7] ])current = array(current)current = tf.constant(current) points_e = tf.expand_dims(current, axis=0)#在第一维增加一维print(current) #Tensor("Const:0", shape=(6, 5), dtype=int32) print(points_e) #Tensor("ExpandDims:0", shape=(1, 6, 5), dtype=int32)with tf.Session() as sess:print(sess.run(current))print(************************)print(sess.run(points_e))

 结果:

[[0 7 1 2 2][1 7 3 4 3][2 7 5 6 6][3 7 7 8 7][4 7 7 8 7][5 7 7 8 7]] ************************* [[[0 7 1 2 2][1 7 3 4 3][2 7 5 6 6][3 7 7 8 7][4 7 7 8 7][5 7 7 8 7]]] #增加了一维

官方示例 shape维度 

# '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]

tf.squeeze()

tf.squeeze(input, squeeze_dims=None, name=None)Removes dimensions of size 1 from the shape of a tensor. 从tensor中删除所有大小是1的维度

参数解释:

input:张量。 输入要挤压。
squeeze_dims:可选的ints列表。 默认为[]。 如果指定,只能挤压列出的尺寸。 维度索引从0开始。挤压不是1的维度是一个错误。
name:操作的名称(可选)。

给定张量输入,此操作返回相同类型的张量,并删除所有尺寸为1的尺寸。 如果不想删除所有尺寸1尺寸,可以通过指定squeeze_dims来删除特定尺寸1尺寸。
如果不想删除所有大小是1的维度,可以通过squeeze_dims指定需要删除的维度。

示例:

# 't' is a tensor of shape [1, 2, 1, 3, 1, 1] shape(squeeze(t)) ==> [2, 3] Or, to remove specific size 1 dimensions:# 't' is a tensor of shape [1, 2, 1, 3, 1, 1] shape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1]

 

总结

以上是生活随笔为你收集整理的tf.expand_dims()和tf.squeeze()的用法详解的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。