user40780 :
Consider this simplest possible case where we want our class to inherit from any sklearn clustering class:
class MyOwnClustering(AgglomerativeClustering):
def __init__(self,mysetting , **kwargs):
super().__init__(**kwargs)
Is it possible to make AgglomerativeClustering
as an argument? So that I can switch freely from any clustering algo (like Kmeans)?
Edit:
Based on 53RT's method: can i do this instead?
def construct_clustering(cls):
class MyOwnClustering(cls):
def __init__(self, mysetting , **kwargs):
super().__init__(**kwargs)
return MyOwnClustering
Tested, yes I can.
53RT :
I think your problem can be solved using the Builder pattern which is showcased here.
This would yield the following solution.
from sklearn.cluster import AgglomerativeClustering, KMeans
from sklearn import datasets
setting = dict()
noisy_moons = datasets.make_moons(n_samples=50, noise=.05)
You wrap your creation into a function
def construct_clustering(cls, setting):
class MyOwnClustering(cls):
def __init__(self, mysetting , **kwargs):
super().__init__(**kwargs)
clustering = MyOwnClustering(setting)
return clustering
And can create instances of MyOwnClustering
with different inheritance
m = construct_clustering(AgglomerativeClustering, setting)
print(isinstance(m, AgglomerativeClustering))
c = m.fit(noisy_moons[0])
c.labels_
>>> array([0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1,
1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0,
0, 1, 1, 0, 0, 1], dtype=int64)
m = construct_clustering(KMeans, setting)
print(isinstance(m, KMeans)) # True
c = m.fit(noisy_moons[0])
c.labels_
>>> array([6, 6, 2, 1, 5, 0, 0, 3, 7, 0, 5, 1, 6, 4, 4, 4, 1, 0, 2, 0, 7, 5,
7, 0, 4, 1, 4, 6, 0, 2, 7, 5, 3, 7, 5, 2, 6, 6, 5, 2, 6, 7, 4, 2,
4, 3, 3, 3, 0, 1])