Python中的多处理-运行DBSCAN时如何使用所有内核?

时间:2018-11-29 02:25:16

标签: python machine-learning multiprocessing

我使用DBSCAN编码了一些代码,但是当运行预测功能时,程序仅使用1个CPU(100%),而其他CPU则免费。任何人都可以修改下面的“ dbscan_predict”函数,以便它可以使用计算机上的所有8个CPU?(CPU 4核8个线程)

def dbscan_predict(dbscan_model, X_new, metric=np.linalg.norm):
# Result is noise by default
y_new = np.ones(shape=len(X_new), dtype=int)*(-1)

# Iterate all input samples for a label
for j, x_new in enumerate(X_new):
    # Find a core sample closer than EPS
    for i, x_core in enumerate(dbscan_model.components_): 
        if metric(x_new - x_core) < dbscan_model.eps:
            # Assign label of x_core to x_new
            y_new[j] = dbscan_model.labels_[dbscan_model.core_sample_indices_[i]]
            break

return y_new

1 个答案:

答案 0 :(得分:0)

使用python的多处理程序包。您可以定义函数并在multiprocessing.pool()方法内拆分数据帧。然后,这会将工作分配到不同的内核上。

您也可以使用multiprocessing.cpu_count()检查核数,然后在此基础上做出决定。