使用tensorflow根據(jù)輸入更改tensor shape
涉及隨機(jī)數(shù)以及類RNN的網(wǎng)絡(luò)構(gòu)建常常需要根據(jù)輸入shape,決定中間變量的shape或步長(zhǎng)。
tf.shape函數(shù)不同于tensor.shape.as_list()函數(shù),后者返回的是常值list,而前者返回的是tensor。
使用tf.shape函數(shù)可以使得中間變量的tensor形狀隨輸入變化,不需要在構(gòu)建Graph的時(shí)候指定。但對(duì)于tf.Variable,因?yàn)樾枰崆胺峙涔潭臻g,其shape無法通過上訴方法設(shè)定。
實(shí)例代碼如下:
a = tf.placeholder(tf.float32,[None,])
b = tf.random_normal(tf.concat([tf.shape(a),[2,]],axis=0))
補(bǔ)充知識(shí):pytorch中model=model.to(device)用法
這代表將模型加載到指定設(shè)備上。
其中,device=torch.device("cpu")代表的使用cpu,而device=torch.device("cuda")則代表的使用GPU。
當(dāng)我們指定了設(shè)備之后,就需要將模型加載到相應(yīng)設(shè)備中,此時(shí)需要使用model=model.to(device),將模型加載到相應(yīng)的設(shè)備中。
將由GPU保存的模型加載到CPU上。
將torch.load()函數(shù)中的map_location參數(shù)設(shè)置為torch.device('cpu')
device = torch.device('cpu') model = TheModelClass(*args, **kwargs) model.load_state_dict(torch.load(PATH, map_location=device))
將由GPU保存的模型加載到GPU上。確保對(duì)輸入的tensors調(diào)用input = input.to(device)方法。
device = torch.device("cuda") model = TheModelClass(*args, **kwargs) model.load_state_dict(torch.load(PATH)) model.to(device)
將由CPU保存的模型加載到GPU上。確保對(duì)輸入的tensors調(diào)用input = input.to(device)方法。map_location是將模型加載到GPU上,model.to(torch.device('cuda'))是將模型參數(shù)加載為CUDA的tensor。最后保證使用.to(torch.device('cuda'))方法將需要使用的參數(shù)放入CUDA。
device = torch.device("cuda") model = TheModelClass(*args, **kwargs) model.load_state_dict(torch.load(PATH, map_location="cuda:0")) # Choose whatever GPU device number you want model.to(device)
以上這篇使用tensorflow根據(jù)輸入更改tensor shape就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python圖形用戶界面tkinter之按鈕Button的使用說明
這篇文章主要介紹了python圖形用戶界面tkinter之按鈕Button的使用說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06pycharm下查看python的變量類型和變量?jī)?nèi)容的方法
今天小編就為大家分享一篇pycharm下查看python的變量類型和變量?jī)?nèi)容的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06pytorch中nn.Flatten()函數(shù)詳解及示例
nn.Flatten是一個(gè)類,而torch.flatten()則是一個(gè)函數(shù),下面這篇文章主要給大家介紹了關(guān)于pytorch中nn.Flatten()函數(shù)詳解及示例的相關(guān)資料,需要的朋友可以參考下2023-01-01淺談Python2之漢字編碼為unicode的問題(即類似\xc3\xa4)
今天小編就為大家分享一篇淺談Python2之漢字編碼為unicode的問題(即類似\xc3\xa4),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-08-08python?keras構(gòu)建和訓(xùn)練模型簡(jiǎn)便性初探
這篇文章主要介紹了python?keras構(gòu)建和訓(xùn)練模型簡(jiǎn)便性初探,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-02-02python自動(dòng)化測(cè)試實(shí)例解析
這篇文章主要介紹了python自動(dòng)化測(cè)試實(shí)例,并對(duì)實(shí)例中的注意點(diǎn)進(jìn)行了簡(jiǎn)單的分析,需要的朋友可以參考下2014-09-09