# How to deal with imbalanced datasets?

{% hint style="info" %}
*Sources:*

* [*Dealing with Imbalanced Data (Tara Boyle)*](https://towardsdatascience.com/methods-for-dealing-with-imbalanced-data-5b761be45a18)
* [*Having an Imbalanced Dataset? Here Is How You Can Fix I (Will Badr)*](https://towardsdatascience.com/having-an-imbalanced-dataset-here-is-how-you-can-solve-it-1640568947eb)
  {% endhint %}

## Using the correct performance metric

[**Accuracy**](https://jgoodman8.gitbook.io/iron-data-science-notebook/ml-techniques/metrics#accuracy) **is not the best metric** to use when evaluating imbalanced datasets as it can be very misleading. It's better to try:

* [**Confusion Matrix**](https://jgoodman8.gitbook.io/iron-data-science-notebook/ml-techniques/metrics#the-confusion-matrix)
* [**Precision**](https://jgoodman8.gitbook.io/iron-data-science-notebook/ml-techniques/metrics#precision)
* [**Recall**](https://jgoodman8.gitbook.io/iron-data-science-notebook/ml-techniques/metrics#recall)
* [**F1**](https://jgoodman8.gitbook.io/iron-data-science-notebook/ml-techniques/metrics#f-score)

## Resampling Techniques

{% hint style="danger" %}
Always **split into test and train sets BEFORE trying to resample** techniques! And applying resample **ONLY in the training set**.
{% endhint %}

**Oversample**: by adding more copies of the minority class.

**Undersample**: by removing observations from the majority class.&#x20;

## Create synthetic samples

* **SMOTE** (Synthetic Minority Oversampling Technique): uses a **kNN algorithm** to generate new and synthetic data we can use for training our model.

## Apply an ensemble algorithm

{% content-ref url="../ml-techniques/ensemble-methods" %}
[ensemble-methods](https://jgoodman8.gitbook.io/iron-data-science-notebook/ml-datascience/ml-techniques/ensemble-methods)
{% endcontent-ref %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jgoodman8.gitbook.io/iron-data-science-notebook/ml-datascience/frequent-questions/how-to-deal-with-imbalanced-datasets.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
