1. Home
  2. Explore
  3. Computer Science
  4. Linear Regression with Scikit-Learn

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Linear Regression with Scikit-Learn

  • 91Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: ML Foundations

What is the main purpose of the practical machine learning course described?

91 questions

  1. 1

    What is the main purpose of the practical machine learning course described?

    Model answer

    It introduces beginners to building, training, and deploying machine learning models with Python and Scikit-Learn for real-world use.

    Explanation

    The course emphasizes hands-on work with common machine learning models and real datasets.

  2. 2

    What are the three main components of a machine learning problem?

    Model answer

    A machine learning problem requires a model structure, a cost or loss function, and an optimization technique.

    Explanation

    The model represents the relationship, the loss measures its error, and optimization adjusts its parameters to reduce that error.

  3. 3

    What is the difference between a model parameter and a hyperparameter?

    Model answer

    A parameter is learned by the model during training, whereas a hyperparameter is specified before training.

    Explanation

    Weights and biases are parameters; values such as tree depth, learning rate, and estimator count are hyperparameters.

  4. 4

    What is supervised learning?

    Model answer

    Supervised learning uses labeled data containing inputs and known target values to learn how to make predictions.

    Explanation

    Classification and regression are supervised because their training datasets include the desired output for each example.

  5. 5

    What is unsupervised learning?

    Model answer

    Unsupervised learning analyzes data without labeled targets to discover patterns, clusters, or lower-dimensional representations.

    Explanation

    Clustering and dimensionality reduction are examples of unsupervised learning.

  6. 6

    What is the difference between regression and classification?

    Model answer

    Regression predicts a continuous numeric value, while classification assigns an input to one or more discrete categories.

    Explanation

    Medical charges and house prices are regression targets; rain/no-rain and benign/malignant are classification targets.

  7. 7

    Why should a machine learning project begin by understanding the business problem?

    Model answer

    Understanding the business objective identifies whether machine learning is needed, how the output will be used, and which performance measure matters.

    Explanation

    Business requirements also determine the acceptable model complexity, interpretability, and error trade-offs.

  8. 8

    What is a typical machine learning workflow?

    Model answer

    The workflow includes understanding the problem, obtaining and exploring data, preparing features, splitting data, training models, evaluating them, improving them, and deploying or presenting the result.

    Explanation

    The process is iterative rather than strictly linear because new findings may require revised features, data, or business assumptions.

  9. 9

    Why is a baseline model useful?

    Model answer

    A baseline provides a simple performance benchmark that more sophisticated models must exceed.

    Explanation

    Examples include always predicting the mean for regression or always predicting the most common class for classification.

  10. 10

    Why should machine learning projects be documented and tracked systematically?

    Model answer

    Tracking ideas, hyperparameters, results, and model versions makes experiments reproducible and prevents useful findings from being lost.

    Explanation

    Experiment sheets and saved notebooks help compare many models and identify which changes actually improved performance.

  11. 11

    In the insurance example, what is the target variable and what are possible input features?

    Model answer

    The target is annual medical charges, while possible inputs include age, sex, BMI, number of children, smoking status, and region.

    Explanation

    The system uses historical customer information to estimate future medical expenditure for new customers.

  12. 12

    What is the equation of a single-feature linear regression model?

    Model answer

    A single-feature linear regression model can be written as y=wx+by = wx + by=wx+b, where www is the weight or slope and bbb is the bias or intercept.

    Explanation

    The equation represents the assumption that the target changes linearly with the input.

  13. 13

    What do the slope and intercept represent in linear regression?

    Model answer

    The slope determines the change in the target for a change in the input, while the intercept is the predicted target when the input is zero.

    Explanation

    In the insurance example, the slope controls how charges change with age and the intercept shifts the fitted line vertically.

  14. 14

    What are inputs and targets in a supervised learning dataset?

    Model answer

    Inputs are the features supplied to the model, and targets are the known outcomes the model is trained to predict.

    Explanation

    Age is an input and medical charges are the target in the single-feature insurance example.

  15. 15

    How does Scikit-Learn train a linear regression model?

    Model answer

    A model is created with LinearRegression, fitted with model.fit(inputs, targets), and then used for predictions with model.predict(new_inputs).

    Explanation

    The fit method determines model parameters that minimize the chosen training objective.

  16. 16

    Why must Scikit-Learn inputs generally be two-dimensional?

    Model answer

    Scikit-Learn expects inputs in the form of samples by features, even when there is only one feature.

    Explanation

    A one-feature input should therefore be represented as a two-dimensional data frame or array with one column.

  17. 17

    What is a residual in regression?

    Model answer

    A residual is the difference between an actual target and the model's prediction for that target.

    Explanation

    Residuals show how far individual observations lie from the fitted model.

  18. 18

    What is root mean squared error?

    Model answer

    Root mean squared error is the square root of the average of the squared prediction errors: RMSE=sqrtfrac1nsumi=1n(yi−hatyi)2RMSE = \\sqrt{\\frac{1}{n}\\sum_{i=1}^{n}(y_i - \\hat{y}_i)^2}RMSE=sqrtfrac1nsumi=1n​(yi​−hatyi​)2.

    Explanation

    It measures the typical prediction error in the same units as the target and gives greater influence to large errors.

  19. 19

    How does mean absolute error differ from root mean squared error?

    Model answer

    Mean absolute error averages absolute differences, while root mean squared error squares differences before averaging and taking a square root.

    Explanation

    Squared error gives outliers more influence than absolute error.

  20. 20

    What does a lower loss value indicate about a model?

    Model answer

    A lower loss generally indicates that the model's predictions are closer to the actual targets.

    Explanation

    Loss represents prediction error or information not captured by the model.

  21. 21

    What patterns were observed in the insurance dataset during exploratory analysis?

    Model answer

    Age had a positive relationship with charges, BMI had a weak relationship for non-smokers, and smoking status had a very strong relationship with medical expenses.

    Explanation

    Smokers had a much higher median medical expense than non-smokers, while charges were strongly skewed by high-cost cases.

  22. 22

    What is the purpose of exploratory data analysis before modeling?

    Model answer

    Exploratory analysis identifies distributions, errors, outliers, relationships, missing values, and possible features for modeling.

    Explanation

    Plots and summary statistics can reveal patterns that guide preprocessing and model selection.

  23. 23

    How can a binary categorical feature such as smoking status be encoded?

    Model answer

    Its two categories can be mapped to numerical values such as no = 000 and yes = 111.

    Explanation

    This allows the feature to participate in numerical model calculations.

  24. 24

    What is one-hot encoding?

    Model answer

    One-hot encoding replaces a categorical column with one binary column for each category, using 111 for the applicable category and 000 for the others.

    Explanation

    A row belonging to one of four regions, for example, receives one 111 and three 000s across the region columns.

  25. 25

    When can ordered categories be converted directly into numbers?

    Model answer

    They can be converted into numbers when the categories have a meaningful natural order, such as cold, neutral, warm, and hot.

    Explanation

    Numerical encoding preserves the order, but it should not be used when categories have no meaningful ranking.

  26. 26

    What is imputation?

    Model answer

    Imputation is the process of replacing missing values with estimated or selected valid values.

    Explanation

    A common strategy is to replace missing numerical values with the column mean or median.

  27. 27

    Why might the median be preferred to the mean for imputing a feature?

    Model answer

    The median is less affected by extreme outliers, so it can be more representative for highly skewed features such as income.

    Explanation

    The mean can be pulled substantially toward unusually large or small observations.

  28. 28

    What does standardization do to a numerical feature?

    Model answer

    Standardization subtracts the feature mean and divides by its standard deviation, producing values centered near zero with standard deviation near one.

    Explanation

    This is commonly expressed as z=fracx−musigmaz = \\frac{x - \\mu}{\\sigma}z=fracx−musigma.

  29. 29

    What does min-max scaling do?

    Model answer

    Min-max scaling transforms values so that the minimum maps near 000 and the maximum maps near 111.

    Explanation

    Scaling places features with different original units on a comparable numerical range.

  30. 30

    Why should numerical features often be scaled?

    Model answer

    Scaling prevents features with large numerical ranges from disproportionately affecting optimization and loss calculations.

    Explanation

    It can also improve numerical stability for algorithms that use gradients or other numerical operations.

  31. 31

    Why should preprocessing objects be fitted only on training data?

    Model answer

    They should be fitted on training data to prevent information from validation or test data leaking into the model-building process.

    Explanation

    The learned means, ranges, and category mappings can then be applied consistently to validation, test, and future inputs.

  32. 32

    What are the purposes of training, validation, and test sets?

    Model answer

    The training set fits the model, the validation set guides model and hyperparameter choices, and the test set provides the final unbiased performance estimate.

    Explanation

    The test set should be used only after development decisions are complete.

  33. 33

    Why is a time-based split preferable for time-series data?

    Model answer

    A time-based split prevents the model from using future observations to predict the past and better simulates real deployment.

    Explanation

    Historical data can be used for training, later data for validation, and the most recent data for testing.

  34. 34

    What is overfitting?

    Model answer

    Overfitting occurs when a model performs very well on training data but poorly on previously unseen data because it memorizes specific examples.

    Explanation

    A large gap between training and validation or test performance is a common sign of overfitting.

  35. 35

    What is logistic regression used for?

    Model answer

    Logistic regression is primarily used for binary classification problems, such as predicting whether it will rain tomorrow.

    Explanation

    Despite its name, logistic regression is a classification algorithm rather than a continuous-value regression method.

  36. 36

    How does logistic regression differ from linear regression?

    Model answer

    Logistic regression applies a sigmoid function to a weighted sum so that its output can be interpreted as a probability between 000 and 111.

    Explanation

    Linear regression directly predicts a continuous value, whereas logistic regression predicts class probabilities.

  37. 37

    What does the sigmoid function do in logistic regression?

    Model answer

    The sigmoid function converts the weighted sum of features into a value between 000 and 111.

    Explanation

    That value is interpreted as the probability of the positive class.

  38. 38

    What loss function is commonly used for logistic regression?

    Model answer

    Logistic regression commonly uses cross-entropy loss.

    Explanation

    Cross-entropy penalizes predicted probabilities that are inconsistent with the actual class labels.

  39. 39

    What is class imbalance?

    Model answer

    Class imbalance occurs when one class has substantially more observations than another.

    Explanation

    In the Australian rainfall data, no-rain observations greatly outnumbered rain observations.

  40. 40

    Why can accuracy be misleading for imbalanced classification data?

    Model answer

    A model can obtain high accuracy by always predicting the majority class while performing poorly on the minority class.

    Explanation

    For imbalanced data, class-specific measures such as precision, recall, or a confusion matrix are also important.

  41. 41

    What is a confusion matrix?

    Model answer

    A confusion matrix counts true positives, true negatives, false positives, and false negatives.

    Explanation

    It shows the types of correct and incorrect classifications rather than reducing performance to one accuracy value.

  42. 42

    What is a false positive?

    Model answer

    A false positive occurs when the model predicts the positive class but the actual class is negative.

    Explanation

    For rainfall prediction, it means predicting rain when no rain actually occurs.

  43. 43

    What is a false negative?

    Model answer

    A false negative occurs when the model predicts the negative class but the actual class is positive.

    Explanation

    For rainfall prediction, it means predicting no rain when rain actually occurs.

  44. 44

    Why might false negatives be especially important for deciding whether to hold an outdoor event?

    Model answer

    A false negative could cause an event to proceed when rain is expected, creating major practical consequences.

    Explanation

    The preferred evaluation measure depends on the cost of each type of error in the business context.

  45. 45

    What is a decision tree?

    Model answer

    A decision tree is a hierarchy of conditional decisions that splits data into progressively more specific groups.

    Explanation

    Each internal node applies a condition and each leaf node produces a prediction.

  46. 46

    How does a decision tree choose a split?

    Model answer

    It evaluates candidate features and split points and selects a split that produces the greatest improvement according to its criterion.

    Explanation

    For classification, the Gini score is commonly used to measure the quality of a split.

  47. 47

    What does a Gini score represent in a decision tree?

    Model answer

    The Gini score measures the impurity of a node; a lower score indicates a purer and generally better split.

    Explanation

    A perfect split has a Gini score of zero, while a mixed node has a higher score.

  48. 48

    Why can an unrestricted decision tree achieve nearly perfect training accuracy?

    Model answer

    It can continue splitting until it isolates individual training examples and effectively memorizes the training set.

    Explanation

    This memorization leads to severe overfitting and poor generalization.

  49. 49

    How can limiting maximum tree depth reduce overfitting?

    Model answer

    A depth limit prevents the tree from making enough successive decisions to memorize individual training examples.

    Explanation

    A shallower tree captures broader patterns and may perform better on validation data.

  50. 50

    What is the purpose of the max_leaf_nodes hyperparameter?

    Model answer

    It limits the number of terminal nodes in a decision tree and therefore controls its complexity.

    Explanation

    Fewer leaf nodes restrict the number of separate regions the tree can create.

  51. 51

    What is a random forest?

    Model answer

    A random forest is an ensemble of decision trees whose predictions are combined to produce a final result.

    Explanation

    For classification, trees vote on the class; for regression, their numeric predictions are averaged.

  52. 52

    Why can a random forest outperform an individual decision tree?

    Model answer

    Different trees make different errors, and combining their predictions can cause some errors to cancel out.

    Explanation

    This is an example of the wisdom-of-the-crowd principle applied to machine learning.

  53. 53

    What is bootstrapping in a random forest?

    Model answer

    Bootstrapping creates training samples by randomly selecting rows with replacement for each tree.

    Explanation

    Some rows may appear more than once and some may be omitted, making the trees more diverse.

  54. 54

    What does the max_features setting control in a random forest?

    Model answer

    It controls how many features are randomly considered when searching for each tree split.

    Explanation

    Randomly limiting candidate features helps prevent all trees from becoming identical.

  55. 55

    What is gradient boosting?

    Model answer

    Gradient boosting builds models sequentially, with each new model trained to correct the errors of the models built previously.

    Explanation

    This differs from a random forest, where trees are generally trained independently and then combined.

  56. 56

    How does a gradient boosting model make its initial prediction?

    Model answer

    It initially predicts the average target value for every input in a regression problem.

    Explanation

    It then calculates residuals and trains a small decision tree to predict those residuals.

  57. 57

    What is the role of residuals in gradient boosting?

    Model answer

    Residuals show the remaining errors, and each new tree is trained to reduce those errors.

    Explanation

    Successive trees improve the combined prediction rather than independently learning the entire target relationship.

  58. 58

    What does the learning rate control in gradient boosting?

    Model answer

    The learning rate scales the contribution of each new tree to the overall prediction.

    Explanation

    A smaller learning rate usually requires more trees but can help control overfitting.

  59. 59

    Why is gradient boosting called boosting?

    Model answer

    It is called boosting because each new model improves or boosts the performance of the existing combined model.

    Explanation

    Each successive estimator focuses on correcting the errors remaining from earlier estimators.

  60. 60

    What is K-fold cross-validation?

    Model answer

    K-fold cross-validation divides the training data into KKK parts and repeatedly trains on K−1K-1K−1 parts while validating on the remaining part.

    Explanation

    Each fold serves as the validation set once, allowing performance to be assessed across multiple splits.

  61. 61

    What is ensembling?

    Model answer

    Ensembling combines predictions from multiple models to obtain a potentially more accurate or robust result.

    Explanation

    Predictions may be averaged for regression or combined by voting for classification.

  62. 62

    What is stacking?

    Model answer

    Stacking trains a second model to learn how to combine the predictions of several first-level models.

    Explanation

    The second model can learn suitable weights instead of relying on a simple average.

  63. 63

    What is feature engineering?

    Model answer

    Feature engineering creates or transforms input features so that they represent useful information in a form the model can learn.

    Explanation

    Examples include extracting month from a date, calculating geographic distance, or combining width and length into area.

  64. 64

    Why should dates often be decomposed into components before modeling?

    Model answer

    Components such as year, month, day, weekday, and hour expose recurring temporal patterns that a raw date value may not represent effectively.

    Explanation

    Sales and weather frequently depend on seasonality, weekdays, and time of day.

  65. 65

    Why might a store being closed be handled as a rule rather than learned by a model?

    Model answer

    If closed stores always have zero sales, returning zero directly is simpler and avoids wasting model capacity learning an obvious relationship.

    Explanation

    The model can then focus on predicting sales for days when stores are open.

  66. 66

    Why should input columns related to the target be checked carefully?

    Model answer

    Including the target or information derived from it creates data leakage and produces unrealistically high evaluation scores.

    Explanation

    A model must use only information that would actually be available at prediction time.

  67. 67

    Why can store identifiers be problematic as numerical features?

    Model answer

    A store ID is usually an arbitrary label, so treating it as a number falsely implies that larger IDs have a meaningful numerical relationship with sales.

    Explanation

    Store IDs may need categorical encoding or replacement with meaningful store-level features.

  68. 68

    Why should a validation set resemble future deployment data?

    Model answer

    A representative validation set gives a more reliable estimate of how model decisions and hyperparameters will perform in production.

    Explanation

    Random validation can be inappropriate when future data differs systematically from historical data.

  69. 69

    What factors should be considered when selecting an evaluation metric?

    Model answer

    The metric should reflect the business objective and the relative cost of different prediction errors.

    Explanation

    Accuracy may be suitable in some settings, while precision, recall, RMSE, or percentage error may be more appropriate in others.

  70. 70

    How can individual predictions help improve a model?

    Model answer

    Examining correct, incorrect, and uncertain individual predictions can reveal missing features, data problems, or unintended relationships.

    Explanation

    Aggregate metrics show how much error exists, but individual examples often explain why it exists.

  71. 71

    What is correlation?

    Model answer

    Correlation measures the strength and direction of the relationship between two variables.

    Explanation

    Its value ranges from −1-1−1 to 111; the sign indicates direction and the absolute value indicates strength.

  72. 72

    Why does correlation not establish causation?

    Model answer

    Two variables may correlate because one causes the other, because the direction is reversed, or because a third variable affects both.

    Explanation

    Automated systems that interpret correlation as causation can produce unfair or harmful decisions.

  73. 73

    What is clustering?

    Model answer

    Clustering groups observations so that items within the same group are more similar to one another than to items in other groups.

    Explanation

    It is an unsupervised technique because the groups are discovered without predefined labels.

  74. 74

    How does K-means clustering work?

    Model answer

    K-means chooses KKK cluster centers, assigns each point to its nearest center, recomputes the centers, and repeats until the assignments stabilize.

    Explanation

    The centers are called centroids and are calculated as means of the assigned points.

  75. 75

    What does the value of KKK represent in K-means?

    Model answer

    The value of KKK is the predetermined number of clusters the algorithm should create.

    Explanation

    The number of clusters can be selected using domain knowledge or an elbow plot of inertia.

  76. 76

    What is inertia in K-means clustering?

    Model answer

    Inertia is the total within-cluster variation, often computed as the sum of squared distances from points to their assigned centroids.

    Explanation

    Lower inertia means points are closer to their cluster centers, although increasing KKK generally lowers inertia.

  77. 77

    What is an elbow curve used for in K-means?

    Model answer

    An elbow curve helps choose the number of clusters by plotting inertia against different values of KKK.

    Explanation

    The preferred value is often near the point where additional clusters produce only small reductions in inertia.

  78. 78

    How does DBSCAN differ from K-means?

    Model answer

    DBSCAN forms clusters from dense regions and can identify noise points, whereas K-means assigns points according to distances from a fixed number of centroids.

    Explanation

    DBSCAN does not require the number of clusters to be specified in advance.

  79. 79

    What do epsilon and min_samples control in DBSCAN?

    Model answer

    epsilon defines the neighborhood radius and min_samples defines how many nearby points are needed for a point to be considered a core point.

    Explanation

    Points connected to core points may be reachable points, while isolated points can be labeled as noise.

  80. 80

    What is hierarchical clustering?

    Model answer

    Hierarchical clustering repeatedly joins the closest clusters to build a hierarchy of nested groups.

    Explanation

    The resulting hierarchy is commonly visualized with a dendrogram.

  81. 81

    What is dimensionality reduction?

    Model answer

    Dimensionality reduction transforms data with many features into fewer dimensions while attempting to preserve important information.

    Explanation

    It can reduce computation and make high-dimensional data easier to visualize.

  82. 82

    How does principal component analysis reduce dimensionality?

    Model answer

    PCA finds orthogonal directions, called principal components, that capture as much variance in the data as possible.

    Explanation

    The data is projected onto selected components, such as reducing hundreds of features to a smaller set.

  83. 83

    Why is t-SNE commonly used after PCA for high-dimensional visualization?

    Model answer

    PCA can first reduce a very high-dimensional dataset to a manageable size, after which t-SNE can create a two- or three-dimensional visualization that preserves local neighborhood relationships.

    Explanation

    t-SNE is mainly a visualization method rather than a general-purpose feature transformation for prediction.

  84. 84

    What is the purpose of a model deployment pipeline?

    Model answer

    It makes a trained model available to users or other software so that it can generate predictions on new inputs.

    Explanation

    A deployment may include a web interface, an API, preprocessing logic, and the saved model.

  85. 85

    Why must a new input undergo the same preprocessing used during training?

    Model answer

    The input must be imputed, scaled, encoded, and ordered in the same way so that it matches the representation expected by the trained model.

    Explanation

    Using different preprocessing can produce invalid or misleading predictions.

  86. 86

    What is the purpose of saving preprocessing objects with a trained model?

    Model answer

    Saving imputers, scalers, encoders, column names, and the model ensures that future inputs can be transformed consistently.

    Explanation

    A saved model alone may not be sufficient to reproduce the prediction pipeline.

  87. 87

    What is an API route for a machine learning model?

    Model answer

    An API route is a web endpoint that accepts structured input, passes it through the model, and returns a prediction, often as JSON.

    Explanation

    An API allows other applications to use the model without interacting with its web page directly.

  88. 88

    What is the role of Flask in the deployment example?

    Model answer

    Flask provides the Python web framework used to create routes, render HTML templates, receive form data, and return predictions.

    Explanation

    It connects the model's prediction logic to a browser-based interface or API.

  89. 89

    Why are trained models commonly saved with Joblib?

    Model answer

    Joblib can serialize Python and Scikit-Learn objects so they can be loaded later without retraining.

    Explanation

    A deployment package can store the model together with preprocessing objects and metadata in a saved file.

  90. 90

    What is the difference between a web form and an API in a deployed model?

    Model answer

    A web form is designed for human interaction through a webpage, while an API accepts programmatic requests and returns structured responses.

    Explanation

    Both can invoke the same underlying model prediction function.

  91. 91

    Why should a deployed model be monitored after release?

    Model answer

    Monitoring detects changes in data, prediction quality, usage patterns, and business conditions that may reduce real-world performance.

    Explanation

    Models may need retraining or revision as new data becomes available or the environment changes.

1 of 91
Question 1 of 91

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent