Skip to content

Instantly share code, notes, and snippets.

@charlie2951
Created June 19, 2022 12:58
Show Gist options
  • Save charlie2951/38102397af5ab4cc9d90f7cb97e6253c to your computer and use it in GitHub Desktop.
Save charlie2951/38102397af5ab4cc9d90f7cb97e6253c to your computer and use it in GitHub Desktop.
import tensorflow as tf
from tensorflow import keras
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pima = pd.read_csv("diabetes.csv")
pima.head()
#split dataset in features and target variable
feature_cols = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness','Insulin','BMI','DiabetesPedigreeFunction', 'Age']
Xraw = pima[feature_cols] # Features
y = pima.Outcome # Target variable
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X = scaler.fit_transform(Xraw)
# split X and y into training and testing sets
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.05,random_state=0)
print(y_test)
# We'll use Keras to create a Neural network
model = tf.keras.Sequential()
model.add(keras.layers.Dense(4, activation='relu', input_shape=(8,)))
model.add(keras.layers.Dense(2,activation='relu'))
#model.add(keras.layers.Dense(8,activation='relu'))
model.add(keras.layers.Dense(1,activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
history_1 = model.fit(X_train, y_train, epochs=500, validation_data=(X_test, y_test))
# Exclude the first few epochs so the graph is easier to read
loss = history_1.history['loss']
val_loss = history_1.history['val_loss']
epochs = range(1, len(loss) + 1)
SKIP = 10
plt.plot(epochs[SKIP:], loss[SKIP:], 'g.', label='Training loss')
plt.plot(epochs[SKIP:], val_loss[SKIP:], 'b.', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
# Find the weights of the model
weights = model.get_weights()
print(weights)
# Saving the array in a text file
file = open("hyper_param.txt", "w+")
content = str(weights)
file.write(content)
file.close()
#y_pred = model.predict(X_test)
# extract the predicted probabilities
p_pred = model.predict(X_test)
p_pred = p_pred.flatten()
print(p_pred.round(2))
# [1. 0.01 0.91 0.87 0.06 0.95 0.24 0.58 0.78 ...
# extract the predicted class labels
y_pred = np.where(p_pred > 0.5, 1, 0)
print(y_pred)
# import the metrics class
from sklearn import metrics
cnf_matrix = metrics.confusion_matrix(y_test, y_pred)
cnf_matrix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment