数据小站
数据科学成长之路

sklearn一般数据集接口使用 sklearn dataset api

klearn提供的数据集都在sklearn.dataset包中,有load和fetch两种方式,数据类型都是集成字典类型

load加载的小数据集,是安装sklearn时已经打包下载到本地,可以直接加载就能使用,fetch的数据线需要先下载才能使用。

dataset.load_的数据集接口

官网目前.load支持的方法

目前官网提供的.load方式加载的数据集中,比较经典的有:
.load_iris()鸢尾花数据集
load_boston()波士顿房价
其中作为入门训练使用最多的也是鸢尾花和波士顿房价的数据集。

iris鸢尾花数据集用在学习sklearn中常用的分类算法,数据简单直观,不管是直接套用算法接口,还是降维,都可以当做熟悉算法的小数据使用。

boston波士顿房价预测数据集,用来熟悉回归算法接口的数据集,,开箱即用。

sklearn dataset api 数据集load数据的特点:

获取的数据集都是类字典类型,可以按照字典的方式使用,通过.keys()查看数据集的元素。
load加载的字典集中,都有data 数据、 target 标签、 target_names 标签名、 feature_names 特征名、DESCR 数据集描述 等元素。
dict_keys([‘data’, ‘target’, ‘target_names’, ‘DESCR’, ‘feature_names’, ‘filename’])

经典数据集简介

1 波士顿房价 Boston house prices dataset

1.1获取方式:

from sklearn import datasets
boston = datasets.load_boston()
print(boston.keys()) 
#dict_keys(['data', 'target', 'feature_names', 'DESCR', 'filename'])
X = boston.data    # boston的特征值,type :numpy.ndarray, shape:506 * 13 
y = boston.target  #boston的标签值,type :numpy.ndarray, shape:506 * 1

注:在打印data时,numpy默认根据数据的精度展示科学计数形式,如果不想以科学计数法形式展示数字,需要设置numpy的set_printoptions()配置,详情查官网源码,pandas同理。

原因print(data)时效果:
[[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]]

设置np的set_printoptions配置
import numpy as np
np.set_printoptions(suppress=True,precision=5)
设置后在打印效果:
[[0.00632  18.        2.31      0.        0.538     6.575    65.2
  4.09      1.      296.       15.3     396.9       4.98]

1.2Data Set Characteristics: 波士顿数据集官方给的描述

波士顿房价数据集样本实例506个,14个属性:13个特征值,和1个用来预测的房价目标值。

官方给定的数据集特征简介:
:Number of Instances: 506   
:Number of Attributes: 13 numeric/categorical predictive. Median Value (attribute 14) is usually the target.  
:Attribute Information (in order):  #特征值属性信息
    - CRIM     per capita crime rate by town
    - ZN       proportion of residential land zoned for lots over 25,000 sq.ft.
    - INDUS    proportion of non-retail business acres per town
    - CHAS     Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
    - NOX      nitric oxides concentration (parts per 10 million)
    - RM       average number of rooms per dwelling
    - AGE      proportion of owner-occupied units built prior to 1940
    - DIS      weighted distances to five Boston employment centres
    - RAD      index of accessibility to radial highways
    - TAX      full-value property-tax rate per $10,000
    - PTRATIO  pupil-teacher ratio by town
    - B        1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town
    - LSTAT    % lower status of the population
    - MEDV     Median value of owner-occupied homes in $1000's
各个字段的含义自行在线翻译吧

1.3boston数据应用:线性回归体验

from sklearn import datasets,model_selection,linear_model
import numpy as np
np.set_printoptions(suppress=True,precision=5)
from matplotlib import pyplot as plt


if __name__ == "__main__":
boston = datasets.load_boston()
X = boston.data
y = boston.target

#将数据分为训练集、测试集
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.4, random_state=0)

lmodel = linear_model.LinearRegression() #使用最基本的线下回归模型
lmodel.fit(X_train,y_train) #采用训练集训练模型
predict_y = lmodel.predict(X_test) #使用模型测试
print(predict_y)

