python中的完全单调插值

2023-11-26

我有一些数据,例如:

enter image description here

我想拟合一条可微分的单调曲线。我试过PchipInterpolator类但在一个非常相似的图表上,结果是:

enter image description here

这并不单调。

如何将单调曲线拟合到这样的数据?

以下是另一个类似图表的 y 值示例集:

[0.1109157119023644, 0.20187393816931934, 0.14466318670239758, 0.16535159414166822, 0.05452708697483864, 0.2153046237959556, 0.2200300476272603, 0.21012762463269324, 0.15947100322395022, 0.2819691842129948, 0.15567770052985092, 0.24850595803020692, 0.1329341593280457, 0.15595107081606913, 0.3232021121832229, 0.23707961921686588, 0.2415887076540357, 0.32363506549779797, 0.3584089204036798, 0.29232772580068433, 0.22145994836140775, 0.22797587985241133, 0.2717787840603025, 0.3245255944762287, 0.29301098282789195, 0.32417076823344143, 0.3450906550996232, 0.34272097408024904, 0.3868714875012437, 0.41876692320045755, 0.3544198724867363, 0.33073960954801895, 0.3921033666371904, 0.33349050060172974, 0.3608862044547096, 0.37375822841635425, 0.5396399750708429, 0.4209201143798284, 0.42004773793166883, 0.5217725632679073, 0.5911731474218788, 0.43389609315065386, 0.4287288396176006, 0.43007525393257007, 0.5687062142675405, 0.6030811498722173, 0.5292225577714743, 0.47710974351051355, 0.6182720730381119, 0.6241033581931327, 0.6236788197617511, 0.6643161356364049, 0.5577616524049582, 0.6888440258481371, 0.6867893120660341, 0.6685257606057502, 0.599481675493677, 0.7309075091448749, 0.7644365338580481, 0.6176797601816733, 0.6751467827192018, 0.6452178017908761, 0.6684778262246701, 0.7003380077556168, 0.667035916425416, 0.8434451759113093, 0.8419343615815968, 0.8657695361433773, 0.7392487161484605, 0.8773282098364621, 0.8265679895117846, 0.7246599961191632, 0.7251899061730714, 0.9271640780410231, 0.9180581424305536, 0.8099033021701689, 0.8268585329594615, 0.8519967080830176, 0.8711231413093845, 0.8689802343798663, 0.8299523829217353, 1.0057741699770046, 0.8538130788729608, 0.9662784297225102, 1.023419780920539, 0.913146849759822, 0.9900885996579213, 0.8740638988529978, 0.8900285618419457, 0.9065474574434158, 1.0749522597307315, 1.0319120938258166, 1.0051369663172995, 0.9893558841613622, 1.051384986916457, 1.0327996870915341, 1.0945543972861898, 0.9716604944496021, 1.1490370559566179, 1.1379231481207432, 1.6836433783615088, 1.8162068766097395, 2.072155286917785, 2.0395966998366, 2.191064589600466, 2.1581974932543617, 2.163403843819597, 2.133441151300847, 2.1726053994136922, 2.1157865673629526, 2.2249636455682866, 2.2313062166802147, 2.1731708496472764, 2.315203950110816, 2.1601242661726827, 2.174940281421225, 2.2653635413275945, 2.337227057574145, 2.3645767548381618, 2.3084919291392527, 2.314014515926446, 2.25166717296155, 2.2621157708115778, 2.2644578546265586, 2.313504860292943, 2.398969190357051, 2.309443951779675, 2.278946047410807, 2.4080802287121146, 2.353652872018618, 2.35527529074088, 2.4233001060410784, 2.428767198055608, 2.35677123091093, 2.497135132404064, 2.3978099128437282, 2.3970802609341972, 2.4967434818740024, 2.511209192435555, 2.541001050440798, 2.5760248002036525, 2.5960512284192245, 2.4778408861721037, 2.5757724103530046, 2.631148267999664, 2.538327346218921, 2.4878734713248507, 2.6133797275761066, 2.6282561527857395, 2.6150327104952447, 3.102757164382848, 3.3318503012160905, 3.3907776288198193, 3.6065313558941936, 3.601180295875859, 3.560491539319038, 3.650095006265445, 3.574812155815713, 3.686227315374108, 3.6338261415040867, 3.5661194785086288, 3.5747332336054645, 3.560674343726918, 3.5678550481603635, 3.5342848534390967, 3.4929538312485913, 3.564544653619436, 3.6861775399566126, 3.6390300636595216, 3.6656336332413666, 3.5731185631923945, 3.5965520044069854, 3.537434489989021, 3.5590937423870144, 3.5331656424410083, 3.640652819618705, 3.5971240740252126, 3.641793843012055, 3.6064014089254295, 3.530378938786505, 3.613631139461306, 3.519542268056021, 3.5416251524576, 3.524789618934195, 3.5519951806099512, 3.6435695455293975, 3.6825670484650863, 3.5993379768209217, 3.628367553897596, 3.633290480934276, 3.5772841681579535, 3.602326323397947, 3.518180278272883, 3.531054006706696, 3.5566645495066167, 3.5410992153240985, 3.630762839301216, 3.5924649123201053, 3.646230633817883, 3.568290612034935, 3.638356129262967, 3.566083243271712, 3.6064978645771797, 3.4942864293427633, 3.595438454812999, 3.681726879126678, 3.6501308156903463, 3.5490717955938593, 3.598535359345363, 3.6328331698421654, 3.595159538698094, 3.556715819008055, 3.6292942886764554, 3.6362895697392856, 3.5965220100874093, 3.6103542985016266, 3.5715010140382493, 3.658769915445062, 3.5939686395400416, 3.4974461928859917, 3.5232691556732267, 3.6145687814416614, 3.5682054018341005, 3.648937250575395, 3.4912089018613384, 3.522426560340423, 3.6757968409374637, 3.651348691084845, 3.5395070091675973, 3.5306275536360383, 3.6153498246329883, 3.599762785949876, 3.5351931286962333, 3.6488316987683054, 3.5198301490992963, 3.5696570079786687, 3.561553836008927, 3.5659475947331423, 3.553147100256108, 3.5475591872743664, 3.6097226797553317, 3.6849600324757934, 3.5264731043844413, 3.506658609738451, 3.5535775980874114, 3.5487291053913554, 3.570651383823912, 3.552993371839188, 3.5054297764661846, 3.5723024888238792]

