Skip to content

Instantly share code, notes, and snippets.

@ahmedbilal
Created June 18, 2019 09:57
Show Gist options
  • Save ahmedbilal/47ea28a2b08c91d29b7dcadd434ba230 to your computer and use it in GitHub Desktop.
Save ahmedbilal/47ea28a2b08c91d29b7dcadd434ba230 to your computer and use it in GitHub Desktop.
import keras
import numpy as np
from os.path import isfile as is_file_exists
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import Adam
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
def get_data(filename):
_list = []
with open(filename, "r") as f:
for line in f.readlines():
_list.append([int(line) for line in line.split(",")])
return np.array(_list)
def get_label(filename):
_list = []
with open(filename, "r") as f:
for label in f.readlines():
_list.append(int(label))
return np.array(_list)
model = Sequential()
# Layers
model.add(Dense(24,activation='relu'))
model.add(Dense(7,activation='softmax'))
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'],
batch_size=16)
data = get_data("data.txt")
labels = get_label("data_labels.txt")
X_train, X_test, y_train, y_test = train_test_split(data, labels,
test_size=0.40, random_state=42)
training_labels = keras.utils.to_categorical(y_train, num_classes=7)
testing_labels = keras.utils.to_categorical(y_test, num_classes=7)
if not is_file_exists("trained_model"):
model.fit(X_train,training_labels,epochs=7)
model.save('trained_model')
else:
model = keras.models.load_model('trained_model')
test_loss, test_accuracy = model.evaluate(X_test, testing_labels)
print("Test Loss", test_loss)
print("Test Accuracy", test_accuracy)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment