文章目录

  • 1. 测试集和训练集的划分
    • 1.1 划分训练集和测试集
    • 2. fit和transform

1. 测试集和训练集的划分

from sklearn.datasets import load_iris, fetch_20newsgroups, load_boston
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report
from sklearn.feature_extraction import DictVectorizer
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
li = load_iris()
# li的属性有‘data’,‘target’
print("获取特征值:")
print(li.data[0:5])
print("目标值:")
print(li.target[0:5])
获取特征值:
[[5.1 3.5 1.4 0.2][4.9 3.  1.4 0.2][4.7 3.2 1.3 0.2][4.6 3.1 1.5 0.2][5.  3.6 1.4 0.2]]
目标值:
[0 0 0 0 0]

注意返回值:训练集 train x_train, y_train 测试集 test x_test, y_test

1.1 划分训练集和测试集

# 调用格式为:
x_train, x_test, y_train, y_test = train_test_split(li.data, li.target, test_size=0.25)
# 数据量较大,打印前5个样本即可。
print("训练集特征值和目标值:", x_train[:5], y_train[:5])
print("测试集特征值和目标值:", x_test[:5], y_test[:5])
训练集特征值和目标值: [[6.3 3.3 6.  2.5][6.  3.  4.8 1.8][7.  3.2 4.7 1.4][4.9 2.5 4.5 1.7][6.7 3.1 4.4 1.4]] [2 2 1 2 1]
测试集特征值和目标值: [[7.7 3.  6.1 2.3][4.9 2.4 3.3 1. ][7.7 2.8 6.7 2. ][7.9 3.8 6.4 2. ][5.4 3.9 1.3 0.4]] [2 1 2 2 0]
print(li.DESCR) # 该数据集的一些描述信息
.. _iris_dataset:Iris plants dataset
--------------------**Data Set Characteristics:**:Number of Instances: 150 (50 in each of three classes):Number of Attributes: 4 numeric, predictive attributes and the class:Attribute Information:- sepal length in cm- sepal width in cm- petal length in cm- petal width in cm- class:- Iris-Setosa- Iris-Versicolour- Iris-Virginica:Summary Statistics:============== ==== ==== ======= ===== ====================Min  Max   Mean    SD   Class Correlation============== ==== ==== ======= ===== ====================sepal length:   4.3  7.9   5.84   0.83    0.7826sepal width:    2.0  4.4   3.05   0.43   -0.4194petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)petal width:    0.1  2.5   1.20   0.76    0.9565  (high!)============== ==== ==== ======= ===== ====================:Missing Attribute Values: None:Class Distribution: 33.3% for each of 3 classes.:Creator: R.A. Fisher:Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov):Date: July, 1988The famous Iris database, first used by Sir R.A. Fisher. The dataset is taken
from Fisher's paper. Note that it's the same as in R, but not as in the UCI
Machine Learning Repository, which has two wrong data points.This is perhaps the best known database to be found in the
pattern recognition literature.  Fisher's paper is a classic in the field and
is referenced frequently to this day.  (See Duda & Hart, for example.)  The
data set contains 3 classes of 50 instances each, where each class refers to a
type of iris plant.  One class is linearly separable from the other 2; the
latter are NOT linearly separable from each other... topic:: References- Fisher, R.A. "The use of multiple measurements in taxonomic problems"Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions toMathematical Statistics" (John Wiley, NY, 1950).- Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.(Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.- Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New SystemStructure and Classification Rule for Recognition in Partially ExposedEnvironments".  IEEE Transactions on Pattern Analysis and MachineIntelligence, Vol. PAMI-2, No. 1, 67-71.- Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE Transactionson Information Theory, May 1972, 431-433.- See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al"s AUTOCLASS IIconceptual clustering system finds 3 classes in the data.- Many, many more ...
data_url = "http://lib.stat.cmu.edu/datasets/boston"
raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]
data[:5]
array([[6.3200e-03, 1.8000e+01, 2.3100e+00, 0.0000e+00, 5.3800e-01,6.5750e+00, 6.5200e+01, 4.0900e+00, 1.0000e+00, 2.9600e+02,1.5300e+01, 3.9690e+02, 4.9800e+00],[2.7310e-02, 0.0000e+00, 7.0700e+00, 0.0000e+00, 4.6900e-01,6.4210e+00, 7.8900e+01, 4.9671e+00, 2.0000e+00, 2.4200e+02,1.7800e+01, 3.9690e+02, 9.1400e+00],[2.7290e-02, 0.0000e+00, 7.0700e+00, 0.0000e+00, 4.6900e-01,7.1850e+00, 6.1100e+01, 4.9671e+00, 2.0000e+00, 2.4200e+02,1.7800e+01, 3.9283e+02, 4.0300e+00],[3.2370e-02, 0.0000e+00, 2.1800e+00, 0.0000e+00, 4.5800e-01,6.9980e+00, 4.5800e+01, 6.0622e+00, 3.0000e+00, 2.2200e+02,1.8700e+01, 3.9463e+02, 2.9400e+00],[6.9050e-02, 0.0000e+00, 2.1800e+00, 0.0000e+00, 4.5800e-01,7.1470e+00, 5.4200e+01, 6.0622e+00, 3.0000e+00, 2.2200e+02,1.8700e+01, 3.9690e+02, 5.3300e+00]])
target[:5]
array([24. , 21.6, 34.7, 33.4, 36.2])

