[*]Загрузил набор данных и применил алгоритм ПК для создания DAG.
[*]Написал функцию для извлечения марковского бланкета целевой переменной из группы обеспечения доступности баз данных.
[*]Я получаю ошибку KeyError при попытке получить марковский бланкет для определенного узла
Код: Выделить всё
import numpy as np
import pandas as pd
from causallearn.search.ConstraintBased.PC import pc
from causallearn.utils.GraphUtils import GraphUtils
import matplotlib.pyplot as plt
# Step 1: Load the dataset
url = 'https://path-to-your-dataset.csv'
data = pd.read_csv(url)`
# Step 2: Drop missing values if necessary
data = data.dropna()
# Step 3: Convert to NumPy format
data_np = data.to_numpy()
# Step 4: Apply the PC Algorithm
pc_output = pc(data_np, alpha=0.05)
# Step 5: Define function to find Markov Blanket
def get_markov_blanket(graph, target_var_index):
parents = graph.get_parents(target_var_index)
children = graph.get_children(target_var_index)
spouses = []
for child in children:
spouses.extend(graph.get_parents(child))
markov_blanket = set(parents + children + spouses)
markov_blanket.discard(target_var_index) # Remove the target variable from the Markov Blanket
return markov_blanket
# Set target variable index (e.g., X13)
target_var_name = 'X13'
target_var_index = 12 # assuming X13 corresponds to index 12
# Step 6: Get the Markov Blanket for the target variable
markov_blanket = get_markov_blanket(pc_output.G, target_var_index)
print(f"Markov Blanket of {target_var_name}: {markov_blanket}")
Код: Выделить всё
Error:
KeyError: 12
Код: Выделить всё
parents = graph.get_parents(target_var_index)
Моя настройка:
- Python: 3.9
- Библиотеки: causallearn, networkx, pydot, pgmpy
- Проверил, существует ли целевая переменная (X13) в графе — есть.
- Пересобрал DAG с помощью разные алгоритмы, но столкнулись с одной и той же проблемой.
- Убедились, что все библиотеки обновлены.
Подробнее здесь: https://stackoverflow.com/questions/790 ... -in-python