#-*- coding：utf-8 -*-
# &Author  AnFany

# 引入方法
import Kmeans_AnFany as K_Af  # AnFany
import Kmeans_Sklearn as K_Sk  # Sklearn
import matplotlib.pyplot as plt
from pylab import mpl  # 作图显示中文
mpl.rcParams['font.sans-serif'] = ['FangSong']  # 设置中文字体新宋体
mpl.rcParams['axes.unicode_minus'] = False
import numpy as np

# 利用sklearn生成数据集
from sklearn.datasets import make_blobs
X, Y = make_blobs(n_samples=600, centers=6, n_features=2)

# 绘制散点图
def fig_scatter(exdata, eydata, titl='训练数据散点图', co=['r', 'g', 'k', 'b', 'y', 'm'], marker=['o','^','H','v','d','>']):
    typeclass = sorted(list(set(eydata)))
    for ii in range(len(typeclass)):
        datax = exdata[eydata == typeclass[ii]]
        plt.scatter(datax[:, 0], datax[:, -1], c=co[ii], s=50, marker=marker[ii])
    plt.title(titl)
    #plt.legend(['%d类'%i for i in typeclass], bbox_to_anchor=(1.2, 0.9))
    plt.xlabel('特征1')
    plt.ylabel('特征2')

# 调用不同的方法

# AnFany
kresult = K_Af.op_kmeans(X, countcen=6)


# Sklearn
sk = K_Sk.KMeans(init='k-means++', n_clusters=6, n_init=10)

train = sk.fit(X)
result = sk.predict(X)
skru = K_Sk.trans(result)



#绘制算法后的类别的散点图
def sca(Xdata, Center, signdict, co=['r', 'g', 'y', 'b', 'c', 'm'], marker=['o','^','H','s','d','*'], titl = 'AnFany 结果'):
    du = 1
    for jj in signdict:
        xdata = Xdata[signdict[jj]]
        plt.scatter(xdata[:, 0], xdata[:, -1], c=co[jj], s=50, marker=marker[jj], label='%d类' % jj)  # 绘制样本散点图
    for ss in Center:
        if du:
            plt.scatter(ss[0], ss[1], c='k', s=100, marker='8', label='类别中心') #绘制类别中心点
            du = 0
        else:
            plt.scatter(ss[0], ss[1], c='k', s=100, marker='8')  # 绘制类别中心点

    plt.legend(bbox_to_anchor=(1.2, 1))
    plt.title(titl)
    plt.xlabel('特征1')
    plt.ylabel('特征2')

# 定义欧几里得距离
def dis(sample, center):
    cen = np.array([center])
    sample = np.array(sample)
    if len(sample) != 0:
        usb = np.sum((sample - cen) ** 2, axis=1) ** 0.5
        return usb
    else:
        return 0
# 计算最终的分类结果的成本值
def Cost(Xdata, typedict):
    center = {}
    for kk in typedict:
        center[kk] = np.mean(Xdata[typedict[kk]], axis=0) # 均值
    cio = 0
    for cc in typedict:
        cio += np.sum(dis(Xdata[typedict[cc]], center[cc]))
    return cio

# 最终的结果展示
plt.subplot(2, 2, 1)
fig_scatter(X, Y)

plt.subplot(2, 2, 2)
sca(X, kresult[0], kresult[2])

plt.subplot(2, 2, 3)
sca(X, train.cluster_centers_, skru, titl='Sklearn 结果')

plt.subplot(2, 2, 4)
plt.axis('off')
plt.text(0.3, 0.6, 'AnFany 最终的分类成本值为：%.5f'%Cost(X, kresult[2]))
plt.text(0.3, 0.3, 'Sklearn 最终的分类成本值为：%.5f'%Cost(X, skru))

plt.show()











[((393, 443), 'sklearn.datasets.make_blobs', 'make_blobs', ([], {'n_samples': '(600)', 'centers': '(6)', 'n_features': '(2)'}), '(n_samples=600, centers=6, n_features=2)\n', (403, 443), False, 'from sklearn.datasets import make_blobs\n'), ((964, 993), 'Kmeans_AnFany.op_kmeans', 'K_Af.op_kmeans', (['X'], {'countcen': '(6)'}), '(X, countcen=6)\n', (978, 993), True, 'import Kmeans_AnFany as K_Af\n'), ((1015, 1069), 'Kmeans_Sklearn.KMeans', 'K_Sk.KMeans', ([], {'init': '"""k-means++"""', 'n_clusters': '(6)', 'n_init': '(10)'}), "(init='k-means++', n_clusters=6, n_init=10)\n", (1026, 1069), True, 'import Kmeans_Sklearn as K_Sk\n'), ((1123, 1141), 'Kmeans_Sklearn.trans', 'K_Sk.trans', (['result'], {}), '(result)\n', (1133, 1141), True, 'import Kmeans_Sklearn as K_Sk\n'), ((2335, 2355), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (2346, 2355), True, 'import matplotlib.pyplot as plt\n'), ((2378, 2398), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (2389, 2398), True, 'import matplotlib.pyplot as plt\n'), ((2434, 2454), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(3)'], {}), '(2, 2, 3)\n', (2445, 2454), True, 'import matplotlib.pyplot as plt\n'), ((2515, 2535), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(4)'], {}), '(2, 2, 4)\n', (2526, 2535), True, 'import matplotlib.pyplot as plt\n'), ((2537, 2552), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2545, 2552), True, 'import matplotlib.pyplot as plt\n'), ((2681, 2691), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2689, 2691), True, 'import matplotlib.pyplot as plt\n'), ((792, 807), 'matplotlib.pyplot.title', 'plt.title', (['titl'], {}), '(titl)\n', (801, 807), True, 'import matplotlib.pyplot as plt\n'), ((887, 904), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""特征1"""'], {}), "('特征1')\n", (897, 904), True, 'import matplotlib.pyplot as plt\n'), ((910, 927), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""特征2"""'], {}), "('特征2')\n", (920, 927), True, 'import matplotlib.pyplot as plt\n'), ((1718, 1753), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(1.2, 1)'}), '(bbox_to_anchor=(1.2, 1))\n', (1728, 1753), True, 'import matplotlib.pyplot as plt\n'), ((1759, 1774), 'matplotlib.pyplot.title', 'plt.title', (['titl'], {}), '(titl)\n', (1768, 1774), True, 'import matplotlib.pyplot as plt\n'), ((1780, 1797), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""特征1"""'], {}), "('特征1')\n", (1790, 1797), True, 'import matplotlib.pyplot as plt\n'), ((1803, 1820), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""特征2"""'], {}), "('特征2')\n", (1813, 1820), True, 'import matplotlib.pyplot as plt\n'), ((1872, 1890), 'numpy.array', 'np.array', (['[center]'], {}), '([center])\n', (1880, 1890), True, 'import numpy as np\n'), ((1905, 1921), 'numpy.array', 'np.array', (['sample'], {}), '(sample)\n', (1913, 1921), True, 'import numpy as np\n'), ((713, 790), 'matplotlib.pyplot.scatter', 'plt.scatter', (['datax[:, (0)]', 'datax[:, (-1)]'], {'c': 'co[ii]', 's': '(50)', 'marker': 'marker[ii]'}), '(datax[:, (0)], datax[:, (-1)], c=co[ii], s=50, marker=marker[ii])\n', (724, 790), True, 'import matplotlib.pyplot as plt\n'), ((1370, 1470), 'matplotlib.pyplot.scatter', 'plt.scatter', (['xdata[:, (0)]', 'xdata[:, (-1)]'], {'c': 'co[jj]', 's': '(50)', 'marker': 'marker[jj]', 'label': "('%d类' % jj)"}), "(xdata[:, (0)], xdata[:, (-1)], c=co[jj], s=50, marker=marker[jj\n    ], label='%d类' % jj)\n", (1381, 1470), True, 'import matplotlib.pyplot as plt\n'), ((2164, 2200), 'numpy.mean', 'np.mean', (['Xdata[typedict[kk]]'], {'axis': '(0)'}), '(Xdata[typedict[kk]], axis=0)\n', (2171, 2200), True, 'import numpy as np\n'), ((1525, 1590), 'matplotlib.pyplot.scatter', 'plt.scatter', (['ss[0]', 'ss[1]'], {'c': '"""k"""', 's': '(100)', 'marker': '"""8"""', 'label': '"""类别中心"""'}), "(ss[0], ss[1], c='k', s=100, marker='8', label='类别中心')\n", (1536, 1590), True, 'import matplotlib.pyplot as plt\n'), ((1648, 1699), 'matplotlib.pyplot.scatter', 'plt.scatter', (['ss[0]', 'ss[1]'], {'c': '"""k"""', 's': '(100)', 'marker': '"""8"""'}), "(ss[0], ss[1], c='k', s=100, marker='8')\n", (1659, 1699), True, 'import matplotlib.pyplot as plt\n'), ((1963, 1998), 'numpy.sum', 'np.sum', (['((sample - cen) ** 2)'], {'axis': '(1)'}), '((sample - cen) ** 2, axis=1)\n', (1969, 1998), True, 'import numpy as np\n')]