以上展示了两种不同类型的数据集,一种target为离散型(类别),一种为连续型(价格)。

2. fit和transform

fit( ): Method calculates the parameters μ and σ and saves them as internal objects.

可以理解为在对数据集进行转换操作之前,对数据的一些基本属性如:均值,方差,最大值,最小值做个类似pd.info()的概况。

transform( ): Method using these calculated parameters apply the transformation to a particular dataset.
在调用transform之前,需要对数据做一个fit预处理,然后可以进行标准化,降维,归一化等操作。(如PCA,StandardScaler等)。

fit_transform(): joins the fit() and transform() method for transformation of dataset.

想当于是fit和transform的组合,既包括了预处理和数据转换。

from sklearn.decomposition import PCA
from sklearn.preprocessing import MinMaxScaler, StandardScaler
sample_1 = [[2,4,2,3],[6,4,3,2],[8,4,5,6]]
s = StandardScaler()
s.fit_transform(sample_1)
array([[-1.33630621,  0.        , -1.06904497, -0.39223227],[ 0.26726124,  0.        , -0.26726124, -0.98058068],[ 1.06904497,  0.        ,  1.33630621,  1.37281295]])
ss = StandardScaler()
ss.fit(sample_1)
StandardScaler()
ss.transform(sample_1)
array([[-1.33630621,  0.        , -1.06904497, -0.39223227],[ 0.26726124,  0.        , -0.26726124, -0.98058068],[ 1.06904497,  0.        ,  1.33630621,  1.37281295]])