这是一个单调曲线拟合器,基本上用 5 行 python 代码,用 numpy 和来自 scipy.signal 的低通滤波器:

enter image description here

#!/usr/bin/env python
"""https://stackoverflow.com/questions/56551114/fully-monotone-interpolation-in-python """
# see also
# https://en.wikipedia.org/wiki/Monotone-spline aka I-spline
# https://scikit-learn.org/stable/modules/isotonic.html
# denis 2 March 2020

from __future__ import division, print_function
import numpy as np
from scipy import signal as sig

from matplotlib import pyplot as plt
import seaborn as sns


def butter_filtfilt( x, Wn=0.5, axis=0 ):
    """ butter( 2, Wn ), filtfilt
        axis 0 each col, -1 each row
    """
    b, a = sig.butter( N=2, Wn=Wn )
    return sig.filtfilt( b, a, x, axis=axis, method="gust" )  # twice, forward backward

def ints( x ):
    return x.round().astype(int)

def minavmax( x ):
    return "min av max %.3g %.3g %.3g" % (
            x.min(), x.mean(), x.max() )

def pvec( x ):
    n = len(x) // 25 * 25
    return "%s \n%s \n" % (
        minavmax( x ),
        ints( x[ - n : ]) .reshape( -1, 25 ))

#...............................................................................
def monofit( y, Wn=0.1 ):
    """ monotone-increasing curve fit """
    y = np.asarray(y).squeeze()
    print( "\n{ monofit: y %d %s  Wn %.3g " % (
        len(y), minavmax( y ), Wn ))
    ygrad = np.gradient( y )
    print( "grad y:", pvec( ygrad ))

        # lowpass filter --
    gradsmooth = butter_filtfilt( ygrad, Wn=Wn )
    print( "gradsmooth:", pvec( gradsmooth ))

    ge0 = np.fmax( gradsmooth, 0 )

    ymono = np.cumsum( ge0 )  # integrate, sensitive to first few
    ymono += (y - ymono).mean()

    err = y - ymono
    print( "y - ymono:", pvec( err ))
    errstr = "average |y - monofit|: %.2g" % np.abs( err ).mean()
    print( errstr )
    print( "} \n" )

    return ymono, err, errstr