plt.scatter(np.arange(len(predict_y)),predict_y)
plt.scatter(np.arange(len(predict_y)),y_test)
plt.show()

用sklearn的linear_model中的LinearRegression线下回归模型,直接将波士顿房价的所有特征值,直接喂给模型算法,然后用模型的predict方法预测测试集。

这是暴力直接的做法。在将参数训练模型算法之前,还需要做一些数据处理的工作,如特征选择,降维,选取好的特征和降低数据维度,减少模型的计算复杂度,同时过滤一些无效的特征。这里只是作为体验。

2 鸢尾花数据集 iris dataset

>>> from sklearn.datasets import load_iris
>>> data = load_iris()
>>>print(data)

文档对数据集的描述,load_iris()返回的数据集是一个字典的数据结构,有data、target、 target_names 、 feature_names 、 DESCR 、 filename 留个属性,分别对应 数据、标签、标签名称、特征名称、描述、数据文件路径。

Dictionary-like object, the interesting attributes are:

‘data’, the data to learn,

‘target’, the classification labels,

‘target_names’, the meaning of the labels,

‘feature_names’, themeaning of the features,

‘DESCR’, the full description of the dataset,

‘filename’, the physical location ofiris csv dataset

2.1 Data Set Characteristics: 鸢尾花数据集官方给的描述

>>>print(data.DESCR)     查看数据集的描述
The iris dataset is a classic and very easy multi-class classification
dataset.

================= ==============
Classes 3
Samples per class 50
Samples total 150
Dimensionality 4
Features real, positive
================= ==============

鸢尾花数据集是一个经典的多分类数据集 ,有3个类别,每个类别对应50个样本,一共150个样本,有4个维度。

: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.7826
sepal width:    2.0  4.4   3.05   0.43   -0.4194
petal 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!)
============== ==== ==== ======= ===== ====================
......

描述就不描述了,就是一个简单的数据集,4个维度,3个类别,每类50个样本。使用的时候只关注分类的标记,也不用关心每个标记对应的类比名称叫什么。叫什么都差不多。

2.2iris数据应用:决策树体验

iris = datasets.load_iris()
X = iris.data
y = iris.target

X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.4, random_state=0)
clf = tree.DecisionTreeClassifier(random_state=0)  #创建决策树分离器
clf.fit(X_train,y_train)       #训练模型
test = clf.predict(X_test)     #模型预测

print(test)
---------
[2 1 0 2 0 2 0 1 1 1 2 1 1 1 1 0 1 1 0 0 2 1 0 0 2 0 0 1 1 0 2 1 0 2 2 1 0 2 1 1 2 0 2 0 0 1 2 2 1 2 1 2 1 1 2 2 1 2 1 2]

>>> print(clf.score(X_test,y_test))
0.95

打印test就能看到对测试集预测的结果。可以用分类器自带的评分方法.score()查看模型的准确率。

决策树的参数比较多,在选择维度作为分类依据时采用基尼系数、熵等, 还是防止过拟合,设计剪枝策略,先后剪枝,最大深度等。

>>>clf.fit(X_train,y_train) 
>>>print(clf)  
模型训练好后,直接打印模型,可以查看模型的一些参数,这些参数可以在模型初始化时设置
DecisionTreeClassifier(
class_weight=None,
criterion='gini', 
max_depth=None,
max_features=None,
max_leaf_nodes=None,
min_impurity_decrease=0.0, 
min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, 
presort=False,
random_state=0, 
splitter='best')

如果想要对决策树可视化,直接绘图会比较麻烦,需要借助外部执行程序graphviz。

sklearn提供的数据,常用的还有一个肿瘤良性恶性的预测,可以练习逻辑回归。其他的数据接口,基本都是一致。可以去查看文档对数据集描述。

datasets.fetch 下载数据集时报错

urllib.error.URLError: urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)

跳过证书的检查

import ssl
ssl._create_default_https_context = ssl._create_unverified_context
赞(0) 打赏
未经允许不得转载:技术文档分享 » sklearn一般数据集接口使用

评论 抢沙发