7

我正在尝试在 scipy 中使用 kmeans 聚类,这正是这里存在的:

http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans.html#scipy.cluster.vq.kmeans

我想要做的是转换列表列表,如下所示:

data without_x[
[0, 0, 0, 0, 0, 0, 0, 20.0, 1.0, 48.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1224.0, 125.5, 3156.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 22.5, 56.0, 41.5, 85.5, 0, 0, 0, 0, 0, 0, 0, 0, 1495.0, 3496.5, 2715.0, 5566.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]

进入一个ndarry,以便将它与Kmeans方法一起使用。当我尝试将列表列表转换为 ndarray 时,我得到一个空数组,从而使整个分析无效。ndarray 的长度是可变的,它取决于收集的样本数量。但是我可以使用 len(data_without_x) 轻松做到这一点

这是返回空列表的代码片段。

import numpy as np
import "other functions"

data, data_without_x = data_preparation.generate_sampled_pdf()
nodes_stats, k, list_of_list= result_som.get_number_k()

data_array = np.array(data_without_x)
whitened = whiten(data_array)
centroids, distortion = kmeans(whitened, int(k), iter=100000)

这就是我得到的输出,只是保存在一个简单的日志文件中:

___________________________
this is the data array[[ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  0.]
 ..., 
 [ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  0.]]
___________________________
This is the whitened array[[ nan  nan  nan ...,  nan  nan  nan]
 [ nan  nan  nan ...,  nan  nan  nan]
 [ nan  nan  nan ...,  nan  nan  nan]
 ..., 
 [ nan  nan  nan ...,  nan  nan  nan]
 [ nan  nan  nan ...,  nan  nan  nan]
 [ nan  nan  nan ...,  nan  nan  nan]]
___________________________

当我尝试将列表列表转换为 numpy.array 时,有人知道会发生什么吗?

谢谢你的帮助

4

3 回答 3

6

这正是如何在 python 中将列表列表转换为 ndarray。你确定你data_without_x的填写正确吗?在我的机器上:

data = [[1,2,3,4],[5,6,7,8]]
data_arr = np.array(data)

data_arr
array([[1,2,3,4],
       [5,6,7,8]])

这是我认为你期待的行为

查看您的输入,您有很多零...请记住,打印输出并未显示所有内容。您可能只是从输入中看到所有“零”。检查特定的非零元素以确保

于 2013-07-03T13:15:56.910 回答
0

vq.whitenvq.kmeans期望一个 shape 数组(M, N),其中每一行都是一个观察值。所以转置你的data_array

import numpy as np
import scipy.cluster.vq as vq
np.random.seed(2013)    

data_without_x = [
    [0, 0, 0, 0, 0, 0, 0, 20.0, 1.0, 48.0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        1224.0, 125.5, 3156.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 22.5, 56.0, 41.5, 85.5, 0, 0, 0, 0, 0, 0, 0, 0, 1495.0,
        3496.5, 2715.0, 5566.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]


data_array = np.array(data_without_x).T
whitened = vq.whiten(data_array)

centroids, distortion = vq.kmeans(whitened, 5)
print(centroids)

产量

[[  1.22649791e+00   2.69573144e+00]
 [  3.91943108e-03   5.57406434e-03]
 [  5.73668382e+00   4.83161524e+00]
 [  0.00000000e+00   1.29763133e+00]]
于 2013-07-03T13:41:44.760 回答
0

使用 numpy 的 asarray 函数。它很简单:参考:https ://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html

于 2016-12-29T07:17:15.660 回答