기계 학습 (1) - K 가까운 이웃 알고리즘

KNN 기능 표현

import numpy as np
from math import sqrt
from collections import Counter

def KNN_classify(k,X_train,y_train,x):
    assert 1<=k<X_train.shape[0],"k must be valid"
    assert X_train.shape[0] == y_train.shape[0],\
    "the size of X_train must equal to the size of y_train"
    assert X_train.shape[1] == x.shape[0],\
    "the feature number of x must be equal to X_train"

    distances=[sqrt(np.sum((X_train-x)**2)) for x_train in X_train]
    nearest=np.argsort(distances)
    topK_y=[y_train[i] for i in nearest[:k]]
    votes=Counter(topK_y)
    return votes.most_common(1)[0][0] #返回类型

KNN을 사용 Scikit는 배우기

from sklearn.neighbors import KNeighborsClassifier
import numpy as np
KNN_classifier=KNeighborsClassifier(n_neighbors=6) #传入k的值
#这里我随便搞的训练数据
x_train=np.arange(0,100).reshape(-1,2) #x是矩阵
y_train=np.random.randint(0,2,50) #y是数组
KNN_classifier.fit(x_train,y_train) #传入训练数据集
x=np.array([1,3]) #测试数据
x=x.reshape(1,-1) #测试数据只能传矩阵为参数
y=KNN_classifier.predict(x)[0] #因为我只测试了一组数据,所以取[0]即可

KNN 클래스 작성

KNN.py

import numpy as np
from math import sqrt
from collections import Counter
from K近邻算法包.metrics import accuracy_score

class KNNClassifier:
    def __init__(self, k):
        """初始化kNN分类器"""
        assert k >= 1, "k must be valid"
        self.k = k
        self._X_train = None #私有变量
        self._y_train = None

    def fit(self, X_train, y_train):
        """根据训练数据集X_train和y_train训练kNN分类器"""
        assert X_train.shape[0] == y_train.shape[0], \
            "the size of X_train must be equal to the size of y_train"
        assert self.k <= X_train.shape[0], \
            "the size of X_train must be at least k."

        self._X_train = X_train
        self._y_train = y_train
        return self

    def predict(self, X_predict):
        """给定待预测数据集X_predict,返回表示X_predict的结果向量"""
        assert self._X_train is not None and self._y_train is not None, \
                "must fit before predict!"
        assert X_predict.shape[1] == self._X_train.shape[1], \
                "the feature number of X_predict must be equal to X_train"

        y_predict = [self._predict(x) for x in X_predict]
        return np.array(y_predict)

    def _predict(self, x):
        """给定单个待预测数据x,返回x的预测结果值"""
        assert x.shape[0] == self._X_train.shape[1], \
            "the feature number of x must be equal to X_train"

        distances = [sqrt(np.sum((x_train - x) ** 2))
                     for x_train in self._X_train]
        nearest = np.argsort(distances)

        topK_y = [self._y_train[i] for i in nearest[:self.k]]
        votes = Counter(topK_y)

        return votes.most_common(1)[0][0]

    def __repr__(self): #自我描述,在创建对象时打印
        return "KNN(k=%d)" % self.k

테스트 알고리즘의 정확성

model_selection.py :

import numpy as np


def train_test_split(X, y, test_ratio=0.2, seed=None):
    """将数据 X 和 y 按照test_ratio分割成X_train, X_test, y_train, y_test"""
    assert X.shape[0] == y.shape[0], \
        "the size of X must be equal to the size of y"
    assert 0.0 <= test_ratio <= 1.0, \
        "test_ration must be valid"

    if seed: #固定随机种子,好调试
        np.random.seed(seed)

    shuffled_indexes = np.random.permutation(len(X)) #len(矩阵)是行数

    test_size = int(len(X) * test_ratio)
    test_indexes = shuffled_indexes[:test_size]
    train_indexes = shuffled_indexes[test_size:]

    X_train = X[train_indexes]
    y_train = y[train_indexes]

    X_test = X[test_indexes]
    y_test = y[test_indexes]

    return X_train, X_test, y_train, y_test

