Created
October 2, 2018 12:11
-
-
Save sabopy/9e51cd4ed106c29f6be1b22d308d2825 to your computer and use it in GitHub Desktop.
Scipyのcurve_fitで最小2乗法近似、決定係数R2も求める。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# AWS cloud9 | |
import matplotlib | |
matplotlib.use("Agg") | |
import matplotlib.pyplot as plt | |
from scipy.optimize import curve_fit | |
import numpy as np | |
x_data = np.linspace(-10, 10, 20) | |
y_data = np.random.rand() * x_data **2 | |
y_data_error_1 = np.random.normal(size=len(x_data)) | |
y_data_1 = y_data + y_data_error_1 | |
def func(x, a): | |
f = a*x**2 | |
return f | |
fig = plt.figure(figsize=(6, 4)) | |
plt.rcParams["font.size"] = 16 | |
ax1 = fig.add_subplot(111) | |
popt, pcov = curve_fit(func,x_data,y_data_1) | |
residuals = y_data_1- func(x_data, popt) | |
rss = np.sum(residuals**2)#residual sum of squares = rss | |
tss = np.sum((y_data_1-np.mean(y_data_1))**2)#total sum of squares = tss | |
r_squared = 1 - (rss / tss) | |
ax1.plot(x_data,y_data_1,'mo') | |
ax1.plot(x_data,func(x_data, popt),'g-') | |
ax1.annotate("$R^2$="+str(r_squared)[0:5], xy=(0.6, 0.6), xycoords='axes fraction') | |
ax1.annotate("$y$="+str(popt)[1:6]+"$x^2$", xy=(0.6,0.7), xycoords='axes fraction') | |
fig.savefig("Scipy_curve_fit_parabolic.png", dpi=200,transparent = False, bbox_inches = 'tight') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment