Fixing ValueError: This solver needs samples of at least 2 classes in Logistic Regression

Open Beginner friendly
#532 2 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 2 days

Nobody has claimed this yet.

  • #533 by @github-actions — closed without merging

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
62/100
Issue type
Documentation
Clarity
Mostly clear
Activity status
Active
Tech stack
python
Domain
documentation

Research direction

The issue provides the question, explanation, and a Python example, but does not name a file or test. Start by checking how this repository stores FAQ entries and whether this answer belongs there; done means the explanation and example are available in the repository’s FAQ format.

Written by the indexing model from the issue text.

Description

faq-proposal
Course

machine-learning-zoomcamp

Question

When training LogisticRegression on the course_lead_scoring_2026.csv dataset in Module 4, the model.fit(X_train, y_train) step fails with:
ValueError: This solver needs samples of at least 2 classes in the data, but the data contains only one class: np.int64(0)
How can I fix this?

Answer

This error occurs because y_train contains only zeros and is missing the positive class (1). This typically happens due to one of two common data preparation mistakes:

  1. Target overwritten during imputation: The target column (converted) was accidentally included in the numerical features list and overwritten when executing .fillna(0.0) for missing values.
  2. Target deleted too early: The target column was dropped from the DataFrame (e.g., del df_train['converted']) before its values were extracted into y_train.

To resolve this, ensure you explicitly exclude the target column when defining your numerical features:

numerical = [c for c in df.select_dtypes(include=['number']).columns if c != 'converted']

### Checklist

- [x] I have searched existing FAQs and this question is not already answered
- [x] The answer provides accurate, helpful information
- [x] I have included any relevant code examples or links
Dominant language
Python
Stars
8
Forks
20
Avg merge
4d 9h
Merged PRs (30d)
27

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from DataTalksClub/faq

All issues in DataTalksClub/faq

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.