<jupyter_start><jupyter_text>KNN的过程<jupyter_code>from math import sqrt
distance = []
for x_train in X_train:
    d = sqrt(np.sum((x_train - x)**2))
    distance.append(d)
distances
distances = [sqrt(np.sum((x_train-  x)**2)) for x_train in X_train]
distances
np.argsort(distances)
nearest = np.argsort(distances)
k = 6
topK_y = [y_train[i] for i in nearest[:k]]
topK_y
from collections import Counter
Counter(topK_y)
votes=Counter(topK_y)
votes.most_common(1)
predict_y=votes.most_common(1)[0][0]
predict_y
%run C:\Users\bufanx\PycharmProjects\MachineLearning\KNN\Knn.py
predict=KNN_classify(6,X_train,y_train,x)
predict<jupyter_output><empty_output><jupyter_text>使用scikit-learn中的KNN<jupyter_code>from sklearn.neighbors import KNeighborsClassifier
KNN_classifier = KNeighborsClassifier(n_neighbors=6)
KNN_classifier.fit(X_train, y_train)
x_predict = x.reshape(1,-1)
x_predict
KNN_classifier.predict(x_predict)
%run C:\Users\bufanx\PycharmProjects\MachineLearning\KNN\knn.py
knn_cls=KNNClassifier(k=6)
knn_cls.fit(X_train,y_train)
x_predict
y_predict=knn_cls.predict(x_predict)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12296564195298372, 'fraction_numerical': 0.0108499095840868, 'mean_word_length': 8.710526315789474, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '658996', 'license': 'Apache-2.0', 'n_tokens_mistral': 488, 'n_tokens_neox': 473, 'n_words': 64, 'path': 'PlayML/jupyter notebook file/KNN.ipynb', 'repo_name': 'bufanx/ML-Learning', 'size': '1106'}