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

文章目录

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

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

相关推荐
北京地铁1号线21 小时前
Qwen-VL(阿里通义千问视觉语言模型)模型架构和损失函数介绍
人工智能·语言模型·自然语言处理
阿豪321 小时前
2025 年职场转行突围:除实习外,这些硬核证书让你的简历脱颖而出(纯经验分享)
大数据·人工智能·经验分享·科技·信息可视化·产品经理
阿杜杜不是阿木木21 小时前
开始 ComfyUI 的 AI 绘图之旅-Stable Diffusion图生图之局部重绘(Inpaint)和扩图(Outpaint)(三)
人工智能·ai·ai作画·aigc·图生图
阿杜杜不是阿木木1 天前
开始 ComfyUI 的 AI 绘图之旅-Stable Diffusion图生图(二)
人工智能·ai·ai作画·aigc·图生图
九章云极AladdinEdu1 天前
存算一体芯片生态评估:从三星PIM到知存科技WTM2101
人工智能·pytorch·科技·架构·开源·gpu算力
张驰课堂1 天前
老树发新芽:六西格玛培训为石油机械制造注入持久活力
大数据·人工智能·制造
和光同尘@1 天前
66. 加一 (编程基础0到1)(Leetcode)
数据结构·人工智能·算法·leetcode·职场和发展
飞哥数智坊1 天前
放弃 Cursor 后,我又试了 CodeBuddy,感觉国产又行了
人工智能·codebuddy
新智元1 天前
世界首富换人!81 岁硅谷狂人 4000 亿身价碾压马斯克,33 岁华裔才女逆袭
人工智能·openai