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

文章目录

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

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

相关推荐
Moshow郑锴1 小时前
人工智能中的(特征选择)数据过滤方法和包裹方法
人工智能
TY-20252 小时前
【CV 目标检测】Fast RCNN模型①——与R-CNN区别
人工智能·目标检测·目标跟踪·cnn
CareyWYR2 小时前
苹果芯片Mac使用Docker部署MinerU api服务
人工智能
失散133 小时前
自然语言处理——02 文本预处理(下)
人工智能·自然语言处理
mit6.8243 小时前
[1Prompt1Story] 滑动窗口机制 | 图像生成管线 | VAE变分自编码器 | UNet去噪神经网络
人工智能·python
sinat_286945193 小时前
AI应用安全 - Prompt注入攻击
人工智能·安全·prompt
迈火4 小时前
ComfyUI-3D-Pack:3D创作的AI神器
人工智能·gpt·3d·ai·stable diffusion·aigc·midjourney
Moshow郑锴5 小时前
机器学习的特征工程(特征构造、特征选择、特征转换和特征提取)详解
人工智能·机器学习
CareyWYR6 小时前
每周AI论文速递(250811-250815)
人工智能
AI精钢6 小时前
H20芯片与中国的科技自立:一场隐形的博弈
人工智能·科技·stm32·单片机·物联网