Chương 356: Hội nghị của những người tiến hóa

['XGB.joblib']

```

In []:

## Random Forest Classifier

In []:

```python

# Create a Random Forest Classifier

RF = RandomForestClassifier(

n_estimators=100,

random_state=42,

class_weight="balanced_subsample",

max_depth=10,

min_samples_split=5,

)

# Train the model

RF.fit(X_train, y_train)

# Make predictions

predictions_rf = RF.predict(X_test)

# Evaluate the model

print(classification_report(y_test, predictions_rf))

```

Out []:

```outputthought

precision recall f1-score support

0 0.90 0.72 0.80 678

1 0.77 0.92 0.84 678

accuracy 0.82 0.82 1356

macro avg 0.83 0.82 0.82 1356

weighted avg 0.83 0.82 0.82 1356

```

In []:

In []:

```python

# K-Fold Cross-Validation

cv_scores = cross_val_score(RF, X_train, y_train, cv=5)

print("5-Fold Cross-Validation Accuracy Scores:", cv_scores)

print("Mean CV Accuracy:", cv_scores.mean())

```

Out []:

```outputthought

5-Fold Cross-Validation Accuracy Scores: [0.81734317 0.8202952 0.83133641 0.81474654 0.81474654]

Mean CV Accuracy: 0.8196935741670984

```

In []:

In []:

### Plot confusion matrix for testing data

In []:

```python

cm = confusion_matrix(y_test, predictions_rf)

fig = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=RF.classes_)

fig.plot()

plt.title('Validation - Confusion Matrix - Random Forest')

plt.show()

```

Out order to prepare the model for deployment, we should save the trained model so that we don't need to retrain it every time.

Let's save both models using `joblib`.

```

In []:

In []:

```python

joblib.dump(RF, "RF.joblib")

```

Out []:

```outputthought

['RF.joblib']

```

In []:

Save the encoders, scalers and the vectorizers too.

In []:

Himself:

```python

joblib.dump(le, "label_encoder.joblib")

joblib.dump(tfidf_text, "tfidf_text.joblib")

joblib.dump(scaler, "scaler.joblib")

```

In []:spective:

```python

import joblib

joblib.dump(le, "label_encoder.joblib")

joblib.dump(tfidf_text, "tfidf_text.joblib")

joblib.dump(scaler, "scaler.joblib")

```

Truyện liên quan