Pytorch中的variable, tensor与numpy相互转化的方法
來(lái)源:https://blog.csdn.net/pengge0433/article/details/79459679
在使用pytorch作為深度學(xué)習(xí)的框架時(shí),經(jīng)常會(huì)遇到變量variable、張量tensor與矩陣numpy的類型的相互轉(zhuǎn)化的問(wèn)題,本章結(jié)合這實(shí)際圖像對(duì)此轉(zhuǎn)化方法進(jìn)行實(shí)現(xiàn)。
1.加載需要用到的模塊
?import torch
from torch.autograd import Variable
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
2.顯示圖片與圖片中的一部分區(qū)域
?test_img = mpimg.imread('example1.jpg')
i_x = 20
i_y = 85
sub_img = test_img[i_y:i_y + 100,i_x:i_x + 100,:] #numpy類型
3.將numpy矩陣轉(zhuǎn)換為T(mén)ensor張量
sub_ts = torch.from_numpy(sub_img) #sub_img為numpy類型4.將Tensor張量轉(zhuǎn)化為numpy矩陣
sub_np1 = sub_ts.numpy() #sub_ts為tensor張量5.將numpy轉(zhuǎn)換為Variable
sub_va = Variable(torch.from_numpy(sub_img))6.將Variable張量轉(zhuǎn)化為numpy
sub_np2 = sub_va.data.numpy()總結(jié)
以上是生活随笔為你收集整理的Pytorch中的variable, tensor与numpy相互转化的方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 部队打胜仗的16字标语有哪些?
- 下一篇: Variable、Tensor、Nump