作业八

import numpy as np
##从1到100随机生成一个20行1列的数组
x = np.random.randint(1,100,[20,1])
print(x.shape)
print(x)
##返回来一个给定形状和类型的用0填充的数组;
y = np.zeros(20)
print(y)
##给定聚类中心的值
k = 3
#numpy.where(condition[, x, y])
# 1、这里x,y是可选参数,condition是条件,这三个输入参数都是array_like的形式;而且三者的维度相同
# 2、当conditon的某个位置的为true时,输出x的对应位置的元素,否则选择y对应位置的元素;
# 3、如果只有参数condition,则函数返回为true的元素的坐标位置信息;

##定义初始中心函数 返回k值
def initcenter(x,k):
    return x[:k]
##定义一个nearset函数
def nearest(x,i):
    d =abs(kc - i)##聚类中心减去数值 abs()返回距离的绝对值
    w = np.where(d == np.min(d))#进行距离最小的分类 返回数组的形式 距离最近的赋给d 把距离最近的数组成一个数组赋值给w
    return w[0][0] #返回数组w

def kcmean(x,y,kc,k):
    l = list(kc)
    flag = False

    for c in range(x.shape[0]):
        m = np.where(y == c)
    if m[0].shape != (0,):
         n = np.mean(x[m])
    if l[c] != n:
        l[c] = n
        flag = True
        return (np.array(l),flag)

def xclassify(x,y,kc):##定义xclassify函数
    for i in range(x.shape[0]):#循环遍历数组x
        y[i]=nearest(kc,x[i])##把离kc最近的x的值赋给y分成k类作为y的元素
        return y

kc = initcenter(x,k)
flag = True
print(x,y,kc,flag)
while flag:
    y = xclassify(x, y, kc)
    kc,flag = kcmean(x,y,kc,k)
    print(y,kc,type(kc))

print(x,y)

 

 

 

 

#2)鸢尾花花瓣长度数据做聚类并用散点图显示。
import numpy as np
import sklearn
from sklearn.datasets import load_iris
iris=load_iris()
x=iris.data[:,1]
y=np.zeros(150)

 #1、选取K个对象作为初始中心,
def initcent(x,k):
    return x[0:k].reshape(k)

 #2、返回数组中的值,与聚类中心最小距离所在类别的索引号
def nearest(kc,i):
    d = (abs(kc - i))
    w = np.where(d == np.min(d))
    return w[0][0]

 #3、更新聚类中心:将每个类别中所有对象对应的均值作为该类别的聚类中心
def kcmean(x, y, kc, k):   #计算各聚类新均值
    l = list(kc)
    flag = False
    for c in range(k):
        m = np.where(y == c)
        if m[0].shape != (0,):
            n = np.mean(x[m])
        if l[c] != n:
            l[c] = n
            flag = True   #聚类中心发生变化
    return (np.array(l),flag)

#2、
def xclassify(x, y, kc):
    for i in range(x.shape[0]):   #对数组的每个值分类
        y[i] = nearest(kc, x[i])
    return y

k = 3
kc = initcent(x, k)

#4、判断聚类中心和目标函数的值是否发生改变,若不变,则输出结果,若改变,则返回2
flag = True
print(x, y, kc, flag)
while flag:
    y = xclassify(x, y, kc)
    kc, flag = kcmean(x, y, kc, k)
print(y, kc)

import matplotlib.pyplot as plt
plt.scatter(x, x, c=y, s=40, cmap='rainbow');
plt.show()

 

 

#3)用sklearn.cluster.KMeans,鸢尾花花瓣长度数据做聚类并用散点图显示.
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import load_iris
iris=load_iris()
data=iris.data
print(data)  #全部数据

#取出所有花瓣的长度
pe_len=data[:, 2:3]
print("花瓣长度:",pe_len)

k=KMeans(n_clusters=3)  #表示类簇数为3,聚成3类数据
est=k.fit(pe_len)
kc = est.cluster_centers_        #类簇中心(cluster centers)
y_kmeans = est.predict(pe_len)  #预测每个样本的聚类索引

print("索引:",y_kmeans,"kc:",kc)
print(kc.shape,y_kmeans.shape)

import matplotlib.pyplot as plt
plt.scatter(pe_len,np.linspace(1,150,150),c=y_kmeans,marker="+",cmap='rainbow')
plt.show()

 



#(4)鸢尾花完整数据做聚类并用散点图显示.
import numpy as np

import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.datasets import load_iris iris=load_iris() data=iris.data print(data) est=KMeans(n_clusters=3) est.fit(data) kc=est.cluster_centers_ y_kmeans=est.predict(data) print(y_kmeans,kc) print(kc.shape,y_kmeans.shape,data.shape) plt.scatter(data[:, 0], data[:, 1], c=y_kmeans, s=50,marker="+",cmap='rainbow') plt.show()

 

posted @ 2018-10-30 11:47  傻猪一号  阅读(256)  评论(0编辑  收藏  举报