{"id":47413,"date":"2026-11-24T22:04:48","date_gmt":"2026-11-24T22:04:48","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=47413"},"modified":"2026-11-24T22:04:48","modified_gmt":"2026-11-24T22:04:48","slug":"machine-learning-scikit-learn-lab-3","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/machine-learning-scikit-learn-lab-3\/","title":{"rendered":"Machine Learning \u2013 scikit-learn &#8211; Lab 3"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This lab uses scikit-learn&#039;s <code>LinearRegression<\/code> to predict <code>median_house_value<\/code> from the California housing dataset (<code>housing.csv<\/code>). It covers cleaning missing and capped values, one-hot encoding <code>ocean_proximity<\/code>, splitting the data, training the model and reading its coefficients. Below the notebook you will find a version that runs on current scikit-learn, because the original <code>normalize=True<\/code> argument has been removed from the library.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/2aea0091b95f246a5be26ca9b837f383.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, step by step<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The notebook above is a standard supervised regression workflow. Each cell moves the data one step closer to something a linear model can learn from. The table maps the main cells to their purpose and the results shown in the notebook.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Cell<\/th><th>Purpose<\/th><th>Result in the notebook<\/th><\/tr><\/thead><tbody><tr><td><code>pd.read_csv(&#039;datasets\/housing.csv&#039;)<\/code><\/td><td>Load the raw data<\/td><td>10 columns, one of them text (<code>ocean_proximity<\/code>)<\/td><\/tr><tr><td><code>dropna()<\/code><\/td><td>Remove rows with missing values (only <code>total_bedrooms<\/code> has gaps)<\/td><td>Shape becomes (20433, 10)<\/td><\/tr><tr><td>Drop rows where <code>median_house_value == 500001<\/code><\/td><td>Remove 958 rows whose target was capped at the top value<\/td><td>Shape becomes (19475, 10)<\/td><\/tr><tr><td><code>pd.get_dummies(..., columns=[&#039;ocean_proximity&#039;])<\/code><\/td><td>Turn the text category into one 0\/1 column per value<\/td><td>Shape becomes (19475, 14)<\/td><\/tr><tr><td><code>train_test_split(X, Y, test_size=0.2)<\/code><\/td><td>Hold back 20% of rows for testing<\/td><td>15580 train rows, 3895 test rows<\/td><\/tr><tr><td><code>LinearRegression(...).fit()<\/code><\/td><td>Fit the model<\/td><td>Training R\u00b2 of about 0.61<\/td><\/tr><tr><td><code>pd.Series(linear_model.coef_, predictors)<\/code><\/td><td>Show how much each feature moves the prediction<\/td><td><code>median_income<\/code> is the strongest positive numeric feature<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> The capped rows matter. The dataset clips house values at 500,001, so those rows do not show the real price. Leaving them in pulls a straight-line fit toward an artificial ceiling.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites and setup<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You need Python 3, Jupyter, pandas, matplotlib and scikit-learn. The notebook expects the California housing CSV (the version with the <code>ocean_proximity<\/code> column) in a <code>datasets<\/code> folder next to the notebook.<\/p>\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\">python3 -m venv .venv\nsource .venv\/bin\/activate\npip install --upgrade pip\npip install pandas matplotlib scikit-learn jupyter\n\n<span class=\"hljs-comment\"># expected layout<\/span>\n<span class=\"hljs-comment\"># lab3\/<\/span>\n<span class=\"hljs-comment\">#   03-LinearRegressionForPricePrediction.ipynb<\/span>\n<span class=\"hljs-comment\">#   datasets\/<\/span>\n<span class=\"hljs-comment\">#     housing.csv<\/span>\n\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<p class=\"wp-block-paragraph\">Check which scikit-learn version you have before you run the training cell, because that cell decides whether the original code works:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">python -c <span class=\"hljs-string\">\"import sklearn; print(sklearn.__version__)\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Fixing the LinearRegression call for current scikit-learn<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The training cell calls <code>LinearRegression(normalize=True, fit_intercept=False)<\/code>. scikit-learn deprecated the <code>normalize<\/code> parameter in version 1.0 and removed it in 1.2. On any current install this cell fails with:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\"><span class=\"hljs-built_in\">TypeError<\/span>: LinearRegression.__init__() got an unexpected keyword argument <span class=\"hljs-string\">'normalize'<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Removing the argument does not change the results. Older versions documented that <code>normalize<\/code> was <strong>ignored when <code>fit_intercept=False<\/code><\/strong>, so it never did anything in this notebook. Scaling also has no effect on the predictions or R\u00b2 of ordinary least squares. It only changes the size of the coefficients. If you want scaled features, for example to compare coefficients, use <code>StandardScaler<\/code> in a pipeline:<\/p>\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\">from sklearn.linear_model import LinearRegression\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\n\n<span class=\"hljs-comment\"># Minimal fix: same behaviour as the original notebook<\/span>\nlinear_model = LinearRegression(fit_intercept=<span class=\"hljs-keyword\">False<\/span>).fit(x_train, y_train)\n\n<span class=\"hljs-comment\"># Preferred: explicit scaling plus a normal intercept<\/span>\nlinear_model = make_pipeline(StandardScaler(), LinearRegression()).fit(x_train, y_train)<\/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<p class=\"wp-block-paragraph\"><strong>Why <code>fit_intercept=False<\/code> still worked:<\/strong> <code>get_dummies<\/code> creates one column for every <code>ocean_proximity<\/code> value, and in every row exactly one of them is 1. Together those five columns act as an intercept, so the model learns one baseline per region. That is why the dummy coefficients are all around -2,000,000: each one is that region&#039;s intercept. A clearer approach is <code>pd.get_dummies(..., drop_first=True)<\/code> with the default <code>fit_intercept=True<\/code>. It drops one category as the reference level and avoids perfectly collinear columns.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Complete working version of the lab<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This script runs end to end on current pandas and scikit-learn. It follows the same steps as the notebook, adds a fixed <code>random_state<\/code> so the results can be repeated, and evaluates the model on the test set with several metrics.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import numpy <span class=\"hljs-keyword\">as<\/span> np\nimport pandas <span class=\"hljs-keyword\">as<\/span> pd\nimport matplotlib.pyplot <span class=\"hljs-keyword\">as<\/span> plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error\n\n<span class=\"hljs-comment\"># 1. Load and clean<\/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>]\n\n<span class=\"hljs-comment\"># 2. One-hot encode; drop_first keeps one category as the baseline<\/span>\nhousing = pd.get_dummies(housing, columns=&#91;<span class=\"hljs-string\">'ocean_proximity'<\/span>],\n                         drop_first=<span class=\"hljs-keyword\">True<\/span>, dtype=int)\n\n<span class=\"hljs-comment\"># 3. Features and target<\/span>\nX = housing.drop(<span class=\"hljs-string\">'median_house_value'<\/span>, axis=<span class=\"hljs-number\">1<\/span>)\ny = housing&#91;<span class=\"hljs-string\">'median_house_value'<\/span>]\n\nx_train, x_test, y_train, y_test = train_test_split(\n    X, y, test_size=<span class=\"hljs-number\">0.2<\/span>, random_state=<span class=\"hljs-number\">42<\/span>)\n\n<span class=\"hljs-comment\"># 4. Train<\/span>\nmodel = LinearRegression().fit(x_train, y_train)\n\n<span class=\"hljs-comment\"># 5. Evaluate on data the model has not seen<\/span>\ny_pred = model.predict(x_test)\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">'Train R2 :'<\/span>, round(model.score(x_train, y_train), <span class=\"hljs-number\">4<\/span>))\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">'Test  R2 :'<\/span>, round(r2_score(y_test, y_pred), <span class=\"hljs-number\">4<\/span>))\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">'MAE      :'<\/span>, round(mean_absolute_error(y_test, y_pred)))\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">'RMSE     :'<\/span>, round(np.sqrt(mean_squared_error(y_test, y_pred))))\n\n<span class=\"hljs-comment\"># 6. Coefficients<\/span>\n<span class=\"hljs-keyword\">print<\/span>(pd.Series(model.coef_, X.columns).sort_values())\n\n<span class=\"hljs-comment\"># 7. Actual vs predicted<\/span>\nplt.figure(figsize=(<span class=\"hljs-number\">6<\/span>, <span class=\"hljs-number\">6<\/span>))\nplt.scatter(y_test, y_pred, s=<span class=\"hljs-number\">5<\/span>, alpha=<span class=\"hljs-number\">0.4<\/span>)\nplt.plot(&#91;y.min(), y.max()], &#91;y.min(), y.max()], <span class=\"hljs-string\">'r--'<\/span>)\nplt.xlabel(<span class=\"hljs-string\">'Actual median_house_value'<\/span>)\nplt.ylabel(<span class=\"hljs-string\">'Predicted median_house_value'<\/span>)\nplt.title(<span class=\"hljs-string\">'Linear regression: actual vs predicted'<\/span>)\nplt.show()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><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\">Expect the train and test R\u00b2 to be close to each other and near the notebook&#039;s 0.61. The exact numbers depend on the split. When train and test scores are similar, the model is not overfitting. Its limit is bias: a straight line cannot capture all of the relationship.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> In pandas 2.x, <code>get_dummies<\/code> returns <code>True<\/code>\/<code>False<\/code> columns by default instead of the 1\/0 shown in the notebook output. scikit-learn accepts either. Passing <code>dtype=int<\/code> makes the output match the notebook.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Reading the coefficients and scores<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>R\u00b2 (<code>score<\/code>)<\/strong> is the share of the variance in house value that the model explains. 1.0 is perfect. 0 is no better than always predicting the mean.<\/li>\n\n\n<li><strong>MAE<\/strong> is the average absolute error in dollars, which is easy to explain to non-specialists. <strong>RMSE<\/strong> penalises large misses more heavily.<\/li>\n\n\n<li><strong>Coefficients<\/strong> give the change in predicted value for a one-unit increase in a feature when all other features stay the same. In the notebook, each extra unit of <code>median_income<\/code> (measured in tens of thousands of dollars) adds roughly 38,000 to the prediction.<\/li>\n\n\n<li>Coefficients on raw features cannot be compared with each other, because the features use different units. <code>total_rooms<\/code> and <code>latitude<\/code> are on very different scales. Standardise the features first if you want to rank them by importance.<\/li>\n\n\n<li><code>total_rooms<\/code>, <code>total_bedrooms<\/code>, <code>households<\/code> and <code>population<\/code> are strongly correlated. Their individual coefficients can flip sign or look odd even when the predictions are fine. That is multicollinearity, not a bug.<\/li>\n<\/ul>\n\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>TypeError: ... unexpected keyword argument &#039;normalize&#039;<\/code><\/td><td>scikit-learn 1.2 or later<\/td><td>Remove <code>normalize=True<\/code>. Use <code>StandardScaler<\/code> if you need scaling<\/td><\/tr><tr><td><code>FileNotFoundError: datasets\/housing.csv<\/code><\/td><td>The notebook was started from a different directory, or the CSV is missing<\/td><td>Put the file in <code>datasets\/<\/code> next to the notebook, or use an absolute path<\/td><\/tr><tr><td><code>ValueError: could not convert string to float: &#039;NEAR BAY&#039;<\/code><\/td><td><code>ocean_proximity<\/code> was not encoded before fitting<\/td><td>Run the <code>get_dummies<\/code> cell before you split the data<\/td><\/tr><tr><td><code>ValueError: Input X contains NaN<\/code><\/td><td><code>dropna()<\/code> was skipped<\/td><td>Drop or impute missing <code>total_bedrooms<\/code> values, for example with <code>SimpleImputer<\/code><\/td><\/tr><tr><td>Different scores on every run<\/td><td><code>train_test_split<\/code> has no <code>random_state<\/code><\/td><td>Pass <code>random_state=42<\/code> or any other fixed integer<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Next steps to improve the model<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Add ratio features such as <code>rooms_per_household<\/code>, <code>bedrooms_per_room<\/code> and <code>population_per_household<\/code>. They usually carry more signal than the raw totals.<\/li>\n\n\n<li>Predict <code>np.log1p(median_house_value)<\/code> and convert predictions back with <code>np.expm1<\/code>. Prices are right-skewed, and a log target often fits a linear model better.<\/li>\n\n\n<li>Use <code>cross_val_score(model, X, y, cv=5, scoring=&#039;r2&#039;)<\/code> instead of a single split to get a more stable estimate.<\/li>\n\n\n<li>Try <code>Ridge<\/code> or <code>Lasso<\/code> to handle the correlated count features, then compare with a tree-based model such as <code>RandomForestRegressor<\/code>.<\/li>\n\n\n<li>Wrap the encoding and the model in a <code>Pipeline<\/code> with <code>ColumnTransformer<\/code>. New data then goes through exactly the same preprocessing at prediction time.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Why does LinearRegression(normalize=True) raise an error?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">scikit-learn deprecated <code>normalize<\/code> in 1.0 and removed it in 1.2. Delete the argument, and put a <code>StandardScaler<\/code> before the model in a pipeline if you want scaled features.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why are the ocean_proximity coefficients around -2,000,000?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The model was fitted with <code>fit_intercept=False<\/code> and a dummy column for every category, so each dummy coefficient acts as that region&#039;s intercept. Use <code>drop_first=True<\/code> with a normal intercept to get coefficients relative to a baseline category.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is a training R\u00b2 of 0.61 good for this dataset?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It is a typical result for plain linear regression on California housing data. Feature engineering, a log-transformed target or non-linear models such as random forests usually do better.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why remove rows where median_house_value equals 500001?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The dataset caps values at 500,001, so those rows do not show the true price. Removing them stops the model from learning an artificial ceiling.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Do I need to scale features for linear regression?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For ordinary least squares, scaling does not change predictions or R\u00b2. It only matters if you want to compare coefficients directly or you switch to regularised models such as Ridge and Lasso.<\/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\/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\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<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>This lab uses scikit-learn&#039;s LinearRegression to predict median_house_value from the California housing dataset (housing.csv). It covers cleaning missing and capped values, one-hot encoding ocean_proximity, splitting the data,&#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-47413","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\/47413","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=47413"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47413\/revisions"}],"predecessor-version":[{"id":80197,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47413\/revisions\/80197"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=47413"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=47413"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=47413"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}