逻辑回归:再访

Python 中的情感分析

Violeta Misheva

Data Scientist

复杂模型与正则化

复杂模型:

  • 复杂模型会拟合数据中的噪声(过拟合)
  • 特征或参数数量多

正则化:

  • 用于简化并降低模型复杂度
Python 中的情感分析

逻辑回归中的正则化

from sklearn.linear_model import LogisticRegression
# Regularization arguments
LogisticRegression(penalty='l2', C=1.0)
  • L2:将所有系数收缩至接近 0
  • C 大:惩罚弱,训练拟合更好
  • C 小:惩罚强,模型更不灵活
Python 中的情感分析

预测概率 vs. 预测类别

log_reg = LogisticRegression().fit(X_train, y_train)
# Predict labels 
y_predicted = log_reg.predict(X_test)
# Predict probability
y_probab = log_reg.predict_proba(X_test)
Python 中的情感分析

预测概率 vs. 预测类别

y_probab
array([[0.5002245, 0.4997755],
       [0.4900345, 0.5099655],
        ...,
       [0.7040499, 0.2959501]])
# Select the probabilities of class 1
y_probab = log_reg.predict_proba(X_test)[:, 1]
array([0.4997755, 0.5099655 ..., 0.2959501]])
Python 中的情感分析

用预测概率计算指标

  • 用概率时会抛出 ValueError
  • 准确率与混淆矩阵适用于类别。
# 默认概率阈值编码:
# 若概率 >= 0.5,则为类别 1;否则为类别 0
Python 中的情感分析

让我们来练习!

Python 中的情感分析

Preparing Video For Download...