《机器学习》——逻辑回归(过采样)

文章目录

什么是逻辑回归和过采样?

  • 逻辑回归 是一种用于二分类(有时也用于多分类)问题的统计模型。它通过将线性组合的输入变量经过一个逻辑函数(如 sigmoid 函数)来预测事件发生的概率。然而,在实际数据集中,经常会遇到类别不平衡的问题,即不同类别的样本数量差异较大。例如,在一个疾病诊断数据集中,患病的人数可能远远少于未患病的人数。
  • 过采样


    主要意思就是将样本不平衡的样本比例,通过过采样增加样本使其变的平衡。

实例

让我们通过实例,来介绍过采样。

1、实例内容

本次实例是对银行的数据进行分类的问题,数据部分内容为

共有28万多条数据。其中Time为无关特征,class为分类特征有两个分类分别为0、1,其余全部为特征变量。如图看看出Amount里的数据与其他特征的数据有区别,故此数据处理中要对Amount进行z标准化处理。

2、步骤
  • 导入数据
python 复制代码
data = pd.read_csv('creditcard.csv', encoding='utf8', engine='python')
  • 数据处理和划分
python 复制代码
from sklearn.preprocessing import StandardScaler
# z标准化
scaler = StandardScaler()
a = data[['Amount']]
data['Amount'] = scaler.fit_transform(data[['Amount']])

data = data.drop(['Time'], axis=1)

from sklearn.model_selection import train_test_split

x_whole = data.drop('Class', axis=1)
y_whole = data.Class
x_train_w, x_test_w, y_train_w, y_test_w = train_test_split(x_whole, y_whole, test_size=0.2, random_state=0)
  • 过采样处理并再次划分数据,画图查看
python 复制代码
from imblearn.over_sampling import SMOTE

oversampler = SMOTE(random_state=0)
os_x_train, os_y_train = oversampler.fit_resample(x_train_w, y_train_w)

mpl.rcParams['font.sans-serif']=['Microsoft YaHei']
mpl.rcParams['axes.unicode_minus']=False
labels_count = pd.value_counts(os_y_train)
plt.title('正负例样本数')
plt.xlabel('类别')
plt.ylabel('频数')
labels_count.plot(kind='bar')
plt.show()


os_x_train_w, os_x_test_w, os_y_train_w, os_y_test_w = \
    train_test_split(os_x_train, os_y_train, test_size=0.2, random_state=0)
  • 挑选最优惩罚因子
python 复制代码
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score

scores = []
c_param_range = [0.01, 0.1, 1, 10, 100]
z = 1
for i in c_param_range:
    start_time = time.time()
    lr = LogisticRegression(C=i, penalty='l2', solver='lbfgs', max_iter=1000)
    score = cross_val_score(lr, os_x_train, os_y_train, cv=5, scoring='recall')
    score_mean = sum(score) / len(score)
    scores.append(score_mean)
    end_time = time.time()
    print(f'第{z}次。。。。')
    print('time spend:{:.2f}'.format(end_time - start_time))
    print(f'recall:{score_mean}')
    z += 1
best_c = c_param_range[np.argmax(scores)]
print("最优惩罚因子为:{}".format(best_c))
  • 训练模型
python 复制代码
lr = LogisticRegression(C=best_c,penalty='l2',solver='lbfgs',max_iter=1000)
lr.fit(os_x_train_w,os_y_train_w)
  • 测试模型并评估模型性能
python 复制代码
train_predicted =lr.predict(os_x_test_w)
print(metrics.classification_report(os_y_test_w,train_predicted))

train_predicted =lr.predict(x_test_w)
print(metrics.classification_report(y_test_w,train_predicted))

因为银行主要观察特征为1的人,宁愿原本为0的预测为1,也不愿判断错一个1的样本。故主要看召回率,从测试结果可以看出准确率还是挺高的,也没有产生过拟合和欠拟合。

相关推荐
@心都15 分钟前
机器学习数学基础:29.t检验
人工智能·机器学习
9命怪猫17 分钟前
DeepSeek底层揭秘——微调
人工智能·深度学习·神经网络·ai·大模型
kcarly2 小时前
KTransformers如何通过内核级优化、多GPU并行策略和稀疏注意力等技术显著加速大语言模型的推理速度?
人工智能·语言模型·自然语言处理
倒霉蛋小马3 小时前
【YOLOv8】损失函数
深度学习·yolo·机器学习
MinIO官方账号3 小时前
使用 AIStor 和 OpenSearch 增强搜索功能
人工智能
补三补四3 小时前
金融时间序列【量化理论】
机器学习·金融·数据分析·时间序列
江江江江江江江江江4 小时前
深度神经网络终极指南:从数学本质到工业级实现(附Keras版本代码)
人工智能·keras·dnn
Fansv5874 小时前
深度学习-2.机械学习基础
人工智能·经验分享·python·深度学习·算法·机器学习
小怪兽会微笑4 小时前
PyTorch Tensor 形状变化操作详解
人工智能·pytorch·python
Erekys5 小时前
视觉分析之边缘检测算法
人工智能·计算机视觉·音视频