机器学习实战 基于Scikit-Learn和TensorFlow 之创建测试集
第二章端到端的机器学习项目 之 创建测试集
P53 用标识符来决定数据是否进入测试集
import hashlib # 把任意长度的数据转换为一个长度固定的数据串
def test_set_check(identifier,test_ratio,hash):
return hash(np.int64(identifier)).digest()[-1] < 256 * test_ratio
# 判断哈希值的最后一个字节是否满足要求
def split_train_test_by_id(data, test_ratio, id_column, hash=hashlib.md5):
ids = data[id_column] # 按索引找出id
in_test_set = ids.apply(lambda id_:test_set_check(id_, test_ratio, hash)) # 对所有数据进行划分
return data.loc[~in_test_set], data.loc[in_test_set] #返回满足条件的划分为训练集和测试集
其中的函数解释说明:
- hash.digest() :返回摘要,作为二进制数据字符串值
- numpy.int64() :numpy模块的int类,与python本身的int基本类型并不同。
- apply(func, axis=0) : 将函数func应用到由各列或行形成的数组上,axis=0为列,axis=1为行
- lambda匿名函数:lambda 输入参数 : 需返回的函数输出值
- loc 根据标签索引行数据
- hashlib.md5() :把任意长度的数据转换为一个长度固定的数据串
运用
1、使用行索引作为ID
housing_with_id = housing.reset_index() #使用行索引做id
train_set, test_set = split_train_test_by_id(housing_with_id, 0.2, "id") #分出训练集和测试集
2、使用经纬度作为ID
housing_with_id["id"] = housing["longitude"] * 1000 + housing["latitude"] #使用经度和纬度作为ID
train_set, test_set = split_train_test_by_id(housing_with_id, 0.2, "id") #分出训练集和测试集
来源:CSDN
作者:敲键盘的大蚂蚁
链接:https://blog.csdn.net/Asdas_/article/details/104214575