Linear Regression with Scikit-Learn


Linear Regression with Scikit-Learn

Maria
Welcome to our practical introduction to machine learning with Python and Scikit-Learn. The course is designed for beginners and focuses on building, training, evaluating, and eventually deploying models on real-world data. Today, we are going to connect several major ideas: linear and logistic regression, decision trees, random forests, gradient boosting, unsupervised learning, project workflow, and deployment.

Corey
That sounds like a lot, but there is one workflow tying everything together. We start with a business problem, understand the available data, prepare it, choose a model and evaluation metric, train the model, check how well it generalizes, improve it, and finally make predictions in a usable application. The specific algorithm changes, but that overall process appears again and again.

Maria
Let’s begin with linear regression and the medical-expenses problem. An insurance company has historical data for more than 1,300 customers, including age, sex, BMI, number of children, smoking status, region, and the medical charges each customer incurred. The objective is to estimate charges for a new customer so the estimate can help determine an insurance premium.

Corey
That is a typical machine-learning problem because we are replacing part of a manual decision-making process with a data-driven system. Instead of relying entirely on an expert’s experience, we use historical examples to learn a relationship between customer information and medical charges. The historical charges are the target, while the other columns are potential input features.

Maria
The first practical step is downloading and exploring the data. A CSV file can be retrieved with Python’s URL-retrieve functionality, uploaded manually, or obtained from sources such as Kaggle. Pandas can then load it into a DataFrame with read_csv, after which we should inspect its structure, data types, statistics, and missing values.

Corey
In the medical dataset, the numerical columns include age, BMI, children, and charges, while sex, smoker, and region are categorical. There are 1,338 rows and seven columns, and the dataset has no missing values. Descriptive statistics show ages from 18 to 64, BMI values roughly from 16 to 53, and charges ranging from about 1,000 to 64,000 dollars.

Maria
Those statistics already reveal useful patterns. Charges are strongly skewed: the mean is higher than the median, and a relatively small number of customers have very high expenses. Visualizations make that clearer. Age is nearly uniform across the dataset, BMI looks approximately Gaussian, and charges follow a heavily skewed, power-law-like pattern.

Corey
Smoking status is especially important. Smokers are a minority of the customers, but their medical charges have a much higher median than non-smokers. That does not prove that smoking causes the difference, but it does show a strong relationship that a model may find useful.

Maria
Exploratory analysis should examine relationships between the target and each input. Scatter plots suggest that age and charges have a roughly increasing relationship, while BMI alone has a much weaker visible relationship. For categorical data, we can compare distributions or use plots such as violin plots to see how charges vary across groups.

Corey
A correlation coefficient summarizes the strength and direction of a linear relationship. It ranges from minus one to one: a positive value indicates an increasing relationship, a negative value indicates a decreasing relationship, and a value near zero indicates little linear relationship. In the example, smoker status has a much stronger correlation with charges than age, BMI, or children.

Maria
But correlation is not causation. Two variables can be correlated because one causes the other, because the reverse relationship holds, or because a third factor influences both. This matters enormously in automated systems, especially in healthcare, finance, and law enforcement, where blindly treating correlations as causes can reinforce unfair or harmful decisions.

Corey
For a single-feature linear regression model, we assume that the target can be approximated by a line: y equals w times x plus b. In the insurance example, charges are modeled as w times age plus b. The weight, or slope, controls how much the prediction changes as age changes, while the bias, or intercept, shifts the line up or down.

Maria
The input values are the features, and the observed charges are the targets. We choose values for the weight and bias so the line fits the training points as closely as possible. A prediction for a new 30-year-old customer is obtained by putting 30 into the learned equation.

Corey
To measure how well the line fits, we calculate residuals, which are the differences between actual targets and predictions. Squaring the residuals prevents positive and negative errors from canceling. Averaging those squared errors and taking the square root gives root mean squared error, or RMSE, which is interpretable in the same units as the target, such as dollars.