당신은에서 jupyter 노트북을 시도 호출 할 수 있습니다 :

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets

iris = datasets.load_iris()
X=iris.data
y=iris.target

%run F:/python3玩转机器学习/K近邻算法/model_selection.py

X_train, X_test, y_train, y_test=train_test_split(X,y,test_ratio=0.2)

%run F:/python3玩转机器学习/K近邻算法/KNN.py
    
my_knn_clf.fit(X_train,y_train)

y_predict=my_knn_clf.predict(X_test)

sum(y_predict==y_test)/len(y_test)

scikit 배우기 中 的 model_selection :

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test=train_test_split(X,y,test_size=0.2,random_state=666)

분류 정확도

자신의 패키지를 쓰기

metrics.py 쓰기 :

import numpy as np


def accuracy_score(y_true, y_predict):
    '''计算y_true和y_predict之间的准确率'''
    assert y_true.shape[0] == y_predict.shape[0], \
        "the size of y_true must be equal to the size of y_predict"

    return sum(y_true == y_predict) / len(y_true)

KNN.py을에 전화 :

import numpy as np
from math import sqrt
from collections import Counter
from K近邻算法包.metrics import accuracy_score

class KNNClassifier:
    def __init__(self, k):
        """初始化kNN分类器"""
        assert k >= 1, "k must be valid"
        self.k = k
        self._X_train = None #私有变量
        self._y_train = None

    def fit(self, X_train, y_train):
        """根据训练数据集X_train和y_train训练kNN分类器"""
        assert X_train.shape[0] == y_train.shape[0], \
            "the size of X_train must be equal to the size of y_train"
        assert self.k <= X_train.shape[0], \
            "the size of X_train must be at least k."

        self._X_train = X_train
        self._y_train = y_train
        return self

    def predict(self, X_predict):
        """给定待预测数据集X_predict,返回表示X_predict的结果向量"""
        assert self._X_train is not None and self._y_train is not None, \
                "must fit before predict!"
        assert X_predict.shape[1] == self._X_train.shape[1], \
                "the feature number of X_predict must be equal to X_train"

        y_predict = [self._predict(x) for x in X_predict]
        return np.array(y_predict)

    def _predict(self, x):
        """给定单个待预测数据x,返回x的预测结果值"""
        assert x.shape[0] == self._X_train.shape[1], \
            "the feature number of x must be equal to X_train"

        distances = [sqrt(np.sum((x_train - x) ** 2))
                     for x_train in self._X_train]
        nearest = np.argsort(distances)

        topK_y = [self._y_train[i] for i in nearest[:self.k]]
        votes = Counter(topK_y)

        return votes.most_common(1)[0][0]

    def score(self, X_test, y_test):
        """根据测试数据集 X_test 和 y_test 确定当前模型的准确度"""

        y_predict = self.predict(X_test)
        return accuracy_score(y_test, y_predict)

    def __repr__(self): #自我描述,在创建对象时打印
        return "KNN(k=%d)" % self.k

1568941342454

sklearn와 정확도 테스트

데이터 datasets.load_digits = ()

X = data.data

Y = data.target

sklearn.model_selection 수입 train_test_split에서

X_train, X_test, y_train, y_test train_test_split = (X, Y, test_size = 0.2)

sklearn.neighbors에서 KNeighborsClassifier를 가져

KNN_clf = KNeighborsClassifier (N_NEIGHBORS 용 = 3)

KNN_clf.fit (X_train, y_train)

y_predict = KNN_clf.predict (X_test)

sklearn.metrics 수입 accuracy_score에서

accuracy_score (y_test, y_predict)이 될 수 KNN_clf.score (X_test, y_test)

Hyperparameter

결정하는 알고리즘 파라미터를 실행하기 전에 : hyperparameter

모델 매개 변수 : 운전 중 알고리즘 파라미터

