import numpy as np
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import torch
from sklearn.metrics import confusion_matrix

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)

# Leemos los datos
D = np.genfromtxt( "creditcard.csv", delimiter=',', skip_header=1, usecols=(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30), dtype=np.float32)
print( D.shape )

# De 0 a 27 son las características

A = StandardScaler().fit_transform( D[:,28].reshape(-1,1) )
print(A.shape)

D[:,28] = A[:,0]
print( D.shape )

Datos = torch.from_numpy( D )

# Leemos el modelo
class AE(torch.nn.Module):
    def __init__(self):
        super().__init__()
         
       
        self.encoder = torch.nn.Sequential(
            torch.nn.Linear(29, 20),
            torch.nn.Tanh(),
            torch.nn.Linear(20, 14),
            torch.nn.ReLU(),
        )
         
        self.decoder = torch.nn.Sequential(
            torch.nn.Linear(14, 20),
            torch.nn.Tanh(),
            torch.nn.Linear(20, 29),
            torch.nn.Tanh()
        )
 
    def forward(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded


autoencoder = AE()

# autoencoder.load_state_dict(torch.load("Adam1270.pt", map_location=torch.device('cpu')))
autoencoder.load_state_dict(torch.load("adam00.pth", map_location=torch.device('cpu')))
autoencoder.to(device)

X_pred = autoencoder( Datos[:,0:29] )

ecm = np.mean(np.power( D[:,0:29]-X_pred.detach().numpy(),2), axis=1)

umbral_fijo = 0.75
umbral_fijo = 0.5
umbral_fijo = 1
Y_pred = [1 if e > umbral_fijo else 0 for e in ecm]

conf_matrix = confusion_matrix( D[:,29], Y_pred)
print(conf_matrix)

