Jam*_*ull 24 python scoring cluster-analysis scikit-learn
我正在聚集大约100条记录的样本(未标记)并尝试使用grid_search来评估具有各种超参数的聚类算法.我正在使用得分silhouette_score
很好.
在这里,我的问题是,我并不需要使用的交叉验证方面GridSearchCV
/ RandomizedSearchCV
,但我不能找到一个简单GridSearch
/ RandomizedSearch
.我可以写我自己,但ParameterSampler
和ParameterGrid
对象是非常有用的.
我的下一步将是子类化BaseSearchCV
并实现我自己的_fit()
方法,但认为值得问一下,有更简单的方法来做到这一点,例如通过传递一些东西到cv
参数?
def silhouette_score(estimator, X):
clusters = estimator.fit_predict(X)
score = metrics.silhouette_score(distance_matrix, clusters, metric='precomputed')
return score
ca = KMeans()
param_grid = {"n_clusters": range(2, 11)}
# run randomized search
search = GridSearchCV(
ca,
param_distributions=param_dist,
n_iter=n_iter_search,
scoring=silhouette_score,
cv= # can I pass something here to only use a single fold?
)
search.fit(distance_matrix)
Run Code Online (Sandbox Code Playgroud)
好吧,这可能是一个老问题,但我使用这种代码:
首先,我们要生成所有可能的参数组合:
def make_generator(parameters):
if not parameters:
yield dict()
else:
key_to_iterate = list(parameters.keys())[0]
next_round_parameters = {p : parameters[p]
for p in parameters if p != key_to_iterate}
for val in parameters[key_to_iterate]:
for pars in make_generator(next_round_parameters):
temp_res = pars
temp_res[key_to_iterate] = val
yield temp_res
Run Code Online (Sandbox Code Playgroud)
然后创建一个循环:
# add fix parameters - here - it's just a random one
fixed_params = {"max_iter":300 }
param_grid = {"n_clusters": range(2, 11)}
for params in make_generator(param_grid):
params.update(fixed_params)
ca = KMeans( **params )
ca.fit(_data)
labels = ca.labels_
# Estimate your clustering labels and
# make decision to save or discard it!
Run Code Online (Sandbox Code Playgroud)
当然,它可以组合成一个漂亮的函数。所以这个解决方案主要是一个例子。
希望它能帮助别人!
该clusteval
库将帮助您评估数据并找到最佳聚类数。该库包含五种可用于评估聚类的方法:剪影、dbindex、导数、dbscan和hdbscan。
pip install clusteval
Run Code Online (Sandbox Code Playgroud)
可以根据您的数据选择评估方法。
# Import library
from clusteval import clusteval
# Set parameters, as an example dbscan
ce = clusteval(method='dbscan')
# Fit to find optimal number of clusters using dbscan
results= ce.fit(X)
# Make plot of the cluster evaluation
ce.plot()
# Make scatter plot. Note that the first two coordinates are used for plotting.
ce.scatter(X)
# results is a dict with various output statistics. One of them are the labels.
cluster_labels = results['labx']
Run Code Online (Sandbox Code Playgroud)
最近我遇到了类似的问题。我定义了自定义迭代cv_custom
,它定义了分割策略,并且是交叉验证参数的输入cv
。这个迭代应该为每个折叠包含一对,并通过其索引标识样本,例如([fold1_train_ids], [fold1_test_ids]), ([fold2_train_ids], [fold2_test_ids]), ...
在我们的例子中,我们只需要一对折叠,其中包含训练和测试部分中所有示例的索引([train_ids], [test_ids])
N = len(distance_matrix)
cv_custom = [(range(0,N), range(0,N))]
scores = cross_val_score(clf, X, y, cv=cv_custom)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7448 次 |
最近记录: |