我使用Keras和TensorFlow後端來構建和運行神經網絡。我需要在丟失函數中對輸出張量使用numpy函數。更具體地說,我的損失函數包括尋找最近的鄰居,並且我需要爲此使用Keras功能ckdTree。我已經嘗試使用K.eval()
將輸出張量轉換爲numpy數組。但是,當我嘗試編譯模型時,這會引發InvalidArgument
錯誤,我相信,因爲您無法在符號變量上運行eval()
。如何在損失函數中對keras張量使用numpy函數?
下面是一個重現此錯誤的玩具代碼片段。
import numpy as np
from keras import backend as K
from keras.models import Sequential
from keras.layers.core import Flatten, Dense, Reshape
from keras.optimizers import Adam
def loss(y_true, y_pred):
y_pred_numpy = K.eval(y_pred)
# perform some numpy operations on y_pred_numpy
return K.constant(0)
''' Model '''
input_shape = (10,10,10,3)
train_images = np.zeros((1,10,10,10,3))
train_labels = np.zeros((1,1,1,1,3))
model = Sequential()
model.add(Flatten(input_shape=input_shape))
model.add(Dense(3000, use_bias=True, bias_initializer='zeros'))
model.add(Reshape((10,10,10,3)))
model.summary()
opt = Adam(lr=1E-4)
model.compile(optimizer=opt, loss=loss)
以上提供了以下錯誤:
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'flatten_3_input' with dtype float
[[Node: flatten_3_input = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
[[Node: reshape_3/Reshape/_11 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_20_reshape_3/Reshape", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
那麼我怎樣Keras張量的工作而不必使用Keras重寫(複雜)numpy的功能?
它是否真的是一個損失函數的問題?你有沒有試過編譯'loss ='mse''? - 儘管如此,我不確定凱拉斯會接受張量的無規律操作。 :( –
你有看看[這個問題](https://stackoverflow.com/questions/39921607/how-to-make-a-custom-activation-function-with-only-python-in-tensorflow)已經? –