多任务Lasso实现联合特征选择

翻译者:@Loopy
校验者:@barrycg

多任务lasso允许多元回归问题上进行合并训练,并在多个任务间强制选择相同的特征。这个示例模拟了部分序列测量,每个任务都是即时的,并且相关的特征幅值趋向相同时,又会随时间变化而震动。多任务lasso强制要求在一个时间点选择的特征必需适用于所有时间点。这使得多任务LASSO的特征选择更加稳定。

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from sklearn.linear_model import MultiTaskLasso, Lasso
  1. rng = np.random.RandomState(42)
  2. # 使用具有随机频率和相位的正弦波生成二维系数
  3. n_samples, n_features, n_tasks = 100, 30, 40
  4. n_relevant_features = 5
  5. coef = np.zeros((n_tasks, n_features))
  6. times = np.linspace(0, 2 * np.pi, n_tasks)
  7. for k in range(n_relevant_features):
  8. coef[:, k] = np.sin((1. + rng.randn(1)) * times + 3 * rng.randn(1))
  9. X = rng.randn(n_samples, n_features)
  10. Y = np.dot(X, coef.T) + rng.randn(n_samples, n_tasks)
  11. coef_lasso_ = np.array([Lasso(alpha=0.5).fit(X, y).coef_ for y in Y.T])
  12. coef_multi_task_lasso_ = MultiTaskLasso(alpha=1.).fit(X, Y).coef_
  1. fig = plt.figure(figsize=(8, 5))
  2. plt.subplot(1, 2, 1)
  3. plt.spy(coef_lasso_)
  4. plt.xlabel('特征')
  5. plt.ylabel('时间 (或者叫 任务)')
  6. plt.text(10, 5, 'Lasso')
  7. plt.subplot(1, 2, 2)
  8. plt.spy(coef_multi_task_lasso_)
  9. plt.xlabel('特征')
  10. plt.ylabel('时间 (或者叫 任务)')
  11. plt.text(10, 5, '多任务Lasso')
  12. fig.suptitle('系数非零的位置')
  1. Text(0.5, 0.98, '系数非零的位置')

png

  1. feature_to_plot = 0
  2. plt.figure()
  3. lw = 2
  4. plt.plot(coef[:, feature_to_plot], color='seagreen', linewidth=lw,
  5. label='真实值')
  6. plt.plot(coef_lasso_[:, feature_to_plot], color='cornflowerblue', linewidth=lw,
  7. label='Lasso')
  8. plt.plot(coef_multi_task_lasso_[:, feature_to_plot], color='gold', linewidth=lw,
  9. label='多任务Lasso')
  10. plt.legend(loc='upper center')
  11. plt.axis('tight')
  12. plt.ylim([-1.1, 1.1])
  13. plt.show()

png