如何使用Python Scikit-learn从数据集获得类似于字典的对象?

如何使用Python Scikit-learn从数据集获得类似于字典的对象?

借助于Scikit-learn的Python库,我们可以得到数据集的类似于字典的对象。一些有趣的字典对象属性如下所示−

  • 数据(data) − 表示要学习的数据。

  • 目标(target) − 表示回归目标。

  • DESCR − 数据集的描述。

  • 目标名称(target_names) − 给出数据集的目标名称。

  • 特征名称(feature_names) − 从数据集中给出特征的名称。

示例1

在下面的示例中,我们使用加利福尼亚住房数据集来获取其类似于字典的对象。

# 导入必要的库
import sklearn
import pandas as pd
from sklearn.datasets import fetch_california_housing

# 加载加利福尼亚住房数据集
housing = fetch_california_housing()

# 打印类似于字典的对象
print(housing.keys())
Bash

输出

将会产生以下输出−

dict_keys(['data', 'target', 'frame', 'target_names', 'feature_names', 'DESCR'])
Bash

示例2

我们也可以使用以下方法更多地了解这些类似于字典的对象−

# 导入必要的库
import sklearn
import pandas as pd
from sklearn.datasets import fetch_california_housing
print(housing.data.shape)
print('\n')
print(housing.target.shape)
print('\n')
print(housing.feature_names)
print('\n')
print(housing.target_names)
print('\n')
print(housing.DESCR)
Bash

输出

将会产生以下输出−

(20640, 8)
(20640,)
['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population', 'AveOccup', 'Latitude', 'Longitude']
['MedHouseVal']
.. _california_housing_dataset:
California Housing dataset
--------------------------
**Data Set Characteristics:**
   :Number of Instances: 20640
   :Number of Attributes: 8 numeric, predictive attributes and the target
   :Attribute Information:
      - MedInc median income in block group
      - HouseAge median house age in区块组中位数收入
      - HouseAge区块组中位数房龄
      - AveRooms每户的平均房间数
      - AveBedrms每户的平均卧室数
      - Population区块组人口
      - AveOccup每个家庭的平均家庭成员数
      - Latitude区块组纬度
      - Longitude区块组经度
   :缺少属性值:无
由于输出内容过长,已省略...
Bash

示例3

# 导入必要的库
import sklearn
import pandas as pd
from sklearn.datasets import fetch_california_housing

# 加载加利福尼亚房屋数据集
housing = fetch_california_housing(as_frame=True)

print(housing.frame.info())
Bash

输出

将产生以下输出 −

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 20640 entries, 0 to 20639
Data columns (total 9 columns):
#    列名          非空值数         数据类型
---  ------      --------------  -----
 0   MedInc       20640 non-null   float64
 1   HouseAge     20640 non-null   float64
 2   AveRooms     20640 non-null   float64
 3   AveBedrms    20640 non-null   float64
 4   Population   20640 non-null   float64
 5   AveOccup     20640 non-null   float64
 6   Latitude     20640 non-null   float64
 7   Longitude    20640 non-null   float64
 8   MedHouseVal  20640 non-null   float64
dtypes: float64(9)
memory usage: 1.4 MB
Bash

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册