智能分类技术作为机器学习领域的核心应用之一,已经渗透到我们日常生活的方方面面。从邮箱里的垃圾邮件过滤到社交媒体的内容推荐,从医疗影像诊断到金融交易欺诈检测,分类算法都在背后默默发挥着作用。作为一名从业多年的数据科学家,我发现很多初学者容易陷入"模型至上"的误区,过分关注算法选择而忽视了更基础的特征工程环节。
在实际项目中,特征选择和模型训练就像是一辆马车的两个轮子,缺一不可。我曾参与过一个电商评论情感分析项目,最初直接使用BERT模型,准确率只有82%;后来通过精心设计的特征选择流程,配合相对简单的逻辑回归模型,准确率反而提升到了89%。这个案例生动说明了特征质量往往比模型复杂度更重要。
过滤法因其计算效率高、与模型无关的特点,成为特征选择的常用起点。在我的实践中,卡方检验特别适合处理文本分类任务。记得在做新闻分类时,我们计算每个词与类别的卡方统计量,筛选出最具区分度的关键词。具体实现如下:
python复制from sklearn.feature_selection import SelectKBest, chi2
selector = SelectKBest(chi2, k=500)
X_new = selector.fit_transform(X_counts, y)
这里有几个实用技巧:
包装法虽然计算成本高,但在关键项目中往往能带来惊喜。递归特征消除(RFE)是我最常用的包装方法之一。在信用卡欺诈检测项目中,我们使用以下流程:
python复制from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
estimator = LogisticRegression(max_iter=1000)
selector = RFE(estimator, n_features_to_select=15, step=1)
selector = selector.fit(X, y)
注意:包装法需要谨慎设置停止条件,过早停止可能错过重要特征,迭代过多则浪费计算资源。
嵌入法完美平衡了效率和效果。L1正则化是我处理高维数据的首选。在最近的用户流失预测项目中,ElasticNet帮我们发现了意想不到的特征组合:
python复制from sklearn.linear_model import ElasticNetCV
enet = ElasticNetCV(l1_ratio=[.1, .5, .7, .9, .95, .99, 1], cv=5)
enet.fit(X, y)
selected_features = enet.coef_ != 0
实践发现,当特征间相关性较高时,设置l1_ratio在0.5-0.8之间通常能取得最佳效果。
逻辑回归不仅是入门算法,在很多场景下依然是首选。上个月帮一家医院做疾病预测时,在特征工程到位的情况下,逻辑回归的AUC达到0.92,远超他们之前尝试的复杂模型。关键配置要点:
python复制from sklearn.linear_model import LogisticRegression
model = LogisticRegression(
penalty='l2',
C=0.1, # 通过网格搜索确定
class_weight='balanced', # 处理不平衡数据
solver='lbfgs',
max_iter=1000
)
对于非线性问题,SVM的核技巧确实强大,但要注意:
当处理图像、语音等复杂数据时,CNN和Transformer确实表现出色。但在实际业务中部署深度学习模型需要考虑更多因素。我们在商品分类项目中总结出以下经验:
python复制from transformers import BertForSequenceClassification
model = BertForSequenceClassification.from_pretrained(
'bert-base-uncased',
num_labels=num_classes,
output_attentions=True
)
XGBoost在结构化数据比赛中屡创佳绩,但工业应用需要注意:
python复制import xgboost as xgb
params = {
'objective': 'binary:logistic',
'max_depth': 6,
'learning_rate': 0.05,
'subsample': 0.8,
'colsample_bytree': 0.8,
'eval_metric': 'auc'
}
dtrain = xgb.DMatrix(X_train, label=y_train)
model = xgb.train(params, dtrain, num_boost_round=500)
在金融风控场景中,单纯看准确率会严重误导决策。我们建立了多维度评估框架:
python复制from sklearn.metrics import precision_recall_curve
precision, recall, thresholds = precision_recall_curve(y_true, y_score)
贝叶斯优化比网格搜索效率高10倍以上。关键配置:
python复制from skopt import BayesSearchCV
opt = BayesSearchCV(
estimator,
{
'C': (1e-6, 1e+6, 'log-uniform'),
'gamma': (1e-6, 1e+1, 'log-uniform')
},
n_iter=32,
cv=5
)
opt.fit(X, y)
除了常见的过采样,我们还开发了动态权重调整策略:
python复制class DynamicWeightedLoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, inputs, targets):
batch_classes = torch.unique(targets, return_counts=True)
weights = 1. / (batch_classes[1] / batch_classes[1].sum())
weights = weights / weights.sum()
return F.cross_entropy(inputs, targets, weight=weights)
我们建立了完整的特征监控体系:
python复制from scipy.stats import entropy
def kl_divergence(p, q):
return entropy(p, q)
current_dist = np.histogram(X_new[:, feature_idx], bins=20)[0]
baseline_dist = np.histogram(X_old[:, feature_idx], bins=20)[0]
divergence = kl_divergence(current_dist, baseline_dist)
SHAP值已经成为我们向业务部门解释模型的标准工具。使用技巧:
python复制import shap
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X)
shap.summary_plot(shap_values, X)
为了让BERT模型满足线上延迟要求,我们采用以下优化组合:
python复制from transformers import DistilBertForSequenceClassification
teacher = BertForSequenceClassification.from_pretrained('bert-base-uncased')
student = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased')
在模型部署后,我们还会持续监控数据分布变化,建立自动化的模型迭代流程。每次特征或模型更新都进行严格的A/B测试,确保新版本在业务指标上确实有提升。