#...............................................................................
if __name__ == "__main__":
    import sys

    np.set_printoptions( threshold=20, edgeitems=15, linewidth=120,
            formatter = dict( float = lambda x: "%.2g" % x ))  # float arrays %.2g
    print( 80 * "=" )

    thispy = sys.argv[0]
    infile = sys.argv[1] if len(sys.argv) > 1 \
        else "so-mono.txt"
    Wn = 0.1  # ?
    params = "%s %s  Wn %g " % (thispy, infile, Wn)
    print( params )

    y = np.loadtxt( infile ) * 100
    print( "y:", y )

    ymono, err, errstr = monofit( y, Wn=Wn )

    if 1:
        sns.set_style("whitegrid")
        fig, ax = plt.subplots( figsize=[10, 5] )
        plt.subplots_adjust( left=.05, right=.99, bottom=.05, top=.90 )
        fig.suptitle(
"Easy monotone curve fit: np.gradient | lowpass filter | clip < 0 | integrate \n"
            + errstr, multialignment="left" )

        ax.plot( ymono, color="orangered" )
        j = np.where( ymono < y )[0]
        xax = np.arange( len(y) )
        plt.vlines( xax[j], ymono[j], y[j], color="blue", lw=1 )
        j = np.where( ymono > y )[0]
        plt.vlines( xax[j], y[j], ymono[j], color="blue", lw=1 )

        png = thispy.replace( ".py", ".png" )
        print( "writing", png )
        plt.savefig( png )
        plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python中的完全单调插值 的相关文章

  • 如何(重新)命名 pandas 数据框中的空列标题而不导出到 csv

    我有一个熊猫数据框df1带有一个索引列和一系列未命名的值 我想为未命名的系列指定一个名称 到目前为止 我知道的唯一方法是导出到df1 csv using df1 to csv df1 csv header Signal 然后使用以下命令重新
  • Python 转换矩阵

    我有一个如下所示的列表 2 1 3 1 2 3 1 2 2 2 我想要的是一个转换矩阵 它向我显示如下序列 1 后跟 1 的频率是多少 1 后面跟着 2 的频率是多少 1 后跟 3 的频率是多少 2 后跟 1 的频率是多少 2 后跟 2 的
  • Keras model.predict 函数给出输入形状错误

    我已经在 Tensorflow 中实现了通用句子编码器 现在我正在尝试预测句子的类概率 我也将字符串转换为数组 Code if model model type universal classifier basic class probs
  • 雅虎财务请求功能出现 404 客户端错误

    yahoo Financials的请求功能出现404 Client Error 直接点击以下网址没有问题 https finance yahoo com quote AAPL financials p AAPL https finance
  • 带有 mkdocs 的本地 mathjax

    我想在无法访问互联网的计算机上使用 MathJax 和 Mkdocs 因此我不能只调用 Mathjax CDN Config mkdocs yml site name My Docs extra javascript javascripts
  • 使用pathlib获取主目录

    翻看新的pathlib在 Python 3 4 中 我注意到没有任何简单的方法来获取用户的主目录 我能想到的获取用户主目录的唯一方法是使用旧的os path像这样的库 import pathlib from os import path p
  • Python - Unicode 到 ASCII 的转换

    我无法在不丢失数据的情况下将以下 Unicode 转换为 ASCII u ABRA xc3O JOS xc9 I tried encode and decode他们不会这么做 有人有建议吗 Unicode 字符u xce0 and u xc
  • 设置高亮大括号的 vim 颜色主题

    如何更改突出显示大括号的 vim 配色方案 我希望实际编辑 vim 主题文件以使更改永久生效 问候 克雷格 匹配括号的自动高亮颜色称为MatchParen 您可以通过执行以下操作来更改 vimrc 中的颜色 highlight MatchP
  • 通过 Python 循环浏览网络上的目录并显示其内容(文件和其他目录)

    同样的道理在Python中处理从源目录到目标目录的一组文件 https stackoverflow com questions 2593399 process a set of files from a source directory t
  • 无法使用 python rasterio、gdal 打开 jp2 (来自哨兵)

    我试图在 python 中将 jp2 栅格产品作为栅格打开 但当我们使用 raterio 和 gdal 包时没有成功 我收到此错误 RasterioIOError b4 jp2 not recognized as a supported f
  • Seaborn 中没有线性拟合的散点图

    我想知道是否有办法关闭seaborn中的线性拟合lmplot或者是否有一个等效函数可以生成散点图 当然 我也可以使用 matplotlib 但是 我发现 seaborn 中的语法和美学非常吸引人 例如 我想绘制以下情节 import sea
  • 为什么 Collections.counter 这么慢?

    我正在尝试解决罗莎琳德的基本问题 即计算给定序列中的核苷酸 并在列表中返回结果 对于那些不熟悉生物信息学的人来说 它只是计算字符串中 4 个不同字符 A C G T 出现的次数 我期望collections Counter是最快的方法 首先
  • 是否可以在Python中将日+月(不是年)与当前日+月进行比较?

    我正在获取 5 月 10 日 格式的数据 我试图弄清楚它是今年还是明年 该日期仅一年 因此 5 月 10 日表示 2015 年 5 月 10 日 而 5 月 20 日表示 2014 年 5 月 20 日 为此 我想将字符串转换为日期格式并进
  • 从迭代器外部将 StopIteration 发送到 for 循环

    有几种方法可以打破一些嵌套循环 他们是 1 使用中断 继续 for x in xrange 10 for y in xrange 10 print x y if x y gt 50 break else continue only exec
  • Django 将 JSON 数据传递给静态 getJSON/Javascript

    我正在尝试从 models py 中获取数据并将其序列化为views py 中的 JSON 对象 模型 py class Platform models Model platformtype models CharField max len
  • 是否可以使用 Anaconda 包作为 Google Cloud Functions 的依赖项?

    我正在使用 Python 运行时编写 Google Cloud Function 我需要包含一些无法使用的依赖项pip 如文档中所述here https cloud google com functions docs writing spe
  • 如何使用 enumerate 来倒数?

    letters a b c 假设这是我的清单 在哪里for i letter in enumerate letters 将会 0 a 1 b 2 c 我怎样才能让它向后枚举 如 2 a 1 b 0 c 这是一个很好的解决方案并且工作完美 i
  • 没有名为“turtle”的模块

    我正在学习并尝试用Python3制作贪吃蛇游戏 我正在进口海龟 我正在使用 Linux mint 19 PyCharm python37 python3 tk Traceback most recent call last File hom
  • 为boost python编译的.so找不到模块

    我正在尝试将 C 代码包装到 python 中 只需一个类即可导出两个函数 我编译为map so 当我尝试时import map得到像噪音一样的错误 Traceback most recent call last File
  • 如何同时接受int和float类型的输入?

    我正在制作一个货币转换器 如何让 python 同时接受整数和浮点数 我就是这样做的 def aud brl amount From to ER 0 42108 if amount int if From strip aud and to