Maria
RMSE gives more influence to large errors because they are squared. An alternative is mean absolute error, which uses absolute differences and is less dominated by outliers. In either case, the lower the loss, the better the model is at matching the targets.

Corey
A computer can search for better weights and biases using optimization. Ordinary least squares directly computes a best fit efficiently for smaller datasets, while gradient descent iteratively adjusts parameters in a direction that reduces the loss. In practice, Scikit-Learn handles these calculations through model classes such as LinearRegression and SGDRegressor.

Maria
With Scikit-Learn, the basic pattern is simple: create a model, call fit with the inputs and targets, call predict on new inputs, and evaluate the predictions. For linear regression, the learned weights are available through coef_, and the intercept is available through intercept_. The same general fit-and-predict style is shared by many Scikit-Learn models.

Corey
Multiple linear regression extends the same idea. Instead of one feature, the prediction is a weighted sum such as weight one times age, plus weight two times BMI, plus weight three times children, plus an intercept. Geometrically, two features produce a plane rather than a line, but it remains linear because the features are combined without powers such as squares or cubes.

Maria
Categorical features must be represented numerically before many machine-learning algorithms can use them. A binary category such as smoker can be mapped from no to zero and yes to one. A category with several unordered values, such as region, is usually one-hot encoded into separate zero-and-one columns, one for each region.

Corey
If categories have a genuine natural order, they may sometimes be represented by ordered numbers, such as cold, neutral, warm, and hot becoming one, two, three, and four. But assigning numbers to unordered categories can create a false relationship. That is why one-hot encoding is safer for categories such as region.

Maria
Feature scaling is another important preparation step. Numerical features may have very different ranges, and large-valued features can disproportionately influence numerical optimization. Min-max scaling brings values into a zero-to-one range, while standardization subtracts the mean and divides by the standard deviation, producing values centered around zero.

Corey
The next major example is logistic regression, which is used for classification rather than predicting a continuous amount. The Australia weather dataset contains daily observations from many weather stations over roughly a decade. The goal is to use today’s conditions to predict whether it will rain tomorrow.

Maria
Classification assigns each input to a discrete class. Rain tomorrow is a binary classification problem because the possible outcomes are yes and no. Other examples include identifying whether a tumor is benign or malignant, predicting whether a loan applicant will repay, or recognizing handwritten digits, which is a multiclass problem.

Corey
Logistic regression begins with a weighted sum of the input features, just like linear regression. It then passes that value through the sigmoid function, which compresses the result into the range zero to one. That output is interpreted as the estimated probability of the positive class, such as the probability that it will rain tomorrow.

Maria
The model is trained by comparing those probabilities with the known yes-or-no labels. Logistic regression commonly uses cross-entropy loss, which penalizes confident but incorrect predictions strongly. The optimization process adjusts the weights and bias to reduce that loss.

Corey
Before training the weather model, we need to handle missing values. Rows with missing target values cannot teach the model what the correct answer is, so they should be removed. Other missing numerical values can be imputed, often by replacing them with the column mean or median using SimpleImputer.

Maria
The weather dataset also requires categorical encoding, including one-hot encoding for location and wind direction. The date column should not usually be passed directly as a feature. Instead, useful parts such as year, month, day, or week can be extracted, provided they are available at prediction time.

Corey
Evaluation for classification starts with accuracy, the fraction of predictions that are correct. But accuracy can be misleading when classes are imbalanced. In the weather data, no-rain days are much more common than rain days, so a model that always predicts no rain can already achieve a surprisingly high accuracy.

Maria
That is why we compare against simple baselines. A random-guess model gives roughly fifty percent accuracy in a binary problem, while an always-no model reflects the class imbalance. A useful machine-learning model must beat those baselines meaningfully, not merely produce an impressive-looking number.

Corey
A confusion matrix gives more detail than accuracy. It records true positives, true negatives, false positives, and false negatives. For weather forecasting, a false negative means rain occurs but the model predicts no rain. Depending on the use case, false negatives or false positives may matter more, so the business goal should determine which metric to emphasize.

