使用sklearn的一系列方法后可以很方便的绘制处ROC曲线,这里简单实现以下.
主要是利用混淆矩阵中的知识作为绘制的数据(如果不是很懂可以先看看这里的基础):
tpr(Ture Positive Rate):真阳率 图像的纵坐标
fpr(False Positive Rate):阳率(伪阳率) 图像的横坐标
mean_tpr:累计真阳率求平均值
mean_fpr:累计阳率求平均值
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.model_selection import StratifiedKFold
iris = datasets.load_iris()
X = iris.data
y = iris.target
n_samples, n_features = X.shape
# 增加噪声特征
random_state = np.random.RandomState(0)
classifier = svm.SVC(kernel='linear', probability=True,random_state=random_state) # SVC模型 可以换作AdaBoost模型试试
# 画平均ROC曲线的两个参数
mean_tpr = 0.0 # 用来记录画平均ROC曲线的信息
mean_fpr = np.linspace(0, 1, 100)
cnt = 0
for i, (train, test) in enumerate(cv.split(X,y)): #利用模型划分数据集和目标变量 为一一对应的下标
cnt +=1
probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test]) # 训练模型后预测每条样本得到两种结果的概率
fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1]) # 该函数得到伪正例、真正例、阈值,这里只使用前两个
mean_tpr += np.interp(mean_fpr, fpr, tpr) # 插值函数 interp(x坐标,每次x增加距离,y坐标) 累计每次循环的总值后面求平均值
mean_tpr[0] = 0.0 # 将第一个真正例=0 以0为起点
roc_auc = auc(fpr, tpr) # 求auc面积
mean_tpr /= cnt # 求数组的平均值
mean_tpr[-1] = 1.0 # 坐标最后一个点为(1,1) 以1为终点
mean_auc = auc(mean_fpr, mean_tpr)
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate') # 可以使用中文,但需要导入一些库即字体
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()
直接在命令提示行的里面运行代码的效果
from sympy import *;
x,y=symbols('x y');
输入以下代码导入我们用到的函数库.
y=np.sin(x);
plt.plot(x,y)
采用刚才代码后有可能无法显示下图,然后在输入以下代码就可以了:
用python怎样画出如题所示的正余弦函数图像? 如此编写代码,使其中两个轴、图例、刻度,大小,LaTex公式等要素与原图一致,需要用到的代码如下,没有缩进:
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(a,b,label=r"$y=\sin(\theta)$")
ax.plot(a,c,label=r"$y=\cos(\theta)$")
ax.grid(True)
ax.set_ylabel(r"$y$")
ax.set_xlabel(r"$\theta$")
plt.title("Sine Cosine Waves")
plt.legend()
plt.savefig("SinCosWaveDegFont.jpg")
代码运行show的窗口图
代码的截图
代码输出的文件的图
以上就是土嘎嘎小编为大家整理的python函数曲线代码相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!