Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从多元拟合中得到方程,以应用进一步的导数_Python_Numpy_Polynomial Math_Data Fitting_Derivative - Fatal编程技术网

Python 从多元拟合中得到方程,以应用进一步的导数

Python 从多元拟合中得到方程,以应用进一步的导数,python,numpy,polynomial-math,data-fitting,derivative,Python,Numpy,Polynomial Math,Data Fitting,Derivative,我已设法对一组平滑数据执行多项式拟合。现在,我需要得到多项式方程,这样我可以对多项式进行一阶和二阶导数,找到最大值和最小值。虽然我可以通过多项式拟合很容易地得到系数,但我不知道如何得到整个多项式,以便我可以应用导数。我想用SimPy来做导数,但是如果不建立完整的多项式方程,我想我做不到 以下是我目前的代码: import matplotlib.pyplot as plt import numpy as np from pandas import * from math import factor

我已设法对一组平滑数据执行多项式拟合。现在,我需要得到多项式方程,这样我可以对多项式进行一阶和二阶导数,找到最大值和最小值。虽然我可以通过多项式拟合很容易地得到系数,但我不知道如何得到整个多项式,以便我可以应用导数。我想用SimPy来做导数,但是如果不建立完整的多项式方程,我想我做不到

以下是我目前的代码:

import matplotlib.pyplot as plt
import numpy as np
from pandas import *
from math import factorial
from scipy import interpolate
import numpy.polynomial.polynomial as poly
import itertools

# savitzky_golay definition
def savitzky_golay(y, window_size, order, deriv=0, rate=1):
    try:
        window_size = np.abs(np.int(window_size))
        order = np.abs(np.int(order))
    except ValueError:
        raise ValueError("window_size and order have to be of type int")
    if window_size % 2 != 1 or window_size < 1:
        raise TypeError("window_size size must be a positive odd number")
    if window_size < order + 2:
        raise TypeError("window_size is too small for the polynomials order")
    order_range = range(order+1)
    half_window = (window_size -1) // 2
    # precompute coefficients
    b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)])
    m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv)
    # pad the signal at the extremes with
    # values taken from the signal itself
    firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )
    lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])
    y = np.concatenate((firstvals, y, lastvals))
    return np.convolve( m[::-1], y, mode='valid')


import os, sys
#get the xlsx files
files= os.listdir(r'C:\Users\Dani\Desktop\REACTIVITY')
file=[f for f in files if f[-4:]=='xlsx']

for file in file:
    #read the files
    data=pandas.read_excel(file, sheet_name=0)

    y1=np.array(data["Viscosity"])
    x=np.array(data["Time (s)"])
    y2=np.array(data["Temperature (oC)"])

    fig, ax1 = plt.subplots()
    #create initial axis
    ax1.set_xlabel("Time (s)", labelpad=10)
    ax1.set_ylabel("Viscosity", color='blue', labelpad=10)
    ax1.tick_params(axis='y', labelcolor='blue')

    #smooth data by using savitzky_golay
    yhat=savitzky_golay(y1, 51, 3)
    ax1.plot(x,yhat, color='blue',linewidth=2)
    #create temperature graph
    ax2=ax1.twinx()
    ax2.set_ylabel(u'Temperature (C)' , color='red', labelpad=10)
    ax2.plot(x, y2, color='red',linewidth=2)
    ax2.tick_params(axis='y', labelcolor='red')

    #fit the Viscosity smoothed data to a polynomial
    for i in itertools.count():
        #create the polynomial fit for different degrees
        coefs=poly.polyfit(x, yhat, i)
        fit=poly.polyval(x, coefs)
        #calculate rsquare
        ybar = np.sum(yhat)/len(yhat)
        ssreg = np.sum((fit-ybar)**2)
        sstot = np.sum((yhat - ybar)**2)
        square = ssreg / sstot

        if square > 0.995:
            #get the desired degree
            ax1.plot(x, fit, color='black', linestyle='--',linewidth=2)
            print(square)
            print(coefs)
            print(i)
            break

    plt.show()
导入matplotlib.pyplot作为plt
将numpy作为np导入
从熊猫进口*
从数学导入阶乘
从scipy导入插值
将numpy.polyman.polyman导入为多边形
进口itertools
#savitzky_golay定义
def savitzky_golay(y,窗口大小,订单,deriv=0,费率=1):
尝试:
窗口大小=np.abs(np.int(窗口大小))
订单=np.abs(np.int(订单))
除值错误外:
raise VALUE ERROR(“窗口大小和顺序必须为int类型”)
如果窗口大小为%2!=1或窗口大小<1:
raise TypeError(“窗口大小必须为正奇数”)
如果窗口大小<订单+2:
raise TypeError(“窗口大小对于多项式顺序来说太小”)
订单\范围=范围(订单+1)
半窗口=(窗口大小-1)//2
#预计算系数
b=np.mat([[k**i表示顺序范围内的i]表示范围内的k(-half_窗口,half_窗口+1)])
m=np.linalg.pinv(b.A[deriv]*速率**deriv*阶乘(deriv)
#在极端情况下,使用
#从信号本身获取的值
firstvals=y[0]-np.abs(y[1:half_window+1][::-1]-y[0])
lastvals=y[-1]+np.abs(y[-half_window-1:-1][:-1]-y[-1])
y=np.连接((第一个VAL,y,最后一个VAL))
返回np.convolve(m[:-1],y,mode='valid')
导入操作系统,系统
#获取xlsx文件
files=os.listdir(r'C:\Users\Dani\Desktop\responsibility')
文件=[f表示文件中的f,如果f[-4:][=='xlsx']
对于文件中的文件:
#读文件
数据=熊猫。读取excel(文件、工作表名称=0)
y1=np.数组(数据[“粘度”])
x=np.数组(数据[“时间])
y2=np.数组(数据[“温度(oC)”)
图,ax1=plt.子批次()
#创建初始轴
ax1.设置标签(“时间”,labelpad=10)
ax1.设置标签(“粘度”,颜色=蓝色,标签垫=10)
ax1.勾选参数(轴为y,标签颜色为蓝色)
#使用savitzky_golay平滑数据
yhat=savitzky_golay(y1,51,3)
ax1.绘图(x,yhat,color='blue',线宽=2)
#创建温度图
ax2=ax1.twinx()
ax2.设置标签(u‘温度(C)’,颜色为红色,标签垫=10)
ax2.绘图(x,y2,颜色为红色,线宽为2)
ax2.勾选参数(轴为y,标签颜色为红色)
#将粘度平滑数据拟合到多项式
对于itertools.count()中的i:
#创建适合不同度数的多项式
coefs=多边形多边形拟合(x,yhat,i)
拟合=poly.polyval(x,coefs)
#计算平方
ybar=np.总和(yhat)/len(yhat)
ssreg=np.和((拟合ybar)**2)
sstot=np.和((yhat-ybar)**2)
平方=ssreg/sstot
如果平方>0.995:
#获得理想的学位
ax1.打印(x,拟合,颜色='黑色',线型='--',线宽=2)
印刷品(方形)
打印(coefs)
印刷品(一)
打破
plt.show()

不确定我是否遇到了问题。如果有系数列表(比如升序),那么导数的系数就是[code>[ak*k代表ak,枚举(a)][1::]不需要sympy。对于按降序排列的系数,您可以使用
numpy.roots
来获取最小值和最大值……您是否检查了
scipy.signal.savgol_filter