Maria
The dataset should be split into training, validation, and test sets. The training set is used to learn parameters, the validation set is used while comparing models and tuning choices, and the test set is held back for the final performance report. If the data is time ordered, the split should also respect time: train on earlier years, validate on a later year, and test on the most recent period.

Corey
This prevents the model from learning from the future when predicting the past. It also makes the test score a more realistic estimate of future performance. A model can be almost perfect on training data and still fail on unseen examples; that is overfitting.

Maria
Decision trees address prediction differently. They build a hierarchy of binary questions, such as whether humidity is below a threshold or whether a promotion is active. The computer chooses the feature and threshold that produce the best split, then repeats the process on the resulting subsets.

Corey
For classification trees, the Gini value measures how mixed the classes are after a split. A lower Gini value represents a purer, better split, while a perfect separation has a value of zero. An unrestricted tree can continue splitting until it effectively memorizes the training examples.

Maria
That explains the classic decision-tree pattern: nearly one-hundred-percent training accuracy but much lower validation accuracy. Regularization reduces this problem by limiting the tree’s complexity. Useful hyperparameters include max_depth, max_leaf_nodes, minimum samples for a split, minimum samples per leaf, and minimum impurity decrease.

Corey
The best complexity is usually somewhere in the middle. A tree that is too small underfits and misses important structure. A tree that is too large overfits and memorizes training examples. We can tune a hyperparameter by plotting training and validation error, then selecting the region where validation error is lowest.

Maria
A random forest combines many decision trees. Each tree is trained with some randomness, such as different sampled rows or subsets of features. For classification, the forest combines predictions by voting; for regression, it generally averages the predicted numbers.

Corey
The wisdom-of-the-crowd intuition explains why this helps. Individual trees make different mistakes, and averaging or voting can cancel some of those errors. Important random-forest hyperparameters include the number of trees, maximum depth, maximum features, bootstrap sampling, maximum samples, and class weights.

Maria
Gradient boosting uses a different ensemble strategy. It begins with a simple prediction, often the average target value. It calculates the residual errors, trains a small decision tree to predict those errors, adds a scaled version of that tree’s prediction, and repeats the process.

Corey
The scaling factor is the learning rate. A small learning rate makes smaller corrections and usually requires more trees; a larger learning rate makes bigger corrections but may overfit. XGBoost and LightGBM are efficient implementations of gradient-boosting ideas and are especially powerful for tabular data.

Maria
Gradient boosting, random forests, and decision trees can provide feature-importance information. For linear models, coefficients show how features contribute to the prediction, although coefficient size must be interpreted alongside feature scale. Standardizing numerical features can make those relative weights more meaningful.

Corey
A complete machine-learning project requires more than choosing an algorithm. First clarify the business objective, how the current process works, who will use the result, what impact success would have, how much historical data exists, whether labels are available, and what known problems affect the data.

Maria
Then classify the problem as supervised or unsupervised. Supervised learning has labeled targets and includes regression and classification. Unsupervised learning has no target labels and is used to discover structure, such as clusters or lower-dimensional representations.

Corey
Feature engineering is often one of the most valuable parts of the project. It means transforming or combining existing columns, or adding information from external sources, to create features that better express the relationship the model needs to learn. For store-sales prediction, useful features might include year, month, day, promotion status, competition information, and seasonal indicators.

Maria
Baseline models should come before extensive tuning. A store-sales baseline might always predict the overall mean, predict the average for that store and month from the previous year, or use another simple business rule. If a complex machine-learning model cannot beat a sensible baseline, something is wrong or the extra complexity is not worthwhile.

Corey
For time-series-like data, validation must resemble how the model will be used. Randomly splitting dates can let future patterns leak into training. A time-based split uses earlier observations for training and later observations for validation or testing, producing a more realistic estimate of future performance.