KNN 아니오 모델 파라미터 K KNN은 하이퍼 파라미터의 전형적인

위의 필기 디지털 데이터 세트는 폭력은 최고의 K를 찾을 수 :

best_score=0.0
best_k=-1
for k in range(1,11):
    knn_clf=KNeighborsClassifier(n_neighbors=k)
    knn_clf.fit(X_train,y_train)
    score=knn_clf.score(X_test,y_test)
    if score>best_score:
        best_k=k
        best_score=score

print("best_k=",best_k)
print("best_score=",best_score)

때때로, 무게는 바로 같은 영향을 미칠 수 있습니다 :1568944373833

가장 최근은 우리가 무게가 역 합계를 복용의 거리의 비율을 누르면, 빨간색입니다.

민코프 스키 거리 :1569216402795

그녀는 슈퍼 매개 변수 P는 원

최고의 p와 K (그리드 검색) 찾기 :

%%time

best_p=-1
best_score=0.0
best_k=-1
for k in range(1,11):
    for p in range(1,6):
        knn_clf=KNeighborsClassifier(n_neighbors=k,weights="distance")
        knn_clf.fit(X_train,y_train)
        score=knn_clf.score(X_test,y_test)
        if score > best_score :
            best_k=k
            best_p=p
            best_score=score
            
print("best_p=",best_p)
print("best_k=",best_k)
print("best_score=",best_score)

그리드 검색 사용 scikit을 배우기 :

그리드 매개 변수를 정의합니다 :

