1、随机划分训练集和测试集

sklearn.model_selection.train_test_split

一般形式:
train_test_split是交叉验证中常用的函数,功能是从样本中随机的按比例选取train data和testdata,形式为:

X_train,X_test, y_train, y_test =
cross_validation.train_test_split(train_data,train_target,test_size=0.4, random_state=0)

参数解释:
- train_data:所要划分的样本特征集
- train_target:所要划分的样本结果
- test_size:样本占比,如果是整数的话就是样本的数量
- random_state:是随机数的种子。
- 随机数种子:其实就是该组随机数的编号,在需要重复试验的时候,保证得到一组一样的随机数。比如你每次都填1,其他参数一样的情况下你得到的随机数组是一样的。但填0或不填,每次都会不一样。
随机数的产生取决于种子,随机数和种子之间的关系遵从以下两个规则:
- 种子不同,产生不同的随机数;种子相同,即使实例不同也产生相同的随机数。

from sklearn.cross_validation import train_test_split
train= loan_data.iloc[0: 55596, :]
test= loan_data.iloc[55596:, :] # 避免过拟合,采用交叉验证,验证集占训练集20%,固定随机种子(random_state)
train_X,test_X, train_y, test_y = train_test_split(train, target, test_size = 0.2, random_state = 0)
train_y= train_y['label']
test_y= test_y['label']

2.将离散变量数值化分类(labelencoder),和虚拟(dummy)变量的转换

sklearn.preprocessing.LabelEncoder\OneHotEncoder

我们一般用LabelEncoder来讲series转换为不同的整数分类,然后将其转化为有序的数字编号

encoder = LabelEncoder()
y = encoder.fit_transform(y)
#这里也可以先进行fit(),然后在进行transform()
#fit()是将样本集数字分类,transform()是将样本集转化为数字分类

onehot的方法则是将数据离散成为无序的离散数据,但是转换的需是整数所以和labelencoder搭配使用

from numpy import array
from numpy import argmax
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
# define example
data = ['cold', 'cold', 'warm', 'cold', 'hot', 'hot', 'warm', 'cold', 'warm', 'hot']
values = array(data)
print(values)
# integer encode
label_encoder = LabelEncoder()
integer_encoded = label_encoder.fit_transform(values)
print(integer_encoded,integer_encoded.shape)
# binary encode
onehot_encoder = OneHotEncoder(sparse=False)
integer_encoded = integer_encoded.reshape(-1, 1)
print(integer_encoded.reshape(-1, 1))
onehot_encoded = onehot_encoder.fit_transform(integer_encoded)
print(onehot_encoded)
# invert first example
inverted = label_encoder.inverse_transform([argmax(onehot_encoded[0, :])])
print(inverted)

3.数据的规范化/标准化

sklearn.preprocessing

标准化:

公式为:(X-mean)/std  计算时对每个属性/每列分别进行。

将数据按期属性(按列进行)减去其均值,并处以其方差。得到的结果是,对于每个属性/每列来说所有数据都聚集在0附近,方差为1。

实现时,有两种不同的方式:

from sklearn import preprocessing
import numpy as np
X = np.array([[ 1., -1., 2.],
... [ 2., 0., 0.],
... [ 0., 1., -1.]])
X_scaled = preprocessing.scale(X) #处理后数据的均值和方差
X_scaled.mean(axis=0)
array([ 0., 0., 0.]) X_scaled.std(axis=0)
array([ 1., 1., 1.])

使用sklearn.preprocessing.StandardScaler类,使用该类的好处在于可以保存训练集中的参数(均值、方差)直接使用其对象转换测试集数据。

scaler = preprocessing.StandardScaler().fit(X)
StandardScaler(copy=True, with_mean=True, with_std=True) scaler.transform(X)
array([[ 0. ..., -1.22..., 1.33...],
[ 1.22..., 0. ..., -0.26...],
[-1.22..., 1.22..., -1.06...]]) #可以直接使用训练集对测试集数据进行转换
scaler.transform([[-1., 1., 0.]])
array([[-2.44..., 1.22..., -0.26...]])

 将属性缩放到一个指定范围:

另一种常用的方法是将属性缩放到一个指定的最大和最小值(通常是1-0)之间,这可以通过preprocessing.MinMaxScaler类实现。

使用这种方法的目的包括:

1、对于方差非常小的属性可以增强其稳定性。

2、维持稀疏矩阵中为0的条目。

 X_train = np.array([[ 1., -1.,  2.],
... [ 2., 0., 0.],
... [ 0., 1., -1.]])
...
min_max_scaler = preprocessing.MinMaxScaler()
X_train_minmax = min_max_scaler.fit_transform(X_train) >>> #将相同的缩放应用到测试集数据中
>>> X_test = np.array([[ -3., -1., 4.]])
>>> X_test_minmax = min_max_scaler.transform(X_test) >>> #缩放因子等属性
>>> min_max_scaler.scale_
array([ 0.5 , 0.5 , 0.33...]) >>> min_max_scaler.min_
array([ 0. , 0.5 , 0.33...])

4.模型参数的选择

sklearn.grid_search

可以用来调节模型的参数:

tree_param_grid={'min_samples_split':list((3,6,9)),'n_estimators':list(10,50,100)}
grid=GridSearchCV(RandomForestRegressor(),param_grid,=tree)param_gridcv=5)
grid.fit(train_x,train_y)
grid.beat_params

sklearn--数据集的处理 模型参数选择的更多相关文章

  1. python进行机器学习(四)之模型验证与参数选择

    一.模型验证 进行模型验证的一个重要目的是要选出一个最合适的模型,对于监督学习而言,我们希望模型对于未知数据的泛化能力强,所以就需要模型验证这一过程来体现不同的模型对于未知数据的表现效果. 这里我们将 ...

  2. 莫烦python教程学习笔记——利用交叉验证计算模型得分、选择模型参数

    # View more python learning tutorial on my Youtube and Youku channel!!! # Youtube video tutorial: ht ...

  3. adaboost 参数选择

    先看下ababoost和决策树效果对比 import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection ...

  4. 【学习笔记】sklearn数据集与估计器

    数据集划分 机器学习一般的数据集会划分为两个部分: 训练数据:用于训练,构建模型 测试数据:在模型检验时使用,用于评估模型是否有效 训练数据和测试数据常用的比例一般为:70%: 30%, 80%: 2 ...

  5. sklearn的常用函数以及参数

    sklearn可实现的函数或者功能可分为如下几个方面 1.分类算法2.回归算法3.聚类算法4.降维算法5.模型优化6.文本预处理 其中分类算法和回归算法又叫监督学习,聚类算法和降维算法又叫非监督学习 ...

  6. libSVM 参数选择

    libSVM 参数选择  [预测标签,准确率,决策值]=svmpredict(测试标签,测试数据,训练的模型);    原文参考:http://blog.csdn.net/carson2005/art ...

  7. libsvm参数选择

    以前接触过libsvm,现在算在实际的应用中学习 LIBSVM 使用的一般步骤是: 1)按照LIBSVM软件包所要求的格式准备数据集: 2)对数据进行简单的缩放操作: 3)首要考虑选用RBF 核函数: ...

  8. sklearn中随机森林的参数

    一:sklearn中决策树的参数: 1,criterion: ”gini” or “entropy”(default=”gini”)是计算属性的gini(基尼不纯度)还是entropy(信息增益),来 ...

  9. 支持向量机SVM 参数选择

    http://ju.outofmemory.cn/entry/119152 http://www.cnblogs.com/zhizhan/p/4412343.html 支持向量机SVM是从线性可分情况 ...

随机推荐

  1. Core Data概述(转)

    Core Data是一个模型层的技术.Core Data帮助你建立代表程序状态的模型层.Core Data也是一种持久化技术,它能将模型对象的状态持久化到磁盘,但它最重要的特点是:Core Data不 ...

  2. Django -- DateTimeField

    默认为时区时间时,需要导入django内置的timezone模块 from django.utils import timezone create_at = models.DateTimeField( ...

  3. EuRoc V203数据集的坑

    EuRoc数据集时间戳问题 以前听别人说过V203序列有问题,今儿仔细看了才发现EuRoc的V203数据集中的左右相机 照片数量不相等,很僵硬,cam0存在大量丢帧,之前一直用单目数据,没什么感觉.. ...

  4. Eureka启动报错:Failed to load property source from location 'classpath:/application.yml'

    原因: 将application.yml添加到classpath时, 由于变更了application.yml的编码格式(或许也改变了些代码内容), 而target内的yml文件没有实时更新, 从而导 ...

  5. exchange 2010入门到精通

    exchange 2010入门到精通 Exchange产品介绍和功能演示 Exchange是什么 目前最受欢迎企业级邮件服务器产品 市场占有率70%(2011数据) 微软消息协作平台中核心产品 Exc ...

  6. cvpr2015papers

    @http://www-cs-faculty.stanford.edu/people/karpathy/cvpr2015papers/ CVPR 2015 papers (in nicer forma ...

  7. NDK学习笔记-JNI多线程

    前面讲到记录到ffmpeg音视频解码的时候,采用的是在主线程中进行操作,这样是不行的,在学习了POSIX多线程操作以后,就可以实现其在子线程中解码了,也可以实现音视频同步了 简单示例 在native实 ...

  8. bootstrap基础学习【表单含按钮】(二)

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  9. mdk3洪水攻击教程

    使得路由器崩溃,直到重启. 1.iwconfig 查看网卡 2.airmon-ng start wlan0 开启网卡监控 3.airodump-ng mon0 查看附近路由信息 4.mdk3 mon0 ...

  10. golang写入csv

    package main import ( "encoding/csv" "fmt" "os" ) func main() { file, ...