import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt print(tf.__version__) from google.colab import files setdate = files.upload() import pandas as pd dataset = pd.read_csv('n7point.csv') dataset.head() dataset.shape x = dataset.iloc[:,0:7].values y = dataset.iloc[:,7].values x[1,:] x.shape, y.shape # split dataset from sklearn.model_selection import train_test_split x_train,x_test, y_train,y_test = train_test_split(x,y,test_size=0.3,random_state=0) x_train.shape, y_train.shape, x_test.shape, y_test.shape x_train.shape, x_test.shape x_train = x_train.reshape(11779, 7, 1) x_test = x_test.reshape(2945, 7, 1) model_CNN9 = tf.keras.models.Sequential() model_CNN9.add(tf.keras.layers.Input(shape=(7,1))) model_CNN9.add(tf.keras.layers.Conv1D(filters=64, kernel_size=2, activation='relu', name="Conv1D_1")) model_CNN9.add(tf.keras.layers.Dropout(0.2)) model_CNN9.add(tf.keras.layers.Conv1D(filters=32, kernel_size=1, activation='relu', name="Conv1D_2")) model_CNN9.add(tf.keras.layers.MaxPooling1D(pool_size=1, name="MaxPooling1D")) model_CNN9.add(tf.keras.layers.Flatten(name="Flatten")) model_CNN9.add(tf.keras.layers.Dense(32, activation="relu")) model_CNN9.add(tf.keras.layers.Dense(1, activation = 'sigmoid')) model_CNN9.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy']) model_CNN9.summary() hist=model_CNN9.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=100) # Commented out IPython magic to ensure Python compatibility. import matplotlib.pyplot as plt # %matplotlib inline import seaborn as sns sns.set() acc = hist.history['accuracy'] val = hist.history['val_accuracy'] epochs = range(1, len(acc) + 1) plt.plot(epochs, acc, '-', label='Training accuracy') plt.plot(epochs, val, ':', label='Validation accuracy') plt.title('Training and Validation Accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend(loc='lower right') plt.plot() acc = hist.history['accuracy'] val_acc = hist.history['val_accuracy'] loss = hist.history['loss'] val_loss = hist.history['val_loss'] epochs_range = range(100) plt.figure(figsize=(8, 8)) plt.plot(epochs_range, acc, label='Training Accuracy') plt.plot(epochs_range, val_acc, label='Validation Accuracy') plt.legend(loc='lower right') plt.title('Accuracy') from google.colab import drive drive.mount('/content/drive') from tensorflow import keras keras.utils.plot_model(model_CNN9, "/content/drive/MyDrive/IA_Samples/Doctorat/model9_CNN.png", show_shapes=True, expand_nested=True) # Evaluate on test data test_loss, test_acc = model_CNN9.evaluate(x_test, y_test) print('Test Accuracy: {}'.format(test_acc)) # Evaluate on training data train_loss, train_acc = model_CNN9.evaluate(x_train, y_train) print('Train Accuracy: {}'.format(train_acc)) from sklearn.metrics import confusion_matrix y_predicted = model_CNN9.predict(x_test) > 0.5 mat = confusion_matrix(y_test, y_predicted) labels = ['class 0', 'class 1'] sns.heatmap(mat, square=True, annot=True, fmt='d', cbar=False, cmap='Blues', xticklabels=labels, yticklabels=labels) plt.xlabel('Predicted label') plt.ylabel('Actual label') from sklearn.metrics import classification_report print(classification_report(y_test, y_predicted)) import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import accuracy_score, confusion_matrix, roc_auc_score, roc_curve def plot_roc_curve(true_y, y_prob): """ plots the roc curve based of the probabilities """ fpr, tpr, thresholds = roc_curve(true_y, y_prob) plt.plot(fpr, tpr) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plot_roc_curve(y_test, y_predicted) print(f'model CNN AUC score: {roc_auc_score(y_test, y_predicted)}') # serialize model to JSON model_json = model_CNN9.to_json() with open("/content/drive/MyDrive/IA_Samples/Doctorat_Moraru1/model9_cnn.json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model_CNN9.save_weights("/content/drive/MyDrive/IA_Samples/Doctorat_Moraru1/model9_cnn.h5") print("Saved model to disk")