param_grid = [
{
'가중치': 유니폼 ',
'N_NEIGHBORS '[I 전 범위 (1,11), 대
},
{
'가중치 ':'거리 ',
'N_NEIGHBORS '[I 대 전 범위 (1,11),
'P'[I 대 전 범위 (1,6)]
}]

분류 자 개체를 초기화 :

knn_clf KNeighborsClassifier = ()

가이드 그리드 검색 :

sklearn.model_selection 수입 GridSearchCV에서

인스턴스화 :

grid_search = GridSearchCV (knn_clf, param_grid)

피팅 :

%% 시간
grid_search.fit (X_train, y_train)

최적의 분류 :

grid_search.best_estimator_

grid_search.best_score_

grid_search.best_params_

분류의 knn_clf 푸 최적의 매개 변수 :

knn_clf = grid_search.best_estimator_

knn_clf.score (X_test, y_test)

특정 정보를 표시, 가속 :

grid_search = GridSearchCV (knn_clf, param_grid, n_jobs = -1 장황 = 2) # 1 - 코어의 모든 세부 사항이되고있다 평행 상세 출력 정보

%% 시간
grid_search.fit (X_train, y_train)

데이터 표준화

모든 데이터는 동일한 규모로 매핑됩니다

대부분의 값은 정규화했다 (정상화)

0과 1 사이에 매핑 된 모든 데이터

1569223086450

이상치의 영향에 의해 명확한 경계 조건의 분포에 적용

벡터의 경우 :

X1 = np.random.randint (0100, 사이즈 = 100)

(X1-np.min (X1)) / (np.max (X1) -np.min (X1))

매트릭스 :

X = np.random.randint (0,100, (50,2))

X = np.array (X, DTYPE = 플로트)

상기 각 열의 정규화 된 값은 :

X의 [0] = (X의 [0] -np.min (X의 [0])) / (np.max (X의 [0]) - np.min (X의 [0 ]))

X의 [1] = (X의 [1] -np.min (X의 [1])) / (np.max (X의 [1]) - np.min (X의 [1 ]))

산포도 그리기 :

plt.scatter (X의 [: 0] X [: 1])
plt.show ()

평균 - 분산 정상화 (표준화)

모든 데이터는 제로 평균 및 단위 분산 분포를 1로 정규화 하였다

그것은 극단적 인 값의 영향에서 데이터에 명확한 경계, 무료 적용되지

1569223351856

S는 표준 편차이다.

예 :

X2 = np.random.randint (0,100, (50,2))

X2 = np.array (X2, DTYPE = 플로트)

X2의 [: 0] = (X2의 [: 0] -np.mean (X2의 [: 0])) / np.std (X2의 [: 0])

X2의 [: 1] = (X2의 [: 1] -np.mean (X2의 [: 1])) / np.std (X2의 [: 1])

plt.scatter (X2의 [: 0], X2의 [: 1])
plt.show ()

어떻게 정규화 데이터 세트를 테스트?

뿐만 아니라 단순히 테스트 데이터 정상화를 사용해야 설정 (x_test-x_mean_train) / std_train에

scikit를 배우고 사용 정상화

sklearn 수입 데이터 집합에서
수입 NumPy와

홍채 datasets.load_iris = ()

iris.data X =
Y = iris.target

sklearn.model_selection 수입 train_test_split에서
X_train, X_test, y_train, y_test = train_test_split (iris.data, iris.target, test_size = 0.2, random_state = 666)

sklearn.preprocessing 수입 StandardScaler에서

standardScaler StandardScaler = ()

standardScaler.fit (X_train)

standardScaler.mean_ # 평균

standardScaler.scale_ # 표준 편차, 표준 사용할 수 없게되었다

X_train = standardScaler.transform (X_train)는 # 정규화 행렬을 반환

X_test_standard = standardScaler.transform (X_test) # 테스트 데이터는 트레이닝 데이터 세트를 사용하도록 설정하는 정규화

의 반환의 정확성을 검사 한 후 :

sklearn.neighbors에서 KNeighborsClassifier를 가져

knn_clf = KNeighborsClassifier (N_NEIGHBORS 용 = 3)

knn_clf.fit (X_train, y_train) # 정규화 된 훈련 데이터 X의 교육을 사용하여

표준화 된 테스트 데이터 X 테스트를 사용 knn_clf.score (X_test_standard, y_test) #

홍채 데이터는 자연적으로 매우 정확하고, 상대적으로 작지만 때문에, 1.0를 돌려줍니다.

사용 유사 MinMaxScaler (정규화 된 대부분의 값)이 sklearn.preprocessing.

자신의 StandardScaler 클래스를 작성

preprocessing.py :

import numpy as np


class StandardScaler:

    def __init__(self):
        self.mean_ = None
        self.scale_ = None

    def fit(self, X):
        """根据训练数据集X获得数据的均值和方差"""
        assert X.ndim == 2, "The dimension of X must be 2"

        self.mean_ = np.array([np.mean(X[:,i]) for i in range(X.shape[1])])
        self.scale_ = np.array([np.std(X[:,i]) for i in range(X.shape[1])])

        return self

    def transform(self, X):
        """将X根据这个StandardScaler进行均值方差归一化处理"""
        assert X.ndim == 2, "The dimension of X must be 2"
        assert self.mean_ is not None and self.scale_ is not None, \
               "must fit before transform!"
        assert X.shape[1] == len(self.mean_), \
               "the feature number of X must be equal to mean_ and std_"

        resX = np.empty(shape=X.shape, dtype=float)
        for col in range(X.shape[1]):
            resX[:,col] = (X[:,col] - self.mean_[col]) / self.scale_[col]
        return resX

K-가장 가까운 이웃 알고리즘에 대해

가장 큰 단점 : 비효율적

트레이닝 세트의 샘플 m, N- 기능, 각 예측 데이터가 O에 존재하는 경우 (m *의 않음)

당신은 KD-트리, 볼 트리 최적화,하지만 비효율적 여전히 사용할 수 있습니다

이 단점 : 관련성이 높은 데이터

3 단점 : 예측 된 결과를 가지고 해석 할 수 없습니다

차원의 저주 : 치수 증가와 함께, "두 점 사이의 거리가 비슷한 증가됩니다 것처럼 보일 수 있습니다."

해결 방법 : 차원 축소 등 PCA 등

기계 학습 과정 :

1569228933482

추천

출처www.cnblogs.com/mcq1999/p/KNN_1.html