I am trying to implement a binarized neural network using keras and tensorflow. Here is my current code:
import tensorflow as tf
from tensorflow import keras
from keras import datasets
from keras.utils.vis_utils import plot_model
from keras.layers import Activation
from keras import backend as K
from keras.utils.generic_utils import get_custom_objects
def sign(x):
result = K.sign(x)
return result
get_custom_objects().update({'custom_activation': Activation(sign)})
digit_data = datasets.mnist
(train_images, train_labels), (test_images, test_labels) = digit_data.load_data()
# import matplotlib.pyplot as plt
# plt.imshow(train_images[0])
# print(train_labels[0])
# print(train_images[0])
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(784, Activation(sign, name='SpecialActivation')),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
# model = keras.Sequential([
# keras.layers.Flatten(input_shape=(28, 28)),
# keras.layers.Dense(128, activation=tf.nn.relu),
# keras.layers.Dense(10, activation=tf.nn.softmax)
# ])
# plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)
model.compile(optimizer=tf.keras.optimizers.Adam(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(test_loss, test_acc)
The activation function I am currently using is a sign function which returns -1 if x < 0 | 0 if x=0 | 1 if x >0 the binarized neural network needs to have a bitwise operation function which returns +1 if x => 0 and -1 if x< 0 (from what i understand)
I'm not sure how to implement that kind of an activation function.