deepcharles / ruptures

ruptures: change point detection in Python
BSD 2-Clause "Simplified" License
1.56k stars 161 forks source link

How do I get the cost of each model. #254

Closed WanBenLe closed 2 years ago

WanBenLe commented 2 years ago

I want to choose the best model by cost, but it seems that ekcpd.c is generated by cython so that I can't modify it well and make it return the cost. If so, can you send me the relevant codes? If it is not convenient to disclose, my email is ben@datalab.run

oboulant commented 2 years ago

Hi @WanBenLe ,

Thanks for your interest in ruptures !

I am not sure I understand what you are looking for, but you can definitively compute some costs using kernel search methods. Please find below one example for each available kernel in ruptures.


import ruptures as rpt
import numpy as np

# creation of data
n, dim = 500, 3  # number of samples, dimension
n_bkps, sigma = 3, 5  # number of change points, noise standard deviation
signal, bkps = rpt.pw_constant(n, dim, n_bkps, noise_std=sigma)

# Linear kernel <===> CostL2
algo_l2 = rpt.KernelCPD(kernel="linear", min_size=2).fit(signal)
# Rbf kernel <===> CostRbf
algo_rbf = rpt.KernelCPD(kernel="rbf", min_size=2).fit(signal)
# Cosine kernel <===> CostCosine
algo_cosine = rpt.KernelCPD(kernel="cosine", min_size=2).fit(signal)

# Compute cost for each kernel
test_cost_l2 = algo_l2.cost.error(50, 150)
test_cost_rbf = algo_rbf.cost.error(50, 150)
test_cost_cosine = algo_cosine.cost.error(50, 150)

# Display results
print(f"L2 cost between points 50 and 150 is: {test_cost_l2}")
print(f"Rbf cost between points 50 and 150 is: {test_cost_rbf}")
print(f"Cosine cost between points 50 and 150 is: {test_cost_cosine}")

Technical note

Please note that, when using a kernel search method with ruptures, the predict() method of the object KernelCPD will use the code implemented in C. On the other hand, if you use explicitly the .cost.error() or .cost.sum_of_costs() methods of the .cost object attached to KernelCPD, then it will use the native python counterparts implemented in ruptures.

deepcharles commented 2 years ago

Closing now. Feel free to reopen if you have another question.