Skip to content

Instantly share code, notes, and snippets.

@vb100
Created March 26, 2018 19:28
Show Gist options
  • Save vb100/177bad75b7506f93fbe12323353683a0 to your computer and use it in GitHub Desktop.
Save vb100/177bad75b7506f93fbe12323353683a0 to your computer and use it in GitHub Desktop.
Automatic implementations of Backward Elimination in Python
import statsmodels.formula.api as sm
def backwardElimination(x, sl):
numVars = len(x[0])
for i in range(0, numVars):
regressor_OLS = sm.OLS(y, x).fit()
maxVar = max(regressor_OLS.pvalues).astype(float)
if maxVar > sl:
for j in range(0, numVars - i):
if (regressor_OLS.pvalues[j].astype(float) == maxVar):
x = np.delete(x, j, 1)
regressor_OLS.summary()
return x
SL = 0.05
X_opt = X[:, [0, 1, 2, 3, 4, 5]]
X_Modeled = backwardElimination(X_opt, SL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment