Exemple #1
0
# insall necessary libraries:
# pip install sklearn pandas tqdm funcsigs pgmpy statsmodels community
# pip install networkx==v1.11
# pip install matplotlib==2.2.3
# link to library info:
# https://pypi.org/project/bnlearn/


import bnlearn as bnlearn
import pandas as pd


# Read the dataframe with the structure to be learned
df = pd.read_csv("X_train_TopLocCust_balanced_allFeatures_pk_non_numeric.csv")
print(df)
model = bnlearn.structure_learning(df)
G = bnlearn.plot(model)
# Rounding off the data and converting it to Integer

combined_data_descrete = round(combined_data).astype(int)

# Bayesian network

# Loading the Banknote dataset containing mixed variables
df_raw = combined_data_descrete


# Structure learning

DAG = bnlearn.structure_learning.fit(df_raw, methodtype='hc',scoretype='bic')
# Plot
G = bnlearn.plot(DAG)
print(df_raw)

# Parameter learning
model = bnlearn.parameter_learning.fit(DAG, combined_data_descrete )
bnlearn.print_CPD(model)

# Print CPDs
bnlearn.print_CPD(model)
# Make inference
q = bnlearn.inference.fit(model, variables=['Class'], evidence={'V1': 10, 'V2': 2})

print(q.values)
print(q.variables)
print(q._str())
def Aprendizaje(model, fold, tipo, score):
    """ Aprendizaje de estructura y parámetros de BNLEARN en Python
    
    Descripción
    -----------
    Encapsula el aprendizaje de estructura y el aprendizaje de parámetros (probabilidad anterior).
    El aprendizaje de la estructura es guardado en un archivo CSV y el DAG aprendido es renderizado y guardado en un 
    archivo PDF en la carpeta \Experimentos con el nombre "EstructuraCPD_'tipo'_fold.gv.pdf"
        
    Parámetros
    ----------
    model: recibe un dataframe con los la información a aprender 
    fold : Valor númerico que indica el cross-validation del cual se está solicitando el aprendizaje
    tipo :  Indicador del tipo de datos del que se desa aprender.  Valores posibles:
        a. "TRAIN"
        b. "TEST"
    score   : Tipo de score a utilizar para el aprendizaje de la estructura
        a. "bic"  -> Bayesian Information Criterion (Tambien llamado MDL)
        b. "k2"   -> 
        c. "bdeu" -> (DB) Bayesian Dirichlet, (e) for likelihood-equivalence, (u) for uniform joint distibution        
         
    Retorna
    -------
    Retorna un modelo aprendido "dict"
       
    """
    # -------------------------------------------------------------------
    # APRENDIENDO LA ESTRUCTURA DE UNA PORCION DE DATOS DE TRAIN O TEST -
    # -------------------------------------------------------------------

    modelo = bn.structure_learning.fit(model,
                                       methodtype='hc',
                                       scoretype=score,
                                       verbose=3)
    # modelo = bn.structure_learning.fit(model, methodtype='hc', scoretype=score, verbose=3, bw_list_method = 'enforce', black_list = ['programa', 'estado'])

    # Guardando la estructura estructura aprendida
    nombreArchivo = 'EstructuraCPD_' + tipo + '_' + str(fold)
    nombreArchivoExt = 'Experimentos\\' + nombreArchivo + '.gv'
    f = Digraph(name=nombreArchivo,
                filename=nombreArchivoExt,
                format='pdf',
                engine='dot',
                encoding="utf-8")

    # Obteniendo la matriz de Source y Target del modelo
    vector = bn.adjmat2vec(modelo['adjmat'])
    col = []

    # Se recorre el la matriz para obtener todas las columnas que esta matriz posee
    for columna in vector:  # recorriendo las columnas
        if columna in ('weight'):
            continue
        else:
            for fila in vector.index:  # recorriendo las filas
                col.append(vector[columna][fila])

    # Se lista la lista dejando solo valores únicos
    vectorUnique = list(set(col))

    # Asignando los nodos de la estructura aprendida
    f.attr('node', shape='circle')
    for x in range(len(vectorUnique)):
        f.node(vectorUnique[x])

    # Asignando los arcos de la estructura aprendida
    edges = modelo['model'].edges()
    f.attr('node', shape='circle')
    for edge in edges:
        xfrom = edge[0]
        xto = edge[1]
        f.edge(xfrom, xto)

    # f.view()
    f.save()
    f.render(filename=nombreArchivoExt, view=False, cleanup=1)

    # Guardando la estructura aprendida
    vector = modelo['adjmat']
    vector = bn.adjmat2vec(vector)
    vector.to_csv("Experimentos\EstructuraCPD_" + tipo + "_" + str(fold) +
                  ".csv",
                  sep=";")
    G = bn.plot(modelo, verbose=0)

    # -------------------------------------------------------------------------
    # APRENDIENDO LOS PARAMETROS DEL MODELO RECIEN APRENDIDO DE SU ESTRUCTURA -
    # -------------------------------------------------------------------------

    modelo = bn.parameter_learning.fit(modelo, model, verbose=1)

    # Convertiendo a BayesianModel para guardar los parametros aprendidos
    if isinstance(modelo, dict):
        model1 = modelo['model']

    filename = "Experimentos\ParametrosCPD_" + tipo + "_" + str(fold) + ".txt"
    if os.path.exists(filename):
        file = open(filename, "a")
    else:
        file = open(filename, "w")

    for cpd in model1.get_cpds():
        file.write("CPD of {variable}:".format(variable=cpd.variable) + "\n")
        file.write(str(cpd) + os.linesep)

    file.close()

    # Muestra como queda la red bayesiana con la porción de los datos entrenados y los parametros aprendidos
    G = bn.plot(modelo, verbose=0)

    return modelo
