Learn

There are a number of Python libraries that can be used to fit a linear regression, but in this course, we will use the `OLS.from_formula()` function from `statsmodels.api` because it uses simple syntax and provides comprehensive model summaries.

Suppose we have a dataset named `body_measurements` with columns `height` and `weight`. If we want to fit a model that can predict weight based on height, we can create the model as follows:

``model = sm.OLS.from_formula('weight ~ height', data = body_measurements)``

We used the formula `'weight ~ height'` because we want to predict `weight` (it is the outcome variable) using `height` as a predictor. Then, we can fit the model using `.fit()`:

``results = model.fit()``

Finally, we can inspect a summary of the results using `print(results.summary())`. For now, we’ll only look at the coefficients using `results.params`, but the full summary table is useful because it contains other important diagnostic information.

``print(results.params)``

Output:

``````Intercept   -21.67
height        0.50
dtype: float64``````

This tells us that the best-fit intercept is `-21.67`, and the best-fit slope is `0.50`.

### Instructions

1.

Using the `students` dataset that has been loaded in script.py, create a linear regression model that predicts student `score` using `hours_studied` as a predictor and save the result as a variable named `model`.

2.

Fit the model using the `.fit()` method on `model` (created in the previous step), and save the fitted model as `results`.

3.

Print out the model coefficients using either `.params`.
{"ft_lang_label":"__label__en","ft_lang_prob":0.81691974,"math_prob":0.97751176,"size":1487,"snap":"2022-40-2023-06","text_gpt3_token_len":332,"char_repetition_ratio":0.13216454,"word_repetition_ratio":0.0,"special_character_ratio":0.22057834,"punctuation_ratio":0.1388889,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99895555,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-02-04T02:51:58Z\",\"WARC-Record-ID\":\"<urn:uuid:d0999d33-b63e-42ae-b70a-3818dc0b1d95>\",\"Content-Length\":\"143868\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:4b6f192e-2514-4829-9d86-e4ba2f9c5a8c>\",\"WARC-Concurrent-To\":\"<urn:uuid:6ab4f92f-19ed-4d6a-9459-4f15c618b9f3>\",\"WARC-IP-Address\":\"104.18.199.63\",\"WARC-Target-URI\":\"https://www.codecademy.com/courses/simple-linear-regression-course/lessons/introduction-to-linear-regression/exercises/fitting-a-linear-regression-model-in-python\",\"WARC-Payload-Digest\":\"sha1:LGKDV5O7YG6J36L4REG2AJ3K4XUPB7GW\",\"WARC-Block-Digest\":\"sha1:4WP5OOPVESXKACIPDQJIQDXORLCBLSGN\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-06/CC-MAIN-2023-06_segments_1674764500080.82_warc_CC-MAIN-20230204012622-20230204042622-00684.warc.gz\"}"}