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

文章目录

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

  • 逻辑回归 是一种用于二分类(有时也用于多分类)问题的统计模型。它通过将线性组合的输入变量经过一个逻辑函数(如 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的样本。故主要看召回率,从测试结果可以看出准确率还是挺高的,也没有产生过拟合和欠拟合。

相关推荐
MYH51631 分钟前
在NLP文本处理中,将字符映射到阿拉伯数字(构建词汇表vocab)的核心目的和意义
人工智能·深度学习·自然语言处理
要努力啊啊啊38 分钟前
KV Cache:大语言模型推理加速的核心机制详解
人工智能·语言模型·自然语言处理
mzlogin3 小时前
DIY|Mac 搭建 ESP-IDF 开发环境及编译小智 AI
人工智能
归去_来兮3 小时前
知识图谱技术概述
大数据·人工智能·知识图谱
就是有点傻3 小时前
VM图像处理之图像二值化
图像处理·人工智能·计算机视觉
行云流水剑3 小时前
【学习记录】深入解析 AI 交互中的五大核心概念:Prompt、Agent、MCP、Function Calling 与 Tools
人工智能·学习·交互
love530love3 小时前
【笔记】在 MSYS2(MINGW64)中正确安装 Rust
运维·开发语言·人工智能·windows·笔记·python·rust
狂小虎3 小时前
02 Deep learning神经网络的编程基础 逻辑回归--吴恩达
深度学习·神经网络·逻辑回归
A林玖3 小时前
【机器学习】主成分分析 (PCA)
人工智能·机器学习
molunnnn3 小时前
DAY 15 复习日
机器学习