<jupyter_start><jupyter_text>测试算法性能<jupyter_code>import numpy as np
from sklearn import datasets
iris = datasets.load_iris()  # 加载鸢尾花数据集
iris.keys()
print(iris.DESCR)
iris.data[:10]  # 鸢尾花四个特征数据
iris.target_names  # 鸢尾花三种类型的名称
iris.target[:10]  # 三种类型对应的code,注意:data和target的数据是一一对应的
X = iris.data
y = iris.target
X.shape  # 总共150行数据
y.shape<jupyter_output><empty_output><jupyter_text>train_test_split分离出一部分数据做训练，另外一部分数据做测试。<jupyter_code>y  # 观察数据发现每个编码都已经分类好了,为了保证训练模型的准确性,需将数据打乱,保证每一项数据参与训练的概率都是相同的
shuffled_indexes = np.random.permutation(len(X))  # 随机置换序列,这样就能保证特征值和标记一一对应
shuffled_indexes
test_ratio = 0.2  # 设置分割比例
test_size = int(len(X) * test_ratio)
test_size
# 分割测试数据和训练数据
test_indexes = shuffled_indexes[:test_size]
train_indexes = shuffled_indexes[test_size:]
# 准备数据

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

X_train = X[train_indexes]
y_train = y[train_indexes]
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)<jupyter_output>(30, 4)
(30,)<jupyter_text>使用封装后的train_test_split算法<jupyter_code>from train_split.model_selection import train_test_split 

# 调用train_test_split,并设置随机数种子为10
X_train2, X_test2, y_train2, y_test2 = train_test_split(X, y, seed=10)
print(X_train2.shape)
print(y_train2.shape)
# 导入自己封装的kNN算法来测试

from train_split.kNN import KNNClassifier

my_knn_clf = KNNClassifier(3)  # 初始化分类器
my_knn_clf.fit(X_train, y_train)  # 拟合
y_predict = my_knn_clf.predict(X_test)
y_predict
# 查看之前分割得测试结果
y_test
# 计算算法性能
sum(y_predict == y_test) / len(y_test)<jupyter_output><empty_output><jupyter_text>sklearn中的train_test_split自己封装train_test_split的思路是借鉴sklearn库model_selection模块train_test_split函数<jupyter_code>from sklearn.model_selection import train_test_split
X_train3, X_test3, y_train3, y_test3 = train_test_split(X,y,test_size=0.1, random_state=10)
print(X_train3.shape)
print(y_train3.shape)
print(X_test3.shape)
print(y_test3.shape)<jupyter_output>(15, 4)
(15,)
{'fraction_non_alphanumeric': 0.10359187922956793, 'fraction_numerical': 0.021863612701717855, 'mean_word_length': 9.27807486631016, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, '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': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '119124', 'license': 'MIT', 'n_tokens_mistral': 1005, 'n_tokens_neox': 1060, 'n_words': 106, 'path': 'ml/03-kNN/03-Test-Our-Algorithm/03-Test-Our-Algorithm.ipynb', 'repo_name': 'dhb15735104415/MLlearning-notes', 'size': '1921'}