使用python生成数据簇?

问题描述 投票:0回答:2

我正在研究一个Python函数,我想在其中对高斯分布进行建模,但我陷入了困境。

import numpy.random as rnd
import numpy as np

def genData(co1, co2, M):
  X = rnd.randn(2, 2M + 1)
  t = rnd.randn(1, 2M + 1)
  numpy.concatenate(X, co1)
  numpy.concatenate(X, co2)
  return(X, t)

我正在尝试两个大小为 M 的簇,簇 1 以 co1 为中心,簇 2 以 co2 为中心。 X 将返回我要绘制图表的数据点,t 是目标值(如果集群 1,则为 1;如果集群 2,则为 2),因此我可以按集群为其着色。

在这种情况下,t 的大小为 2M,即 1s/2s,X 的大小为 2M * 1,其中如果 X[i] 在集群 1 中,则 t[i] 为 1,对于集群 2 也相同。

我认为开始执行此操作的最佳方法是使用 numpys random 生成数组 array。我困惑的是如何让它根据集群居中?


最好的方法是生成一个大小为 M 的簇,然后将 co1 添加到每个点吗?我如何使其随机,并确保 t[i] 的颜色正确?

我正在使用此函数来绘制数据图表:

def graphData():
    co1 = (0.5, -0.5)
    co2 = (-0.5, 0.5)
    M = 1000
    X, t = genData(co1, co2, M)
    colors = np.array(['r', 'b'])
    plt.figure()
    plt.scatter(X[:, 0], X[:, 1], color = colors[t], s = 10)
python numpy cluster-analysis gaussian
2个回答
7
投票

为了您的目的,我会选择

sklearn
示例生成器 make_blobs:

from sklearn.datasets import make_blobs

centers = [(-5, -5), (5, 5)]
cluster_std = [0.8, 1]

X, y = make_blobs(n_samples=100, cluster_std=cluster_std, centers=centers, n_features=2, random_state=1)

plt.scatter(X[y == 0, 0], X[y == 0, 1], color="red", s=10, label="Cluster1")
plt.scatter(X[y == 1, 0], X[y == 1, 1], color="blue", s=10, label="Cluster2")

您可以用它生成多维集群。

X
产生数据点,
y
确定
X
中的对应点属于哪个簇。

这对于您在这种情况下尝试实现的目标来说可能太多了,但一般来说,我认为最好依赖更通用和经过更好测试的库代码,这些代码也可以在其他情况下使用。


3
投票

您可以使用类似以下代码的内容:

center1 = (50, 60)
center2 = (80, 20)
distance = 20


x1 = np.random.uniform(center1[0], center1[0] + distance, size=(100,))
y1 = np.random.normal(center1[1], distance, size=(100,)) 

x2 = np.random.uniform(center2[0], center2[0] + distance, size=(100,))
y2 = np.random.normal(center2[1], distance, size=(100,)) 

plt.scatter(x1, y1)
plt.scatter(x2, y2)
plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.