python 相关性分析切点寻找,Python自然平滑样条线

2023-10-24 15:30

本文主要是介绍python 相关性分析切点寻找,Python自然平滑样条线,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

I am trying to find a python package that would give an option to fit natural smoothing splines with user selectable smoothing factor. Is there an implementation for that? If not, how would you use what is available to implement it yourself?

By natural spline I mean that there should be a condition that the second derivative of the fitted function at the endpoints is zero (linear).

By smoothing spline I mean that the spline should not be 'interpolating' (passing through all the datapoints). I would like to decide the correct smoothing factor lambda (see the Wikipedia page for smoothing splines) myself.

What I have found

scipy.interpolate.CubicSpline [link]: Does natural (cubic) spline fitting. Does interpolation, and there is no way to smooth the data.

scipy.interpolate.UnivariateSpline [link]: Does spline fitting with user selectable smoothing factor. However, there is no option to make the splines natural.

解决方案

After hours of investigation, I did not find any pip installable packages which could fit a natural cubic spline with user-controllable smoothness. However, after deciding to write one myself, while reading about the topic I stumbled upon a blog post by github user madrury. He has written python code capable of producing natural cubic spline models.

The model code is available here (NaturalCubicSpline) with a BSD-licence. He has also written some examples in an IPython notebook.

But since this is the Internet and links tend to die, I will copy the relevant parts of the source code here + a helper function (get_natural_cubic_spline_model) written by me, and show an example of how to use it. The smoothness of the fit can be controlled by using different number of knots. The position of the knots can be also specified by the user.

Example

from matplotlib import pyplot as plt

import numpy as np

def func(x):

return 1/(1+25*x**2)

# make example data

x = np.linspace(-1,1,300)

y = func(x) + np.random.normal(0, 0.2, len(x))

# The number of knots can be used to control the amount of smoothness

model_6 = get_natural_cubic_spline_model(x, y, minval=min(x), maxval=max(x), n_knots=6)

model_15 = get_natural_cubic_spline_model(x, y, minval=min(x), maxval=max(x), n_knots=15)

y_est_6 = model_6.predict(x)

y_est_15 = model_15.predict(x)

plt.plot(x, y, ls='', marker='.', label='originals')

plt.plot(x, y_est_6, marker='.', label='n_knots = 6')

plt.plot(x, y_est_15, marker='.', label='n_knots = 15')

plt.legend(); plt.show()

3f3a5b82f015ba8333b227668f2b60af.png

The source code for get_natural_cubic_spline_model

import numpy as np

import pandas as pd

from sklearn.base import BaseEstimator, TransformerMixin

from sklearn.linear_model import LinearRegression

from sklearn.pipeline import Pipeline

def get_natural_cubic_spline_model(x, y, minval=None, maxval=None, n_knots=None, knots=None):

"""

Get a natural cubic spline model for the data.

For the knots, give (a) `knots` (as an array) or (b) minval, maxval and n_knots.

If the knots are not directly specified, the resulting knots are equally

space within the *interior* of (max, min). That is, the endpoints are

*not* included as knots.

Parameters

----------

x: np.array of float

The input data

y: np.array of float

The outpur data

minval: float

Minimum of interval containing the knots.

maxval: float

Maximum of the interval containing the knots.

n_knots: positive integer

The number of knots to create.

knots: array or list of floats

The knots.

Returns

--------

model: a model object

The returned model will have following method:

- predict(x):

x is a numpy array. This will return the predicted y-values.

"""

if knots:

spline = NaturalCubicSpline(knots=knots)

else:

spline = NaturalCubicSpline(max=maxval, min=minval, n_knots=n_knots)

p = Pipeline([

('nat_cubic', spline),

('regression', LinearRegression(fit_intercept=True))

])

p.fit(x, y)

return p

class AbstractSpline(BaseEstimator, TransformerMixin):

"""Base class for all spline basis expansions."""

def __init__(self, max=None, min=None, n_knots=None, n_params=None, knots=None):

if knots is None:

if not n_knots:

n_knots = self._compute_n_knots(n_params)

knots = np.linspace(min, max, num=(n_knots + 2))[1:-1]

max, min = np.max(knots), np.min(knots)

self.knots = np.asarray(knots)

@property

def n_knots(self):

return len(self.knots)

def fit(self, *args, **kwargs):

return self

class NaturalCubicSpline(AbstractSpline):

"""Apply a natural cubic basis expansion to an array.

The features created with this basis expansion can be used to fit a

piecewise cubic function under the constraint that the fitted curve is

linear *outside* the range of the knots.. The fitted curve is continuously

differentiable to the second order at all of the knots.

This transformer can be created in two ways:

- By specifying the maximum, minimum, and number of knots.

- By specifying the cutpoints directly.

If the knots are not directly specified, the resulting knots are equally

space within the *interior* of (max, min). That is, the endpoints are

*not* included as knots.

Parameters

----------

min: float

Minimum of interval containing the knots.

max: float

Maximum of the interval containing the knots.

n_knots: positive integer

The number of knots to create.

knots: array or list of floats

The knots.

"""

def _compute_n_knots(self, n_params):

