首页 > 技术文章 > 从0开始的机器学习——knn算法篇(3)

xiyoushumu 2020-07-15 15:20 原文

把训练集分成两部分,一大部分作为训练数据,另一部分作为测试数据,这样可以发现模型是否合理,然后进行修改。

用鸢尾花数据集(iris)和Anaconda进行演示操作。

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

iris = datasets.load_iris()

x = iris.data
y = iris.target

x.shape

————>(150,4)

y.shape

————>(150,)

train_set_split (如何将数据集分块?)

首先看一下鸢尾花数据集的标签集:

可以发现数据分布非常有规律,如果用这个数据进行训练,比如取前100个进行训练,后50个进行测试,这样测试数据只有2没有0和1,这样是不合理的。

shuffle_indexes = np.random.permutation(len(x))  //这个函数可以对传入的数据进行乱序,返回的是索引

 

test_ratio = 0.2
test_size = int(len(x) * test_ratio)

//150*0.2,取了30个样本作为测试数据

test_indexes = shuffle_indexes[:test_size]  //取了前30个作为测试样本
train_indexes = shuffle_indexes[test_size:]  //后120个作为训练样本

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

X_teats = X[test_indexes]
y_tests = y[test_indexes]

 

也可以直接调用sklearn中的train_test_split

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)  //test_size相当于test_ratio,不设置的话默认为0.2

 

推荐阅读