Skip to content

Instantly share code, notes, and snippets.

@coderfi
Created May 14, 2018 21:59
Show Gist options
  • Save coderfi/a00174e79d7ca694d8c1888d01462aec to your computer and use it in GitHub Desktop.
Save coderfi/a00174e79d7ca694d8c1888d01462aec to your computer and use it in GitHub Desktop.
MultiLabel classifier example using Keras + Tensorflow
#!/usr/bin/env python
''' MultiLabel classifier example using Keras + Tensorflow.
Based on
* https://www.depends-on-the-definition.com/guide-to-multi-label-classification-with-neural-networks/
* https://www.depends-on-the-definition.com/classifying-genres-of-movies-by-looking-at-the-poster-a-neural-approach/
* https://keras.io/getting-started/sequential-model-guide/#examples
'''
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import random
nn = Sequential()
nn.add(Dense(10, activation="relu", input_shape=(10,)))
nn.add(Dense(5, activation='sigmoid'))
nn.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
x_train = np.random.random((1000, 10))
y_train = np.random.randint(2, size=(1000, 5))
x_test = np.random.random((100, 10))
y_test = np.random.randint(2, size=(100, 5))
nn.fit(x_train, y_train, batch_size=16, epochs=5, verbose=1, validation_split=0.1)
score = nn.evaluate(x_test, y_test, batch_size=128)
print("Evaluation score:", score)
x, y = x_test[:1], y_test[:1]
print("X:\n\t", x[0])
print("Y (Actual):\n\t", y[0])
prediction = nn.predict(x)
print("Prediction:\n\t", prediction)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment