Using Python produce code that generates a multiple linear regression model that checks for multicolinarity and reduced models terms that have vif > 5 printing the summary of model diagnostics. Create sample data with 100 rows and 5 random independent features and 1 dependant feature that each follow a normal distribution with mean randomly selected from range(1:100) and sd range(0.25-4).
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here is the Python code to generate a multiple linear regression model on sample data with 100 rows and 5 random independent features and 1 dependent feature, check for multicollinearity, remove terms with VIF > 5, and print the model diagnostics summary:
python
import pandas as pd
from sklearn.linear_model import LinearRegression
from statsmodels.stats.outliers_influence import variance_inflation_factor
from sklearn.model_selection import train_test_split
# Generate sample data
np.random.seed(123)
X = np.random.normal(loc=np.random.randint(1,100,size=5), scale=np.random.uniform(0.25,4,size=5), size=(100,5))
y = np.random.normal(loc=np.random.randint(1,100), scale=np.random.uniform(0.25,4), size=100)
df = pd.DataFrame(np.c_[X,y], columns=['X1','X2','X3','X4','X5','y'])
# Split into train and test
X_train, X_test, y_train, y_test = train_test_split(X, y)
# Fit full model
lr = LinearRegression().fit(X_train, y_train)
# Check VIF
vif = pd.DataFrame()
vif["VIF Factor"] = [variance_inflation_factor(X_train, i) for i in range(X_train.shape[1])]
# Remove terms with VIF > 5
drop_cols = vif[vif["VIF Factor"]>5].index
X_train.drop(X_train.columns[drop_cols],axis=1,inplace=True)
# Fit reduced model
lr = LinearRegression().fit(X_train, y_train)
# Print model diagnostics
print('Model Diagnostics:')
print('Coefficients:', lr.coef_)
print('Intercept:', lr.intercept_)
print('R-squared:', lr.score(X_train, y_train))
This generates sample data, fits a full and reduced regression model removing highly collinear terms, and prints the model diagnostics summary.