Skip to content

Instantly share code, notes, and snippets.

@cpdef
Created November 25, 2019 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpdef/404807e3874133ac279d94aa287d8007 to your computer and use it in GitHub Desktop.
Save cpdef/404807e3874133ac279d94aa287d8007 to your computer and use it in GitHub Desktop.
odd-even test tensorflow
# what you need to run this:
# tensorflow 2.0.0
from __future__ import absolute_import, division, print_function, unicode_literals
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import random
# convert a number to a 2 dimensional binary representation
# because tensorflow can work better with it
def pproc_num(num):
binary = bin(num)[2:].zfill(4*6)
result = []
for i in range(6):
idx_begin = 4*i
idx_end = idx_begin+4
result.append([int(j) for j in binary[idx_begin:idx_end]])
return np.array(result)
def load_data():
numbers = []
labels = []
for i in range(167772):
# get one random number
rnd = random.randrange(16777216)
# preprocess it
pproced_num = pproc_num(rnd)
# push it back to numbers
numbers.append(pproced_num)
# calculate wether its odd or even
labels.append(rnd % 2)
a = np.array
return (a(numbers[:-100000]), a(labels[:-100000])), (a(numbers[-100000:-(100000-6000)]), a(labels[-100000:-(100000-6000)]))
# load the data
(train_data, train_labels), (test_data, test_labels) = load_data()
print("shape:")
print(train_data.shape)
print(train_labels.shape)
print(test_data.shape)
print(test_labels.shape)
# define the model
model = keras.Sequential([
# first net layer is to flatten the data
keras.layers.Flatten(input_shape=train_data[0].shape),
# one hidden layer
keras.layers.Dense(64, activation='relu'),
# one result layer
keras.layers.Dense(2, activation='softmax')
])
# train the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_data, train_labels, epochs=6)
# test the model
test_loss, test_acc = model.evaluate(test_data, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
# test the net on the numbers from 0 to 99
class_names = ['even', 'odd']
predictions = model.predict(np.array(
[ pproc_num(i) for i in range(100) ]
))
for i in range(100):
# get the best match
result = np.argmax(predictions[i])
# map the match to the class name
result = class_names[result]
print(i, result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment