An estimator has two jobs: fit on examples, then predict on new rows. Classification predicts a label (0 / 1). accuracy_score is the fraction of matching labels.
Goal
Build a toy dataset, fit logistic regression, and print accuracy on held-out rows.
Make data, fit, predict
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
X, y = make_classification(n_samples=200, n_features=4, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
clf = LogisticRegression(max_iter=200)
clf.fit(X_train, y_train)
pred = clf.predict(X_test)
print("train", X_train.shape, "test", X_test.shape)
print("accuracy:", round(accuracy_score(y_test, pred), 3))random_state=0 makes the dataset and split repeatable. max_iter=200 gives the solver enough steps on this toy data.
What fit learned
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
X, y = make_classification(n_samples=200, n_features=4, random_state=0)
clf = LogisticRegression(max_iter=200)
clf.fit(X, y)
print("coef", clf.coef_.round(3))
print("intercept", clf.intercept_.round(3))
print("classes", clf.classes_)Coefficients are the weights on the four features. Larger absolute values move the decision more.
Pitfall
Accuracy on the same rows you fit is optimistic. Always hold out a test set (next chapters) before you trust a number.