<jupyter_start><jupyter_text>Adjusted R-squared - Exercise SolutionUsing the code from the lecture, create a function which will calculate the adjusted R-squared for you, given the independent variable(s) (x) and the dependent variable (y).Check if you function is working properly.Solution at the bottom.  Import the relevant libraries<jupyter_code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()

from sklearn.linear_model import LinearRegression<jupyter_output><empty_output><jupyter_text>Load the data<jupyter_code>data = pd.read_csv('1.02. Multiple linear regression.csv')
data.head()
data.describe()<jupyter_output><empty_output><jupyter_text>Create the multiple linear regression  Declare the dependent and independent variables<jupyter_code>x = data[['SAT','Rand 1,2,3']]
y = data['GPA']<jupyter_output><empty_output><jupyter_text>Regression itself<jupyter_code>reg = LinearRegression()
reg.fit(x,y)
reg.coef_
reg.intercept_<jupyter_output><empty_output><jupyter_text>Calculating the R-squared<jupyter_code>reg.score(x,y)<jupyter_output><empty_output><jupyter_text>Formula for Adjusted R^2$R^2_{adj.} = 1 - (1-R^2)*\frac{n-1}{n-p-1}$<jupyter_code>x.shape
r2 = reg.score(x,y)
n = x.shape[0]
p = x.shape[1]

adjusted_r2 = 1-(1-r2)*(n-1)/(n-p-1)
adjusted_r2<jupyter_output><empty_output><jupyter_text>Adjusted R^2 function<jupyter_code># There are different ways to solve this problem
# To make it as easy and interpretable as possible, we have preserved the original code
def adj_r2(x,y):
    r2 = reg.score(x,y)
    n = x.shape[0]
    p = x.shape[1]
    adjusted_r2 = 1-(1-r2)*(n-1)/(n-p-1)
    return adjusted_r2
# Here's the result
adj_r2(x,y)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1226252158894646, 'fraction_numerical': 0.02072538860103627, 'mean_word_length': 6.427350427350428, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '436603', 'license': 'MIT', 'n_tokens_mistral': 675, 'n_tokens_neox': 643, 'n_words': 147, 'path': 'course_2/edited_material/Part_5_Advanced_Statistical_Methods_(Machine_Learning)/S34_L214/sklearn - Multiple Linear Regression and Adjusted R-squared - Exercise Solution.ipynb', 'repo_name': 'Alexander-Meldrum/learning-data-science', 'size': '1737'}