{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "James Andrew Godwin",
  "title_listed": "Ridge, LASSO, and ElasticNet Regression",
  "keywords": "",
  "domain": "机器学习",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/ridge-lasso-and-elasticnet-regression-b1f9c00ea3a3/",
  "publish_date": "2021-04-03",
  "corpus_stage": "",
  "notes": "",
  "id": "0b3419aa6237",
  "collected_at": "2026-10-02T08:36:48",
  "title": "Ridge, LASSO, and ElasticNet Regression | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# Ridge, LASSO, and ElasticNet Regression\nThe continuing adventures of regularization and the eternal quest to prevent model overfitting!\n[James Andrew Godwin](https://towardsdatascience.com/author/james-andrew/)\nApril 2, 202119 min read\n![LASSO, Ridge, and Elasticnet regression | Photo by Daniele Levis Pulusi](../images/000.jpeg)\nLASSO, Ridge, and Elasticnet regression | Photo by [Daniele Levis Pulusi](https://unsplash.com/@yogidan2012)\nThis article is a continuation of last week's intro to [regularization with linear regression](https://towardsdatascience.com/regularization-and-linear-regression-bcaeba547c46). Lettuce yonder back into the nitty-gritty of making the best data science/ machine learning models possible with more advanced techniques on simplifying our models. How do we simplify our models? By removing as many features as possible. Why do I want to do this? I want to have a simpler model. Why do I want a simpler model? Well, because a simpler model generalizes better. What does generalization mean? **It means that you can actually use it in the real world**. The model does not just explain the training data but it also has a better chance of explaining data that we have not seen before.\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n### Regularization\nRegularization seeks to control variance by adding a tuning parameter, lambda, or alpha:\n### LASSO (L1 regularization)\n  * regularization term penalizes absolute value of the coefficients\n  * sets irrelevant values to 0\n  * might remove too many features in your model\n\n\n### Ridge regression (**L2 regularization**)\n  * penalizes the size (square of the magnitude) of the regression coefficients\n  * enforces the _B_ (slope/partial slope) coefficients to be lower, but not 0\n  * does not remove irrelevant features, but minimizes their impact\n\n\nNow do not worry about that lambda. For right now assume lambda is one. For ridge regression, we penalize the size of the regression coefficient. So a larger regression coefficient is a larger penalty.\n![b and c are the regression coefficients](../images/001.png)\nb and c are the regression coefficients\nSo in this ridge regression, I would take the square of **b** and add it to the square of **c**. And that would be my penalty. Now it is slightly more complex than that because sometimes I want to do make the penalty stronger or less strong, I now introduce this lambda, this tuning parameter. So my penalty now becomes:\n![Otherwise known as the L2 or Euclidian norm](../images/002.png)\nOtherwise known as the L2 or Euclidian norm\nSo this is what the Ridge regression does. By adding this penalty to my cost function, during training, it's going to keep these b's and these c's small. And by doing so this is going to simplify the model; that means any given column is not going to have that much power.\nLASSO does pretty much the same thing. Except for the regularization penalty is without the square:\n![Otherwise known as the L1 or Manhattan/taxicab norm](../images/003.png)\nOtherwise known as the L1 or Manhattan/taxicab norm\nPlease take note that because you could have negative values here, so you need to add an absolute value on the coefficients, on the partial slopes.\nThe coefficients b, and c, in the above example, are adjusted by the algorithm you are using. We add another quirk to it by introducing a lambda penalty that is not 1 - it has always been there behind the scenes but we kept it at 1 for simplicity. When it comes time to evaluate the goodness of your model, through the cost function, we are going to multiply a penalty we called lambda to your coefficients (or to the square of your coefficients), and that will be an additional penalty.\nWe still have our general cost function. This is just an addition to that cost function. Our general cost function is always the same and it is the one where we have y - predicted y and take the square of that and sum all those up. So that is our cost function, the baseline. Now, the additional penalty in order to regularize is either this Ridge regression, which uses the so-called L2 norm, or the LASSO (least absolute shrinkage and selection operator) regression, which uses the so-called L1 norm.\nFor both types of regression, a larger coefficient penalizes the model. With Ridge, the penalty is disproportionately larger because of the square, but in general, a larger coefficient reduces model performance, a larger coefficient reduces the goodness of fit.\nN.B: The _**L**_ notation is a reference to Minkowski norms and _**Lp**_ spaces. These just generalize the notion of taxicab and Euclidean distances to _p >0p>0_ in the following expression:\n![For those of you who remember back to Linear Algebra](../images/004.png)\nFor those of you who remember back to Linear Algebra\n### Ridge regression\nReiterating again, Ridge regression is a way to limit the number of independent variables (columns/features/attributes) in the regression. The regular least-squares criterion minimizes the least-squares of the error plus a regularization term that is a product of a constant and the sum of squared coefficients:\n![Ridge regression cost function, expressed another way | alpha is sometimes used instead of lambda in certain literature](../images/005.png)\nRidge regression cost function, expressed another way | alpha is sometimes used instead of lambda in certain literature\nEssentially this is preventing the partial slope terms from getting too large.\nHere I am calling this penalty coefficient alpha as opposed to lambda. And this is a little bit confusing since alpha has a few meanings that are very closely related in this jargon. So just want to warn you, in general, you might have some problems, lambda is a safe bet. Alpha has at least two very closely, but still different meanings.\nHere, we have this beta squared. What is beta? Beta is a vector of your coefficients. So beta is a vector that is basically in my would have been b and c in my previous example. Remember, I had y = a +b _X1 + c_ X2, b and c were two coefficients. Beta is a vector, and here composed of two numbers. In my example, those two numbers are b and c; a is the intercept, sometimes confusingly referred to as b.\nSo beta squared is exactly the same thing as the equation above. What is a partial slope? Another word for partial slope is a coefficient. Why do we call it a partial slope? Well, if you remember, we have a slope when we have a linear regression, y = a + b _X, b is the slope. Well, if you have multiple x's, so y = a + b_ X1 + c _X2 + d_ X3 and so on and so on. Then, in my example, that I just mentioned b, c, and d are all partial slopes, that is because they are multiplied by the columns. And the way the input value from the column changes from those variables change will affect the output. And it will affect it more if that coefficient or that partial slope is greater. When I say greater, I mean in magnitude.\nSo the Ridge objective *_is the residual sum of squares (RSS) +lambda_ (sum of squares of the coefficients)**.\n  * use lambda to balance minimizing RSS vs. minimizing the coefficients\n  * when lambda = 0, results are the same as regular linear regression: you have removed the Ridge regression penalty\n  * as lambda increases to infinity, coefficients become closer to 0\n  * any non-zero lambda value will shrink the coefficients to be smaller than with non-regularized regression\n  * as lambda (alpha) increases, model complexity decreases\n\n\nLambda is just a scalar that should be learned from your data using cross-validation (tuning). So lambda is always positive and is between zero and infinity. And just to give you a basic idea of its range, it is rarely much larger than one, maybe going to two or three, and often is a small fraction of one. Why is that? Well, that is just the way things work out. There exist counterexamples to what I just said, but as a general heuristic, what you generally find is that the lambda is between zero and, and a small value, let us say roughly two.\nIf the model complexity decreases as lambda increases, how can you see this?\n![Our regression lines fit the blue dots well](../images/006.jpeg)\nOur regression lines fit the blue dots well\nIn the example fits above I approximate some form of regression, in this case, probably not a linear regression. And that regression worked pretty well. And then we added the lambda parameter. And hopefully, things got better. If I were to eyeball this here, I would probably want the one on the right. My rationale is, I see these blue dots, they are flying all over the place, they are up and down above and beneath that black line. I expect there to be overall, more variation in where those blue dots can land, a lot of variation. And so I think that trying to find the model that tries to minimize the residuals of these blue dots will try to minimize it too much, what will happen is it will become too complex of a model, it will overfit. And then when new data comes by, data that the model has never seen, that new data is not going to be there where this model is fitting.\n![The red circle is likely overfitting the residuals](../images/007.jpeg)\nThe red circle is likely overfitting the residuals\nSo for instance, this little quirk circled in red, looks pretty good. But my guess is that is just because one or two data points had these high y values relatively - high y values. Methinks that was just a quirk. Probably this should just go straight over, as it does on the right-most image. Because if I look at how much overall these blue points are going up and down, I cannot really justify creating a model that is trying to go down to catch to minimize the residual of this one bluepoint and then going right back up. As such, the small lambda value is likely overfitting and I believe that the 1/100 lambda value on the right actually fits the data much better and will generalize better.\n### LASSO\nLASSO regression does pretty much the same thing; it is another way to limit the number of independent variables in the regression. The only difference is, it uses the absolute value. Now the thing is that because of the math, what it does is not just reduce the coefficients, LASSO actually removes the coefficients. Many people like LASSO for this reason: **the coefficients can actually go to zero, whereas in the Ridge regression, they do not go to zero, they become small, but they never vanish**.\nNow, you can always help the last way, if you see that coefficient has gotten really small, you can just say, \"Okay, I'm going to just toss this column, because it has such a small coefficient.\" What is nice about LASSO is that it will actually do that for you in an intelligent way.\n![y is the predicted for j points, there are i terms with beta coefficients - lambda limits the betas](../images/008.png)\ny is the predicted for j points, there are i terms with beta coefficients - lambda limits the betas\nBeta a vector of your coefficients. Instead of squaring them, you just take the absolute value.\n### Linear algebra\nNext is a quick review of linear algebra. Why do we have a quick review of linear algebra? Well, because machine learning is a lot of linear algebra and the more you understand about the machine learning algorithms, the often the better you can apply them. **When studying data science, you are not studying machine learning, you are studying how to use the machine learning algorithms**.\nAlgebraic properties of matrices:\n  * add/subtract matrices: must be of the same dimensions (m * n)\n  * for multiplication of matrices: inner dimensions must match\n  * remember that matrix multiplication is not commutative: A x B != B x A\n  * a matrix multiplied by its inverse yields the identity matrix\n  * matrix division is not defined\n\n\n### Linear regression with matrices\nConsider the linear regression formula:\n![](../images/body-a7bd2dfef727e9182a24.png)\nwritten as a matrix:\n![](../images/body-ca5691c55bd1fa4716df.png)\nwhich can be rewritten as:\n![](../images/body-31dfd96ad466661f5262.png)\nFor linear regression with matrices, if you have, say 10 cases, that means 10 points and you will have 10 columns, then there will be an exact, best solution. There will be a simple solution to that. However, not in every case, there are cases where you have colinearity, which means when one column is basically the same as another column or the same as a combination of some other columns. When this occurs you generally have infinitely many solutions. And we do not like this because having infinitely many solutions, means you do not have any useful solutions. If then there are situations where there is simply no solution can occur. But the general case or the case that you hope for is that you have exactly one good solution.\nMost of the time, when we do machine learning, or data science is we have many more cases than we have variables; we have many more data points than we have columns; we have many more rows than we have columns - I am just repeating the same thing over and over with slightly different words. This is going to cause us an issue, for one thing, that means our matrix of x is not a square matrix.\nSo when we want to invert it, and I will show you that we will want to do that, it is going to cause us some problems, along with colinearity and stuff like that.\n![Succinctly: y = X * Beta + Epsion](../images/009.png)\nSuccinctly: y = X * Beta + Epsion\nThese concepts are best demonstrated in code.\n## Python example: Singular value decomposition\n[Previously](https://towardsdatascience.com/regularization-and-linear-regression-bcaeba547c46), I mentioned stepwise regression as a way to regularize, by finding meaningful features one at a time, either by the forward or backward methodology. I now introduce singular value decomposition (SVD) as another meaningful way to find features.\nRegularization methods stabilize the inverse of the **model matrix**. We will use the SVD method to stabilize a model matrix.\nN.B: Stepwise regression is a computationally-intensive process since we must recompute the model many times. There are methods that allow computation of the updated model, but with a large number of features, there are numerous permutations. We need methods that can handle hundreds, thousands, or even millions of features. Consider a small data set with only 20 features. The amount of possible linear models with NO interaction terms is given by:\n![](../images/body-b9ea7f374412afbb2f72.png)\nWhich is the sum of the 21st row of Pascal's triangle. This comes out to be:\n![](../images/body-a5cfc35313dd5c2ce048.png)\nAlthough according to our algorithm, this would be the maximum number of models to compute, you can see how computationally hard this becomes when naively considering stepwise regression.\nIn order to understand the motivation and methods of feature selection/transformation, I will review some linear algebra.\n### Linear algebra review\ntext\n\n```\nimport numpy as np\n```\n\ntext\n\n```\na_list = [2]*3\nprint(a_list)\nprint(type(a_list))\na = np.array([2]*3)\nprint(a)\nprint(type(a))\nb = np.arange(1, 4)\nprint(b)\nprint(type(b))\n```\n\n![Jupyter displays lists and arrays similarly](../images/010.png)\nJupyter displays lists and arrays similarly\nMatrix multiplication and addition\ntext\n\n```\na2d = np.array([[2]*3, [3]*3])\nprint('a: n{} n a-size: {}'.format(a2d, a2d.shape))\nb2d = np.reshape(np.arange(1,7), newshape=(2, 3))\nprint('nb: n{} n b-size: {}'.format(b2d, b2d.shape))\n```\n\ntext\n\n```\n# Addition\nprint('nAddition: n {}'.format(a2d + b2d))\n# Multiplication\nprint('nMultiplication: n {}'.format(a2d * b2d))\n```\n\n![](../images/body-bdbfe3eed3e2e4fc4fa9.png)\n### Matrix transposition\nWe can also transpose a two-dimensional matrix by flipping the rows and columns. We use the `numpy` method `np.transpose`.\ntext\n\n```\nprint('Try transposing on a vector...')\nprint(np.transpose(a))\n# Transposition on a vector does not work\n```\n\ntext\n\n```\nprint('Now reshape a into 2D and then transpose:')\nprint(np.transpose(np.reshape(a, newshape=(1,3))))\nprint('Now transpose a 2d matrix:')\nprint(np.transpose(a2d))\n```\n\n![](../images/body-a15f6a8a8e324ffc0b7b.png)\n### Matrix dot product\nWe need to know how to compute the **dot product** , which is also known as the **scalar product** or **inner product** of two vectors of equal length, via element-wise multiplication then summing them all up:\n![](../images/body-d46f15701840a3211108.png)\ntext\n\n```\nprint('np.dot(a, b) = np.dot({}, {})'.format(a, b))\nnp.dot(a, b)\n```\n\n![](../images/body-c45e108713cc72fa250c.png)\nThe square root of the inner product of a vector with itself is the length or L2 norm of the vector:\n![](../images/body-8ae76dc316d847a04b9e.png)\nWe can also write the inner product as:\n![](../images/body-6cd41f7c9551d576e45c.png)\n![](../images/body-f2db9025dec6e67b1f2d.png)\n![Notice that the inner product of orthogonal vectors is 0](../images/011.png)\nNotice that the inner product of orthogonal vectors is 0\ntext\n\n```\naa = np.array([1, 0, 0])\nbb = np.array([0, 1, 1])\nprint(inner_prod(aa, bb))\n```\n\n![Linearly independent vectors are completely orthogonal](../images/012.png)\nLinearly independent vectors are completely orthogonal\nHere are some operations on matrices. Let A and B be m=4 rows by n=3 columns matrices:\ntext\n\n```\nA = np.array([[4]*3]*4) \nprint(A)\nB = np.array(np.reshape(np.arange(1, 13), newshape = (4, 3)))\nprint(B)\nC = np.array(np.reshape(np.arange(1, 9), newshape = (4, 2)))\nprint(C)\nnp.dot(np.transpose(A), C)\n```\n\n![](../images/body-a92f8fc1a892a4babcda.png)\n### Identity matrix\nThis special, square matrix has ones on the diagonal and zeros elsewhere:\n![The matrix equivalent of 1](../images/013.png)\nThe matrix equivalent of 1\nThe identity multiplied by any matrix gives that matrix. If AB is a rectangular matrix then:\n![](../images/body-9df8435236349b79b1c7.png)\nIn `numpy` the Identity matrix is called `np.eye` and takes as an argument the number of rows/columns:\ntext\n\n```\nI3 = np.eye(3)\nI4 = np.eye(4)\n```\n\ntext\n\n```\nprint('I (3X3) = n{}'.format(I3))\nprint(np.dot(I3, AtB))\n```\n\ntext\n\n```\nprint('I (4x4) = n{}'.format(I4))\nprint(np.dot(I4, ABt))\n```\n\n![](../images/body-3c97e3f18484642e037e.png)\n## Inverse of a matrix\nDefine and compute an inverse of a matrix such that:\n![](../images/body-30d864598b59893036cd.png)\n![](../images/body-3a25d05976c8fb4d3588.png)\n![](../images/body-84580fb7c87824aaa17e.png)\nUse the Linear Algebra methods in `numpy` to get the inverse of matrix M with `np.linalg.inv`\ntext\n\n```\nM = np.array([[1., 4.], [-3., 2.]])\nM_inverse = np.linalg.inv(M)\n```\n\ntext\n\n```\nprint('M: n{}'.format(M))\nprint('nM_inv = n{}'.format(M_inverse))\nprint('nM_inv * M = n{}'.format(np.dot(M_inverse, M)))\nprint('nM * M_inv = n{}'.format(np.dot(M, M_inverse)))\n```\n\n![](../images/body-ef17faa798105196e6aa.png)\nWith this brief refresher aside, we can now jump into regularizing models with SVD.\n## Singular Value Decomposition\nIn machine learning, we often encounter matrices that cannot be inverted directly. Instead, we need a decomposition of A that allows us to compute A^−1, which we can do with SVD:\n![](../images/body-4dca5bded34d9d47ee6d.png)\n  * U is the orthogonal unit norm left singular vectors\n  * V is the orthogonal unit norm right singular vectors, and V∗ is the conjugate transpose; for real-valued A this is just VT\n  * D is a diagonal matrix of singular values, which are said to define a **spectrum**\n  * A is comprised of the linear combination of singular vectors scaled by singular values\n\n\nTo compute the SVD of a matrix and view the results execute the code in the cell below. We use the `numpy` method called `np.linalg.svd` using `s` for the singular values:\ntext\n\n```\nU, s, V = np.linalg.svd(B, full_matrices=False)\nprint('B: {}'.format(B)) # ESHx\nprint('U: {}'.format(U))\nprint('s: {}'.format(s))\nprint('V: {}'.format(V))\n```\n\n![](../images/body-bbcd7baf799a78d5e13c.png)\n## Regularization with Ridge and Lasso Regression\nSo far, we have looked at two approaches for dealing with over-parameterized models; feature selection by stepwise regression and singular value decomposition. In this section, we will explore the most widely used regularization method for optimization-based machine learning models, **Ridge regression**.\nLet's start by examining the matrix-equation formulation of the linear regression problem. The goal is to compute a vector of **model coefficients** or weights which minimize the mean squared residuals, given a vector of data 𝑥x and a m**odel matrix** A. We can express our model as:\n![](../images/body-85bde8f81651104d3bd6.png)\nExecute the code in the cell below which computes the (𝐴^𝑇 _𝐴+𝜆²)^-1_ A^T matrix with a lambda value of 0.1``\ntext\n\n```\nU, s, V = np.linalg.svd(M, full_matrices=False)\n```\n\ntext\n\n```\n# Calculate the inverse singular value matrix from SVD\nlambda_val = 1.0\nd = np.diag(1. / (s + lambda_val))\n```\n\ntext\n\n```\nprint('Inverse Singular Value Matrix:')\nprint(d)\n```\n\ntext\n\n```\n# Compute pseudo-inverse\nmInv = np.dot(np.transpose(V), np.dot(d, np.transpose(U)))\n```\n\ntext\n\n```\nprint('M Inverse')\nprint(mInv)\n```\n\n![](../images/body-9e62d84e36ee7ffbc523.png)\n### Bias-variance trade-off\nThe bias-variance trade-off is a fundamental property of machine learning models. To understand this trade-off let's decompose the mean square error for a model as follows:\n![](../images/body-0126ac7c6813c0359448.png)\nRegularization will reduce variance, but increases bias. Regularization parameters are chosen to minimize delta_X. In many cases, this process proves challenging, involving significant time-consuming trial and error.\nThe **irreducible error** is the limit of model accuracy. Even if you had a perfect model with no bias or variance, the irreducible error is inherent in the data and model. You cannot do better.\nThe `statsmodels` package allows us to compute a sequence of Ridge regression solutions. The function that does this uses a method called 'Elasticnet', know that ridge regression is a specific case of elastic-net, and I will talk more about this later.\n**N.B: This is a continuation of my previous work on the Galton family dataset.**\nThe code in the cell below computes solutions for 20 values of lambda:\ntext\n\n```\n# Ridge regression with various penalties in Statsmodels\n# sequence of lambdas\nlog_lambda_seq = np.linspace(-6, 2, 50)\nlambda_seq = np.exp(log_lambda_seq)\n```\n\ntext\n\n```\ncoeffs_array = []\nrsq_array = []\nformula = 'childHeight ~ mother + father + mother_sqr + father_sqr + 1'\n```\n\ntext\n\n```\nfor lamb in lambda_seq:\n ridge_model = sm.ols(formula, data=male_df).fit_regularized(method='elastic_net', alpha=lamb, L1_wt=0)\n coeffs_array.append(list(ridge_model.params))\n predictions = ridge_model.fittedvalues\n residuals = [x - y for x, y in zip(np.squeeze(predictions), childHeight)]\n```\n\ntext\n\n```\nSSR = np.sum(np.square(residuals))\n SST = np.sum(np.square(childHeight - np.mean(childHeight)))\n```\n\ntext\n\n```\nrsq = 1 - (SSR / SST) \n rsq_array.append(rsq)\n```\n\ntext\n\n```\n# pull out partial slopes (drop intercept version)\nbeta_coeffs = [x[1:] for x in coeffs_array]\nplt.plot(log_lambda_seq, beta_coeffs)\nplt.title('Partial Slopes vs Log-Lambda')\nplt.ylabel('Partial Slope Values')\nplt.xlabel('Log-Lambda')\nplt.show()\n```\n\n![](../images/body-2640d92894bb36831cfe.png)\nPlot partial slopes vs R²:\ntext\n\n```\n# % deviance explained\nplt.plot(rsq_array, beta_coeffs)\nplt.xlim([0.0, 0.25])\nplt.title('Partial Slopes vs Log-Lambda')\nplt.xlabel('R-squared')\nplt.ylabel('Partial Slopes')\nplt.show()\n```\n\n![](../images/body-6070fdfcd373b532b8a8.png)\nNotice that as lambda increases, the values of the 4 model coefficients decrease toward zero. When all coefficients are zero, the model predicts all values of the label as zero! In other words, high values of lambda give highly biased solutions, but with very low variance.\nFor small values of lambda, the situation is just the opposite. The solution has a low bias, but is quite unstable, having maximum variance. This **bias-variance trade-off** is a key concept in machine learning.\n## LASSO regression\nWe can also do regularization using other norms. LASSO or L1 regularization limits the sum of the absolute values of the model coefficients. The L1 norm is sometimes known as the Manhattan norm since distances are measured as if you were traveling on a rectangular grid of streets.\nYou can also think of LASSO regression as limiting the L1 norm of the values of the model coefficient vector. The value of lambda determines how much the norm of the coefficient vector constrains the solution.\nPerforming the same calculations as before, but with a different regularization norm and associated penalty:\ntext\n\n```\n# LASSO regression with a sequence of lambdas\n# sequence of lambdas\nlog_lambda_seq = np.linspace(-6, 2, 50)\nlambda_seq = np.exp(log_lambda_seq)\n```\n\ntext\n\n```\ncoeffs_array = []\nrsq_array = []\nformula = 'childHeight ~ mother + father + mother_sqr + father_sqr + 1'\n```\n\ntext\n\n```\nfor lamb in lambda_seq:\n ridge_model = sm.ols(formula, data=male_df).fit_regularized(method='elastic_net', alpha=lamb, L1_wt=1)\n coeffs_array.append(list(ridge_model.params))\n predictions = ridge_model.fittedvalues\n residuals = [x - y for x, y in zip(np.squeeze(predictions), childHeight)]\n```\n\ntext\n\n```\nSSR = np.sum(np.square(residuals))\n SST = np.sum(np.square(childHeight - np.mean(childHeight)))\n```\n\ntext\n\n```\nrsq = 1 - (SSR / SST)\n rsq_array.append(rsq)\n```\n\ntext\n\n```\n# drop intercept version\nbeta_coeffs = [x[1:] for x in coeffs_array]\nplt.plot(log_lambda_seq, beta_coeffs)\nplt.title('Partial Slopes vs Log-Lambda')\nplt.ylabel('Partial Slope Values')\nplt.xlabel('Log-Lambda')\nplt.show()\n```\n\n![](../images/body-5ee6f40bd322a2235a05.png)\ntext\n\n```\n# plot partial slopes vs R squared (% deviance explained)\nplt.plot(rsq_array, beta_coeffs)\nplt.xlim([0.0, 0.25])\nplt.title('Partial Slopes vs Log-Lambda')\nplt.xlabel('R-squared')\nplt.ylabel('Partial Slopes')\nplt.show()\n```\n\n![](../images/body-b6c7c8fa801829b995de.png)\nNotice that model coefficients are much more tightly constrained than for L2 regularization. In fact, only two of the possible model coefficients have non-zero values at all! This is typical of L1 or LASSO regression.\n## Elastic Net regression\nThe **elastic net** algorithm uses a weighted combination of L1 and L2 regularization. As you can probably see, the same function is used for LASSO and Ridge regression with only the `L1_wt` argument changing. This argument determines how much weight goes to the L1-norm of the partial slopes. If the regularization is pure L2 (Ridge) and if `L1_wt = 1.0` the regularization is pure L1 (LASSO).\nThe code in the cell below gives equal weight to each regression method. Execute this code and examine the results:\ntext\n\n```\n# ElasticNet Regression with a sequence of lambdas\n# sequence of lambdas\nlog_lambda_seq = np.linspace(-6, 0, 50)\nlambda_seq = np.exp(log_lambda_seq)\n```\n\ntext\n\n```\ncoeffs_array = []\nrsq_array = []\nformula = 'childHeight ~ mother + father + mother_sqr + father_sqr + 1'\n```\n\ntext\n\n```\nfor lamb in lambda_seq:\n ridge_model = sm.ols(formula, data=male_df).fit_regularized(method='elastic_net', alpha=lamb, L1_wt=0.75)\n coeffs_array.append(list(ridge_model.params))\n predictions = ridge_model.fittedvalues\n residuals = [x - y for x, y in zip(np.squeeze(predictions), childHeight)]\n```\n\ntext\n\n```\nSSR = np.sum(np.square(residuals))\n SST = np.sum(np.square(childHeight - np.mean(childHeight)))\n```\n\ntext\n\n```\nrsq = 1 - (SSR / SST)\n rsq_array.append(rsq)\n```\n\ntext\n\n```\n# pull out partial slopes (drop intercept version)\nbeta_coeffs = [x[1:] for x in coeffs_array]\nplt.plot(log_lambda_seq, beta_coeffs)\nplt.title('Partial Slopes vs Log-Lambda')\nplt.ylabel('Partial Slope Values')\nplt.xlabel('Log-Lambda')\nplt.show()\n```\n\n![](../images/body-2f9b39d8a5f2f1be63f0.png)\ntext\n\n```\n# plot partial slopes vs R squared (% deviance explained)\nplt.plot(rsq_array, beta_coeffs)\nplt.xlim([0.0, 0.25])\nplt.title('Partial Slopes vs Log-Lambda')\nplt.xlabel('R-squared')\nplt.ylabel('Partial Slopes')\nplt.show()\n```\n\n![](../images/body-4635e4a67cb13009bc15.png)\nNotice that the elastic net model combines some of the behaviors of both L2 and L1 regularization.\n## Conclusion\nIn this article and last week's I looked at 3 methods as a solution to the problem of overfitting models:\n  * Stepwise Regression to eliminate features one at a time\n  * Singular Value Decomposition to find meaningful features\n  * Lasso, Ridge, and ElasticNet Regularization to stabilize over-parameterized models\n\n\nImportant terms include:\n  * AIC - the model log-likelihood adjusted for the number of model parameters\n  * Deviance - a measure of the relative likelihood of the model (a generalization of variance)\n  * SVD - Singular Value Decomposition describes a matrix as a linear combination of a series of vectors U, V, D\n  * Singular values s - the diagonal matrix of singular values used as a scaling term\n  * Lambda - a small bias term added to singular values to stabilize the inverse singular value matrix\n  * PCA - Principal Component Analysis to determine what new features can be made from linear combinations that are independent of each other by using functions and the SVD\n  * PCR - Principal Component Regression uses the PCA to perform a \"regularized\" regression\n  * L1 regularization - LASSO regularization using the \"Manhattan\" norm\n  * L2 Norm regularization - Ridge regularization limiting the \"Euclidean\" norm of values of the model coefficient vector\n  * ElasticNet algorithm - a weighted combination of L1 and L2 regularization\n\n\nAnd I briefly reviewed linear algebra operations:\n  * Adding vectors and matrices\n  * Multiplying vectors and matrices\n  * Transposing matrices with `np.transpose`\n  * Dot product or scalar product or inner product with `np.dot`\n  * L2 norm of a vector\n  * Identity matrix with `np.eye`\n  * Inverse of a matrix with `np.linalg.inv`\n  * Singular value decomposition with `np.linalg.svd`\n  * Creating a diagonal matrix with `np.diag`\n\n\nUp to now, I have been working strictly with linear regression models. Next, I will look at a widely used variation on the linear model know as [**logistic regression**](https://towardsdatascience.com/logistic-regression-cebee0728cbf)**!**\nFind me on [Linkedin](https://www.linkedin.com/in/james-a-w-godwin/)\n_Physicist cum Data Scientist- Available for new opportunity | SaaS | Sports | Start-ups | Scale-ups_\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-92fdfcb3140ff02db487.jpeg)\nWritten By\n## [James Andrew Godwin](https://towardsdatascience.com/author/james-andrew/)\n[See all from James Andrew Godwin](https://towardsdatascience.com/author/james-andrew/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Python](https://towardsdatascience.com/tag/python/)[Regression Analysis](https://towardsdatascience.com/tag/regression-analysis/)[Towards Data Science](https://towardsdatascience.com/tag/towards-data-science/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fridge-lasso-and-elasticnet-regression-b1f9c00ea3a3%2F&title=Ridge%2C%20LASSO%2C%20and%20ElasticNet%20Regression)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fridge-lasso-and-elasticnet-regression-b1f9c00ea3a3%2F&title=Ridge%2C%20LASSO%2C%20and%20ElasticNet%20Regression)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fridge-lasso-and-elasticnet-regression-b1f9c00ea3a3%2F&text=Ridge%2C%20LASSO%2C%20and%20ElasticNet%20Regression)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/014.jpg)](https://towardsdatascience.com/a-survival-analysis-guide-with-python-using-time-to-event-models-to-forecast-customer-lifetime/)\n## [A Survival Analysis Guide with Python: Using Time-To-Event Models to Forecast Customer Lifetime](https://towardsdatascience.com/a-survival-analysis-guide-with-python-using-time-to-event-models-to-forecast-customer-lifetime/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nHow to calculate time-to-event probabilities and hazard rates for telecommunications subscribers.\n[Gustavo Santos](https://towardsdatascience.com/author/gustavorsantos/)\nApril 9, 202611 min read\n  * [![](../images/015.png)](https://towardsdatascience.com/matchy-matchy-object-detection-using-template-matching-in-python-3b2bdfa6e250/)\n## [Matchy matchy! Object detection using Template Matching in Python](https://towardsdatascience.com/matchy-matchy-object-detection-using-template-matching-in-python-3b2bdfa6e250/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nWe discussed object detection on my previous article so this time around I'll be showing another example of how to identify objects...\n[Nico Aguila](https://towardsdatascience.com/author/nico-aguila/)\nJanuary 30, 20213 min read\n  * [![](../images/016.gif)](https://towardsdatascience.com/conformal-prediction-in-julia-351b81309e30/)\n## [Conformal Prediction in Julia 🟣🔴🟢](https://towardsdatascience.com/conformal-prediction-in-julia-351b81309e30/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nPart 1 - Introduction\n[Patrick Altmeyer](https://towardsdatascience.com/author/patrick.altmeyer/)\nOctober 24, 20225 min read\n  * [![](../images/017.jpeg)](https://towardsdatascience.com/three-mysterious-behaviours-of-python-95c9dffa88fe/)\n## [Three Mysterious Behaviours of Python](https://towardsdatascience.com/three-mysterious-behaviours-of-python-95c9dffa88fe/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThe unexpected running outcomes for Dictionary, Try Except and For-Loop\n[Christopher Tao](https://towardsdatascience.com/author/christophertao/)\nSeptember 12, 20216 min read\n  * [![](../images/018.jpeg)](https://towardsdatascience.com/bar-plots-best-practices-and-issues-30f1ad32c68f/)\n## [Bar Plots: Best Practices and Issues](https://towardsdatascience.com/bar-plots-best-practices-and-issues-30f1ad32c68f/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nHow to create an insightful graph\n[Elena Kosourova](https://towardsdatascience.com/author/elena-kosourova/)\nMarch 27, 202113 min read\n  * [![](../images/019.jpg)](https://towardsdatascience.com/data-wrangling-solutions-working-with-dates-part-3-b8b5caccc4ed/)\n## [Data Wrangling Solutions - Working With Dates - Part 3](https://towardsdatascience.com/data-wrangling-solutions-working-with-dates-part-3-b8b5caccc4ed/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nExtract information from columns containing DateTime data. In the last two tutorials, we went from...\n[Ujjwal Dalmia](https://towardsdatascience.com/author/ujjwal-dalmia/)\nMay 7, 20214 min read\n  * [![](../images/020.jpeg)](https://towardsdatascience.com/how-i-deployed-my-first-machine-learning-model-1147c04c449b/)\n## [How I deployed my first machine learning model](https://towardsdatascience.com/how-i-deployed-my-first-machine-learning-model-1147c04c449b/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nProcesses and tools I used to deliver my first commercial machine learning model\n[Artur Lunardi Di Fante](https://towardsdatascience.com/author/arturlunardi/)\nDecember 15, 202112 min read\n  * [![](../images/body-63beb50f664a055ed739.jpg)](https://towardsdatascience.com/how-to-learn-to-solve-data-science-problems-like-a-pro-and-become-employable-b3fd2f4bec71/)\n## [How To Learn To Solve Data Science Problems Like a Pro and Become Employable](https://towardsdatascience.com/how-to-learn-to-solve-data-science-problems-like-a-pro-and-become-employable-b3fd2f4bec71/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThe most practical way to learn data science (Includes best-in-class references)\n[Sharan Kumar Ravindran](https://towardsdatascience.com/author/rsharankumar/)\nNovember 3, 202110 min read\n  * [![](../images/022.png)](https://towardsdatascience.com/serverless-ml-is-this-the-cheapest-way-to-host-machine-learning-models-on-aws-83ba3dee8be4/)\n## [Serverless ML. Is this the cheapest way to host Machine Learning models on AWS?](https://towardsdatascience.com/serverless-ml-is-this-the-cheapest-way-to-host-machine-learning-models-on-aws-83ba3dee8be4/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nI'm hosting my Resnet-152 (152 layer CNN) model on AWS for pretty much free right now. Does it scale? What's the trade-offs?\n[Phil Whelan](https://towardsdatascience.com/author/philwhln/)\nMarch 17, 20218 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "metadata": {
    "title": "Ridge, LASSO, and ElasticNet Regression | Towards Data Science",
    "description": "The continuing adventures of regularization and the eternal quest to prevent model overfitting!",
    "keywords": null,
    "author": "James Andrew Godwin",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Ridge, LASSO, and ElasticNet Regression",
    "og:description": "The continuing adventures of regularization and the eternal quest to prevent model overfitting!",
    "og:url": "https://towardsdatascience.com/ridge-lasso-and-elasticnet-regression-b1f9c00ea3a3/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/10_N5bV721QeYcTKF4X1Njw.jpeg",
    "og:image:width": "640",
    "og:image:height": "405",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "James Andrew Godwin",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "19 min read",
    "article:published_time": "2021-04-02T20:18:53.000Z",
    "article:modified_time": "2021-04-02T20:18:53.000Z",
    "article:author": "https://towardsdatascience.com/author/james-andrew/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_000.txt",
      "chars": 19
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_001.txt",
      "chars": 137
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_002.txt",
      "chars": 186
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_003.txt",
      "chars": 120
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_004.txt",
      "chars": 105
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_005.txt",
      "chars": 163
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_006.txt",
      "chars": 65
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_007.txt",
      "chars": 76
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_008.txt",
      "chars": 202
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_009.txt",
      "chars": 30
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_010.txt",
      "chars": 57
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_011.txt",
      "chars": 57
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_012.txt",
      "chars": 65
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_013.txt",
      "chars": 176
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_014.txt",
      "chars": 155
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_015.txt",
      "chars": 48
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_016.txt",
      "chars": 107
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_017.txt",
      "chars": 49
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_018.txt",
      "chars": 84
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_019.txt",
      "chars": 31
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_020.txt",
      "chars": 155
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_021.txt",
      "chars": 105
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_022.txt",
      "chars": 290
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_023.txt",
      "chars": 96
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_024.txt",
      "chars": 46
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_025.txt",
      "chars": 246
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_026.txt",
      "chars": 184
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_027.txt",
      "chars": 144
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_028.txt",
      "chars": 105
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_029.txt",
      "chars": 290
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_030.txt",
      "chars": 96
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_031.txt",
      "chars": 45
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_032.txt",
      "chars": 220
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_033.txt",
      "chars": 219
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_034.txt",
      "chars": 149
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_035.txt",
      "chars": 105
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_036.txt",
      "chars": 293
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_037.txt",
      "chars": 96
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_038.txt",
      "chars": 45
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_039.txt",
      "chars": 246
    },
    {
      "language": "txt",
      "file": "attachments/0b3419aa6237/code/block_040.txt",
      "chars": 219
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:59:52Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:59:52Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:59:52Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:59:52Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/james-andrew/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/regularization-and-linear-regression-bcaeba547c46"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/logistic-regression-cebee0728cbf"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/python/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/regression-analysis/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/towards-data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/a-survival-analysis-guide-with-python-using-time-to-event-models-to-forecast-customer-lifetime/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/gustavorsantos/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/matchy-matchy-object-detection-using-template-matching-in-python-3b2bdfa6e250/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/nico-aguila/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/conformal-prediction-in-julia-351b81309e30/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://unsplash.com/@yogidan2012"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-data-scientist"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/in/james-a-w-godwin/"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Ridge%2C+LASSO%2C+and+ElasticNet+Regression&u=https%3A%2F%2Ftowardsdatascience.com%2Fridge-lasso-and-elasticnet-regression-b1f9c00ea3a3%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Ridge%2C+LASSO%2C+and+ElasticNet+Regression&url=https%3A%2F%2Ftowardsdatascience.com%2Fridge-lasso-and-elasticnet-regression-b1f9c00ea3a3%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=Ridge%2C+LASSO%2C+and+ElasticNet+Regression&url=https%3A%2F%2Ftowardsdatascience.com%2Fridge-lasso-and-elasticnet-regression-b1f9c00ea3a3%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    },
    {
      "type": "external",
      "href": "https://insightmediagroup.io/creator-network"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:30:11Z",
  "source_url": "https://towardsdatascience.com/ridge-lasso-and-elasticnet-regression-b1f9c00ea3a3/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# Ridge, LASSO, and ElasticNet Regression\nThe continuing adventures of regularization and the eternal quest to prevent model overfitting!\n[James Andrew Godwin](https://towardsdatascience.com/author/james-andrew/)\nApril 2, 202119 min read\n![LASSO, Ridge, and Elasticnet regression | Photo by Daniele Levis Pulusi](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/10_N5bV721QeYcTKF4X1Njw.jpeg)\nLASSO, Ridge, and Elasticnet regression | Photo by [Daniele Levis Pulusi](https://unsplash.com/@yogidan2012)\nThis article is a continuation of last week's intro to [regularization with linear regression](https://towardsdatascience.com/regularization-and-linear-regression-bcaeba547c46). Lettuce yonder back into the nitty-gritty of making the best data science/ machine learning models possible with more advanced techniques on simplifying our models. How do we simplify our models? By removing as many features as possible. Why do I want to do this? I want to have a simpler model. Why do I want a simpler model? Well, because a simpler model generalizes better. What does generalization mean? **It means that you can actually use it in the real world**. The model does not just explain the training data but it also has a better chance of explaining data that we have not seen before.\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n### Regularization\nRegularization seeks to control variance by adding a tuning parameter, lambda, or alpha:\n### LASSO (L1 regularization)\n  * regularization term penalizes absolute value of the coefficients\n  * sets irrelevant values to 0\n  * might remove too many features in your model\n\n\n### Ridge regression (**L2 regularization**)\n  * penalizes the size (square of the magnitude) of the regression coefficients\n  * enforces the _B_ (slope/partial slope) coefficients to be lower, but not 0\n  * does not remove irrelevant features, but minimizes their impact\n\n\nNow do not worry about that lambda. For right now assume lambda is one. For ridge regression, we penalize the size of the regression coefficient. So a larger regression coefficient is a larger penalty.\n![b and c are the regression coefficients](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0uK4qRdiVxlzszBFf.png)\nb and c are the regression coefficients\nSo in this ridge regression, I would take the square of **b** and add it to the square of **c**. And that would be my penalty. Now it is slightly more complex than that because sometimes I want to do make the penalty stronger or less strong, I now introduce this lambda, this tuning parameter. So my penalty now becomes:\n![Otherwise known as the L2 or Euclidian norm](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0X_ha1fCNxGYOXXqu.png)\nOtherwise known as the L2 or Euclidian norm\nSo this is what the Ridge regression does. By adding this penalty to my cost function, during training, it's going to keep these b's and these c's small. And by doing so this is going to simplify the model; that means any given column is not going to have that much power.\nLASSO does pretty much the same thing. Except for the regularization penalty is without the square:\n![Otherwise known as the L1 or Manhattan/taxicab norm](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0KwVfRWXAu2Dgdfp9.png)\nOtherwise known as the L1 or Manhattan/taxicab norm\nPlease take note that because you could have negative values here, so you need to add an absolute value on the coefficients, on the partial slopes.\nThe coefficients b, and c, in the above example, are adjusted by the algorithm you are using. We add another quirk to it by introducing a lambda penalty that is not 1 - it has always been there behind the scenes but we kept it at 1 for simplicity. When it comes time to evaluate the goodness of your model, through the cost function, we are going to multiply a penalty we called lambda to your coefficients (or to the square of your coefficients), and that will be an additional penalty.\nWe still have our general cost function. This is just an addition to that cost function. Our general cost function is always the same and it is the one where we have y - predicted y and take the square of that and sum all those up. So that is our cost function, the baseline. Now, the additional penalty in order to regularize is either this Ridge regression, which uses the so-called L2 norm, or the LASSO (least absolute shrinkage and selection operator) regression, which uses the so-called L1 norm.\nFor both types of regression, a larger coefficient penalizes the model. With Ridge, the penalty is disproportionately larger because of the square, but in general, a larger coefficient reduces model performance, a larger coefficient reduces the goodness of fit.\nN.B: The _**L**_ notation is a reference to Minkowski norms and _**Lp**_ spaces. These just generalize the notion of taxicab and Euclidean distances to _p >0p>0_ in the following expression:\n![For those of you who remember back to Linear Algebra](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0jxt0lMsMKyqQ5tLg.png)\nFor those of you who remember back to Linear Algebra\n### Ridge regression\nReiterating again, Ridge regression is a way to limit the number of independent variables (columns/features/attributes) in the regression. The regular least-squares criterion minimizes the least-squares of the error plus a regularization term that is a product of a constant and the sum of squared coefficients:\n![Ridge regression cost function, expressed another way | alpha is sometimes used instead of lambda in certain literature](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0JIXBmlxn_0VPPK4t.png)\nRidge regression cost function, expressed another way | alpha is sometimes used instead of lambda in certain literature\nEssentially this is preventing the partial slope terms from getting too large.\nHere I am calling this penalty coefficient alpha as opposed to lambda. And this is a little bit confusing since alpha has a few meanings that are very closely related in this jargon. So just want to warn you, in general, you might have some problems, lambda is a safe bet. Alpha has at least two very closely, but still different meanings.\nHere, we have this beta squared. What is beta? Beta is a vector of your coefficients. So beta is a vector that is basically in my would have been b and c in my previous example. Remember, I had y = a +b _X1 + c_ X2, b and c were two coefficients. Beta is a vector, and here composed of two numbers. In my example, those two numbers are b and c; a is the intercept, sometimes confusingly referred to as b.\nSo beta squared is exactly the same thing as the equation above. What is a partial slope? Another word for partial slope is a coefficient. Why do we call it a partial slope? Well, if you remember, we have a slope when we have a linear regression, y = a + b _X, b is the slope. Well, if you have multiple x's, so y = a + b_ X1 + c _X2 + d_ X3 and so on and so on. Then, in my example, that I just mentioned b, c, and d are all partial slopes, that is because they are multiplied by the columns. And the way the input value from the column changes from those variables change will affect the output. And it will affect it more if that coefficient or that partial slope is greater. When I say greater, I mean in magnitude.\nSo the Ridge objective *_is the residual sum of squares (RSS) +lambda_ (sum of squares of the coefficients)**.\n  * use lambda to balance minimizing RSS vs. minimizing the coefficients\n  * when lambda = 0, results are the same as regular linear regression: you have removed the Ridge regression penalty\n  * as lambda increases to infinity, coefficients become closer to 0\n  * any non-zero lambda value will shrink the coefficients to be smaller than with non-regularized regression\n  * as lambda (alpha) increases, model complexity decreases\n\n\nLambda is just a scalar that should be learned from your data using cross-validation (tuning). So lambda is always positive and is between zero and infinity. And just to give you a basic idea of its range, it is rarely much larger than one, maybe going to two or three, and often is a small fraction of one. Why is that? Well, that is just the way things work out. There exist counterexamples to what I just said, but as a general heuristic, what you generally find is that the lambda is between zero and, and a small value, let us say roughly two.\nIf the model complexity decreases as lambda increases, how can you see this?\n![Our regression lines fit the blue dots well](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1aCivvOcF1tVvRD8prl64aA.jpeg)\nOur regression lines fit the blue dots well\nIn the example fits above I approximate some form of regression, in this case, probably not a linear regression. And that regression worked pretty well. And then we added the lambda parameter. And hopefully, things got better. If I were to eyeball this here, I would probably want the one on the right. My rationale is, I see these blue dots, they are flying all over the place, they are up and down above and beneath that black line. I expect there to be overall, more variation in where those blue dots can land, a lot of variation. And so I think that trying to find the model that tries to minimize the residuals of these blue dots will try to minimize it too much, what will happen is it will become too complex of a model, it will overfit. And then when new data comes by, data that the model has never seen, that new data is not going to be there where this model is fitting.\n![The red circle is likely overfitting the residuals](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/19oNj4QMsODqGfGuOn_vdKA.jpeg)\nThe red circle is likely overfitting the residuals\nSo for instance, this little quirk circled in red, looks pretty good. But my guess is that is just because one or two data points had these high y values relatively - high y values. Methinks that was just a quirk. Probably this should just go straight over, as it does on the right-most image. Because if I look at how much overall these blue points are going up and down, I cannot really justify creating a model that is trying to go down to catch to minimize the residual of this one bluepoint and then going right back up. As such, the small lambda value is likely overfitting and I believe that the 1/100 lambda value on the right actually fits the data much better and will generalize better.\n### LASSO\nLASSO regression does pretty much the same thing; it is another way to limit the number of independent variables in the regression. The only difference is, it uses the absolute value. Now the thing is that because of the math, what it does is not just reduce the coefficients, LASSO actually removes the coefficients. Many people like LASSO for this reason: **the coefficients can actually go to zero, whereas in the Ridge regression, they do not go to zero, they become small, but they never vanish**.\nNow, you can always help the last way, if you see that coefficient has gotten really small, you can just say, \"Okay, I'm going to just toss this column, because it has such a small coefficient.\" What is nice about LASSO is that it will actually do that for you in an intelligent way.\n![y is the predicted for j points, there are i terms with beta coefficients - lambda limits the betas](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0r9MmZLQX46s4KVdx.png)\ny is the predicted for j points, there are i terms with beta coefficients - lambda limits the betas\nBeta a vector of your coefficients. Instead of squaring them, you just take the absolute value.\n### Linear algebra\nNext is a quick review of linear algebra. Why do we have a quick review of linear algebra? Well, because machine learning is a lot of linear algebra and the more you understand about the machine learning algorithms, the often the better you can apply them. **When studying data science, you are not studying machine learning, you are studying how to use the machine learning algorithms**.\nAlgebraic properties of matrices:\n  * add/subtract matrices: must be of the same dimensions (m * n)\n  * for multiplication of matrices: inner dimensions must match\n  * remember that matrix multiplication is not commutative: A x B != B x A\n  * a matrix multiplied by its inverse yields the identity matrix\n  * matrix division is not defined\n\n\n### Linear regression with matrices\nConsider the linear regression formula:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0JnsHXROQ9WS7dgQG.png)\nwritten as a matrix:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0Z-26flhaNz1MQlcd.png)\nwhich can be rewritten as:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/00UOpAdGToI6UyByG.png)\nFor linear regression with matrices, if you have, say 10 cases, that means 10 points and you will have 10 columns, then there will be an exact, best solution. There will be a simple solution to that. However, not in every case, there are cases where you have colinearity, which means when one column is basically the same as another column or the same as a combination of some other columns. When this occurs you generally have infinitely many solutions. And we do not like this because having infinitely many solutions, means you do not have any useful solutions. If then there are situations where there is simply no solution can occur. But the general case or the case that you hope for is that you have exactly one good solution.\nMost of the time, when we do machine learning, or data science is we have many more cases than we have variables; we have many more data points than we have columns; we have many more rows than we have columns - I am just repeating the same thing over and over with slightly different words. This is going to cause us an issue, for one thing, that means our matrix of x is not a square matrix.\nSo when we want to invert it, and I will show you that we will want to do that, it is going to cause us some problems, along with colinearity and stuff like that.\n![Succinctly: y = X * Beta + Epsion](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1AwyzxvvGCf1HiWjQE_lDxw.png)\nSuccinctly: y = X * Beta + Epsion\nThese concepts are best demonstrated in code.\n## Python example: Singular value decomposition\n[Previously](https://towardsdatascience.com/regularization-and-linear-regression-bcaeba547c46), I mentioned stepwise regression as a way to regularize, by finding meaningful features one at a time, either by the forward or backward methodology. I now introduce singular value decomposition (SVD) as another meaningful way to find features.\nRegularization methods stabilize the inverse of the **model matrix**. We will use the SVD method to stabilize a model matrix.\nN.B: Stepwise regression is a computationally-intensive process since we must recompute the model many times. There are methods that allow computation of the updated model, but with a large number of features, there are numerous permutations. We need methods that can handle hundreds, thousands, or even millions of features. Consider a small data set with only 20 features. The amount of possible linear models with NO interaction terms is given by:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0w1UBgYnKAYwWKfDr.png)\nWhich is the sum of the 21st row of Pascal's triangle. This comes out to be:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0GcUl192zPdQWg8XZ.png)\nAlthough according to our algorithm, this would be the maximum number of models to compute, you can see how computationally hard this becomes when naively considering stepwise regression.\nIn order to understand the motivation and methods of feature selection/transformation, I will review some linear algebra.\n### Linear algebra review\ntext\n\n```\nimport numpy as np\n```\n\ntext\n\n```\na_list = [2]*3\nprint(a_list)\nprint(type(a_list))\na = np.array([2]*3)\nprint(a)\nprint(type(a))\nb = np.arange(1, 4)\nprint(b)\nprint(type(b))\n```\n\n![Jupyter displays lists and arrays similarly](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1n7pFNehaDPimGBscPEQhuw.png)\nJupyter displays lists and arrays similarly\nMatrix multiplication and addition\ntext\n\n```\na2d = np.array([[2]*3, [3]*3])\nprint('a: n{} n a-size: {}'.format(a2d, a2d.shape))\nb2d = np.reshape(np.arange(1,7), newshape=(2, 3))\nprint('nb: n{} n b-size: {}'.format(b2d, b2d.shape))\n```\n\ntext\n\n```\n# Addition\nprint('nAddition: n {}'.format(a2d + b2d))\n# Multiplication\nprint('nMultiplication: n {}'.format(a2d * b2d))\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1CINY3mSObBW-8ojBH3p5Ww.png)\n### Matrix transposition\nWe can also transpose a two-dimensional matrix by flipping the rows and columns. We use the `numpy` method `np.transpose`.\ntext\n\n```\nprint('Try transposing on a vector...')\nprint(np.transpose(a))\n# Transposition on a vector does not work\n```\n\ntext\n\n```\nprint('Now reshape a into 2D and then transpose:')\nprint(np.transpose(np.reshape(a, newshape=(1,3))))\nprint('Now transpose a 2d matrix:')\nprint(np.transpose(a2d))\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1c-CoXJLr_fKDvMQnhFA8OA.png)\n### Matrix dot product\nWe need to know how to compute the **dot product** , which is also known as the **scalar product** or **inner product** of two vectors of equal length, via element-wise multiplication then summing them all up:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/05TGmuOCmx4hOtGlh.png)\ntext\n\n```\nprint('np.dot(a, b) = np.dot({}, {})'.format(a, b))\nnp.dot(a, b)\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1EBLSTjDbpmAzj0ww4dxoUw.png)\nThe square root of the inner product of a vector with itself is the length or L2 norm of the vector:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0Wh8Cqr7BZxhO2NI9.png)\nWe can also write the inner product as:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0zxaatyFMS1fzZvd7.png)\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0kl-z6Dtr97FrW4XH.png)\n![Notice that the inner product of orthogonal vectors is 0](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0MxYqDFnVgMjH5tW9.png)\nNotice that the inner product of orthogonal vectors is 0\ntext\n\n```\naa = np.array([1, 0, 0])\nbb = np.array([0, 1, 1])\nprint(inner_prod(aa, bb))\n```\n\n![Linearly independent vectors are completely orthogonal](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1WdfeDemQdsqUMEcZq4fn6Q.png)\nLinearly independent vectors are completely orthogonal\nHere are some operations on matrices. Let A and B be m=4 rows by n=3 columns matrices:\ntext\n\n```\nA = np.array([[4]*3]*4) \nprint(A)\nB = np.array(np.reshape(np.arange(1, 13), newshape = (4, 3)))\nprint(B)\nC = np.array(np.reshape(np.arange(1, 9), newshape = (4, 2)))\nprint(C)\nnp.dot(np.transpose(A), C)\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1ilygMFy4EIOLf2g1ejUDsg.png)\n### Identity matrix\nThis special, square matrix has ones on the diagonal and zeros elsewhere:\n![The matrix equivalent of 1](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0zX9l0oRlZ3-QNrKR.png)\nThe matrix equivalent of 1\nThe identity multiplied by any matrix gives that matrix. If AB is a rectangular matrix then:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0nhNr_gchlyroLEvL.png)\nIn `numpy` the Identity matrix is called `np.eye` and takes as an argument the number of rows/columns:\ntext\n\n```\nI3 = np.eye(3)\nI4 = np.eye(4)\n```\n\ntext\n\n```\nprint('I (3X3) = n{}'.format(I3))\nprint(np.dot(I3, AtB))\n```\n\ntext\n\n```\nprint('I (4x4) = n{}'.format(I4))\nprint(np.dot(I4, ABt))\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1cAWDft2Lt_k3NvVSkTA6GQ.png)\n## Inverse of a matrix\nDefine and compute an inverse of a matrix such that:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0cc91Q_KmwtTboyWv.png)\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0MJJU47Vsupq7JuJT.png)\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0FcfmsC8RKXssMEGN.png)\nUse the Linear Algebra methods in `numpy` to get the inverse of matrix M with `np.linalg.inv`\ntext\n\n```\nM = np.array([[1., 4.], [-3., 2.]])\nM_inverse = np.linalg.inv(M)\n```\n\ntext\n\n```\nprint('M: n{}'.format(M))\nprint('nM_inv = n{}'.format(M_inverse))\nprint('nM_inv * M = n{}'.format(np.dot(M_inverse, M)))\nprint('nM * M_inv = n{}'.format(np.dot(M, M_inverse)))\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1XR1zFOU-t-ZpjEqzUEhrZg.png)\nWith this brief refresher aside, we can now jump into regularizing models with SVD.\n## Singular Value Decomposition\nIn machine learning, we often encounter matrices that cannot be inverted directly. Instead, we need a decomposition of A that allows us to compute A^−1, which we can do with SVD:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/00iKonB-3gB3LyeZX.png)\n  * U is the orthogonal unit norm left singular vectors\n  * V is the orthogonal unit norm right singular vectors, and V∗ is the conjugate transpose; for real-valued A this is just VT\n  * D is a diagonal matrix of singular values, which are said to define a **spectrum**\n  * A is comprised of the linear combination of singular vectors scaled by singular values\n\n\nTo compute the SVD of a matrix and view the results execute the code in the cell below. We use the `numpy` method called `np.linalg.svd` using `s` for the singular values:\ntext\n\n```\nU, s, V = np.linalg.svd(B, full_matrices=False)\nprint('B: {}'.format(B)) # ESHx\nprint('U: {}'.format(U))\nprint('s: {}'.format(s))\nprint('V: {}'.format(V))\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/11ekRI3ZV3OnpdqjXfp04dQ.png)\n## Regularization with Ridge and Lasso Regression\nSo far, we have looked at two approaches for dealing with over-parameterized models; feature selection by stepwise regression and singular value decomposition. In this section, we will explore the most widely used regularization method for optimization-based machine learning models, **Ridge regression**.\nLet's start by examining the matrix-equation formulation of the linear regression problem. The goal is to compute a vector of **model coefficients** or weights which minimize the mean squared residuals, given a vector of data 𝑥x and a m**odel matrix** A. We can express our model as:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0xumy-Hf7L7A20P9x.png)\nExecute the code in the cell below which computes the (𝐴^𝑇 _𝐴+𝜆²)^-1_ A^T matrix with a lambda value of 0.1``\ntext\n\n```\nU, s, V = np.linalg.svd(M, full_matrices=False)\n```\n\ntext\n\n```\n# Calculate the inverse singular value matrix from SVD\nlambda_val = 1.0\nd = np.diag(1. / (s + lambda_val))\n```\n\ntext\n\n```\nprint('Inverse Singular Value Matrix:')\nprint(d)\n```\n\ntext\n\n```\n# Compute pseudo-inverse\nmInv = np.dot(np.transpose(V), np.dot(d, np.transpose(U)))\n```\n\ntext\n\n```\nprint('M Inverse')\nprint(mInv)\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1U0SBJDS9JxYkIe06-FYOQA.png)\n### Bias-variance trade-off\nThe bias-variance trade-off is a fundamental property of machine learning models. To understand this trade-off let's decompose the mean square error for a model as follows:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0HlfGnbe1w6QgIHpR.png)\nRegularization will reduce variance, but increases bias. Regularization parameters are chosen to minimize delta_X. In many cases, this process proves challenging, involving significant time-consuming trial and error.\nThe **irreducible error** is the limit of model accuracy. Even if you had a perfect model with no bias or variance, the irreducible error is inherent in the data and model. You cannot do better.\nThe `statsmodels` package allows us to compute a sequence of Ridge regression solutions. The function that does this uses a method called 'Elasticnet', know that ridge regression is a specific case of elastic-net, and I will talk more about this later.\n**N.B: This is a continuation of my previous work on the Galton family dataset.**\nThe code in the cell below computes solutions for 20 values of lambda:\ntext\n\n```\n# Ridge regression with various penalties in Statsmodels\n# sequence of lambdas\nlog_lambda_seq = np.linspace(-6, 2, 50)\nlambda_seq = np.exp(log_lambda_seq)\n```\n\ntext\n\n```\ncoeffs_array = []\nrsq_array = []\nformula = 'childHeight ~ mother + father + mother_sqr + father_sqr + 1'\n```\n\ntext\n\n```\nfor lamb in lambda_seq:\n ridge_model = sm.ols(formula, data=male_df).fit_regularized(method='elastic_net', alpha=lamb, L1_wt=0)\n coeffs_array.append(list(ridge_model.params))\n predictions = ridge_model.fittedvalues\n residuals = [x - y for x, y in zip(np.squeeze(predictions), childHeight)]\n```\n\ntext\n\n```\nSSR = np.sum(np.square(residuals))\n SST = np.sum(np.square(childHeight - np.mean(childHeight)))\n```\n\ntext\n\n```\nrsq = 1 - (SSR / SST) \n rsq_array.append(rsq)\n```\n\ntext\n\n```\n# pull out partial slopes (drop intercept version)\nbeta_coeffs = [x[1:] for x in coeffs_array]\nplt.plot(log_lambda_seq, beta_coeffs)\nplt.title('Partial Slopes vs Log-Lambda')\nplt.ylabel('Partial Slope Values')\nplt.xlabel('Log-Lambda')\nplt.show()\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1CbM9BBaAhnjY2ocicThBdg.png)\nPlot partial slopes vs R²:\ntext\n\n```\n# % deviance explained\nplt.plot(rsq_array, beta_coeffs)\nplt.xlim([0.0, 0.25])\nplt.title('Partial Slopes vs Log-Lambda')\nplt.xlabel('R-squared')\nplt.ylabel('Partial Slopes')\nplt.show()\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1X6YRZEO-XEzHQnUuNTus1g.png)\nNotice that as lambda increases, the values of the 4 model coefficients decrease toward zero. When all coefficients are zero, the model predicts all values of the label as zero! In other words, high values of lambda give highly biased solutions, but with very low variance.\nFor small values of lambda, the situation is just the opposite. The solution has a low bias, but is quite unstable, having maximum variance. This **bias-variance trade-off** is a key concept in machine learning.\n## LASSO regression\nWe can also do regularization using other norms. LASSO or L1 regularization limits the sum of the absolute values of the model coefficients. The L1 norm is sometimes known as the Manhattan norm since distances are measured as if you were traveling on a rectangular grid of streets.\nYou can also think of LASSO regression as limiting the L1 norm of the values of the model coefficient vector. The value of lambda determines how much the norm of the coefficient vector constrains the solution.\nPerforming the same calculations as before, but with a different regularization norm and associated penalty:\ntext\n\n```\n# LASSO regression with a sequence of lambdas\n# sequence of lambdas\nlog_lambda_seq = np.linspace(-6, 2, 50)\nlambda_seq = np.exp(log_lambda_seq)\n```\n\ntext\n\n```\ncoeffs_array = []\nrsq_array = []\nformula = 'childHeight ~ mother + father + mother_sqr + father_sqr + 1'\n```\n\ntext\n\n```\nfor lamb in lambda_seq:\n ridge_model = sm.ols(formula, data=male_df).fit_regularized(method='elastic_net', alpha=lamb, L1_wt=1)\n coeffs_array.append(list(ridge_model.params))\n predictions = ridge_model.fittedvalues\n residuals = [x - y for x, y in zip(np.squeeze(predictions), childHeight)]\n```\n\ntext\n\n```\nSSR = np.sum(np.square(residuals))\n SST = np.sum(np.square(childHeight - np.mean(childHeight)))\n```\n\ntext\n\n```\nrsq = 1 - (SSR / SST)\n rsq_array.append(rsq)\n```\n\ntext\n\n```\n# drop intercept version\nbeta_coeffs = [x[1:] for x in coeffs_array]\nplt.plot(log_lambda_seq, beta_coeffs)\nplt.title('Partial Slopes vs Log-Lambda')\nplt.ylabel('Partial Slope Values')\nplt.xlabel('Log-Lambda')\nplt.show()\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1Itld6sXEyw_DDOeg5NdCaw.png)\ntext\n\n```\n# plot partial slopes vs R squared (% deviance explained)\nplt.plot(rsq_array, beta_coeffs)\nplt.xlim([0.0, 0.25])\nplt.title('Partial Slopes vs Log-Lambda')\nplt.xlabel('R-squared')\nplt.ylabel('Partial Slopes')\nplt.show()\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1atGaYDT1FbiZZWHe7SmJuQ.png)\nNotice that model coefficients are much more tightly constrained than for L2 regularization. In fact, only two of the possible model coefficients have non-zero values at all! This is typical of L1 or LASSO regression.\n## Elastic Net regression\nThe **elastic net** algorithm uses a weighted combination of L1 and L2 regularization. As you can probably see, the same function is used for LASSO and Ridge regression with only the `L1_wt` argument changing. This argument determines how much weight goes to the L1-norm of the partial slopes. If the regularization is pure L2 (Ridge) and if `L1_wt = 1.0` the regularization is pure L1 (LASSO).\nThe code in the cell below gives equal weight to each regression method. Execute this code and examine the results:\ntext\n\n```\n# ElasticNet Regression with a sequence of lambdas\n# sequence of lambdas\nlog_lambda_seq = np.linspace(-6, 0, 50)\nlambda_seq = np.exp(log_lambda_seq)\n```\n\ntext\n\n```\ncoeffs_array = []\nrsq_array = []\nformula = 'childHeight ~ mother + father + mother_sqr + father_sqr + 1'\n```\n\ntext\n\n```\nfor lamb in lambda_seq:\n ridge_model = sm.ols(formula, data=male_df).fit_regularized(method='elastic_net', alpha=lamb, L1_wt=0.75)\n coeffs_array.append(list(ridge_model.params))\n predictions = ridge_model.fittedvalues\n residuals = [x - y for x, y in zip(np.squeeze(predictions), childHeight)]\n```\n\ntext\n\n```\nSSR = np.sum(np.square(residuals))\n SST = np.sum(np.square(childHeight - np.mean(childHeight)))\n```\n\ntext\n\n```\nrsq = 1 - (SSR / SST)\n rsq_array.append(rsq)\n```\n\ntext\n\n```\n# pull out partial slopes (drop intercept version)\nbeta_coeffs = [x[1:] for x in coeffs_array]\nplt.plot(log_lambda_seq, beta_coeffs)\nplt.title('Partial Slopes vs Log-Lambda')\nplt.ylabel('Partial Slope Values')\nplt.xlabel('Log-Lambda')\nplt.show()\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1ZFH-W_9Mpll1C3eg5IfWkg.png)\ntext\n\n```\n# plot partial slopes vs R squared (% deviance explained)\nplt.plot(rsq_array, beta_coeffs)\nplt.xlim([0.0, 0.25])\nplt.title('Partial Slopes vs Log-Lambda')\nplt.xlabel('R-squared')\nplt.ylabel('Partial Slopes')\nplt.show()\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1Wvq2iSKX8avYPpe5O7F9EQ.png)\nNotice that the elastic net model combines some of the behaviors of both L2 and L1 regularization.\n## Conclusion\nIn this article and last week's I looked at 3 methods as a solution to the problem of overfitting models:\n  * Stepwise Regression to eliminate features one at a time\n  * Singular Value Decomposition to find meaningful features\n  * Lasso, Ridge, and ElasticNet Regularization to stabilize over-parameterized models\n\n\nImportant terms include:\n  * AIC - the model log-likelihood adjusted for the number of model parameters\n  * Deviance - a measure of the relative likelihood of the model (a generalization of variance)\n  * SVD - Singular Value Decomposition describes a matrix as a linear combination of a series of vectors U, V, D\n  * Singular values s - the diagonal matrix of singular values used as a scaling term\n  * Lambda - a small bias term added to singular values to stabilize the inverse singular value matrix\n  * PCA - Principal Component Analysis to determine what new features can be made from linear combinations that are independent of each other by using functions and the SVD\n  * PCR - Principal Component Regression uses the PCA to perform a \"regularized\" regression\n  * L1 regularization - LASSO regularization using the \"Manhattan\" norm\n  * L2 Norm regularization - Ridge regularization limiting the \"Euclidean\" norm of values of the model coefficient vector\n  * ElasticNet algorithm - a weighted combination of L1 and L2 regularization\n\n\nAnd I briefly reviewed linear algebra operations:\n  * Adding vectors and matrices\n  * Multiplying vectors and matrices\n  * Transposing matrices with `np.transpose`\n  * Dot product or scalar product or inner product with `np.dot`\n  * L2 norm of a vector\n  * Identity matrix with `np.eye`\n  * Inverse of a matrix with `np.linalg.inv`\n  * Singular value decomposition with `np.linalg.svd`\n  * Creating a diagonal matrix with `np.diag`\n\n\nUp to now, I have been working strictly with linear regression models. Next, I will look at a widely used variation on the linear model know as [**logistic regression**](https://towardsdatascience.com/logistic-regression-cebee0728cbf)**!**\nFind me on [Linkedin](https://www.linkedin.com/in/james-a-w-godwin/)\n_Physicist cum Data Scientist- Available for new opportunity | SaaS | Sports | Start-ups | Scale-ups_\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657234707_1wi608.jpeg)\nWritten By\n## [James Andrew Godwin](https://towardsdatascience.com/author/james-andrew/)\n[See all from James Andrew Godwin](https://towardsdatascience.com/author/james-andrew/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Python](https://towardsdatascience.com/tag/python/)[Regression Analysis](https://towardsdatascience.com/tag/regression-analysis/)[Towards Data Science](https://towardsdatascience.com/tag/towards-data-science/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fridge-lasso-and-elasticnet-regression-b1f9c00ea3a3%2F&title=Ridge%2C%20LASSO%2C%20and%20ElasticNet%20Regression)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fridge-lasso-and-elasticnet-regression-b1f9c00ea3a3%2F&title=Ridge%2C%20LASSO%2C%20and%20ElasticNet%20Regression)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fridge-lasso-and-elasticnet-regression-b1f9c00ea3a3%2F&text=Ridge%2C%20LASSO%2C%20and%20ElasticNet%20Regression)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/04/blog2.jpg)](https://towardsdatascience.com/a-survival-analysis-guide-with-python-using-time-to-event-models-to-forecast-customer-lifetime/)\n## [A Survival Analysis Guide with Python: Using Time-To-Event Models to Forecast Customer Lifetime](https://towardsdatascience.com/a-survival-analysis-guide-with-python-using-time-to-event-models-to-forecast-customer-lifetime/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nHow to calculate time-to-event probabilities and hazard rates for telecommunications subscribers.\n[Gustavo Santos](https://towardsdatascience.com/author/gustavorsantos/)\nApril 9, 202611 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/1hr0VwOiA-PR4Hi59RTRhSQ.png)](https://towardsdatascience.com/matchy-matchy-object-detection-using-template-matching-in-python-3b2bdfa6e250/)\n## [Matchy matchy! Object detection using Template Matching in Python](https://towardsdatascience.com/matchy-matchy-object-detection-using-template-matching-in-python-3b2bdfa6e250/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nWe discussed object detection on my previous article so this time around I'll be showing another example of how to identify objects...\n[Nico Aguila](https://towardsdatascience.com/author/nico-aguila/)\nJanuary 30, 20213 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/10/1sK1df7R9FZx2HHS5bIYDhg.gif)](https://towardsdatascience.com/conformal-prediction-in-julia-351b81309e30/)\n## [Conformal Prediction in Julia 🟣🔴🟢](https://towardsdatascience.com/conformal-prediction-in-julia-351b81309e30/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nPart 1 - Introduction\n[Patrick Altmeyer](https://towardsdatascience.com/author/patrick.altmeyer/)\nOctober 24, 20225 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/09/1neRHnOeJh9qCCYL_TfBqwA.jpeg)](https://towardsdatascience.com/three-mysterious-behaviours-of-python-95c9dffa88fe/)\n## [Three Mysterious Behaviours of Python](https://towardsdatascience.com/three-mysterious-behaviours-of-python-95c9dffa88fe/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThe unexpected running outcomes for Dictionary, Try Except and For-Loop\n[Christopher Tao](https://towardsdatascience.com/author/christophertao/)\nSeptember 12, 20216 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/03/1yoJgEScoy5xxvqTgR2beBQ-scaled.jpeg)](https://towardsdatascience.com/bar-plots-best-practices-and-issues-30f1ad32c68f/)\n## [Bar Plots: Best Practices and Issues](https://towardsdatascience.com/bar-plots-best-practices-and-issues-30f1ad32c68f/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nHow to create an insightful graph\n[Elena Kosourova](https://towardsdatascience.com/author/elena-kosourova/)\nMarch 27, 202113 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/05/0W082Zy7tb8DXOjg4-scaled.jpg)](https://towardsdatascience.com/data-wrangling-solutions-working-with-dates-part-3-b8b5caccc4ed/)\n## [Data Wrangling Solutions - Working With Dates - Part 3](https://towardsdatascience.com/data-wrangling-solutions-working-with-dates-part-3-b8b5caccc4ed/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nExtract information from columns containing DateTime data. In the last two tutorials, we went from...\n[Ujjwal Dalmia](https://towardsdatascience.com/author/ujjwal-dalmia/)\nMay 7, 20214 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1z-P1ZDZSL8yWbShShdii_w-scaled.jpeg)](https://towardsdatascience.com/how-i-deployed-my-first-machine-learning-model-1147c04c449b/)\n## [How I deployed my first machine learning model](https://towardsdatascience.com/how-i-deployed-my-first-machine-learning-model-1147c04c449b/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nProcesses and tools I used to deliver my first commercial machine learning model\n[Artur Lunardi Di Fante](https://towardsdatascience.com/author/arturlunardi/)\nDecember 15, 202112 min read\n  * [![](https://towardsdatascience.com/images/fallback-image.jpg)](https://towardsdatascience.com/how-to-learn-to-solve-data-science-problems-like-a-pro-and-become-employable-b3fd2f4bec71/)\n## [How To Learn To Solve Data Science Problems Like a Pro and Become Employable](https://towardsdatascience.com/how-to-learn-to-solve-data-science-problems-like-a-pro-and-become-employable-b3fd2f4bec71/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThe most practical way to learn data science (Includes best-in-class references)\n[Sharan Kumar Ravindran](https://towardsdatascience.com/author/rsharankumar/)\nNovember 3, 202110 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/03/1VbWc7i6htu3NcUNKapYO-w.png)](https://towardsdatascience.com/serverless-ml-is-this-the-cheapest-way-to-host-machine-learning-models-on-aws-83ba3dee8be4/)\n## [Serverless ML. Is this the cheapest way to host Machine Learning models on AWS?](https://towardsdatascience.com/serverless-ml-is-this-the-cheapest-way-to-host-machine-learning-models-on-aws-83ba3dee8be4/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nI'm hosting my Resnet-152 (152 layer CNN) model on AWS for pretty much free right now. Does it scale? What's the trade-offs?\n[Phil Whelan](https://towardsdatascience.com/author/philwhln/)\nMarch 17, 20218 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "body_base_path": "attachments/0b3419aa6237/pages/",
  "body_markdown_path": "attachments/0b3419aa6237/pages/archived-body.md",
  "local_html": "attachments/0b3419aa6237/pages/archived-body.html",
  "body_source": "prior_capture"
}