python画曲线函数 用python画函数曲线

Python matplotlib之函数图像绘制、线条rc参数设置

为避免中文显示出错,需导入matplotlib.pylab库

称多网站制作公司哪家好,找创新互联公司!从网页设计、网站建设、微信开发、APP开发、响应式网站开发等网站项目制作,到程序开发,运营维护。创新互联公司公司2013年成立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联公司

1.2.1 确定数据

1.2.2 创建画布

1.2.3 添加标题

1.2.4 添加x,y轴名称

1.2.5 添加x,y轴范围

1.2.6 添加x,y轴刻度

1.2.7 绘制曲线、图例, 并保存图片

保存图片时,dpi为清晰度,数值越高越清晰。请注意,函数结尾处,必须加plt.show(),不然图像不显示。

绘制流程与绘制不含子图的图像一致,只需注意一点:创建画布。

合理调整figsize、dpi,可避免出现第一幅图横轴名称与第二幅图标题相互遮盖的现象.

2.2.1 rc参数类型

2.2.2 方法1:使用rcParams设置

2.2.3 方法2:plot内设置

2.2.4 方法3:plot内简化设置

方法2中,线条形状,linestyle可简写为ls;线条宽度,linewidth可简写为lw;线条颜色,color可简写为c,等等。

不能直接写出函数的表达式 怎么在python里画函数图象呢?

不写出y=f(x)这样的表达式,由隐函数的等式直接绘制图像,以x²+y²+xy=1的图像为例,使用sympy间接调用matplotlib工具的代码和该二次曲线图像如下(注意python里的乘幂符号是**而不是^,还有,python的sympy工具箱的等式不是a==b,而是a-b或者Eq(a,b),这几点和matlab的区别很大)

直接在命令提示行的里面运行代码的效果

from sympy import *;

x,y=symbols('x y');

plotting.plot_implicit(x**2+y**2+x*y-1);

python之KS曲线

# 自定义绘制ks曲线的函数

def plot_ks(y_test, y_score, positive_flag):

# 对y_test,y_score重新设置索引

y_test.index = np.arange(len(y_test))

#y_score.index = np.arange(len(y_score))

# 构建目标数据集

target_data = pd.DataFrame({'y_test':y_test, 'y_score':y_score})

# 按y_score降序排列

target_data.sort_values(by = 'y_score', ascending = False, inplace = True)

# 自定义分位点

cuts = np.arange(0.1,1,0.1)

# 计算各分位点对应的Score值

index = len(target_data.y_score)*cuts

scores = target_data.y_score.iloc[index.astype('int')]

# 根据不同的Score值,计算Sensitivity和Specificity

Sensitivity = []

Specificity = []

for score in scores:

    # 正例覆盖样本数量与实际正例样本量

    positive_recall = target_data.loc[(target_data.y_test == positive_flag) (target_data.y_scorescore),:].shape[0]

    positive = sum(target_data.y_test == positive_flag)

    # 负例覆盖样本数量与实际负例样本量

    negative_recall = target_data.loc[(target_data.y_test != positive_flag) (target_data.y_score=score),:].shape[0]

    negative = sum(target_data.y_test != positive_flag)

    Sensitivity.append(positive_recall/positive)

    Specificity.append(negative_recall/negative)

# 构建绘图数据

plot_data = pd.DataFrame({'cuts':cuts,'y1':1-np.array(Specificity),'y2':np.array(Sensitivity),

                          'ks':np.array(Sensitivity)-(1-np.array(Specificity))})

# 寻找Sensitivity和1-Specificity之差的最大值索引

max_ks_index = np.argmax(plot_data.ks)

plt.plot([0]+cuts.tolist()+[1], [0]+plot_data.y1.tolist()+[1], label = '1-Specificity')

plt.plot([0]+cuts.tolist()+[1], [0]+plot_data.y2.tolist()+[1], label = 'Sensitivity')

# 添加参考线

plt.vlines(plot_data.cuts[max_ks_index], ymin = plot_data.y1[max_ks_index],

          ymax = plot_data.y2[max_ks_index], linestyles = '--')

# 添加文本信息

plt.text(x = plot_data.cuts[max_ks_index]+0.01,

        y = plot_data.y1[max_ks_index]+plot_data.ks[max_ks_index]/2,

        s = 'KS= %.2f' %plot_data.ks[max_ks_index])

# 显示图例

plt.legend()

# 显示图形

plt.show()

# 调用自定义函数,绘制K-S曲线

plot_ks(y_test = y_test, y_score = y_score, positive_flag = 1)

Python如何画函数的曲线

输入以下代码导入我们用到的函数库。

import numpy as np

import matplotlib.pyplot as plt

x=np.arange(0,5,0.1);

y=np.sin(x);

plt.plot(x,y)

采用刚才代码后有可能无法显示下图,然后在输入以下代码就可以了:

plt.show()

python 怎么画与其他方法进行比较的ROC曲线?

使用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

X, y = X[y != 2], y[y != 2] # 去掉了label为2,label只能二分,才可以。

n_samples, n_features = X.shape

# 增加噪声特征

random_state = np.random.RandomState(0)

X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]

cv = StratifiedKFold(n_splits=6) #导入该模型,后面将数据划分6份

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面积

plt.plot(fpr, tpr, lw=1, label='ROC fold {0:.2f} (area = {1:.2f})'.format(i, roc_auc)) # 画出当前分割数据的ROC曲线

plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck') # 画对角线

mean_tpr /= cnt # 求数组的平均值

mean_tpr[-1] = 1.0 # 坐标最后一个点为(1,1) 以1为终点

mean_auc = auc(mean_fpr, mean_tpr)

plt.plot(mean_fpr, mean_tpr, 'k--',label='Mean ROC (area = {0:.2f})'.format(mean_auc), lw=2)

plt.xlim([-0.05, 1.05]) # 设置x、y轴的上下限,设置宽一点,以免和边缘重合,可以更好的观察图像的整体

plt.ylim([-0.05, 1.05])

plt.xlabel('False Positive Rate')

plt.ylabel('True Positive Rate') # 可以使用中文,但需要导入一些库即字体

plt.title('Receiver operating characteristic example')

plt.legend(loc="lower right")

plt.show()

本文标题:python画曲线函数 用python画函数曲线
文章起源:https://www.cdcxhl.com/article24/dosdjje.html

成都网站建设公司_创新互联,为您提供全网营销推广静态网站微信公众号网站内链网站营销企业网站制作

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都定制网站网页设计