「自動車保険価格設定への機械学習の応用」実験レポート

 

目次

1. 実験テーマ

        自動車保険の価格設定における機械学習の応用

2. 実験設定

1. オペレーティング システム:

2.IDE:

3. パイソン:

4. ライブラリ:

3. 実験内容

実験前の推測:

4. 実験結果

1. データの前処理とデータ分割

ワンホットエンコード処理結果(リージョンを例に)

2. モデルのトレーニング

3. 最初の決定木を描く

4. モデルの評価

5. モデルの最適化

最適化されたデシジョン ツリーを描画する

6. サンプルとグリッド検索パラメータを変更して、モデルをさらに最適化します。

5. 実験分析


 

 

1. 実験テーマ

        自動車保険の価格設定における機械学習の応用

2. 実験設定

1. オペレーティング システム:

        Windows 11 ホーム

2.IDE:

        PyCharm 2022.3.1 (プロフェッショナル版)

3. パイソン

        3.8.0

4. ライブラリ:

しこり

1.20.0

 

マットプロットライブラリ

3.7.1

 

パンダ

1.1.5

 

scikit-learn

0.24.2

 

 

conda create -n ML python==3.8 pandas scikit-learn numpy matplotlib

3. 実験内容

        この実験では、自動車保険データの分析を実現するためのモデリングにデシジョン ツリー モデルが使用されます 。自動車保険データは、次の MTPLdata.csvデータ セットです。

f2dccf851f8245909e63b5e927fd0e01.png

        自動車保険データセットには 500,000 のサンプルが含まれており、それぞれに 8 つの特徴と 1 つのラベルがあります。このうち、label は、所有者が自動車保険金請求を報告したかどうかを示す 0 または 1 の値を持つバイナリ変数 (clm、int64)、特徴には所有者の年齢 (age、int64)、車両の年齢 (ac) が含まれます。 、 int64)、電力 ( power、int64)、燃料の種類 (ガス、オブジェクト)、ブランド (ブランド、オブジェクト)、所有者のエリア (エリア、オブジェクト)、住宅用車両密度 (dens、int64)、自動車免許の種類 (ct、物体)。

実験前の推測:

        詳細は実験レポートをご覧ください

4. 実験結果

1. データの前処理とデータ分割

        データを読み取り、ダミー変数の処理やトレーニング セットとテスト セットの分割などのデータ前処理を実行します。

MTPLdata = pd.read_csv('MTPLdata.csv')
# 哑变量处理-独热编码
# 将clm列的数据类型转换为字符串
MTPLdata['clm'] = MTPLdata['clm'].map(str)
# 选择包括第1、2、3、4、5、6、7、8列的数据作为特征输入
# ac、brand、age、gas、power
X_raw = MTPLdata.iloc[:, [0, 1, 2, 3, 4]]
# X_raw = MTPLdata.iloc[:, [0, 1, 2, 3, 4, 5, 6, 7]]
# 对X进行独热编码
X = pd.get_dummies(X_raw)
# 选择第9列作为标签y
y = MTPLdata.iloc[:, 8]

# 将数据划分为训练集和测试集,测试集占总数据的20%
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.2, random_state=1)

 

ワンホットエンコード処理結果(リージョンを例に)

bca076c069c04a629d08ec60ca4b6d9d.png

2. モデルのトレーニング

        トレーニングにはデシジョン ツリー分類子モデルを使用します (ツリーの最大深さを 2 に設定し、バランスのとれたクラス重みを使用し、デフォルトで精度をチェックするためにジニ係数を使用します)。

model = DecisionTreeClassifier(max_depth=2, class_weight='balanced', random_state=123)
model.fit(X_train, y_train)     # 数据拟合
model.score(X_test, y_test)     # 在测试集上评估模型

3. 最初の決定木を描く

        デシジョン ツリー モデルをより適切に解釈するには、plot_tree 関数を呼び出してデシジョン ツリーを描画します。

plt.figure(figsize=(11, 11))
plot_tree(model, feature_names=X.columns, node_ids=True, rounded=True, precision=2)
plt.show()

e3ef80d6c242491193ea5a23b4866f78.png

 

4. モデルの評価

pred = model.predict(X_test)
table = pd.crosstab(y_test, pred, rownames=['Actual'], colnames=['Predicted'])
# table

# 计算模型的准确率、错误率、召回率、特异度和查准率
table = np.array(table)  # 将pandas DataFrame转换为numpy array
Accuracy = (table[0, 0] + table[1, 1]) / np.sum(table)      # 准确率
Error_rate = 1 - Accuracy  # 错误率
Sensitivity = table[1, 1] / (table[1, 0] + table[1, 1])     # 召回率
Specificity = table[0, 0] / (table[0, 0] + table[0, 1])     # 特异度
Recall = table[1, 1] / (table[0, 1] + table[1, 1])          # 查准率

5. モデルの最適化

        より良いモデルを見つけるために、cost_complexity_pruning_path 関数を使用して、さまざまな ccp_alpha に対応する決定木の葉ノードの合計不純物を計算し、ccp_alpha と合計不純物の関係を描画します。

model = DecisionTreeClassifier(class_weight='balanced', random_state=123)
path = model.cost_complexity_pruning_path(X_train, y_train)
plt.plot(path.ccp_alphas, path.impurities, marker='o', drawstyle='steps-post')
plt.xlabel('alpha (cost-complexity parameter)')
plt.ylabel('Total Leaf Impurities')
plt.title('Total Leaf Impurities vs alpha for Training Set')
plt.show()

                                        1wサンプル 50wサンプル

74fe13bc704a4a1c9f27b316cd7fd8c6.png

         次に、相互検証によって最適な ccp_alpha を選択し、最適な ccp_alpha を使用してモデルを再トレーニングします。

 

最適化されたデシジョン ツリーを描画する

rangeccpalpha = np.linspace(0.000001, 0.0001, 10, endpoint=True)
param_grid = {
    'max_depth':  np.arange(3, 7, 1),
    # 'ccp_alpha': rangeccpalpha,
    'min_samples_leaf': np.arange(1, 5, 1)
}
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=1)
model = GridSearchCV(DecisionTreeClassifier(class_weight='balanced', random_state=123),
                     param_grid, cv=kfold)
model.fit(X_train, y_train)

8a1af918529548a9b3d2294700c4d59d.png

 

さらに、個々の特徴の重要性が計算され、特徴重要度マップがプロットされます。

plt.figure(figsize=(20, 20))
sorted_index = model.feature_importances_.argsort()
plt.barh(range(X_train.shape[1]), model.feature_importances_[sorted_index])
plt.yticks(np.arange(X_train.shape[1]), X_train.columns[sorted_index])
plt.xlabel('Feature Importance')
plt.ylabel('Feature')
plt.title('Decision Tree')
plt.tight_layout()
plt.show()

d24a68bc5d2242bd9b054d558b1c8567.png

6. サンプルとグリッド検索パラメータを変更して、モデルをさらに最適化します。

 

   詳細は実験レポートをご覧ください

 

5. 実験分析

        この実験に対応するコードと実験レポートのリソースをダウンロードしてください (実験分析部分は 2 ページ、1162 ワードあります)

      

 

 

おすすめ

転載: blog.csdn.net/m0_63834988/article/details/132307577