我正在尝试实现一个层(通过lambda层),它执行以下numpy过程:
def func(x, n):
return np.concatenate((x[:, :n], np.tile(x[:, n:].mean(axis = 0), (x.shape[0], 1))), axis = 1)
Run Code Online (Sandbox Code Playgroud)
我被卡住了,因为我不知道如何获得x的第一个维度的大小(这是批量大小).后端函数int_shape(x)返回(None, ...).
所以,如果我知道batch_size,相应的Keras过程将是:
def func(x, n):
return K.concatenate([x[:, :n], K.tile(K.mean(x[:, n:], axis=0), [batch_size, 1])], axis = 1)
Run Code Online (Sandbox Code Playgroud)
正如@pitfall所说, 的第二个参数K.tile应该是张量。根据keras backend 的文档,K.shape返回一个张量并K.int_shape返回一个 int 或 None 条目的元组。所以正确的方法是使用K.shape. 以下是 MWE:
import keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
import numpy as np
batch_size = 8
op_len = ip_len = 10
def func(X):
return K.tile(K.mean(X, axis=0, keepdims=True), (K.shape(X)[0], 1))
ip = Input((ip_len,))
lbd = Lambda(lambda x:func(x))(ip)
model = Model(ip, lbd)
model.summary()
model.compile('adam', loss='mse')
X = np.random.randn(batch_size*100, ip_len)
Y = np.random.randn(batch_size*100, op_len)
#no parameters to train!
#model.fit(X,Y,batch_size=batch_size)
#prediction
np_result = np.tile(np.mean(X[:batch_size], axis=0, keepdims=True),
(batch_size,1))
pred_result = model.predict(X[:batch_size])
print(np.allclose(np_result, pred_result))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2143 次 |
| 最近记录: |