【问题标题】:Dealing with Memory Error (Python sklearn clustering)处理内存错误(Python sklearn 聚类)
【发布时间】:2019-09-12 00:06:14
【问题描述】:

我有一个数据集,每个数据都有稀疏标签。 所以,下面是数据的样子。

[["Snow","Winter","Freezing","Fun","Beanie","Footwear","Headgear","Fur","Playing in the snow","Photography"],[ “树”、“天空”、“白天”、“市区”、“分支”、“首都圈”、“冬季”、“城镇”、“城市”、“路灯”],...]

标签总数在 50 个左右,数据数为 200K。我想对这些数据进行聚类,但我无法处理。

我想用四种聚类算法(AgglomerativeClustering、SpectralClustering、MiniBatchKMeans、KMeans)对数据进行聚类,但由于内存问题,这些算法都不起作用。

下面是我的代码。

from scipy.sparse import csr_matrix
from sklearn.cluster import KMeans
from sklearn.cluster import MiniBatchKMeans
from sklearn.cluster import AgglomerativeClustering
from sklearn.cluster import SpectralClustering
import json

NUM_OF_CLUSTERS = 10

with open('./data/sample.json') as json_file:
    json_data = json.load(json_file)
indptr = [0]
indices = []
data = []
vocabulary = {}
for d in json_data:
    for term in d:
        index = vocabulary.setdefault(term, len(vocabulary))
        indices.append(index)
        data.append(1)
    indptr.append(len(indices))

X = csr_matrix((data, indices, indptr), dtype=int).toarray()

# None of these algorithms work properly. I think it's because of memory issues.
# miniBatchKMeans = MiniBatchKMeans(n_clusters=NUM_OF_CLUSTERS, n_init=5, random_state=0).fit(X)
# agglomerative = AgglomerativeClustering(n_clusters=NUM_OF_CLUSTERS).fit(X)
# spectral = SpectralClustering(n_clusters=NUM_OF_CLUSTERS, assign_labels="discretize", random_state=0).fit(X)
#
# print(miniBatchKMeans.labels_)
# print(agglomerative.labels_)
# print(spectral.labels_)
with open('data.json', 'w') as outfile:
    json.dump(miniBatchKMeans.labels_.tolist(), outfile)

对于我的问题是否有任何解决方案或其他建议?

【问题讨论】:

  • 每次我在我的 MacOS 中运行此代码时,它都会永久运行。所以我用我的 Windows 笔记本电脑运行相同的代码,它只是在一段时间后中断并显示内存已满消息。
  • 我想用我的 MacOS 运行这段代码,我正在用 Pycharm 运行它。下面是我的vmoptions。 # 自定义 PyCharm VM 选项 -Xms1024m -Xmx2048m -XX:ReservedCodeCacheSize=240m -XX:+UseCompressedOops -Dfile.encoding=UTF-8 -XX:+UseConcMarkSweepGC -XX:SoftRefLRUPolicyMSPerMB=50 -ea -Dsun.io.useCanonCaches=false - Djava.net.preferIPv4Stack=true -Djdk.http.auth.tunneling.disabledSchemes="" -XX:+HeapDumpOnOutOfMemoryError -XX:-OmitStackTraceInFastThrow -Xverify:none -XX:ErrorFile=$USER_HOME/java_error_in_pycharm_%p.log -XX: HeapDumpPath=$USER_HOME/java_error_in_pycharm.hprof
  • 您的 Java IDE 设置显然不应该影响 python 程序。当然,胖 IDE 本身会占用相当多的内存。

标签: python python-3.x scikit-learn cluster-analysis


【解决方案1】:

X 的大小是多少?

使用toarray(),您可以将数据转换为感知格式。这会显着增加内存需求。

对于 200k 个实例,您不能使用谱聚类而不是亲和传播,因为这些实例需要 O(n²) 内存。因此,您要么选择其他算法,要么对数据进行二次抽样。显然,同时做 kmeans 和 minibatch kmeans(这是 kmeans 的近似值)也没有用。只使用一个。

要高效处理稀疏数据,您可能需要自己实现算法。 Kmeans 是为密集数据设计的,因此默认情况下为密集数据的实现计时是有意义的。事实上,在稀疏数据上使用 mean 是相当有问题的。因此,我也不希望使用 kmeans 对您的数据产生非常好的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-30
    • 2014-10-15
    • 2018-12-10
    • 2017-03-16
    • 2019-04-30
    • 2017-07-15
    • 2016-02-02
    • 2020-02-01
    相关资源
    最近更新 更多