Exemple #4
0
# %%
import bnlearn as bn
print(bn.__version__)
print(dir(bn))

# %%
dir(bn.structure_learning)

# %%
# Example dataframe sprinkler_data.csv can be loaded with:
df = bn.import_example()
# df = pd.read_csv('sprinkler_data.csv')
model = bn.structure_learning.fit(df)
G = bn.plot(model)

# %% Load example dataframe from sprinkler
df = bn.import_example('sprinkler')
# Structure learning
model = bn.structure_learning.fit(df)
# Plot
G = bn.plot(model)

model_hc_bic = bn.structure_learning.fit(df, methodtype='hc', scoretype='bic')

# %% Try all methods vs score types
model_hc_bic = bn.structure_learning.fit(df, methodtype='hc', scoretype='bic')
model_hc_k2 = bn.structure_learning.fit(df, methodtype='hc', scoretype='k2')
model_hc_bdeu = bn.structure_learning.fit(df,
                                          methodtype='hc',
                                          scoretype='bdeu')
model_ex_bic = bn.structure_learning.fit(df, methodtype='ex', scoretype='bic')
Exemple #5
0
# %%
import bnlearn as bn
print(bn.__version__)
print(dir(bn))

# %%
print(dir(bn.structure_learning))
print(dir(bn.parameter_learning))
print(dir(bn.inference))

# %%
# Example dataframe sprinkler_data.csv can be loaded with: 
df = bn.import_example()
# df = pd.read_csv('sprinkler_data.csv')
model = bn.structure_learning.fit(df)
G = bn.plot(model)

# %% Load example dataframe from sprinkler
DAG = bn.import_DAG('sprinkler', verbose=0)
df = bn.sampling(DAG, n=1000, verbose=0)

# Structure learning
model = bn.structure_learning.fit(df, verbose=0)
# Plot
G = bn.plot(model)

model_hc_bic  = bn.structure_learning.fit(df, methodtype='hc', scoretype='bic', verbose=0)

# %% Load example dataframe from sprinkler
df = bn.import_example('sprinkler', verbose=0)
# Structure learning
Exemple #6
0
def grafico_modelo(modelo):
    bn.plot(modelo)