随机推荐

  • jQuery Mobile 1.1.1 自定义选择菜单 - 占位符文本不可见

    今天早些时候 2012 年 7 月 13 日 升级到 jQuery Mobile 1 1 1 后 我注意到我的所有自定义选择菜单不再在页面加载时显示占位符文本 在 1 1 1 中我需要做一些不同的事情才能在自定义选择菜单中显示占位符文本吗
  • Java:BufferedImage 到字节数组并返回

    我发现很多人都有类似的问题 但是我还没有尝试找到我正在寻找的东西 因此 我有一个读取输入图像并将其转换为字节数组的方法 File imgPath new File ImageName BufferedImage bufferedImage
  • 如何在 Bootstrap 3 模态中居中输入?

    我目前正在从 Bootstrap 2 切换到 Bootstrap 3 如何将 Bootstrap 3 中的输入字段居中 文本正确居中 它曾经为 BS2 工作 我尝试过移动 div 中的 style text align center 但仍然
  • 如何找到word在文件中的位置?

    例如我有文件和单词 test 文件部分是二进制的 但有字符串 test 如何在不加载该文件到内存的情况下找到文件中单词 索引 的位置 除非打开文件 否则无法找到文件中文本的位置 这就像要求某人在不睁开眼睛的情况下阅读报纸一样 回答你问题的第
  • GWT 从 2.8.1 升级到 2.8.2 后出现“XmlRootElement 无法解析为类型”错误

    为了修复 Chrome 61 中损坏的 GWT 拖放功能 我们决定升级 GWT 因为修复是在 GWT 2 8 2 中 升级后 我遇到了数百个以下错误 ERROR Line 7 XmlRootElement cannot be resolve
  • Form_for 带有 url、格式和 html 选项

    我觉得我在这里缺少一些简单的东西 我正在将 form for 助手与对象一起使用 我指定 url 格式和 html 方法 但是 在渲染时 action 属性中的 url 不会采用该格式 这是我的代码 form for site url co
  • 将自定义元数据保存在从 iOS 中的 AVFoundation 获取的图像中

    当我使用以下命令获取图像时 如何在图像中保存自定义元数据AVFoundation framework 我知道我可以访问属性 只要我的图像是UIImage or CIImage但它们的属性似乎彼此不同 即使是同一图像 到目前为止 我像这样访问
  • 无法将 Type 隐式转换为 My Type

    我不确定这是否是协方差和逆变问题 但我无法使其正常工作 这是代码 public interface IDto public class PaginatedDto
  • Brunch:分离供应商和应用程序 javascript

    我从我们的项目供应商和应用程序中制作了两个 javascript 包 我按照建议的方式执行此操作文档 如我的 brunch config js 中的这段代码所示 files javascripts joinTo js vendor js s
  • 如何在Android中像Wifi分析仪应用程序一样绘制图表?

    您好 我正在尝试开发一个现场测试应用程序 我必须检索相邻小区的信号强度等信息 所以我的问题是 如何显示具有不同相邻单元格的图表 X 轴和 Y 轴上的信号强度是实时的吗 一个例子here 我已经获得了 5 或 6 个相邻小区以及每个小区的信号
  • Mac OS X / iOS 中的正则表达式匹配表情符号

    Note 在不支持所包含表情符号的系统上 这个问题可能看起来很奇怪 这是一个后续问题如何从字符串中删除表情符号 我想构建一个正则表达式来匹配可以在 Mac OS X iOS 中输入的所有表情符号 明显的 Unicode 块涵盖了大部分表情符
  • 如何在 MVVM 中使用同一个 ViewModel 拥有多个视图?

    我对 WPF 和 MVVM 都很陌生 在尝试设置DataContext到两个单独视图中的 ViewModel 的同一实例 这是因为
  • 如何在 AngularJS 中关闭浏览器窗口

    我有一个登录表单作为单独的浏览器窗口弹出 一旦 API 验证用户已登录 我如何在 AngularJS 中关闭该登录浏览器窗口 Use window close in window服务 您可以像这样将结果广播到另一个控制器AngularJS
  • 是否可以捕获包含 Windows 7 DWM 缩略图的窗口?

    我开始相信你不能用 Windows API 做任何事 我有两个窗户 其中有一个 DWM 缩略图 我想要做的是 我希望能够将窗口屏幕的缩略图捕获到另一个窗口中 当我使用 bitblt 执行此操作时 除了缩略图之外的所有内容都会被复制 它只是位
  • 在android中画圆[关闭]

    很难说出这里问的是什么 这个问题模棱两可 含糊不清 不完整 过于宽泛或言辞激烈 无法以目前的形式合理回答 如需帮助澄清此问题以便重新打开 访问帮助中心 如何使用 Android SDK 在两点之间绘制圆 创建一个位图 然后在其画布上绘制 然
  • Postgresql base64 编码

    我需要将 db 值转换为 base64encode 我试过 select encode cast est name as text base64 from establishments 它显示错误 SQL select encode str
  • 在提交表单之前添加确认提醒

    我有一个表单允许用户从数据库中删除一些数据 我想要一些确认信息以防止意外删除 我想做以下事情 按下提交后 会弹出警告 您确定吗 如果用户点击 是 则运行脚本 如果用户点击 否 则不要提交脚本 如何才能做到这一点 我已经添加了 onSubmi
  • np.array() 和 np.asarray() 有什么区别?

    NumPy 和 NumPy 有什么区别np array and np asarray 我什么时候应该使用其中一种而不是另一种 它们似乎产生相同的输出 The 的定义asarray is def asarray a dtype None or
  • table-header-group 、 table-footer-group 属性在 Chrome 中不起作用

    这是我的代码 http furkan brove net syflm php 当我打印它时 它在 Chrome 中不起作用 我希望它在打印模式下将页眉和页脚放在每一页上 此外 在每个浏览器中 最后一个页脚位于内容的底部 但我希望它位于页面底
  • python中的完全单调插值

    我有一些数据 例如 我想拟合一条可微分的单调曲线 我试过PchipInterpolator类但在一个非常相似的图表上 结果是 这并不单调 如何将单调曲线拟合到这样的数据 以下是另一个类似图表的 y 值示例集 0 11091571190236