聚类的python实现(1)

1.创建数据

创建一个(100,2)的数组

np.random.randint(-20, 20, size=(100, 2))

2.随机取点并计算距离

随机取2个100以内的整数作为点的索引,并在data中取出

index1 = random.choice(range(100))
index2 = random.choice(range(100))
if index1 == index2:
    index2 = random.choice(range(100))
target1 = self.data[index1]
target2 = self.data[index2]

比较所有点到点1的距离和到点2的距离,并返回比较结果(为一组bool值组成的数组)。

temp = np.sum((self.data - target1) ** 2, axis=1)-np.sum((self.data - target2) ** 2, axis=1)
        return temp < 0

3.切分

先把比较结果插入源数据组中

data2 = self.dist()
df = pd.DataFrame(self.data, columns=['x', 'y'])
df.insert(2, 'type', data2)

再根据type把数据分为2个dataframe

A = df[df['type'] == True]
B = df[df['type'] == False]

画图

把切分好的数据画出来

A,B = self.cut_data(df)
plt.scatter(A['x'], A['y'], color='red')
plt.scatter(B['x'], B['y'], color='blue')
# savefig要写在show之前
plt.savefig('./julei.png')
plt.show()

完整代码:

import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
"""
单次聚类
"""


class julei():
    def __init__(self):
        self.data = np.random.randint(-20, 20, size=(100, 2))

    # 求距离
    def dist(self):
        index1 = random.choice(range(100))
        index2 = random.choice(range(100))
        if index1 == index2:
            index2 = random.choice(range(100))
        target1 = self.data[index1]
        target2 = self.data[index2]
        temp = np.sum((self.data - target1) ** 2, axis=1)-np.sum((self.data - target2) ** 2, axis=1)
        return temp < 0

    def cut_data(self, df):
        A = df[df['type'] == True]
        B = df[df['type'] == False]
        return A, B

    # 画图
    def draw(self, df):
        A,B = self.cut_data(df)
        plt.scatter(A['x'], A['y'], color='red')
        plt.scatter(B['x'], B['y'], color='blue')
        # savefig要写在show之前
        plt.savefig('./julei.png')
        plt.show()

    # 分类
    def des(self):
        # 第一次分类
        data2 = self.dist()
        df = pd.DataFrame(self.data, columns=['x', 'y'])
        df.insert(2, 'type', data2)
        self.draw(df)


if __name__ == '__main__':
    func = julei()
    func.des()

效果如下:在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值