TypeError при подгонке кривой - PullRequest
       64

TypeError при подгонке кривой

0 голосов
/ 14 февраля 2019

Я пытаюсь подогнать кривую к некоторым имеющимся у меня данным, но по какой-то причине я просто получаю сообщение об ошибке «объект« numpy.float64 »не может быть интерпретирован как целое число», и я не понимаю, почему или какпочини это.Был бы признателен за некоторую помощь, код ниже:

import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize


mud=[0.0014700734999999996,
 0.0011840320799999997,
 0.0014232304799999995,
 0.0008501509799999997,
 0.0007235751599999999,
 0.0005770661399999999,
 0.0005581295999999999,
 0.00028703807999999994,
 0.00014850233999999998]
F=[0.5750972123893806,
 0.5512177433628319,
 0.5638906194690266,
 0.5240915044247788,
 0.5217873451327435,
 0.5066008407079646,
 0.5027256637168142,
 0.4847113274336283,
 0.46502123893805314]


fitfunc = lambda p, x: p[0]+p[1]*x # Target function
errfunc = lambda p, x, y: fitfunc(p, x) - y # Distance to the target function
p0 = [0.46,80,1] # Initial guess for the parameters
p1, success = optimize.leastsq(errfunc, p0[:], args=(mud, F))

m = np.linspace(max(mud),min(mud), 9)
ax = plot(mud,F,"b^")
ax3 = plot(m,fitfunc(p2,m),"g-")

Ответы [ 2 ]

0 голосов
/ 14 февраля 2019

Вот графическое средство, использующее уравнение хроматографии Ван-Димтера, оно хорошо подходит для ваших данных.

plot

import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

# mud
xData=numpy.array([0.0014700734999999996,
0.0011840320799999997,
0.0014232304799999995,
0.0008501509799999997,
0.0007235751599999999,
0.0005770661399999999,
0.0005581295999999999,
0.00028703807999999994,
0.00014850233999999998])

# F
yData=numpy.array([0.5750972123893806,
0.5512177433628319,
0.5638906194690266,
0.5240915044247788,
0.5217873451327435,
0.5066008407079646,
0.5027256637168142,
0.4847113274336283,
0.46502123893805314])


def func(x, a, b, c): # Van Deemter chromatography equation
    return a + b/x + c*x


# these are the same as the scipy defaults
initialParameters = numpy.array([1.0, 1.0, 1.0])

# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)

modelPredictions = func(xData, *fittedParameters) 

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))

print('Parameters:', fittedParameters)
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()


##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = func(xModel, *fittedParameters)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data (mud)') # X axis data label
    axes.set_ylabel('Y Data (F)') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)
0 голосов
/ 14 февраля 2019

Ваша проблема в том, что ваши аргументы mud и F являются списками, а не массивами, что означает, что вы не можете просто умножить их на число.Отсюда и ошибка.Если вы определите эти параметры как np.ndarray с, он будет работать:

import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize

mud=np.array([0.0014700734999999996,
 0.0011840320799999997,
 0.0014232304799999995,
 0.0008501509799999997,
 0.0007235751599999999,
 0.0005770661399999999,
 0.0005581295999999999,
 0.00028703807999999994,
 0.00014850233999999998])
F=np.array([0.5750972123893806,
 0.5512177433628319,
 0.5638906194690266,
 0.5240915044247788,
 0.5217873451327435,
 0.5066008407079646,
 0.5027256637168142,
 0.4847113274336283,
 0.46502123893805314])


fitfunc = lambda p, x: p[0]+p[1]*x # Target function
errfunc = lambda p, x, y: fitfunc(p, x) - y # Distance to the target function
p0 = [0.46,80,1] # Initial guess for the parameters
p1, success = optimize.leastsq(errfunc, p0[:], args=(mud, F))

print(p1, success)

дает

[ 0.46006301 76.7920086   1.        ] 2
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...