我使用1个或2个特征拟合了一个逻辑回归模型:
X = df[["decile_score", "age"]]X_train, X_test, y_train, y_test = model_selection.train_test_split( X, y, test_size=0.20, random_state=100)logistic_age_model = linear_model.LogisticRegression()logistic_age_model.fit(X_train, y_train)beta_0 = logistic_age_model.intercept_[0]beta_1, beta_2 = logistic_age_model.coef_[0]print(f"Fit model: p(recid) = L({beta_0:.4f} + {beta_1:.4f} decile_score + {beta_2:.4f} age)")
如果我有超过2个特征(例如15个),我该如何编写代码来查看模型的变化?
例如
拟合模型: p(recid) = L(-0.8480 + 0.2475 decile_score + -0.0135 age) 我想查看这15个特征如何影响结果。
我是否需要为每个系数声明一个beta,如果是的话,我该如何操作?
回答:
我想你是在寻找一种更有效的方法来打印多个变量的逻辑回归公式。
# 初始化模型logistic_age_model = LogisticRegression()# 拟合模型(X现在有15个特征)logistic_age_model.fit(X, y)# 系数值列表coefs = np.union1d(logistic_age_model.intercept_, logistic_age_model.coef_[0]).tolist()# 名称列表betas = ['beta_' + str(i) for i in range(len(coefs))]# 组合`coefs` & `betas`形成字典d = dict(zip(betas, coefs))# 以公式形式打印print('L(' + str(d) + ')')