custom python matlabplot

本文介绍了一种使用Python绘制多分类精度-召回率曲线的方法,并展示了如何从测试集中加载预测得分和真实标签来生成这些曲线。此外,还提供了设置图表样式、颜色和标记的具体细节。
部署运行你感兴趣的模型镜像

Add Parameters:

import matplotlib.pyplot as plt
import numpy as np
from itertools import cycle

from sklearn import svm, datasets
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import average_precision_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier

#load data
y_test = np.loadtxt('./y_test_201708101147.txt')
y_score = np.loadtxt('./y_score_201708101147.txt')

# Compute Precision-Recall and plot curve
precision = dict()
recall = dict()
threshold = dict()
for i in range(3):
    precision[i], recall[i], threshold[i] = precision_recall_curve(y_test[:, i], y_score[:, i])

# setup plot details
params = {'legend.fontsize': 30,
          'font.family':'sans-serif',
          'font.sans-serif':'Calibri',
          'figure.figsize': (15, 15),
         'axes.labelsize': 40,
         'axes.titlesize':40,
         'xtick.labelsize':30,
         'ytick.labelsize':30}
plt.rcParams.update(params)
colors = cycle(['navy', 'turquoise', 'darkorange', 'cornflowerblue', 'teal'])
className = ['s1', 'm1', 'max_s1_m1']
markerName = ['|', 'x', '^']
lw = 2

# Plot Precision-Recall curve for each class
plt.clf()
#plt.figure(figsize=(15,15))
#for i, color in zip(range(3), colors):
#    plt.plot(recall[i], precision[i], '{0}'.format(styleName[i]), markersize=4, label='Precision-Recall curve of {0}'.format(className[i]))

plt.plot(recall[0], precision[0], 'r^', markersize=6, label='Precision-Recall curve of s1')
plt.plot(recall[1], precision[1], 'b.', markersize=4, label='Precision-Recall curve of m1')
plt.plot(recall[2], precision[2], 'y--', markersize=6, label='Precision-Recall curve of max_s1_m1')
    
plt.plot(recall[0][:recall[0].size-1], threshold[0], color='cornflowerblue', lw=lw, label='Threshold-Recall curve of s1')

plt.
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('Recall')
plt.ylabel('Precision/Threshold')
plt.title('Precision-Recall curve to multi-class')
plt.legend(loc="lower right")
plt.savefig('tmp.pdf')
plt.show()

不新开窗口没法执行plt.show()

# This code is written in python
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# x-axis values
x_axis=[1,4,5,7]
# y-axis values
y_axis=[2,10,7,9]
# Plotting the points
plt.plot(x_axis, y_axis)

#grid is on
plt.grid()

# Saving the figure in local memory
plt.savefig('Figure1.png')

# # function to show the plot
# plt.show()
#不新开窗口没法show
plt.imshow(mpimg.imread('Figure1.png'))  
#不新开窗口没法show
plt.show() 

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

### Python中实现ESMD方法 ESMD(Extreme-point Symmetric Mode Decomposition)是一种基于极点对称的模态分解方法,用于处理非线性和非平稳时间序列数据。尽管Python社区中有许多关于EMD及其变体(如EEMD和CEEMDAN)的库,但目前并没有广泛使用的专门针对ESMD的现成库。 以下是通过自定义代码实现在Python中使用ESMD的方法: #### 自定义ESMD函数 由于缺乏官方支持的Python库,可以通过手动编写代码来实现ESMD的核心逻辑。以下是一个简单的实现框架: ```python import numpy as np from scipy.interpolate import interp1d import matplotlib.pyplot as plt def find_extrema(signal): """ 找到信号的最大值和最小值 """ peaks = [] troughs = [] for i in range(1, len(signal)-1): if signal[i] > signal[i-1] and signal[i] > signal[i+1]: peaks.append(i) elif signal[i] < signal[i-1] and signal[i] < signal[i+1]: troughs.append(i) return np.array(peaks), np.array(troughs) def interpolate_signal(extremas, time_axis, signal): """ 插值生成上下包络 """ extrema_values = signal[extremas] f_interpolate = interp1d(time_axis[extremas], extrema_values, kind='cubic', fill_value="extrapolate") interpolated_signal = f_interpolate(time_axis) return interpolated_signal def esmd_decompose(signal, t=None): """ 实现ESMD分解 """ if t is None: t = np.arange(len(signal)) imfs = [] residual = signal.copy() while True: sifting_complete = False sifted_component = residual.copy() iteration_count = 0 while not sifting_complete: iteration_count += 1 # 查找极大值和极小值 peaks, troughs = find_extrema(sifted_component) if len(peaks) < 2 or len(troughs) < 2: break # 构建上下包络 upper_envelope = interpolate_signal(peaks, t, sifted_component) lower_envelope = interpolate_signal(troughs, t, sifted_component) mean_envelope = (upper_envelope + lower_envelope) / 2 sifted_component -= mean_envelope # 判断是否满足停止条件 sd = np.sum((sifted_component - mean_envelope)**2) / np.sum(sifted_component**2) if sd < 0.01: # 停止阈值可以根据需求调整 sifting_complete = True imfs.append(sifted_component) residual -= sifted_component # 如果剩余部分不足以继续分解,则退出循环 if len(find_extrema(residual)[0]) < 3: break return imfs, residual if __name__ == "__main__": # 创建测试信号 t = np.linspace(0, 1, 1000) S = np.sin(2 * np.pi * 5 * t) + np.sin(2 * np.pi * 10 * t) + 0.5 * np.random.randn(len(t)) # 使用ESMD分解 imfs, residue = esmd_decompose(S, t=t) # 绘制结果 plt.figure(figsize=(10, 6)) plt.subplot(len(imfs)+2, 1, 1) plt.plot(t, S, 'k') plt.title("Original Signal") for idx, imf in enumerate(imfs, start=2): plt.subplot(len(imfs)+2, 1, idx) plt.plot(t, imf) plt.title(f"IMF {idx-1}") plt.subplot(len(imfs)+2, 1, len(imfs)+2) plt.plot(t, residue) plt.title("Residue") plt.tight_layout() plt.show() ``` 以上代码实现了基本的ESMD分解功能[^custom_esmd]。它通过对信号进行多次筛选操作提取固有模态分量(IMFs),直到残余信号不再含有足够的极值为止。 --- #### 已有的第三方工具 虽然当前没有专门为ESMD设计的标准Python库,但可以尝试寻找类似的替代方案或扩展现有库的功能。例如: - **PyEMD**: 提供了经典的EMD以及其改进版本的支持,可能作为基础模块进一步开发。 - **Rapyuta4ML**: 包含一些高级的时间序列分析工具,或许能够提供灵感。 如果需要更精确的结果或者特定领域应用下的优化参数设置,建议参考Matlab中的`ESMD`实现并移植至Python环境[^matlab_to_python]. --- ### 注意事项 在实际应用过程中需要注意以下几个方面: 1. 数据预处理:对于噪声较大的输入信号,应先进行平滑或其他形式的数据清理工作。 2. 参数调优:包括但不限于迭代次数上限、SD容忍度等超参的选择都会影响最终效果。 3. 边界效应:极端情况下可能会出现边界不连续的现象,需额外考虑修正策略。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值