CDA数据分析师:数据科学、人工智能从业者的在线大学。
数据科学(Python/R/Julia)数据分析、机器学习、深度学习 Q群:874447702
ElasticNet回归是对Lasso回归和岭回归的融合,其惩罚项是L1范数和L2范数的一个权衡。ElasticNet类实现了ElasticNet回归模型,其原型为:
class sklearn.linear_model.ElasticNet(alpha=1.0, l1_ratio=0.5, fit_intercept=True, normalize=False, precompute=False, max_iter=1000, copy_X=True, tol=0.001, warm_start=False, positive=False, random_state=None, selection='cyclic')
下面我们对其参数做简单的说明:
alpha: a值。
fit_intercept:一个布尔值,指定是否需要计算b值。如果为False,那么不计算b值(模型会认为你已经将数据中心化了)。
max_iter:整数值,指定最大迭代次数。
normalize:一个布尔值。如果为True,那么训练样本会在回归之前被归一化。
copy_X:一个布尔值,如果为True,则会复制X值
precompute:一个布尔值或者一个序列。他决定是否提前计算Gram矩阵来加速计算。
tol:一个浮点数,指定判断迭代收敛与否的阈值。
warm_start:一个布尔值,如为True,那么使用前一次训练结果继续训练。否则重头开始训练。
positive:一个布尔值,如为Ture,那么强制要求全中响亮的分量都为整数。
selection:一个字符串,可以为‘cyclic’(更新时候,从前向后一次选择权重向量的一个分量来更新)或者‘random'(随机选择权重向量的一个分量来更新),他指定了当每轮迭代的时候,选择权重向量的一个分量来更新
random_state:一个整数或者一个RandomState实例,或者为None。如果为整数,则他指定了随机数生成器种子。如果为RandomState实例,则指定了随机数生成器。如果为None,则使用默认的随机数生成器。
我们来看如下示例代码(使用默认的alpha和l1_ratio值):
from sklearn import datasets, linear_model, discriminant_analysis, cross_validation
def load_data: #定义加载数据集的函数,其返回值为一个元组,元组内容依次为训练样本集、测试样本集#以及两者的坐标签值
diabetes = datasets.load_diabetes #加载糖尿病病人采样数据
return cross_validation.train_test_split(diabetes.data, diabetes.target, test_size=0.25, random_state=0)
def test_ElasticNet(*data): #测试在默认情况下的均方误差以及测试分数
x_train, x_test, y_train, y_test = data
regr = linear_model.ElasticNet
regr.fit(x_train, y_train)
print('Coefficients:%s, intercept %.2f'%(regr.coef_, regr.intercept_))
print("Residual sum of squares: %.2f"% np.mean((regr.predict(x_test) - y_test)**2))
print("Test set score: {:.2f}".format(regr.score(x_test, y_test)))
x_train, x_test, y_train, y_test = load_data
test_ElasticNet(x_train, x_test, y_train, y_test)
运行后结果如下:
Coefficients:[ 0.40560736 0. 3.76542456 2.38531508 0.58677945 0.22891647
-2.15858149 2.33867566 3.49846121 1.98299707], intercept 151.93
Residual sum of squares: 4922.36
Test set score: 0.01
由运行结果可以看出,均方误差为4922.36,预测性能很低,仅为0.01.
下面我们调整alpha值和l1_ratio的值,以下是测试函数:
def test_ElasticNet_alpha_rho(*data):
x_train, x_test, y_train, y_test = data
alphas = np.logspace(-3, 3)
rhos = np.linspace(0.01, 1)
scores = []
for alpha in alphas:
for rho in rhos:
regr = linear_model.ElasticNet(alpha=alpha, l1_ratio=rho)
regr.fit(x_train, y_train)
scores.append(regr.score(x_test, y_test))
#将对应结果绘图出来
alphas, rhos = np.meshgrid(alphas, rhos)
scores = np.array(scores).reshape(alphas.shape)
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
fig = plt.figure
ax = Axes3D(fig)
surf = ax.plot_surface(alphas, rhos, scores, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=5)
ax.set_xlabel(r"$\alpha$")
ax.set_ylabel(r"$\rho$")
ax.set_zlabel("\score")
ax.set_title("ElasticNet")
plt.show
x_train, x_test, y_train, y_test = load_data
test_ElasticNet_alpha_rho(x_train, x_test, y_train, y_test)
运行后结果如下图所示:
调整alpha和l1_ratio后的输出结果图形
由上图可以看出,随着alpha值的增大,预测性能下降,而l1_ratio则是影响性能下降的速度。