Python 如何将无量纲添加回张量?
我在Lambda层中做了一些转换,现在我有了shapePython 如何将无量纲添加回张量?,python,tensorflow,keras,reshape,Python,Tensorflow,Keras,Reshape,我在Lambda层中做了一些转换,现在我有了shape(1,),我如何回到(无,1) 这是我的手术 def function_lambda(x): import keras.backend aux_array = keras.backend.sign(x) #the shape is (?, 11) here OK aux_array = keras.backend.relu(aux_array) #the shape is (?, 11) here
(1,)
,我如何回到(无,1)
这是我的手术
def function_lambda(x):
import keras.backend
aux_array = keras.backend.sign(x)
#the shape is (?, 11) here OK
aux_array = keras.backend.relu(aux_array)
#the shape is (?, 11) here still OK
aux_array = keras.backend.any(aux_array)
#the shape is () here not OK
aux_array = keras.backend.reshape(aux_array, [-1])
#now the shape is (1,) almost OK
return aux_array
如何重塑并放回
None
批处理维度?如果您有一个完全定义的形状(如(1,)
),那么您不需要None
维度,因为您确切地知道张量有多少个元素。但您可以通过以下两个维度来重塑形状:
aux_array = keras.backend.reshape(aux_array, [-1, 1])
这将为您提供一个具有shape(1,1)
的数组,该数组与shape(None,1)
兼容,因此应该可以。请注意,重塑
中的-1
表示“需要多少个元素来适应此形状中的张量”,但在这种情况下,您知道只有一个元素,因此使用以下元素也是一样的:
aux_array = keras.backend.reshape(aux_array, [1, 1])
因为,同样,形状是完全定义的,您知道每个维度的大小应该是什么。但是,使用
-1
很方便,因为无论您是否完全了解形状,它都会起作用,Keras/TensorFlow会计算出尺寸应该是多少(如果可以计算,尺寸将具有必要的尺寸;如果形状的一部分未知,则无)。tf.reforme有一个无法使用的限制“无”维度。据我所知,我们唯一可以定义“无”维度的地方是在tf.placeholder中。以下应该可以使用:
def function_lambda(x):
import keras.backend
aux_array = keras.backend.sign(x)
#the shape is (?, 11) here OK
aux_array = keras.backend.relu(aux_array)
#the shape is (?, 11) here still OK
aux_array = keras.backend.any(aux_array)
#the shape is () here not OK
aux_array = keras.backend.placeholder_with_default(aux_array, [None,1])
#now the shape is (?,1) OK
return aux_array
附加说明:当尝试使用Google机器学习引擎时,创建新的占位符以重新引入“无”维度非常有用。MLE要求第一个维度(批处理)始终保持“无”“或者未知。你明白了吗?我也在想同样的问题。你弄明白了吗?我想这没有抓住重点。当定义一个模型来操作Tensorflow中的张量时,通常需要第一个维度为None或?来表示minibatch维度。例如,[None,12,12]
表示第一个维度未完全指定,将在培训时设置。。在这种情况下,确实需要“无”维度。