机器学习生成实验数据仿真-指定KS或AUC值

有的我们在做机器学习的时候,需要自己做一些实验。这时候我们经常会制造一些数据用于训练,比如我们要生成一个KS值等于66的样本数据,那么如何来操作呢

from sklearn.datasets import make_classification
from sklearn.metrics import roc_auc_score,roc_curve
import pandas as pd

def generate_simulated_data(n_samples, n_features, auc_target):
    while True:
        # 生成随机数据
        X, y = make_classification(n_samples=n_samples, n_features=n_features)
        
        # 计算实际AUC值
        fpr_cdt,tpr_cdt,thresholds_cdt = roc_curve(y, X[:, 0])
        auc_actual=round(max(abs(tpr_cdt-fpr_cdt)),4)
        
        # 如果实际AUC值与目标AUC值接近,则返回数据
        if abs(auc_actual - auc_target) < 0.01:
            return X, y

# 指定参数
n_samples = 1000
n_features = 10
auc_target = 0.66

# 生成数据
X, y = generate_simulated_data(n_samples, n_features, auc_target)

这样X,y的数据我们都生成了,然后我们再使用该数据进行画图,看一下是否满足KS为66呢

from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt
import numpy as np

fpr, tpr, thresholds= roc_curve(y, X[:,0])
ks_value = max(abs(fpr-tpr))

# 画图,画出曲线
fig = plt.figure(dpi=400) 
plt.plot(fpr, label='bad')
plt.plot(tpr, label='good')
plt.plot(abs(fpr-tpr), label='diff')
# 标记ks
x = np.argwhere(abs(fpr-tpr) == ks_value)[0, 0]
plt.plot((x, x), (0, ks_value), label='ks - {:.3f}'.format(ks_value), color='r', marker='o', markerfacecolor='r', markersize=5)
plt.scatter((x, x), (0, ks_value), color='r')
plt.legend()
plt.show()

生成KS曲线如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田晖扬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值