Python Theano TypeError: Cannot convert Type TensorType(float64, vector) (of Variable Subtensor{int64:int64:}.0) into Type TensorType(float64, matrix)


參考: https://groups.google.com/forum/#!topic/theano-users/teA-07wOFpE

 

這個問題出現的原因是,我在讀文件的時候,應該Train_X讀成matrix(rows * dimensions),Train_Y讀成vector(因為只有label一維)

因為才接觸python第一天,所以誤以為column=1的matrix就是vector(汗汗汗!)

話不多說,直接貼代碼:

train_X_matrix = numpy.empty((train_rows,n_ins),numpy.float64)#初始化為矩陣
train_Y_matrix = []#為什么要初始化為list,詳見下面解釋

#按行讀文件的float進矩陣
rownum = 0
f = open(train_X_path)
for line in f.readlines():
    train_X_matrix[rownum] = numpy.asarray(line.strip('\n ').split(' '), dtype=float)
    rownum += 1

#按行讀每一行的int進vector
f = open(train_Y_path)
for line in f.readlines():
    train_Y_matrix.append(int(line.strip('\n')))
train_Y_matrix = numpy.asarray(train_Y_matrix)

為什么要初始化list,而非直接初始化一個numpy的array,然后一行一行加呢?

因為網上的一篇文章提到:(參考:http://stackoverflow.com/questions/568962/how-do-i-create-an-empty-array-matrix-in-numpy)

“You have the wrong mental model for using NumPy efficiently. NumPy arrays are stored in contiguous blocks of memory. If you want to add rows or columns to an existing array, the entire array needs to be copied to a new block of memory, creating gaps for the new elements to be stored. This is very inefficient if done repeatedly to build an array.”

意思是什么呢?就是numpy array是連續在內存中保存的,如果append的話它會不斷copy block到新內存,效率太低。

他提供的方式是,先初始化固定大小,然后逐行改array的值,如下:

>>> import numpy
>>> a = numpy.zeros(shape=(5,2))
>>> a
array([[ 0.,  0.],
   [ 0.,  0.],
   [ 0.,  0.],
   [ 0.,  0.],
   [ 0.,  0.]])
>>> a[0] = [1,2]
>>> a[1] = [2,3]
>>> a
array([[ 1.,  2.],
   [ 2.,  3.],
   [ 0.,  0.],
   [ 0.,  0.],
   [ 0.,  0.]])

但是感覺這樣還是不方便,於是就先初始化空list,再不斷append,最后全部轉化為numpy 的 array,就是代碼中寫的。

 

這里為什么非要轉化為numpy的array呢?

因為theano代碼中默認的是需要share成他的tensor型變量(這句話待定,時間到了,具體不誤人子弟了,反正就是他需要share一下)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM