《模式识别与智能计算》基于类中心的欧式距离法分类

基于类中心的欧式距离法分类

算法过程:
1 选取某一样本
2 计算类中心
3 计算样本与每一类的类中心距离,这里采用欧式距离
4 循环计算待测样品和训练集中各类中心距离找出距离待测样品最近的类别

函数代码

import numpy as np
import random
def train_test_split(x,y,ratio = 3):
    """
    :function: 对数据集划分为训练集、测试集
    :param x: m*n维 m表示数据个数 n表示特征个数
    :param y: 标签
    :param ratio: 产生比例 train:test = 3:1(默认比例)
    :return: x_train y_train  x_test y_test
    """
    n_samples , n_train = x.shape[0] , int(x.shape[0]*(ratio)/(1+ratio))
    train_id = random.sample(range(0,n_samples),n_train)
    x_train = x[train_id,:]
    y_train = y[train_id]
    x_test = np.delete(x,train_id,axis = 0)
    y_test = np.delete(y,train_id,axis = 0)
    return x_train,y_train,x_test,y_test
    
def euclid(x_train,y_train,sample):
    """
    :function: 基于类中心的模板匹配法
    :param x_train:训练集 M*N  M为样本个数 N为特征个数
    :param y_train:训练集标签 1*M
    :param sample: 待识别样品
    :return: 返回判断类别
    """
    disMin = np.inf
    label = 0
    #去除标签重复元素
    target = np.unique(y_train)
    for i in target:
        #将同一类别的数据下标集中到一起
        trainId =([j for j,y in enumerate(y_train) if y==i])
        train = x_train[trainId,:]
        trainMean = np.mean(train, axis=0)
        dis = np.dot((sample-trainMean),(sample - trainMean).T)
        if(disMin>dis):
            disMin = dis
            label = i
    return label
测试代码
from sklearn import datasets
from Include.chapter3 import function
import numpy as np

#读取数据
digits = datasets.load_digits()
x , y = digits.data,digits.target

#划分数据集
x_train, y_train, x_test, y_test = function.train_test_split(x,y)
testId = np.random.randint(0, x_test.shape[0])
sample = x_test[testId, :]

#基于类中心的欧式距离法分类
ans = function.euclid(x_train,y_train,sample)
y_test[testId]
print("预测的数字类型",ans)
print("真实的数字类型",y_test[testId])
结果
预测的数字类型 4
真实的数字类型 4

你可能感兴趣的:(《模式识别与智能计算》)