return n_params

@property

def n_params(self):

return self.n_knots - 1

def transform(self, X, **transform_params):

X_spl = self._transform_array(X)

if isinstance(X, pd.Series):

col_names = self._make_names(X)

X_spl = pd.DataFrame(X_spl, columns=col_names, index=X.index)

return X_spl

def _make_names(self, X):

first_name = "{}_spline_linear".format(X.name)

rest_names = ["{}_spline_{}".format(X.name, idx)

for idx in range(self.n_knots - 2)]

return [first_name] + rest_names

def _transform_array(self, X, **transform_params):

X = X.squeeze()

try:

X_spl = np.zeros((X.shape[0], self.n_knots - 1))

except IndexError: # For arrays with only one element

X_spl = np.zeros((1, self.n_knots - 1))

X_spl[:, 0] = X.squeeze()

def d(knot_idx, x):

def ppart(t): return np.maximum(0, t)

def cube(t): return t*t*t

numerator = (cube(ppart(x - self.knots[knot_idx]))

- cube(ppart(x - self.knots[self.n_knots - 1])))

denominator = self.knots[self.n_knots - 1] - self.knots[knot_idx]

return numerator / denominator

for i in range(0, self.n_knots - 2):

X_spl[:, i+1] = (d(i, X) - d(self.n_knots - 2, X)).squeeze()

return X_spl

这篇关于python 相关性分析切点寻找,Python自然平滑样条线的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/276122

相关文章

Python中conda虚拟环境创建及使用小结

《Python中conda虚拟环境创建及使用小结》本文主要介绍了Python中conda虚拟环境创建及使用小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们... 目录0.前言1.Miniconda安装2.conda本地基本操作3.创建conda虚拟环境4.激活c

MySQL表锁、页面锁和行锁的作用及其优缺点对比分析

《MySQL表锁、页面锁和行锁的作用及其优缺点对比分析》MySQL中的表锁、页面锁和行锁各有特点,适用于不同的场景,表锁锁定整个表,适用于批量操作和MyISAM存储引擎,页面锁锁定数据页,适用于旧版本... 目录1. 表锁(Table Lock)2. 页面锁(Page Lock)3. 行锁(Row Lock

使用Python创建一个能够筛选文件的PDF合并工具

《使用Python创建一个能够筛选文件的PDF合并工具》这篇文章主要为大家详细介绍了如何使用Python创建一个能够筛选文件的PDF合并工具,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录背景主要功能全部代码代码解析1. 初始化 wx.Frame 窗口2. 创建工具栏3. 创建布局和界面控件4

一文详解如何在Python中使用Requests库

《一文详解如何在Python中使用Requests库》:本文主要介绍如何在Python中使用Requests库的相关资料,Requests库是Python中常用的第三方库,用于简化HTTP请求的发... 目录前言1. 安装Requests库2. 发起GET请求3. 发送带有查询参数的GET请求4. 发起PO

Python与DeepSeek的深度融合实战

《Python与DeepSeek的深度融合实战》Python作为最受欢迎的编程语言之一,以其简洁易读的语法、丰富的库和广泛的应用场景,成为了无数开发者的首选,而DeepSeek,作为人工智能领域的新星... 目录一、python与DeepSeek的结合优势二、模型训练1. 数据准备2. 模型架构与参数设置3

Python进行PDF文件拆分的示例详解

《Python进行PDF文件拆分的示例详解》在日常生活中,我们常常会遇到大型的PDF文件,难以发送,将PDF拆分成多个小文件是一个实用的解决方案,下面我们就来看看如何使用Python实现PDF文件拆分... 目录使用工具将PDF按页数拆分将PDF的每一页拆分为单独的文件将PDF按指定页数拆分根据页码范围拆分

Python中常用的四种取整方式分享

《Python中常用的四种取整方式分享》在数据处理和数值计算中,取整操作是非常常见的需求,Python提供了多种取整方式,本文为大家整理了四种常用的方法,希望对大家有所帮助... 目录引言向零取整(Truncate)向下取整(Floor)向上取整(Ceil)四舍五入(Round)四种取整方式的对比综合示例应

python 3.8 的anaconda下载方法

《python3.8的anaconda下载方法》本文详细介绍了如何下载和安装带有Python3.8的Anaconda发行版,包括Anaconda简介、下载步骤、安装指南以及验证安装结果,此外,还介... 目录python3.8 版本的 Anaconda 下载与安装指南一、Anaconda 简介二、下载 An

Python自动化处理手机验证码

《Python自动化处理手机验证码》手机验证码是一种常见的身份验证手段,广泛应用于用户注册、登录、交易确认等场景,下面我们来看看如何使用Python自动化处理手机验证码吧... 目录一、获取手机验证码1.1 通过短信接收验证码1.2 使用第三方短信接收服务1.3 使用ADB读取手机短信1.4 通过API获取

python安装whl包并解决依赖关系的实现

《python安装whl包并解决依赖关系的实现》本文主要介绍了python安装whl包并解决依赖关系的实现,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录一、什么是whl文件?二、我们为什么需要使用whl文件来安装python库?三、我们应该去哪儿下