机器学习基础(二)——训练集和测试集的划分相关推荐

  1. 处理训练集和测试集分布同的方法(对抗训练)

    https://www.kaggle.com/c/santander-value-prediction-challenge 在kaggle该题中,需要通过所给的匿名变量来预测target值 featu ...

  2. iris数据集_sklearn日志(二)训练集和测试集划分

    机器学习算法需要大量的数据,这些数据一部分用于模型训练,另一部分作为测试或验证. 机器学习入坑者:sklearn日志(一)体验官方提供的标准数据集​zhuanlan.zhihu.com sklearn ...

  3. python机器学习 train_test_split()函数用法解析及示例 划分训练集和测试集 以鸢尾数据为例 入门级讲解

    文章目录 train_test_split()用法 获取数据 划分训练集和测试集 完整代码脚手架 train_test_split()用法 python机器学习中常用 train_test_split ...

  4. 机器学习中训练集和测试集归一化(matlab版)

    转载自   https://blog.csdn.net/lkj345/article/details/50352385 背景介绍: 归一化后加快了梯度下降求最优解的速度,归一化有可能提高精度. 训练集 ...

  5. [机器学习笔记] 将数据拆分成训练集和测试集的几种方法

    问题描述: 一般情况下, 我们习惯将原始数据中的80% 作为训练集, 20% 作为测试集(当数据量足够大的时候,也可以将10% 作为测试集. 数据量较小时,如果每次都是随机划分训练集,执行多次训练后, ...

  6. 31,32,33_过拟合、欠拟合的概念、L2正则化,Pytorch过拟合欠拟合,交叉验证-Train-Val-Test划分,划分训练集和测试集,K-fold,Regularization

    1.26.过拟合.欠拟合及其解决方案 1.26.1.过拟合.欠拟合的概念 1.26.1.1.训练误差和泛化误差 1.26.1.2.验证数据集与K-fold验证 1.26.1.3.过拟合和欠拟合 1.2 ...

  7. idea2020.2中@test是怎么测试的_Sklearn 划分训练集和测试集

    [从零开始学机器学习第 03 篇] 摘要:手写 Sklearn 的 train_test_split 函数. 之前两篇文章以酒吧的红酒故事引出了 kNN 分类算法,根据已倒好的酒(样本),预测新倒的酒 ...

  8. 深度学习之数据处理——如何将图片和标签打乱并划分为训练集和测试集

    深度学习之数据处理--如何将图片和标签打乱并划分为训练集和测试集 记录我的第一篇CSDN博客 最近我在网上找到Office31数据集,这个数据集中包含了三个子数据集,分别为:Amazon.dslr.w ...

  9. 5.sklearn之转换器(划分训练集和测试集、以及标准化、归一化数据会用transform,独热编码也会用到)

    文章目录 1. 什么是转换器? 2. 测试集和训练集 2.1 训练集 .测试集.验证集 2.2 拆分训练集测试集有个问题 2.3 代码 3. 标准化 3.1 上离差标准化代码(举一反三就好了,其他几个 ...

  10. sklearn.model_selection.train_test_split随机划分训练集和测试集

    1 函数用途 train_test_split()是交叉验证中常用的函数,功能是将数组或矩阵按比例随机划分为训练集和测试集,使用方法为: X_train,X_test, y_train, y_test ...

最新文章

  1. WDS使用捕获映像制作企业自定义映像
  2. [Android] AlertDialog获取网上天气并显示各城市天气
  3. k近邻算法C++二维情况下的实现
  4. html菜鸟ruby,Ruby 循环
  5. linux sybase 自动备份,Linux平台下Sybase数据库备份方法分析.doc
  6. cartographer坐标系_cartographer个人对框架解读
  7. lpc3250 TFT-4238液晶支持
  8. ADO.NET 【攻击及防御】
  9. 程序实现对数据排序并按出现次数进行排序 程序实现对数据排序并按出现次数进行排序(注:用面向对象的方式实现,用for循环进行排序,别用comparable接口实现){1,4,2,1,3,2,1,4}作为
  10. stm32 整数加法循环时间_剑指 Offer 65. 不用加减乘除做加法 leetcode 剑指offer系列...
  11. 电商项目数据库设计 | 第五篇:参考京东商城详细讲解商品数据库设计
  12. apache VSF 操作类
  13. 住房贷款等额本息(等额本金)还款计划计算
  14. php ini 分号,当分号(;)被包含在值中时,用PHP解析INI文件
  15. 快速指数运算:平方-乘算法
  16. 多个激光雷达同时校准、定位和建图的框架
  17. 微信小程序开发账号找回
  18. 《看不见的森林:林中自然笔记》书摘二
  19. 《我在未来等你》的读书笔记和读后感作文2900字
  20. [物理学与PDEs]第4章习题1 反应力学方程组形式的化约 - 动量方程与未燃流体质量平衡方程...

热门文章

  1. Threejs导入OBJ模型出错的一些经验之谈
  2. 搜狗微信文章url解码
  3. windows域环境搭建上
  4. Linux 远程拷贝命令
  5. 二叉树非递归遍历思路总结
  6. 蔡学镛:写SOP(标准作业程序)就是写程序
  7. matlab数据类型 —— 整型
  8. java企业员工管理系统_基于JavaWeb的企业员工信息管理系统的设计任务书
  9. 控制工程中的数学建模(2)——二阶有源低通滤波器(之二)
  10. 课时1 Excel简介与基本操作