如何实现下采样(教科书级别教你拿捏)

在数据处理、信号处理、图像处理以及机器学习等多个领域中,下采样(Downsampling)是一项至关重要的技术。下采样旨在减少数据集中的样本数量,同时尽量保留原始数据的关键信息,以便在降低计算成本、提高处理速度或适应特定分析需求时仍然保持数据的代表性。本文将详细介绍下采样的基本概念、应用场景以及几种常用的实现方法。

一、下采样的基本概念

下采样,也称为降采样,是通过对原始数据进行抽样或聚合操作,以较低的频率重新表示数据的过程。在图像处理中,这通常意味着减少图像的分辨率;在信号处理中,则可能意味着减少采样率。下采样的目标是减少数据量,同时尽可能保持数据的统计特性和重要特征。

二、下采样的应用场景

  1. 图像处理:在图像压缩、图像缩放、特征提取等场景中,下采样能够减少图像的像素数量,降低处理难度和存储需求。
  2. 信号处理:在音频和视频处理中,下采样可以降低信号的采样率,以适应不同的播放设备或网络传输要求。
  3. 机器学习:在训练大规模数据集时,下采样可以帮助减少计算量,加速模型训练过程,尤其是在处理不平衡数据集时,下采样可以有效平衡类别分布。

例子:

import pandas as pd
import matplotlib.pyplot as plt
from pylab import mpl
import numpy as np


def cm_plot(y, yp):
    from sklearn.metrics import confusion_matrix
    import matplotlib.pyplot as plt

    cm = confusion_matrix(y, yp)
    plt.matshow(cm, cmap=plt.cm.Blues)
    plt.colorbar()
    for x in range(len(cm)):
        for y in range(len(cm)):
            plt.annotate(cm[x, y], xy=(y, x), horizontalalignment='center',
                         verticalalignment='center')
            plt.ylabel('True label')
            plt.xlabel('Predicted label')
    return plt


data = pd.read_csv(r"./creditcard.csv")


from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
a = data[['Amount']]
data['Amount'] = scaler.fit_transform(data[['Amount']])

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

positive_eg = data[data['Class'] == 0]
negative_eg = data[data['Class'] == 1]
np.random.seed(seed=4)
positive_eg = positive_eg.sample(len(negative_eg))
data_c = pd.concat([positive_eg,negative_eg])
print(data_c)

mpl.rcParams['font.sans-serif'] = ['Microsoft YaHei']
mpl.rcParams['axes.unicode_minus'] = False

labels_count = pd.value_counts(data['Class'])
plt.title("正负例样本数")
plt.xlabel("类别")
plt.ylabel("频数")
labels_count.plot(kind='bar')
plt.show()

from sklearn.model_selection import train_test_split

x = data_c.drop('Class', axis=1)
y = data_c.Class
x_train, x_test, y_train, y_test = \
    train_test_split(x, y, train_size=0.3, random_state=0)

from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression

scores = []
c_param_range = [0.01, 0.1, 1, 10, 100]
for i in c_param_range:
    lr = LogisticRegression(C=i, penalty='l2', solver='lbfgs', max_iter=1000)
    score = cross_val_score(lr, x_train, y_train, cv=8, scoring='recall')
    score_mean = sum(score) / len(score)
    scores.append(score_mean)
    print(score_mean)

best_c = c_param_range[np.argmax(scores)]

lr = LogisticRegression(C=best_c, penalty='l2', max_iter=1000)
lr.fit(x_train, y_train)

from sklearn import metrics

train_predicted = lr.predict(x_train)
print(metrics.classification_report(y_train, train_predicted))
cm_plot(y_train, train_predicted).show()

test_predicted = lr.predict(x_test)
print(metrics.classification_report(y_test, test_predicted))
cm_plot(y_test, test_predicted).show()


x1 = data.drop('Class', axis=1)
y1 = data.Class
x1_train, x1_test, y1_train, y1_test = \
    train_test_split(x1, y1, train_size=0.3, random_state=0)

test_predicted_big = lr.predict(x1_test)
print(metrics.classification_report(y1_test, test_predicted_big))
cm_plot(y1_test, test_predicted_big).show()


recalls = []
thresholds = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
for i in thresholds:
    y_perdict_proba = lr.predict_proba(x_test)
    y_perdict_proba = pd.DataFrame(y_perdict_proba)
    y_perdict_proba = y_perdict_proba.drop([0], axis=1)
    y_perdict_proba[y_perdict_proba[[1]] > i] = 1
    y_perdict_proba[y_perdict_proba[[1]] <= i] = 0

    recall = metrics.recall_score(y_test, y_perdict_proba[1])
    recalls.append(recall)
    print("{} Recall metric in the testing dataset: {:.3f}".format(i, recall))
  1. 导入库

    • pandas 用于数据处理。
    • matplotlib.pyplot 和 pylab.mpl 用于绘图。
    • numpy 用于数值计算。
    • sklearn 中的 confusion_matrix 和其他模块用于机器学习任务。
  2. 定义混淆矩阵绘制函数 cm_plot

    • 计算混淆矩阵,并用 matplotlib 绘制。
    • 在矩阵中添加每个元素的值,便于观察。
  3. 数据加载和预处理

    • 读取数据集 creditcard.csv
    • 标准化 Amount 特征,确保其均值为 0,方差为 1。
    • 删除 Time 列,因为它对模型训练没有帮助。
    • 对数据进行平衡处理:通过随机抽样将正负样本数量调整一致。
    • 打印平衡后的数据集。
  4. 绘制正负例样本数的柱状图

    • 使用 pandas 计算每个类别的样本数,并用 matplotlib 绘制柱状图。
  5. 模型训练和评估

    • 划分数据集为训练集和测试集。
    • 使用逻辑回归模型,调整正则化参数 C,并通过交叉验证评估模型的召回率。
    • 选择最佳的 C 参数,并用其训练最终模型。
    • 输出训练集和测试集上的分类报告,并绘制混淆矩阵。
  6. 对整个数据集的最终模型评估

    • 重新划分数据集为训练集和测试集,并评估模型的性能。
    • 打印最终的分类报告和混淆矩阵。
  7. 调整阈值进行召回率分析

    • 修改预测概率的阈值,计算不同阈值下的召回率。
    • 绘制不同阈值下的召回率,帮助理解模型在不同条件下的表现。
  • 19
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值