Open BobZiyangDing opened 5 years ago
import tensorflow as tf
from keras.models import Model
from keras.layers import Subtract, Lambda, Dense, Input, Flatten
from keras import backend as K
from keras.datasets import mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
x_train = x_train.reshape((-1, 784))
x_test = x_test.reshape((-1, 784))
inputs = Input(shape=(784,))
x1 = Dense(64, activation='relu')(inputs)
x2 = Dense(64, activation='relu')(x1)
predictions = Dense(10, activation='softmax')(x2)
model = Model(inputs=inputs, outputs=predictions)
model.compile(optimizer='rmsprop',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train)
## And yours
threshold = 30
distance = Subtract()([x1, x2])
def getOutput(X):
distance = tf.norm(X, axis = 1)
output = K.cast(tf.less_equal(distance, threshold), tf.float32)
return output
output = Lambda(getOutput)(distance)
model_i = Model(inputs=inputs, outputs=output)
predicted_i = model_i.predict(x_test)
import numpy as np
print(np.unique(predicted_i, return_counts=True))
# And this gives following:
>>> (array([0., 1.], dtype=float32), array([ 4, 9996]))
I couldn't reproduce your error, it worked just fine as you intended. And by the way, this kind of question is better to be asked in Stackoverflow I guess, since it seems like it's not an issue or a bug of the project. :)
Here's the task: I've got 2 Keras layers, encode_p_neck & encode_g_neck. They are of the same dimension. I want to calculate the distance between these 2 vectors, and if the distance is greater than a threshold, then I predict this pair of 2 vectors as negative. If the distance is smaller than a threshold, then I predict this pair of 2 vectors as positive. At last, I want to calculate AUC and output this prediction. The responsible code is as follows:
because the output for Keras model has to be a layer, so I did this. But error shows:
Why? How to fix this?