Skip to content

Instantly share code, notes, and snippets.

@johnifegwu
Last active April 13, 2020 13:44
Show Gist options
  • Save johnifegwu/804dc3933153d1674efd9d88ad06080a to your computer and use it in GitHub Desktop.
Save johnifegwu/804dc3933153d1674efd9d88ad06080a to your computer and use it in GitHub Desktop.
Deep Learning Example (Python Implementation) requires the file (prima-indians-diabetes.csv) available as a separate gist.
# my first neural network with keras
# requires that TensorFlow or Theano be installed
from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense
from keras.models import model_from_json
import numpy
import os
# fix random seed for reproducibility
numpy.random.seed(7)
# load the data into a Dataset
#There are eigth input variables:
#
# input Variable (x):
#
# 1. Number of times pregnant.
# 2. Plasma glucose concentration, 2 hours in an Oral glucose tolerance test.
# 3. Diastolic blood pressure (mm Hg).
# 4. Triceps skin fold thickness (mm).
# 5. 2-Hour Serum Insulin (mu U/ml).
# 6. Body mass index (weigth in kg/(height in m)^2).
# 7. Diabetes pedigree function.
# 8. Age (Years).
#
# Output Variable (y):
#
# 1. Class variable (0 or 1)
dataset = loadtxt('prima-indians-diabetes.csv', delimiter=',')
save_dir = os.path.join(os.getcwd(), 'saved_models')
model_name = 'keras_Sugar_Predictions_trained_model.h5'
model_json_name = "Keras_Prima.json"
# we will train the system 30 times to determine its accuracy.
for i in range(30):
# split into input (x) and output (y) variables
x = dataset[:,0:8]
y = dataset[:,8]
# define the keras model
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# compile the keras model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# fit the keras model on the dataset
# we will use 200 epochs and batch size of 10 for improved Accuracy of (upto %80.2.)
model.fit(x, y, epochs=200, batch_size=10, verbose=0) #set verbose to 1 if you want the training progress displayed.
# evaluate the keras model
_, accuracy = model.evaluate(x, y)
print("Accuracy: %{0}".format(accuracy*100))
# we will save if our desired accuracy is reached.
if ((accuracy*100) > 79.50):
# Save model and weights
# serialize model to JSON
model_json = model.to_json()
with open(os.path.join(save_dir, model_json_name), "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model_path = os.path.join(save_dir,model_name)
model.save_weights(model_path)
print("Saved trained model to disk")
break # stop the loop.
# make class predictions with the model
#
# split into input (x) and output (y) variables
x = dataset[:,0:8]
y = dataset[:,8]
# Load from disk
model_json_path = os.path.join(save_dir,model_json_name)
model_path = os.path.join(save_dir,model_name)
if (os.path.exists(model_path) and os.path.exists(model_json_path)):
#load json and create model
json_file = open(model_json_path, "r")
loaded_model_json = json_file.read()
json_file.close()
model2 = model_from_json(loaded_model_json)
# load weights into new model
model2.load_weights(model_path)
print("Loaded model from disk")
model2.compile(loss="binary_crossentropy", optimizer="rmsprop", metrics=["accuracy"])
predictions = model2.predict_classes(x)
# summarize the first five cases
for i in range(5):
print('%s => %d (expected %d)' % (x[i].tolist(), predictions[i], y[i]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment