《模式識別與智慧計算》夾角餘弦距離分類

  • 2020 年 1 月 16 日
  • 筆記

演算法流程
  1. 計算待測樣品與訓練集里每個樣品x的角度距離
  2. 角度距離最大的就是所屬的樣品類別
演算法實現

計算夾角餘弦

def anglecos(x_train,y_train,sample):      """      :function 按照夾角餘弦距離法計算待測樣品與樣品庫中的相似度      :param x_train: 訓練集 M*N  M為樣本個數 N為特徵個數      :param y_train: 訓練集標籤 1*M      :param sample: 待識別樣品      :return: 返回判斷類別      """      label = 0      disMax = -1*np.inf      for i,train in enumerate(x_train):          dis = np.sum(train*sample)/(np.sqrt(np.sum(train*train)*np.sum(sample*sample)))          if disMax<dis:              disMax = dis              label = y_train[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.anglecos(x_train,y_train,sample)  print(ans==y_test[testId])
演算法結果
True

Tags: