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中你不知道的gzip高级用法分享

《Python中你不知道的gzip高级用法分享》在当今大数据时代,数据存储和传输成本已成为每个开发者必须考虑的问题,Python内置的gzip模块提供了一种简单高效的解决方案,下面小编就来和大家详细讲... 目录前言:为什么数据压缩如此重要1. gzip 模块基础介绍2. 基本压缩与解压缩操作2.1 压缩文

Python设置Cookie永不超时的详细指南

《Python设置Cookie永不超时的详细指南》Cookie是一种存储在用户浏览器中的小型数据片段,用于记录用户的登录状态、偏好设置等信息,下面小编就来和大家详细讲讲Python如何设置Cookie... 目录一、Cookie的作用与重要性二、Cookie过期的原因三、实现Cookie永不超时的方法(一)

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提