《模式識別與智慧計算》二值化的夾角餘弦距離法分類
- 2020 年 1 月 16 日
- 筆記
演算法流程
- 將樣本庫中的每個樣本進行二值化,閾值為(最大值-最小值)/2
- 利用夾角餘弦距離法對待測樣品進行分類
演算法實現
def erzhianglecos(x_train,y_train,sample): """ :function 按照二值夾角餘弦距離法計算待測樣品與樣品庫中的相似度 :param x_train: 訓練集 M*N M為樣本個數 N為特徵個數 :param y_train: 訓練集標籤 1*M :param sample: 待識別樣品 :return: 返回判斷類別 """ #二值化 spit = 0.5*(np.max(x_train) - np.min(x_train)) train = np.where(x_train>spit,1,0) sample = np.where(sample>spit,1,0) #計算夾角餘弦 erZhiAng = np.sum(train*sample)/np.sqrt(np.sum(train^2)*np.sum(sample^2)) #值越大越相似 disMaxId = np.argmax(erZhiAng) label = y_train[disMaxId] 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.anglecos(x_train,y_train,sample) print(ans==y_test[testId])
演算法結果
True
