Skip to content

Instantly share code, notes, and snippets.

@danieldaeschle
Created July 28, 2018 11:49
Show Gist options
  • Save danieldaeschle/df229cdaf86455b4b4a66766c9b08b76 to your computer and use it in GitHub Desktop.
Save danieldaeschle/df229cdaf86455b4b4a66766c9b08b76 to your computer and use it in GitHub Desktop.
My second NN which can see if a number is even or odd
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense
from random import sample
import numpy as np
import os
# Train data (Number 0 to 99 in binary list format with maximum length of 10)
x_train = np.array(list(map(lambda x: [0 for _ in range(
10 - len(format(x[0], "b")))] + list(format(x[0], "b")), sample([[x] for x in range(100)], 100))))
y_train = np.array([not bool(int(''.join(x), 2) % 2) for x in x_train])
y_train_binary = to_categorical(y_train)
# Test data same like train data
x_test = np.array(list(map(lambda x: [0 for _ in range(
10 - len(format(x[0], "b")))] + list(format(x[0], "b")), sample([[x] for x in range(100)], 100))))
y_test = np.array([not bool(int(''.join(x), 2) % 2) for x in x_test])
y_test_binary = to_categorical(y_test)
# Neural Network
model = Sequential([
Dense(units=2, activation="relu", input_dim=10),
Dense(units=2, activation="softmax")
])
model.compile(optimizer="sgd", loss="binary_crossentropy",
metrics=["accuracy"])
if os.path.exists("weights.h5"):
model.load_weights("weights.h5")
else:
model.fit(x_train, y_train_binary, epochs=30, batch_size=1)
model.save_weights("weights.h5")
loss_metrics = model.evaluate(x_test, y_test_binary, batch_size=1)
print("Loss:", loss_metrics[0], "Accuracy: ", str(loss_metrics[1] * 100) + "%")
while True:
x_predict = input("Give me a number: ")
# Parse input to integer
try:
x_predict = int(x_predict)
except ValueError:
print("This wasn't a number.")
continue
# Check if number is too long
if len(list(format(x_predict, "b"))) > 10:
print("Number is too big.")
continue
# Check for negative number
if x_predict < 0:
x_predict *= -1
x_predict = np.array(
[[0 for _ in range(10 - len(format(x_predict, "b")))] + list(format(x_predict, "b"))])
result = model.predict(x_predict)
print("Number is even." if result[0][1] > result[0][0] else "Number is odd.", result[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment