이 코드는 함수로 만들기 전에 잘 작동했습니다. 그런데 무엇이 잘못 되었나요? 코드의 어느 곳에서나 문자열 / 목록을 부동 숫자로 곱한 것을 볼 수 없습니다.
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
from numpy import * #This is temporary
def NonlinearReg(xdata,ydata,f):
Constants, Covariance = curve_fit(f, xdata, ydata)
return Constants
def Nonlinear_Plot(xdata,ydata,f,a,b,c):
plt.figure(figsize=(6, 4))
plt.scatter(xdata, ydata, label='Data')
plt.plot(xdata, f(xdata, a, b, c), label='Best Fit')
plt.legend(loc='best')
plt.show()
def main():
xdata = [2,8,6,7]
ydata = [9,6,5,4]
NonlinearFunction = input("Type in the Nonlinear Function : \n")
ff= lambda x,a,b,c: eval(NonlinearFunction)
a,b,c=NonlinearReg(xdata,ydata,ff)
if (c==1): #The initial guess is as it is; the given function doesn't involve in c
print('\n', '[a b] for the best fit= ', '['+str(a) +' '+str(b)+ ']' ,'\n')
else:
print('\n', '[a b c] for the best fit= ', '['+str(a) +' '+str(b)+' '+str(c)+ ']' ,'\n')
Nonlinear_Plot(xdata, ydata,ff, a,b,c)
main()
'a + b * x'와 같은 입력 함수로 이것을 실행하면 다음과 같은 결과를 얻을 수 있습니다 (Visual Studio 2019에서 실행).
Type in the Nonlinear Function :
a+b*x
C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\scipy\optimize\minpack.py:808: OptimizeWarning: Covariance of the parameters could not be estimated #How can I stop this error from coming up?
category=OptimizeWarning)
[a b] for the best fit= [9.879518072308521 -0.6746987951843755] #it does provide the constants a,b
Traceback (most recent call last):
File "C:\Users\Essam\source\repos\PythonApplication2\PythonApplication2\PythonApplication2.py", line 44, in <module>
main()
File "C:\Users\Essam\source\repos\PythonApplication2\PythonApplication2\PythonApplication2.py", line 42, in main
Nonlinear_Plot(xdata, ydata,ff, a,b,c)
File "C:\Users\Essam\source\repos\PythonApplication2\PythonApplication2\PythonApplication2.py", line 13, in Nonlinear_Plot
plt.plot(xdata, f(xdata, a, b, c), label='Best Fit')
File "C:\Users\Essam\source\repos\PythonApplication2\PythonApplication2\PythonApplication2.py", line 34, in <lambda>
ff= lambda x,a,b,c: eval(NonlinearFunction)
File "<string>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'numpy.float64'
코드는 함수로 만들기 전에 실행되었습니다.
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
from numpy import *
def func(x, a, b,c):
return ff(x,a,b,c)
ff= lambda x,a,b,c: eval("a*x**b")
xdata = [0 ,866, 2753, 4763, 6942, 10593]
ydata = [30, 23, 27, 26, 23, 20]
popt, pcov = curve_fit(func, xdata, ydata)
print('\n', '[a b] for agmad fitting = ', popt,'\n')
plt.figure(figsize=(6, 4))
plt.scatter(xdata, ydata, label='Data')
plt.plot(xdata, ff(xdata, popt[0], popt[1], popt[2]), label='Agmad Fit')
plt.legend(loc='best')
plt.show()
이렇게하면 오류 메시지가 재현됩니다.
In [442]: [1,2,3]*np.float(1.2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-442-84f5d06cd969> in <module>
----> 1 [1,2,3]*np.float(1.2)
TypeError: can't multiply sequence by non-int of type 'float'
In [443]: [1,2,3]*np.float64(1.2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-443-9e2c2f15c70b> in <module>
----> 1 [1,2,3]*np.float64(1.2)
TypeError: can't multiply sequence by non-int of type 'numpy.float64'
이를 바탕으로 평가시 'a + b * x'표현식에서 b
목록 (또는 문자열)이고 x
numpy 배열의 요소라고 생각합니다.
일반화 된 평가 방법을 사용하면 변수 유형을 추적하기가 어렵습니다. 그 표현은 a
, b
그리고 x
numpy 배열 이라면 괜찮을 것입니다 .하지만 쉽게 실패 할 수 있습니다.
그 확인 a
, b
, c
"상수". 정확하다고 가정하지 마십시오.
또는이 경우 x
입니다 xdata
목록 :
In [445]: np.array([1.23])[0]*[2,8,6,7]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-445-fd8778299d95> in <module>
----> 1 np.array([1.23])[0]*[2,8,6,7]
TypeError: can't multiply sequence by non-int of type 'numpy.float64'
하지만 xdata
배열 인 경우 :
In [446]: np.array([1.23])[0]*np.array([2,8,6,7])
Out[446]: array([2.46, 9.84, 7.38, 8.61])
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다