Sklearn 住宅価格予測
次に、sklearn を使って北京の住宅価格予測を行います。
データの読み込み、探索的データ分析、特徴量エンジニアリングからモデルのトレーニングと最適化まで段階的に進め、sklearn のツールとライブラリを使用して予測タスクを完了する方法をデモンストレーションします。
内容概要:
1. データ生成と表示
- 辞書を使用して模擬データを作成し、それを DataFrame に変換しました。
pandas DataFrame。 - データには、住宅の面積、部屋数、階数、建築年、所在地(カテゴリ変数)、および住宅価格(目的変数)が含まれています。
- によって
df.head()とdf.describe()データの基本構造と統計情報を確認します。
2. データ前処理
- 特徴量の選択:元データから住宅価格に関連する特徴量(面積、部屋数、階数、建築年、所在地)を選択しました。
- データ分割:を使用して
train_test_splitデータセットを80%のトレーニングセットと20%のテストセットに分割します。 - 数値特徴量の標準化:を使用して
StandardScaler数値特徴量を標準化します。 - カテゴリ特徴量のエンコーディング:を使用して
OneHotEncoderカテゴリ特徴量(location)をOne-Hotエンコーディングします。 ColumnTransformer数値特徴量とカテゴリ特徴量の処理を1つのステップに統合します。
3. モデルトレーニング
- を使用して
Pipelineデータ前処理とモデルトレーニングのステップを組み合わせて、プロセス全体をパイプライン化します。 - 線形回帰モデル(
LinearRegression)を使用してトレーニングします。
4. モデル評価
- により
mean_squared_error平均二乗誤差(MSE)を計算し、またr2_score決定係数(R²)を計算します。 - 評価結果を出力し、モデルの予測精度を確認します。
5. モデル最適化
- を使用して
GridSearchCV線形回帰のハイパーパラメータを調整します。主に調整するのはfit_intercept(切片を適合させるかどうか)です。 - グリッドサーチで最適なハイパーパラメータを見つけ、最適なモデルを使用してテストセットを予測します。
- 最適化後のモデル評価指標(MSE と R²)を再計算します。
1、データ生成と表示
まず、一般的な住宅価格予測の特徴量(住宅面積、部屋数、階数、建築年、所在地(カテゴリ変数))を含む模擬 DataFrame を構築します。
実例
import pandas as pd
import numpy as np
# 模擬データ:住宅面積(平方メートル)、部屋数、階数、建築年、所在地(カテゴリ変数)
data = {
'area': [70, 85, 100, 120, 60, 150, 200, 80, 95, 110],
'rooms': [2, 3, 3, 4, 2, 5, 6, 3, 3, 4],
'floor': [5, 2, 8, 10, 3, 15, 18, 7, 9, 11],
'year_built': [2005, 2010, 2012, 2015, 2000, 2018, 2020, 2008, 2011, 2016],
'location': ['Chaoyang', 'Haidian', 'Chaoyang', 'Dongcheng', 'Fengtai', 'Haidian', 'Chaoyang', 'Fengtai', 'Dongcheng', 'Haidian'],
'price': [5000000, 6000000, 6500000, 7000000, 4500000, 10000000, 12000000, 5500000, 6200000, 7500000] # 住宅価格(目的変数)
}
# DataFrame を作成
df = pd.DataFrame(data)
# データを表示
print("データプレビュー:")
print(df.head())
import numpy as np
# 模擬データ:住宅面積(平方メートル)、部屋数、階数、建築年、所在地(カテゴリ変数)
data = {
'area': [70, 85, 100, 120, 60, 150, 200, 80, 95, 110],
'rooms': [2, 3, 3, 4, 2, 5, 6, 3, 3, 4],
'floor': [5, 2, 8, 10, 3, 15, 18, 7, 9, 11],
'year_built': [2005, 2010, 2012, 2015, 2000, 2018, 2020, 2008, 2011, 2016],
'location': ['Chaoyang', 'Haidian', 'Chaoyang', 'Dongcheng', 'Fengtai', 'Haidian', 'Chaoyang', 'Fengtai', 'Dongcheng', 'Haidian'],
'price': [5000000, 6000000, 6500000, 7000000, 4500000, 10000000, 12000000, 5500000, 6200000, 7500000] # 住宅価格(目的変数)
}
# DataFrame を作成
df = pd.DataFrame(data)
# データを表示
print("データプレビュー:")
print(df.head())
出力:
数据预览: area rooms floor year_built location price 0 70 2 5 2005 Chaoyang 5000000 1 85 3 2 2010 Haidian 6000000 2 100 3 8 2012 Chaoyang 6500000 3 120 4 10 2015 Dongcheng 7000000 4 60 2 3 2000 Fengtai 4500000
2、データ前処理
データ前処理には通常、特徴量の選択、特徴量の変換、欠損値の処理、データの標準化などが含まれます。ここでは、数値特徴量を標準化し、カテゴリ特徴量をOne-Hotエンコーディングします。
実例
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
# 特徴量の選択
X = df[['area', 'rooms', 'floor', 'year_built', 'location']] # 特徴量
y = df['price'] # 目的変数
# トレーニングセットとテストセットに分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 前処理ステップを構築
numeric_features = ['area', 'rooms', 'floor', 'year_built']
categorical_features = ['location']
numeric_transformer = Pipeline(steps=[
('scaler', StandardScaler()) # 数値特徴量の標準化
])
categorical_transformer = Pipeline(steps=[
('onehot', OneHotEncoder(handle_unknown='ignore')) # テストセット内の新しいカテゴリを処理
])
# ColumnTransformer に結合
preprocessor = ColumnTransformer(
transformers=[
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features)
]
)
# データ前処理後の構造を表示
X_train_transformed = preprocessor.fit_transform(X_train)
print("前処理後のトレーニングデータ:")
print(X_train_transformed)
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
# 特徴量の選択
X = df[['area', 'rooms', 'floor', 'year_built', 'location']] # 特徴量
y = df['price'] # 目的変数
# トレーニングセットとテストセットに分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 前処理ステップを構築
numeric_features = ['area', 'rooms', 'floor', 'year_built']
categorical_features = ['location']
numeric_transformer = Pipeline(steps=[
('scaler', StandardScaler()) # 数値特徴量の標準化
])
categorical_transformer = Pipeline(steps=[
('onehot', OneHotEncoder(handle_unknown='ignore')) # テストセット内の新しいカテゴリを処理
])
# ColumnTransformer に結合
preprocessor = ColumnTransformer(
transformers=[
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features)
]
)
# データ前処理後の構造を表示
X_train_transformed = preprocessor.fit_transform(X_train)
print("前処理後のトレーニングデータ:")
print(X_train_transformed)
出力結果は次のとおりです:
tianqixin@Mac-mini サンプル-test % python3 test.py 预处理后的训练数据: [[ 0.89826776 1.0440738 1.14636101 0.96800387 0. 0. 0. 1. ] [-0.95622052 -1.23390539 -0.98640366 -1.04544418 1. 0. 0. 0. ] [-0.72440948 -0.474579 -0.55985073 -0.58080232 0. 0. 1. 0. ] [-0.26078741 -0.474579 -0.34657426 0.03872015 1. 0. 0. 0. ] [-0.02897638 0.2847474 0.29325514 0.65824263 0. 0. 0. 1. ] [-1.18803155 -1.23390539 -1.4129566 -1.81984727 0. 0. 1. 0. ] [ 0.20283466 0.2847474 0.07997868 0.50336201 0. 1. 0. 0. ] [ 2.05732294 1.80340019 1.78619041 1.2777651 1. 0. 0. 0. ]]
3、モデル構築
次に、線形回帰モデルを使用して住宅価格を予測します。前処理とモデルトレーニングのステップを統合するために Pipeline を使用します。
実例
from sklearn.linear_model import LinearRegression
# 前処理と回帰モデルを含む Pipeline を構築
model_pipeline = Pipeline(steps=[
('preprocessor', preprocessor), # データ前処理ステップ
('regressor', LinearRegression()) # 回帰モデル
])
# モデルをトレーニング
model_pipeline.fit(X_train, y_train)
# 予測を実行
y_pred = model_pipeline.predict(X_test)
# 予測結果を出力
print("\n予測結果:")
print(y_pred)
# 前処理と回帰モデルを含む Pipeline を構築
model_pipeline = Pipeline(steps=[
('preprocessor', preprocessor), # データ前処理ステップ
('regressor', LinearRegression()) # 回帰モデル
])
# モデルをトレーニング
model_pipeline.fit(X_train, y_train)
# 予測を実行
y_pred = model_pipeline.predict(X_test)
# 予測結果を出力
print("\n予測結果:")
print(y_pred)
出力結果は次のとおりです:
预测结果: [6375000.00000001 4874999.99999998]
4、モデル評価
モデル評価では、通常、平均二乗誤差(MSE)と決定係数(R²)を使用して回帰モデルの性能を評価します。
実例
from sklearn.metrics import mean_squared_error, r2_score
# 平均二乗誤差(MSE)と決定係数(R²)を計算
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
# 評価結果を出力
print("\nモデル評価:")
print(f"平均二乗誤差 (MSE): {mse:.2f}")
print(f"決定係数 (R²): {r2:.2f}")
# 平均二乗誤差(MSE)と決定係数(R²)を計算
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
# 評価結果を出力
print("\nモデル評価:")
print(f"平均二乗誤差 (MSE): {mse:.2f}")
print(f"決定係数 (R²): {r2:.2f}")
出力結果は次のとおりです:
预测结果: [6375000.00000001 4874999.99999998] tianqixin@Mac-mini サンプル-test % python3 test.py 模型评估: 均方误差 (MSE): 648125000000.03 决定系数 (R²): -63.81
5、モデル最適化(グリッドサーチ)
モデルの性能を向上させるために、GridSearchCV を使用してモデルのハイパーパラメータを調整できます。この例では、線形回帰のパラメータは調整しません。調整できるハイパーパラメータが多くないためです。より複雑なモデル(例:ランダムフォレスト、XGBoost など)では、グリッドサーチを使用して最適なパラメータを見つけることができます。
実例
from sklearn.model_selection import GridSearchCV
# 5. モデル最適化:グリッドサーチでハイパーパラメータを調整
# 線形回帰のハイパーパラメータを調整('fit_intercept' のみ調整)
param_grid = {
'regressor__fit_intercept': [True, False], # 切片を適合させるかどうか
}
grid_search = GridSearchCV(model_pipeline, param_grid, cv=5, scoring='neg_mean_squared_error', verbose=1)
grid_search.fit(X_train, y_train)
# 最適なパラメータと結果を出力
print("\n最適なパラメータ:")
print(grid_search.best_params_)
# 最適なモデルを使用して予測
best_model = grid_search.best_estimator_
y_pred_optimized = best_model.predict(X_test)
# 最適化後の評価結果を出力
mse_opt = mean_squared_error(y_test, y_pred_optimized)
r2_opt = r2_score(y_test, y_pred_optimized)
print("\n最適化後のモデル評価:")
print(f"平均二乗誤差 (MSE): {mse_opt:.2f}")
print(f"決定係数 (R²): {r2_opt:.2f}")
# 5. モデル最適化:グリッドサーチでハイパーパラメータを調整
# 線形回帰のハイパーパラメータを調整('fit_intercept' のみ調整)
param_grid = {
'regressor__fit_intercept': [True, False], # 切片を適合させるかどうか
}
grid_search = GridSearchCV(model_pipeline, param_grid, cv=5, scoring='neg_mean_squared_error', verbose=1)
grid_search.fit(X_train, y_train)
# 最適なパラメータと結果を出力
print("\n最適なパラメータ:")
print(grid_search.best_params_)
# 最適なモデルを使用して予測
best_model = grid_search.best_estimator_
y_pred_optimized = best_model.predict(X_test)
# 最適化後の評価結果を出力
mse_opt = mean_squared_error(y_test, y_pred_optimized)
r2_opt = r2_score(y_test, y_pred_optimized)
print("\n最適化後のモデル評価:")
print(f"平均二乗誤差 (MSE): {mse_opt:.2f}")
print(f"決定係数 (R²): {r2_opt:.2f}")
出力結果は次のとおりです:
Fitting 5 folds for each of 2 candidates, totalling 10 fits
最佳参数:
{'regressor__fit_intercept': True}
优化后的模型评估:
均方误差 (MSE): 648125000000.03
决定系数 (R²): -63.81
完全なコード
北京の住宅価格予測の完全なコード:
実例
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
模擬データ:住宅の面積、部屋数、階数、建築年、所に地(カテゴリ変数)、および住宅価格(目的変数)を含む
data = {
'area': [70, 85, 100, 120, 60, 150, 200, 80, 95, 110],
'rooms': [2, 3, 3, 4, 2, 5, 6, 3, 3, 4],
'floor': [5, 2, 8, 10, 3, 15, 18, 7, 9, 11],
'year_built': [2005, 2010, 2012, 2015, 2000, 2018, 2020, 2008, 2011, 2016],
'location': ['Chaoyang', 'Haidian', 'Chaoyang', 'Dongcheng', 'Fengtai', 'Haidian', 'Chaoyang', 'Fengtai', 'Dongcheng', 'Haidian'],
'price': [5000000, 6000000, 6500000, 7000000, 4500000, 10000000, 12000000, 5500000, 6200000, 7500000] # 住宅価格(目的変数)
}
# DataFrame を作成
df = pd.DataFrame(data)
# データを表示
print("データプレビュー:")
print(df.head())
# 特徴量の選択
X = df[['area', 'rooms', 'floor', 'year_built', 'location']] # 特徴量データ
y = df['price'] # 目的変数
# トレーニングセットとテストセットに分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# データ前処理:数値特徴量の標準化、カテゴリ特徴量のOne-Hotエンコーディング
numeric_features = ['area', 'rooms', 'floor', 'year_built']
categorical_features = ['location']
# 数値特徴量の前処理:標準化
numeric_transformer = Pipeline(steps=[
('scaler', StandardScaler())
])
# カテゴリ特徴量の前処理:One-Hotエンコーディング、handle_unknown='ignore' を設定
categorical_transformer = Pipeline(steps=[
('onehot', OneHotEncoder(handle_unknown='ignore')) # テストセット内の新しいカテゴリを処理
])
# 数値特徴量とカテゴリ特徴量の処理ステップを結合
preprocessor = ColumnTransformer(
transformers=[
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features)
]
)
# 3. モデル構築
# 線形回帰モデルを使用し、データ前処理ステップと組み合わせる
model_pipeline = Pipeline(steps=[
('preprocessor', preprocessor),
('regressor', LinearRegression())
])
# モデルをトレーニング
model_pipeline.fit(X_train, y_train)
# 予測を実行
y_pred = model_pipeline.predict(X_test)
# 予測結果を出力
print("\n予測結果:")
print(y_pred)
# 4. モデル評価:平均二乗誤差(MSE)と決定係数 R² を計算
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("\nモデル評価:")
print(f"平均二乗誤差 (MSE): {mse:.2f}")
print(f"決定係数 (R²): {r2:.2f}")
# 5. モデル最適化:グリッドサーチでハイパーパラメータを調整
# 線形回帰のハイパーパラメータを調整('fit_intercept' のみ調整)
param_grid = {
'regressor__fit_intercept': [True, False], # 切片を適合させるかどうか
}
grid_search = GridSearchCV(model_pipeline, param_grid, cv=5, scoring='neg_mean_squared_error', verbose=1)
grid_search.fit(X_train, y_train)
# 最適なパラメータと結果を出力
print("\n最適なパラメータ:")
print(grid_search.best_params_)
# 最適なモデルを使用して予測
best_model = grid_search.best_estimator_
y_pred_optimized = best_model.predict(X_test)
# 最適化後の評価結果を出力
mse_opt = mean_squared_error(y_test, y_pred_optimized)
r2_opt = r2_score(y_test, y_pred_optimized)
print("\n最適化後のモデル評価:")
print(f"平均二乗誤差 (MSE): {mse_opt:.2f}")
print(f"決定係数 (R²): {r2_opt:.2f}")
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
模擬データ:住宅の面積、部屋数、階数、建築年、所に地(カテゴリ変数)、および住宅価格(目的変数)を含む
data = {
'area': [70, 85, 100, 120, 60, 150, 200, 80, 95, 110],
'rooms': [2, 3, 3, 4, 2, 5, 6, 3, 3, 4],
'floor': [5, 2, 8, 10, 3, 15, 18, 7, 9, 11],
'year_built': [2005, 2010, 2012, 2015, 2000, 2018, 2020, 2008, 2011, 2016],
'location': ['Chaoyang', 'Haidian', 'Chaoyang', 'Dongcheng', 'Fengtai', 'Haidian', 'Chaoyang', 'Fengtai', 'Dongcheng', 'Haidian'],
'price': [5000000, 6000000, 6500000, 7000000, 4500000, 10000000, 12000000, 5500000, 6200000, 7500000] # 住宅価格(目的変数)
}
# DataFrame を作成
df = pd.DataFrame(data)
# データを表示
print("データプレビュー:")
print(df.head())
# 特徴量の選択
X = df[['area', 'rooms', 'floor', 'year_built', 'location']] # 特徴量データ
y = df['price'] # 目的変数
# トレーニングセットとテストセットに分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# データ前処理:数値特徴量の標準化、カテゴリ特徴量のOne-Hotエンコーディング
numeric_features = ['area', 'rooms', 'floor', 'year_built']
categorical_features = ['location']
# 数値特徴量の前処理:標準化
numeric_transformer = Pipeline(steps=[
('scaler', StandardScaler())
])
# カテゴリ特徴量の前処理:One-Hotエンコーディング、handle_unknown='ignore' を設定
categorical_transformer = Pipeline(steps=[
('onehot', OneHotEncoder(handle_unknown='ignore')) # テストセット内の新しいカテゴリを処理
])
# 数値特徴量とカテゴリ特徴量の処理ステップを結合
preprocessor = ColumnTransformer(
transformers=[
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features)
]
)
# 3. モデル構築
# 線形回帰モデルを使用し、データ前処理ステップと組み合わせる
model_pipeline = Pipeline(steps=[
('preprocessor', preprocessor),
('regressor', LinearRegression())
])
# モデルをトレーニング
model_pipeline.fit(X_train, y_train)
# 予測を実行
y_pred = model_pipeline.predict(X_test)
# 予測結果を出力
print("\n予測結果:")
print(y_pred)
# 4. モデル評価:平均二乗誤差(MSE)と決定係数 R² を計算
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("\nモデル評価:")
print(f"平均二乗誤差 (MSE): {mse:.2f}")
print(f"決定係数 (R²): {r2:.2f}")
# 5. モデル最適化:グリッドサーチでハイパーパラメータを調整
# 線形回帰のハイパーパラメータを調整('fit_intercept' のみ調整)
param_grid = {
'regressor__fit_intercept': [True, False], # 切片を適合させるかどうか
}
grid_search = GridSearchCV(model_pipeline, param_grid, cv=5, scoring='neg_mean_squared_error', verbose=1)
grid_search.fit(X_train, y_train)
# 最適なパラメータと結果を出力
print("\n最適なパラメータ:")
print(grid_search.best_params_)
# 最適なモデルを使用して予測
best_model = grid_search.best_estimator_
y_pred_optimized = best_model.predict(X_test)
# 最適化後の評価結果を出力
mse_opt = mean_squared_error(y_test, y_pred_optimized)
r2_opt = r2_score(y_test, y_pred_optimized)
print("\n最適化後のモデル評価:")
print(f"平均二乗誤差 (MSE): {mse_opt:.2f}")
print(f"決定係数 (R²): {r2_opt:.2f}")
このコードを実行すると、次のように出力されます:
数据预览:
area rooms floor year_built location price
0 70 2 5 2005 Chaoyang 5000000
1 85 3 2 2010 Haidian 6000000
2 100 3 8 2012 Chaoyang 6500000
3 120 4 10 2015 Dongcheng 7000000
4 60 2 3 2000 Fengtai 4500000
预测结果:
[6375000.00000001 4874999.99999998]
模型评估:
均方误差 (MSE): 648125000000.03
决定系数 (R²): -63.81
Fitting 5 folds for each of 2 candidates, totalling 10 fits
最佳参数:
{'regressor__fit_intercept': True}
优化后的模型评估:
均方误差 (MSE): 648125000000.03
决定系数 (R²): -63.81
その他の拡張