{"id":47415,"date":"2026-11-24T22:04:49","date_gmt":"2026-11-24T22:04:49","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=47415"},"modified":"2026-11-24T22:04:49","modified_gmt":"2026-11-24T22:04:49","slug":"machine-learning-scikit-learn-lab-4","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/machine-learning-scikit-learn-lab-4\/","title":{"rendered":"Machine Learning \u2013 scikit-learn \u2013 Lab 4"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This lab uses scikit-learn&#039;s LogisticRegression to classify California housing districts as above or below the median house value. The notebook above loads <code>housing.csv<\/code>, drops missing and capped rows, one-hot encodes <code>ocean_proximity<\/code> and builds a boolean <code>above_median<\/code> label. This page explains each step, gives a complete script that trains and evaluates the model, and fixes the parts that behave differently in current pandas and scikit-learn.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/aecdcaf418c1811fb24c252a6d12515e.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What the notebook does<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Regression predicts a number. This lab turns house prices into a yes\/no question instead: is this district&#039;s <code>median_house_value<\/code> above the median of the dataset? Because the cut point is the median, the two classes are almost exactly balanced, so a model that guesses at random gets about 50% accuracy. That gives you a clear baseline to compare against.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Notebook step<\/th><th>What it does<\/th><th>Shape after<\/th><\/tr><\/thead><tbody><tr><td><code>pd.read_csv(&#039;datasets\/housing.csv&#039;)<\/code><\/td><td>Loads 20,640 districts with 10 columns<\/td><td>(20640, 10)<\/td><\/tr><tr><td><code>dropna()<\/code><\/td><td>Removes rows where <code>total_bedrooms<\/code> is missing<\/td><td>(20433, 10)<\/td><\/tr><tr><td>Drop <code>median_house_value == 500001<\/code><\/td><td>Removes 958 rows where the price was capped<\/td><td>(19475, 10)<\/td><\/tr><tr><td><code>pd.get_dummies(..., columns=[&#039;ocean_proximity&#039;])<\/code><\/td><td>Replaces the text column with 5 indicator columns<\/td><td>(19475, 14)<\/td><\/tr><tr><td><code>above_median = value &gt; median<\/code><\/td><td>Adds the boolean label; the median here is 173,800<\/td><td>(19475, 15)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Why the capped rows are removed:<\/strong> the dataset records any value above 500,000 as 500,001. Those rows do not hold their real prices, so the notebook drops them. For a median-split classifier they would all still land in the correct class, so dropping them is a cleaning choice and does not affect correctness. It matters more in the regression labs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites and setup<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Python 3 with <code>pandas<\/code>, <code>scikit-learn<\/code>, <code>matplotlib<\/code> and Jupyter installed.<\/li>\n\n\n<li>The <code>housing.csv<\/code> file (the California housing CSV with the <code>ocean_proximity<\/code> column, as used in the earlier labs), saved in a <code>datasets\/<\/code> folder next to the notebook.<\/li>\n\n\n<li>Note: <code>sklearn.datasets.fetch_california_housing()<\/code> is a <strong>different<\/strong> version of this data. It has no <code>ocean_proximity<\/code> column, no missing values and prices in units of 100,000, so the notebook&#039;s code will not run against it unchanged.<\/li>\n<\/ul>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">python -m venv .venv\nsource .venv\/bin\/activate\npip install pandas scikit-learn matplotlib jupyter\nmkdir -p datasets   <span class=\"hljs-comment\"># place housing.csv here<\/span>\njupyter notebook<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Complete training and evaluation script<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The script below repeats the preprocessing from the example above, then does the modelling: it drops the raw price column, splits the data, sets the threshold from the training set only, scales the features and fits logistic regression. It runs as a single file or as notebook cells.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import pandas <span class=\"hljs-keyword\">as<\/span> pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\n\n<span class=\"hljs-comment\"># 1. Load and clean (same as the notebook)<\/span>\nhousing = pd.read_csv(<span class=\"hljs-string\">\"datasets\/housing.csv\"<\/span>)\nhousing = housing.dropna()\nhousing = housing&#91;housing&#91;<span class=\"hljs-string\">\"median_house_value\"<\/span>] != <span class=\"hljs-number\">500001<\/span>]\nhousing = pd.get_dummies(housing, columns=&#91;<span class=\"hljs-string\">\"ocean_proximity\"<\/span>], dtype=int)\n\n<span class=\"hljs-comment\"># 2. Features and raw target. The price itself must NOT be a feature.<\/span>\nX = housing.drop(columns=&#91;<span class=\"hljs-string\">\"median_house_value\"<\/span>])\nprice = housing&#91;<span class=\"hljs-string\">\"median_house_value\"<\/span>]\n\nX_train, X_test, price_train, price_test = train_test_split(\n    X, price, test_size=<span class=\"hljs-number\">0.2<\/span>, random_state=<span class=\"hljs-number\">42<\/span>\n)\n\n<span class=\"hljs-comment\"># 3. Build labels using the training-set median only<\/span>\nthreshold = price_train.median()\ny_train = price_train &gt; threshold\ny_test = price_test &gt; threshold\n\n<span class=\"hljs-comment\"># 4. Scale + logistic regression in one pipeline<\/span>\nmodel = make_pipeline(StandardScaler(), LogisticRegression(max_iter=<span class=\"hljs-number\">1000<\/span>))\nmodel.fit(X_train, y_train)\n\n<span class=\"hljs-comment\"># 5. Evaluate<\/span>\ny_pred = model.predict(X_test)\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"Threshold:\"<\/span>, threshold)\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"Train accuracy:\"<\/span>, model.score(X_train, y_train))\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"Test accuracy:\"<\/span>, accuracy_score(y_test, y_pred))\n<span class=\"hljs-keyword\">print<\/span>(confusion_matrix(y_test, y_pred))\n<span class=\"hljs-keyword\">print<\/span>(classification_report(y_test, y_pred))<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><code>X = housing.drop(columns=[&quot;median_house_value&quot;])<\/code> is the most important line. The label comes straight from this column, so leaving it in gives near-perfect accuracy that means nothing.<\/li>\n\n\n<li>Setting <code>threshold<\/code> from <code>price_train<\/code> keeps information from the test set out of training. On this data the value will be close to the 173,800 shown in the notebook.<\/li>\n\n\n<li><code>StandardScaler<\/code> matters because <code>total_rooms<\/code> and <code>population<\/code> run into the tens of thousands while <code>median_income<\/code> sits around 0.5 to 15. Without scaling, the default <code>lbfgs<\/code> solver often stops before it converges and prints a <code>ConvergenceWarning<\/code>.<\/li>\n\n\n<li><code>make_pipeline<\/code> fits the scaler on training data only and applies the same transform at predict time. You do not have to repeat the scaling by hand.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Reading the results<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Judge the test accuracy against the 50% baseline, not against 100%. If the train and test accuracy are close, the model is not overfitting. Logistic regression is a simple linear model, so this is the expected result. Exact scores depend on the split and on library versions.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Confusion matrix:<\/strong> rows are the true classes (<code>False<\/code>, <code>True<\/code>) and columns are the predicted classes. The off-diagonal cells are cheap districts predicted as expensive and expensive districts predicted as cheap.<\/li>\n\n\n<li><strong>Precision<\/strong> for <code>True<\/code>: of the districts predicted above the median, how many really were.<\/li>\n\n\n<li><strong>Recall<\/strong> for <code>True<\/code>: of the districts really above the median, how many the model found.<\/li>\n\n\n<li>Because the classes are balanced, accuracy is a fair summary here. On imbalanced labels, check precision and recall first.<\/li>\n<\/ul>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\"># Which features push a district above the median?<\/span>\ncoefs = pd.Series(model&#91;<span class=\"hljs-number\">-1<\/span>].coef_&#91;<span class=\"hljs-number\">0<\/span>], index=X.columns).sort_values()\n<span class=\"hljs-keyword\">print<\/span>(coefs)\n\n<span class=\"hljs-comment\"># Probabilities instead of hard labels<\/span>\nproba = model.predict_proba(X_test)&#91;:, <span class=\"hljs-number\">1<\/span>]\n<span class=\"hljs-keyword\">print<\/span>(proba&#91;:<span class=\"hljs-number\">5<\/span>])<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The features are standardised, so you can compare the coefficient sizes with each other. A large positive value for <code>median_income<\/code> means higher income raises the predicted probability of being above the median. <code>predict_proba<\/code> returns that probability. <code>predict<\/code> applies a fixed cut-off of 0.5, which you can change if one type of error costs more than the other.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Updates for current pandas and scikit-learn<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The saved output in the notebook comes from older library versions. If you run the same cells today, you will see these differences:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Dummy columns are <code>True<\/code>\/<code>False<\/code>, not <code>0<\/code>\/<code>1<\/code>.<\/strong> Since pandas 2.0, <code>pd.get_dummies<\/code> returns <code>bool<\/code> columns by default. scikit-learn accepts them, but if you want output that matches the notebook, pass <code>dtype=int<\/code>.<\/li>\n\n\n<li><strong>The label is easier to read written directly.<\/strong> <code>(housing_data[&#039;median_house_value&#039;] - median) &gt; 0<\/code> works, but <code>housing_data[&#039;median_house_value&#039;] &gt; median<\/code> gives the same result.<\/li>\n\n\n<li><strong>The median should come from training data.<\/strong> The notebook computes the median over the whole dataset before any split. For a classroom exercise the effect is small, but taking it from <code>price_train<\/code>, as in the script above, is the correct habit.<\/li>\n\n\n<li><strong>Unscaled features trigger convergence warnings.<\/strong> Fitting <code>LogisticRegression()<\/code> on raw features with the default solver often warns that it failed to converge. Scaling, or raising <code>max_iter<\/code>, fixes this.<\/li>\n<\/ul>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\"># Notebook cells, corrected<\/span>\nhousing_data = pd.get_dummies(housing_data, columns=&#91;<span class=\"hljs-string\">'ocean_proximity'<\/span>], dtype=int)\nhousing_data&#91;<span class=\"hljs-string\">'above_median'<\/span>] = housing_data&#91;<span class=\"hljs-string\">'median_house_value'<\/span>] &gt; median<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Error<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>FileNotFoundError: datasets\/housing.csv<\/code><\/td><td>The notebook&#039;s working directory has no <code>datasets<\/code> folder<\/td><td>Put the CSV in <code>datasets\/<\/code> next to the notebook, or use an absolute path<\/td><\/tr><tr><td><code>KeyError: &quot;None of [Index([&#039;ocean_proximity&#039;])] are in the [columns]&quot;<\/code><\/td><td>The <code>get_dummies<\/code> cell ran twice, and the column was already replaced<\/td><td>Restart the kernel and run the cells in order<\/td><\/tr><tr><td><code>ValueError: could not convert string to float: &#039;NEAR BAY&#039;<\/code><\/td><td>The <code>ocean_proximity<\/code> text column was never encoded<\/td><td>Run <code>pd.get_dummies<\/code> before fitting<\/td><\/tr><tr><td><code>ValueError: Input X contains NaN<\/code><\/td><td><code>dropna()<\/code> was skipped; <code>total_bedrooms<\/code> has missing values<\/td><td>Drop the rows, or impute with <code>SimpleImputer<\/code> inside the pipeline<\/td><\/tr><tr><td><code>ConvergenceWarning: lbfgs failed to converge<\/code><\/td><td>Features are on very different scales<\/td><td>Add <code>StandardScaler<\/code> or increase <code>max_iter<\/code><\/td><\/tr><tr><td>Accuracy close to 1.0<\/td><td><code>median_house_value<\/code> (or <code>above_median<\/code>) left in the features<\/td><td>Drop both from <code>X<\/code> before training<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Experiments to try next<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Replace the single split with <code>cross_val_score(model, X, y, cv=5)<\/code> to get a more stable accuracy estimate. This needs one global label, so build <code>y<\/code> with the full-data median for this experiment.<\/li>\n\n\n<li>Tune the regularisation strength with <code>GridSearchCV<\/code> over <code>logisticregression__C<\/code> values such as <code>[0.01, 0.1, 1, 10]<\/code>.<\/li>\n\n\n<li>Add ratio features such as <code>rooms_per_household = total_rooms \/ households<\/code> and see whether accuracy improves.<\/li>\n\n\n<li>Use a <code>ColumnTransformer<\/code> to scale only the numeric columns and pass the one-hot columns through unchanged.<\/li>\n\n\n<li>Compare against <code>DecisionTreeClassifier<\/code> or <code>RandomForestClassifier<\/code> on the same split.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> The <code>ISLAND<\/code> category has only a handful of rows. A random split can leave it out of the test set, or nearly out. That is harmless here, but on small categories it is worth checking <code>value_counts()<\/code> before you trust per-category results.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Why use logistic regression for house prices if prices are continuous?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The lab turns the price into a binary label (above or below the median), and logistic regression is a standard first model for binary classification. It shows how to reframe a regression dataset as a classification problem.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why do I need to drop median_house_value before training?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>above_median<\/code> label is computed from that column, so keeping it gives the model the answer. Accuracy would be close to perfect but would tell you nothing about real predictive power.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why does scikit-learn say lbfgs failed to converge?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The features are on very different scales, so the optimiser runs out of iterations before it settles. Wrap the model in a pipeline with <code>StandardScaler<\/code>, or increase <code>max_iter<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why are my get_dummies columns True\/False instead of 0\/1?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">pandas 2.0 changed the default dtype of <code>pd.get_dummies<\/code> to <code>bool<\/code>. Pass <code>dtype=int<\/code> if you want 0\/1 integers; scikit-learn accepts either.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What accuracy should I expect?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Compare it against the 50% baseline you would get by guessing on balanced classes. A scaled logistic regression should do clearly better than that. The exact score depends on the split and the library versions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/artificial-intelligence\/machine-learning\/\">More Machine Learning tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/lead-machine-learning-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/staff-mlops-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>This lab uses scikit-learn&#039;s LogisticRegression to classify California housing districts as above or below the median house value. The notebook above loads housing.csv, drops missing and capped&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[6512],"tags":[26386],"class_list":["post-47415","post","type-post","status-publish","format-standard","hentry","category-machine-learning","tag-scikit-learn"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47415","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=47415"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47415\/revisions"}],"predecessor-version":[{"id":80198,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47415\/revisions\/80198"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=47415"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=47415"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=47415"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}