numpy.asarray與theano.shared比較

1、numpy.asarray

當設置了類型並且類型不一致時,asarray返回一個副本,否則返回一個引用。舉例:

>>> a = np.array([1, 2], dtype=np.float32)
>>> np.asarray(a, dtype=np.float32) is aTrue
>>> np.asarray(a, dtype=np.float64) is aFalse

詳見:https://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html


2、theano.shared用於關聯Theano內存空間和用戶內存空間,使用參數borrow=Ture進行設置。舉例:

import numpy, theano
np_array = numpy.ones(2, dtype='float32')
s_default = theano.shared(np_array)
s_false   = theano.shared(np_array, borrow=False)
s_true    = theano.shared(np_array, borrow=True)
np_array += 1 # now it is an array of 2.0 s
print(s_default.get_value())
print(s_false.get_value())
print(s_true.get_value())
[ 1.  1.]
[ 1.  1.]
[ 2.  2.]
get_value都會返回副本,當borrow=ture時,會把兩個空間進行關聯,這種情況下不要對返回值進行更改,否則代碼會變成設備相關,導致部分操作無法執行

詳見:http://deeplearning.net/software/theano/tutorial/aliasing.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章