sklearn.datasets.fetch_california_housing()
fetch_california_housing()
是 sklearn.datasets
提供的 加州房价预测数据集,用于 回归任务,适用于 机器学习算法测试和特征工程研究。
1. fetch_california_housing()
数据集简介
属性 | 说明 |
---|---|
样本数 | 20640 |
特征数 | 8 (人口、房间数、房屋年龄等) |
任务类型 | 回归问题(预测房价) |
目标值 | 房价中位数(单位:万美元) |
2. fetch_california_housing()
代码示例
(1) 加载数据集
from sklearn.datasets import fetch_california_housing
# 加载数据
housing = fetch_california_housing()
# 获取特征矩阵和目标变量
X, y = housing.data, housing.target
print("特征矩阵形状:", X.shape)
print("目标变量形状:", y.shape)
print("特征名称:", housing.feature_names)
输出
特征矩阵形状: (20640, 8)
目标变量形状: (20640,)
特征名称: ['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population', 'AveOccup', 'Latitude', 'Longitude']
解释
X.shape = (20640, 8)
:20640
个样本,每个样本8
个特征。y.shape = (20640,)
:20640
个目标值(房价)。feature_names
:包含 收入 (MedInc
)、房龄 (HouseAge
)、人口 (Population
) 等 8 个特征。
(2) 数据集格式
print(type(housing))
输出
<class 'sklearn.utils._bunch.Bunch'>
解释
fetch_california_housing()
返回的是Bunch
对象,类似于字典,可通过.data
、.target
、.feature_names
访问数据。
(3) 转换为 Pandas DataFrame
import pandas as pd
# 转换为 DataFrame
df = pd.DataFrame(housing.data, columns=housing.feature_names)
df["target"] = housing.target # 添加目标变量(房价)
print(df.head())
输出
MedInc HouseAge AveRooms AveBedrms Population AveOccup Latitude Longitude target
0 8.3252 41.0 6.984127 1.023810 322.0 2.555556 37.88 -122.23 4.526
1 8.3014 21.0 6.238137 0.971880 240.0 2.109842 37.86 -122.22 3.585
2 7.2574 52.0 8.288136 1.073446 496.0 2.802260 37.85 -122.24 3.521
3 5.6431 52.0 5.817352 1.073059 558.0 2.547945 37.85 -122.25 3.413
4 3.8462 52.0 6.281853 1.081081 565.0 2.181467 37.85 -122.25 3.422
解释
- 数据已经标准化,单位仍然是可解释的真实值。
- 目标值 (
target
) 是房价中位数,单位是万美元。
3. fetch_california_housing()
数据分析
(1) 目标值分布
import seaborn as sns
import matplotlib.pyplot as plt
sns.histplot(df["target"], bins=30, kde=True)
plt.title("加州房价分布")
plt.show()
解释
- 查看房价的分布情况,判断是否需要归一化。
(2) 特征相关性
import numpy as np
import seaborn as sns
# 计算相关性
corr_matrix = df.corr()
# 可视化
plt.figure(figsize=(10, 8))
sns.heatmap(corr_matrix, annot=True, cmap="coolwarm")
plt.title("特征相关性热图")
plt.show()
解释
- 观察特征与目标变量的相关性,决定是否进行特征选择。
4. 适用场景
- 回归任务(预测房价)。
- 特征工程与数据可视化(数据已标准化)。
- 机器学习算法测试(如
线性回归
、随机森林
、XGBoost
)。
5. fetch_california_housing()
vs. 其他数据集
数据集 | 任务类型 | 样本数 | 特征数 | 适用场景 |
---|---|---|---|---|
load_iris() | 多分类 | 150 | 4 | 经典分类问题 |
load_wine() | 多分类 | 178 | 13 | 葡萄酒分类 |
load_digits() | 多分类 | 1797 | 64 | 手写数字识别 |
load_diabetes() | 回归 | 442 | 10 | 糖尿病预测 |
fetch_california_housing() | 回归 | 20640 | 8 | 房价预测 |
6. 结论
fetch_california_housing()
提供了 20640 个样本,用于回归任务,适用于 房价预测、特征工程研究。- 数据 未经归一化,单位仍然可解释,适用于 真实世界的回归问题。