目录
一.分类准确度
统计预测结果和test结果真实标签相同的个数。
sum(y_predict == y_test) / len(y_test)#相同个数/样本总量。
1.我们的封装accuracy_score
(1)KNN.py
import numpy as np
from math import sqrt
from collections import Counter
from .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
(2)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))
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
(3)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)
在jupter中实现:
下载手写字体数据
scikit-learn中的accuracy_score
注:调包问题。包、py文件、类、函数使用
①from playML.model_selection import train_test_split
# playML是包
#train_test_split为model_selection.py的函数
X_train, X_test, y_train, y_test = train_test_split(X, y, test_ratio=0.2)
②from playML.kNN import KNNClassifier
#KNNClassifier为kNN.py的类
my_knn_clf = KNNClassifier(k=3)#类实例化
my_knn_clf.fit(X_train, y_train)#fit为类的函数,实例化的类调用函数
y_predict = my_knn_clf.predict(X_test)#同上
③from playML.metrics import accuracy_score
#accuracy_score为metrics.py的函数
accuracy_score(y_test, y_predict)
二.超参数
1.概念
- 超参数:在算法运行前需要决定的参数
- 模型参数:算法运行过程中学习的参数
kNN算法没有模型参数
kNN算法中的k是典型的超参数
- 领域知识
- 经验数值
- 实验搜索
2.寻找最好的k、weight、p
1.先加载数据
2.寻找最好K
3.考虑距离?不考虑距离?
4.搜索明可夫斯基距离相应的p
三.网格搜索
四.数据归一化
1.为什么归一化
由于样本数据单位不一样,计算出两个样本的距离可能有偏差,不能准确反映样本中每一个特征的重要程度。
解决方案:将所有数据映射到同一尺度
- 最大值归一化
把所有数据映射到0-1之间
适用于分布有明显边界的情况(成绩)
一维
(x - np.min(x)) / (np.max(x) - np.min(x))
二维
- 均值方差归一化
数据分布没有明显边界;有可能存在极端数据值
把所有数据归一到均值为0方差为1的分布中
2.测试数据集归一化
要保存训练数据集得到的均值和方差
利用scikit-learn中的StandardScaler对数据进行均值方差归一化
import numpy as np
from sklearn import datasets
iris = datasets.load_iris()
x = iris.data
y = iris.target
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)
from sklearn.preprocessing import StandardScaler
# 构造均值方差归一化对象
standardScaler = StandardScaler()
# fit,standardScaler中存放了计算均值方差归一化的关键信息
standardScaler.fit(x_train)
# 均值
print('训练数据均值:',standardScaler.mean_ )
# 描述数据分布范围 包括:方差 标准差等
print('训练数据方差:',standardScaler.scale_)
# 对训练数据进行归一化处理
x_train = standardScaler.transform(x_train)
# 对测试数据进行归一化处理,并赋值给 x_test_standard
x_test_standard = standardScaler.transform(x_test)
from sklearn.neighbors import KNeighborsClassifier
# 创建一个kNN分类器
knn_clf = KNeighborsClassifier(n_neighbors=3)
# 将均值方差归一化后的数据进行写入
knn_clf.fit(x_train,y_train)
# 计算分类器准确度
print("测试数据经过均值方差归一化后 准确度:",knn_clf.score(x_test_standard,y_test))
# 测试数据集没有进行归一化处理
print("测试数据未经过均值方差归一化后 准确度:",knn_clf.score(x_test,y_test))