from sklearn.utils.class_weight import compute_class_weight # クラスの重みを計算 class_weights = compute_class_weight(‘balanced’, np.unique(y_train), y_train) # クラスの重みを辞書に変換 class_weight_dict = dict(zip(np.unique(y_train), class_weights)) # ランダムフォレストモデルの作成とトレーニング rf_model_weighted = RandomForestClassifier(n_estimators=100, random_state=100, class_weight=class_weight_dict) rf_model_weighted.fit(X_train_scaled, y_train) # テストセットでの予測 y_pred_weighted = rf_model_weighted.predict(X_test_scaled) # モデルの評価 accuracy_weighted = accuracy_score(y_test, y_pred_weighted) precision_weighted = precision_score(y_test, y_pred_weighted, average=’weighted’) recall_weighted = recall_score(y_test, y_pred_weighted, average=’weighted’) f1_weighted = f1_score(y_test, y_pred_weighted, average=’weighted’) roc_auc_weighted = roc_auc_score(y_test, rf_model_weighted.predict_proba(X_test_scaled), multi_class=’ovr’) print(“Weighted Accuracy:”, accuracy_weighted) print(“Weighted Precision:”, precision_weighted) print(“Weighted Recall:”, recall_weighted) print(“Weighted F1 Score:”, f1_weighted) print(“Weighted ROC AUC Score:”, roc_auc_weighted) TypeError Traceback (most recent call last) Cell In[26], line 4 1 from sklearn.utils.class_weight import compute_class_weight 3 # クラスの重みを計算 —-> 4 class_weights = compute_class_weight(‘balanced’, np.unique(y_train), y_train) 6 # クラスの重みを辞書に変換 7 class_weight_dict = dict(zip(np.unique(y_train), class_weights)) TypeError: compute_class_weight() takes 1 positional argument but 3 were given

compute_class_weight関数は3つの引数を受け取る必要がありますが、3つ与えられています。これは関数の引数の数が間違っていることを示しています。

compute_class_weight関数は、クラスの重みを計算する際に、クラスのラベル(y_train)のみを必要とします。したがって、このエラーが発生しています。

正しい形式は次のようになります:

python
class_weights = compute_class_weight('balanced', np.unique(y_train), y_train)

このコードでは、compute_class_weight関数に 'balanced' を重みのバランスを取る方法として指定し、そして np.unique(y_train) によってトレーニングデータのラベルの一意な値の配列を取得しています。そして、最後に、y_train によってトレーニングデータのラベル自体を指定しています。

正しい形式に修正してみてください。

未分類

Posted by ぼっち