1. 程式人生 > 程式設計 >Pytorch中的variable, tensor與numpy相互轉化的方法

Pytorch中的variable, tensor與numpy相互轉化的方法

在使用pytorch作為深度學習的框架時,經常會遇到變數variable、張量tensor與矩陣numpy的型別的相互轉化的問題,本章結合這實際影象對此轉化方法進行實現。

1.載入需要用到的模組

import torch
from torch.autograd import Variable
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

2.顯示圖片與圖片中的一部分割槽域

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矩陣轉換為Tensor張量

sub_ts = torch.from_numpy(sub_img)  #sub_img為numpy型別

4.將Tensor張量轉化為numpy矩陣

sub_np1 = sub_ts.numpy()       #sub_ts為tensor張量

5.將numpy轉換為Variable

sub_va = Variable(torch.from_numpy(sub_img))

6.將Variable張量轉化為numpy

sub_np2 = sub_va.data.numpy()

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。