3

Ich versuche, meine Daten an (cos(x))^n anzupassen. The vale of n in der Theorie ist 2, aber meine Daten sollten mir etwa 1,7 geben. Wenn ich meine Anpassungsfunktion definieren, und ich versuche curve_fit, bekomme ich einen FehlerKurvenanpassung mit Python Fehler

def f(x,a,b,c): 
    return a+b*np.power(np.cos(x),c) 

param, extras = curve_fit(f, x, y) 

Diese meine Daten

x y    error 
90 3.3888756187 1.8408898986 
60 2.7662844365 1.6632150903 
45 2.137309503  1.4619540017 
30 1.5256883339 1.2351875703 
0 1.4665463518 1.2110104672 

Der Fehler wie folgt aussieht:

/usr/local/lib/python3.5/dist-packages/ipykernel_launcher.py: 4: RuntimeWarning: Ungültiger Wert, der nach dem Entfernen der cwd aus sys.path in Kraft trat.

/usr/lib/python3/dist-packages/scipy/optimize/minpack.py:690: OptimizeWarning: Kovarianz des Parameters kann nicht
Kategorie = OptimizeWarning)

+0

Gibt es noch etwas fehlt/nicht funktioniert? Wenn ja, lassen Sie mich wissen, dass ich meine Antwort ändern kann, wenn nicht, bitte überlegen Sie, zu upvote und akzeptieren Sie die Antwort, wenn es Ihr Problem gelöst hat :) – Cleb

+1

Zunächst einmal vielen Dank, es war wirklich hilfreich. Das Problem war, dass die x-Daten in Grad und in Radianten angegeben wurden. Anders als das habe ich gelernt, von * popt alle Elemente in der Anordnung zu nennen, so dass es großartig war! –

Antwort

4

Das Problem geschätzt werden ist, dass cos(x) kann negativ werden und dann cos(x)^n kann undefiniert sein. Illustration:

np.cos(90) 
-0.44807361612917013 

und z.B.

np.cos(90) ** 1.7 
nan 

Das verursacht die zwei Fehlermeldungen, die Sie erhalten.

Es funktioniert gut, wenn Sie Ihr Modell, z. zu a + b * np.cos(c * x + d). Dann sieht die Handlung wie folgt:

enter image description here

Der Code kann unter einigen Inline-Kommentare zu finden:

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


def f(x, a, b, c, d): 

    return a + b * np.cos(c * x + d) 

# your data 
xdata = [90, 60, 45, 30, 0] 
ydata = [3.3888756187, 2.7662844365, 2.137309503, 1.5256883339, 1.4665463518] 

# plot data 
plt.plot(xdata, ydata, 'bo', label='data') 

# fit the data 
popt, pcov = curve_fit(f, xdata, ydata, p0=[3., .5, 0.1, 10.]) 

# plot the result 
xdata_new = np.linspace(0, 100, 200) 
plt.plot(xdata_new, f(xdata_new, *popt), 'r-', label='fit') 
plt.legend(loc='best') 
plt.show()