TensorFlow用expand_dim()來(lái)增加維度的方法
TensorFlow中,想要維度增加一維,可以使用tf.expand_dims(input, dim, name=None)函數(shù)。當(dāng)然,我們常用tf.reshape(input, shape=[])也可以達(dá)到相同效果,但是有些時(shí)候在構(gòu)建圖的過(guò)程中,placeholder沒(méi)有被feed具體的值,這時(shí)就會(huì)包下面的錯(cuò)誤:TypeError: Expected binary or unicode string, got 1
在這種情況下,我們就可以考慮使用expand_dims來(lái)將維度加1。比如我自己代碼中遇到的情況,在對(duì)圖像維度降到二維做特定操作后,要還原成四維[batch, height, width, channels],前后各增加一維。如果用reshape,則因?yàn)樯鲜鲈驁?bào)錯(cuò)
one_img2 = tf.reshape(one_img, shape=[1, one_img.get_shape()[0].value, one_img.get_shape()[1].value, 1])
用下面的方法可以實(shí)現(xiàn):
one_img = tf.expand_dims(one_img, 0) one_img = tf.expand_dims(one_img, -1) #-1表示最后一維
在最后,給出官方的例子和說(shuō)明
# '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()來(lái)增加維度的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python趣味挑戰(zhàn)之爬取天氣與微博熱搜并自動(dòng)發(fā)給微信好友
忙著畢設(shè)與打游戲之余,突然想著寫個(gè)爬蟲(chóng)練練手,想了想,就寫了一個(gè)爬蟲(chóng)爬取“中國(guó)天氣網(wǎng)”與“微博熱搜”并定時(shí)發(fā)送給微信好友,放到服務(wù)器上運(yùn)行了幾天算是正常,需要的朋友可以參考下2021-05-05
PyQt5實(shí)現(xiàn)五子棋游戲(人機(jī)對(duì)弈)
這篇文章主要為大家詳細(xì)介紹了PyQt5實(shí)現(xiàn)五子棋游戲,人機(jī)對(duì)弈,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01
Python實(shí)現(xiàn)學(xué)生管理系統(tǒng)的完整代碼(面向?qū)ο?
這篇文章主要介紹了Python實(shí)現(xiàn)學(xué)生管理系統(tǒng)的完整代碼(面向?qū)ο?,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
用python實(shí)現(xiàn)英文字母和相應(yīng)序數(shù)轉(zhuǎn)換的方法
這篇文章主要介紹了用python實(shí)現(xiàn)英文字母和相應(yīng)序數(shù)轉(zhuǎn)換的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09