Maria
Model experiments should be tracked systematically. Record the model type, features, hyperparameters, training score, validation score, test score, and a link to the notebook version. This makes it possible to compare ideas, avoid repeating failed experiments, and understand why a particular model was selected.

Corey
Unsupervised learning provides another set of tools. K-means clustering assigns observations to a chosen number of clusters by repeatedly updating cluster centers. Each point belongs to the nearest center, and the algorithm tries to minimize the total within-cluster variance, called inertia.

Maria
The number of clusters can be explored with an elbow curve. We train K-means for several values of K and plot inertia against K. The preferred value is often near the point where adding more clusters produces diminishing reductions in inertia.

Corey
DBSCAN works differently. Instead of requiring a predetermined number of clusters, it uses neighborhood density. Points with enough nearby neighbors become core points, nearby boundary points become reachable points, and isolated observations can be treated as noise or outliers.

Maria
Hierarchical clustering builds a tree of clusters. It begins with each observation as its own cluster, repeatedly combines the closest clusters, and produces a hierarchy that can be visualized as a dendrogram. This is useful when we want to study relationships at several levels, such as a taxonomy.

Corey
Dimensionality reduction addresses datasets with many features. Principal component analysis, or PCA, finds linear directions that preserve as much variance as possible and projects the data into fewer dimensions. It can reduce computation and help visualize high-dimensional data, though some information may be lost.

Maria
T-SNE is a nonlinear dimensionality-reduction method mainly used for visualization. It attempts to keep nearby points nearby in the reduced representation, making it useful for visualizing structures such as handwritten digits. A common workflow is to use PCA first to reduce a very high-dimensional dataset and then T-SNE to display it in two dimensions.

Corey
Once a model is satisfactory, it must be used on new inputs. Every preprocessing step applied during training must also be applied to new data in exactly the same way: date transformations, imputation, scaling, and categorical encoding. The fitted imputer, scaler, encoder, feature names, and model should all be saved together.

Maria
Joblib can serialize those Python objects into a file. Saving the whole pipeline or a dictionary of required components means the model can be loaded later without retraining. The saved model is a compact representation of patterns learned from a much larger dataset.

Corey
Deployment turns that model into something people can use. A Flask application can receive input through a webpage, pass it through the saved preprocessing objects and model, and return a prediction. A basic application can contain an HTML template with a form, a text area or other input controls, and a route that handles the submitted data.

Maria
For the email-spam example, the application accepts an email body, transforms it with a saved count vectorizer, sends the transformed input to a saved classifier, and displays whether the message is spam. Flask routes separate the home page from the prediction endpoint, while HTML and CSS control the interface.

Corey
The same application can expose an API route. Instead of submitting a browser form, a client sends JSON, such as an object containing the email content. The Flask route reads the JSON, makes the prediction, and returns a JSON response. Tools such as Postman, Insomnia, or Thunder Client can be used to test that endpoint.

Maria
A practical deployment workflow includes creating a GitHub repository, using a consistent Python or Conda environment, recording dependencies in requirements.txt, committing the code, and deploying the repository to a cloud service such as Render. Environment versions matter because code that works locally can fail elsewhere when library versions differ.

Corey
The final lesson is that machine learning is iterative and applied. A good result is not just a high training score. We need realistic validation, meaningful baselines, careful feature engineering, appropriate metrics, regularization, interpretability, and communication with domain experts and nontechnical stakeholders.

Maria
Exactly. The essential cycle is: understand the business problem, inspect and clean the data, define inputs and targets, engineer useful features, split the data properly, establish a baseline, train several appropriate models, tune and regularize them, evaluate on unseen data, interpret individual predictions, save the complete system, and deploy it responsibly.

Corey
And keep learning through practice. Kaggle datasets and competitions provide realistic problems, public notebooks reveal techniques used by other practitioners, and publishing your own notebooks or blog posts forces you to explain your reasoning. The code for many models is short, but developing good judgment about data, validation, features, and deployment takes repeated experimentation.

Ask anything
We've read this whole study set, so questions about it get the best answers.