py-why / causal-learn

Causal Discovery in Python. It also includes (conditional) independence tests and score functions.
https://causal-learn.readthedocs.io/en/latest/
MIT License
1.04k stars 174 forks source link

How to save and reload CausalGraph class? #150

Closed WilliamsToTo closed 5 months ago

WilliamsToTo commented 7 months ago

Hey, just wanna know how to save and reload the CausalGraph return by PC algorithm.

kunwuz commented 7 months ago

I don't think there is an existing function to save the CausalGraph object, but perhaps you could try to save the adjacency matrix of the graph (cg.G.graph), which is a numpy array so np.save( ) works.

priamai commented 7 months ago

What about using the pickle module, so you save a binary representation? I didn't test it but it should work.

priamai commented 7 months ago

@WilliamsToTo try this it works for me

image

priamai commented 7 months ago
from causallearn.search.ConstraintBased.PC import pc
import pickle
# default parameters
cg = pc(data)

print(len(cg.G.nodes))
with open('myG.pkl', 'wb') as f:
  pickle.dump(cg.G, f, pickle.HIGHEST_PROTOCOL)

with open('myG.pkl', 'rb') as f:
  myG = pickle.load(f)
  print(len(myG.nodes))
WilliamsToTo commented 7 months ago

@priamai Thanks a lot.