tf.expand_dims()和tf.squeeze()的用法详解
生活随笔
收集整理的這篇文章主要介紹了
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()的用法详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ARCore:ARCore的初体验
- 下一篇: 深入理解Windows域概念