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

文章目录

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

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

相关推荐
charley.layabox2 小时前
8月1日ChinaJoy酒会 | 游戏出海高端私享局 | 平台 × 发行 × 投资 × 研发精英畅饮畅聊
人工智能·游戏
DFRobot智位机器人3 小时前
AIOT开发选型:行空板 K10 与 M10 适用场景与选型深度解析
人工智能
想成为风筝5 小时前
从零开始学习深度学习—水果分类之PyQt5App
人工智能·深度学习·计算机视觉·pyqt
F_D_Z5 小时前
MMaDA:多模态大型扩散语言模型
人工智能·语言模型·自然语言处理
大知闲闲哟6 小时前
深度学习G2周:人脸图像生成(DCGAN)
人工智能·深度学习
飞哥数智坊6 小时前
Coze实战第15讲:钱都去哪儿了?Coze+飞书搭建自动记账系统
人工智能·coze
wenzhangli76 小时前
低代码引擎核心技术:OneCode常用动作事件速查手册及注解驱动开发详解
人工智能·低代码·云原生
潘达斯奈基~7 小时前
大模型的Temperature、Top-P、Top-K、Greedy Search、Beem Search
人工智能·aigc
倔强青铜三7 小时前
苦练Python第18天:Python异常处理锦囊
人工智能·python·面试
倔强青铜三7 小时前
苦练Python第17天:你必须掌握的Python内置函数
人工智能·python·面试