LoginSignup
0
0

More than 3 years have passed since last update.

scipy の OptimizeWarningを例外としてキャッチする

Posted at

次のページを参考にしました。
python - OptimizeWarningを例外としてキャッチする

curve_fit02.py
#! /usr/bin/python
#
import sys
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

import warnings
from scipy.optimize import OptimizeWarning

warnings.simplefilter("error", OptimizeWarning)
# ------------------------------------------------------------------
def exp(xx, aa, bb, dd, pp):
    rvalue = 0.0
    try:
        rvalue = dd * np.exp(aa * xx - bb) + pp
    except Exception as ee:
        sys.stderr.write("*** error *** in exp ***\n")
        sys.stderr.write(str(ee) + "\n")
    return rvalue
# ------------------------------------------------------------------
xx = np.array([0,1,2,3,4,5])
yy = np.array([195.0, 200.0, 224.0,254.0, 298.0,345.0])
yy = np.array([195.0, 203.0, 224.0,254.0, 298.0,345.0])

popt = np.array([0.0,0.0,0.0,0.0])
print(type(popt))

try:
    popt, pcov = curve_fit(exp, xx, yy)
    print(popt)
    print(type(popt))
except Exception as ee:
    sys.stderr.write("*** error *** in curve_fit ***\n")
    sys.stderr.write(str(ee) + "\n")

plt.figure()
plt.plot(xx, yy, 'ko', label="Original Data")
plt.plot(xx,exp(xx, *popt), 'r-',label="Fitted Curve")
plt.legend()
plt.show()
# ------------------------------------------------------------------

次のメッセージが出ます。

<class 'numpy.ndarray'>
*** error *** in curve_fit ***
Covariance of the parameters could not be estimated
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0