text_plain_output_1.png
from keras.callbacks import EarlyStopping ,ReduceLROnPlateau

from keras.callbacks import ModelCheckpoint, TensorBoard

from keras.layers import Input, Dense

from keras.models import Model, load_model

from sklearn import preprocessing

from sklearn.model_selection import train_test_split

import matplotlib.pyplot as plt

import pandas as pd

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import seaborn as sns

df_cred = pd.read_csv('/kaggle/input/creditcardfraud/creditcard.csv')

df_cred.shape

plt.style.use('ggplot') # Using ggplot2 style visuals 

f, ax = plt.subplots(figsize=(11, 15))

ax.set_facecolor('#fafafa')
ax.set(xlim=(-5, 5))
plt.ylabel('Variables')
plt.title("Overview Data Set")
ax = sns.boxplot(data = df_cred.drop(columns=['Amount', 'Class', 'Time']), 
  orient = 'h', 
  palette = 'Set2')

def plot_distribution(data_select):
    figsize = (15, 8)
    sns.set_style('ticks')
    s = sns.FacetGrid(df_cred, hue='Class', aspect=2.5, palette={0: 'lime', 1: 'black'})
    s.map(sns.kdeplot, data_select, shade=True, alpha=0.6)
    s.set(xlim=(df_cred[data_select].min(), df_cred[data_select].max()))
    s.add_legend()
    s.set_axis_labels(data_select, 'proportion')

min_max_scaler = preprocessing.MinMaxScaler()
df_cred = df_cred.drop('Time', axis=1)
df_cred_scaled = min_max_scaler.fit_transform(df_cred.iloc[:, :-1])
df_cred_normalized = pd.DataFrame(df_cred_scaled)

df_cred_normalized_train = df_cred_normalized[df_cred_normalized['Class'] == 0]
df_cred_normalized_test = df_cred_normalized[df_cred_normalized['Class'] == 1]

df_cred_normalized_test_part_1 = df_cred_normalized_train.sample(frac=0.05)
df_cred_normalized_train = df_cred_normalized_train.drop(df_cred_normalized_test_part_1.index)
df_cred_normalized_test_part_2 = df_cred_normalized_train.sample(frac=0.05)
df_cred_normalized_train = df_cred_normalized_train.drop(df_cred_normalized_test_part_2.index)

df_cred_normalized_test_class_1 = df_cred_normalized_test.sample(frac=0.5)
df_cred_normalized_validation_class_1 = df_cred_normalized_test.drop(df_cred_normalized_test_class_1.index)

df_cred_normalized_test_class_1.shape

df_cred_normalized_test_set = df_cred_normalized_test_part_1.append(df_cred_normalized_test_class_1)
df_cred_normalized_validation_set = df_cred_normalized_test_part_2.append(df_cred_normalized_validation_class_1)

X_train, X_test = train_test_split(df_cred_normalized_train, test_size=0.2, random_state=2020)
X_train = X_train[X_train.Class == 0]
X_train = X_train.drop(['Class'], axis=1)
y_test = X_test['Class']
X_test = X_test.drop(['Class'], axis=1)
X_train = X_train.values
X_test = X_test.values
X_train.shape

input_dim = X_train.shape[1]
encoding_dim = 20
input_layer = Input(shape=(input_dim,))
encoder = Dense(encoding_dim * 2, activation='sigmoid')(input_layer)
encoder = Dense(encoding_dim, activation='sigmoid')(input_layer)
encoder = Dense(8, activation='sigmoid')(encoder)
decoder = Dense(20, activation='sigmoid')(encoder)
decoder = Dense(40, activation='sigmoid')(encoder)
decoder = Dense(input_dim, activation='sigmoid')(decoder)
autoencoder = Model(inputs=input_layer, outputs=decoder)

nb_epoch = 50
batch_size = 32
autoencoder.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=15)
checkpointer = ModelCheckpoint(filepath='model.h5', verbose=0, save_best_only=True)
history = autoencoder.fit(X_train, X_train, epochs=nb_epoch, batch_size=batch_size, shuffle=True, validation_data=(X_test, X_test), callbacks=[es, checkpointer], verbose=1)

plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper right')
plt.show()
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model acc')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper right')
plt.show()