0Pricing
Data Science Academy · Урок

Веса классов и пороги

Настройка модели с учётом меньшинства

«Веса классов и пороги» — бесплатный урок Data Science Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Data Science Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Data Science Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Fix It Without Resampling

You can fight imbalance without touching the data at all. Two model-side levers help: class weights and the decision threshold.

What Class Weights Do

Class weights tell the model that mistakes on the rare class hurt more. It pays a bigger penalty for missing minority rows.

The Easy Default

Many scikit-learn models accept class_weight set to balanced. It auto-weights each class inversely to how often it appears.

model = LogisticRegression(class_weight='balanced')
model.fit(X_train, y_train)

Weights vs Resampling

Class weights reshape the loss instead of the dataset. No rows are added or dropped, so you keep all your original data.

The Hidden 0.5 Cutoff

Most classifiers predict a probability, then label it positive if it tops 0.5. That default cutoff is a choice, not a law.

Move the Threshold

Lower the threshold and the model flags positives more eagerly. That catches more rare cases, at the price of more false alarms.

Predict Probabilities First

To tune a threshold, ask the model for probabilities, not hard labels. Then apply your own cutoff to those scores.

proba = model.predict_proba(X_test)[:, 1]
preds = (proba >= 0.30).astype(int)

The Core Trade-Off

A lower threshold lifts recall but drops precision. Raising it does the reverse. The right point depends on which mistake costs more.

Let Cost Drive the Cutoff

If a missed fraud is far worse than a false alarm, lean toward a lower threshold so the rare class is rarely missed.

Combine the Levers

Class weights and threshold tuning stack nicely. Weight the rare class during training, then pick a cutoff that matches your real costs.

Tune, Then Lock It In

Choose the threshold using validation data, never the test set. Then apply that same fixed cutoff for an honest final score.

Quick Check

What happens when you lower the decision threshold?

Recap

Without resampling, class weights penalize rare-class errors and a tuned threshold trades recall against precision to fit your costs. 🎯

Часто задаваемые вопросы

Урок «Веса классов и пороги» бесплатный?

Да — полный текст урока «Веса классов и пороги» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Data Science Academy, подпишись на CoddyKit PRO. Курс Data Science Academy содержит 4 уроков всего.

Чему я научусь в уроке «Веса классов и пороги»?

Настройка модели с учётом меньшинства Ты практикуешь Data Science Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Data Science Academy?

Предыдущий опыт не требуется. Data Science Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Веса классов и пороги»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Data Science Academy?

Да. Каждый урок Data Science Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Почему точность вводит в заблуждение при дисбалансе
  2. Ресэмплинг: SMOTE и уменьшение выборки
  3. Веса классов и пороги
  4. Выбор метрик для редких событий
← Назад к Data Science Academy