scipy
Scipy.optimize वक्र_फिट के साथ फिटिंग फ़ंक्शन
खोज…
परिचय
एक फ़ंक्शन को फिट करना जो वास्तविक डेटा में डेटा बिंदुओं की अपेक्षित घटना का वर्णन करता है, अक्सर वैज्ञानिक अनुप्रयोगों में इसकी आवश्यकता होती है। इस कार्य के लिए एक संभावित अनुकूलक, scipy.optimize से वक्र_फिट है। निम्नलिखित में, कर्व_फिट के आवेदन का एक उदाहरण दिया गया है।
हिस्टोग्राम से डेटा के लिए एक फ़ंक्शन फिटिंग
मान लें कि एक घातांक की पृष्ठभूमि में सामान्य रूप से (गॉसियन) वितरित डेटा (मतलब: 3.0, मानक विचलन: 0.3) है। यह वितरण कुछ चरणों के भीतर कर्व_फिट के साथ फिट किया जा सकता है:
1.) आवश्यक पुस्तकालयों को आयात करें।
2.) फिट फ़ंक्शन को परिभाषित करें जिसे डेटा के लिए फिट किया जाना है।
3.) प्रयोग से डेटा प्राप्त करें या डेटा उत्पन्न करें। इस उदाहरण में, पृष्ठभूमि और सिग्नल का अनुकरण करने के लिए यादृच्छिक डेटा उत्पन्न होता है।
4.) संकेत और पृष्ठभूमि जोड़ें।
5.) कर्व_फिट वाले डेटा के लिए फ़ंक्शन को फ़िट करें।
6.) (वैकल्पिक रूप से) परिणाम और डेटा प्लॉट करें।
इस उदाहरण में, देखे गए y मान हिस्टोग्राम binscenters की ऊंचाइयां हैं, जबकि देखे गए एक्स मान हिस्टोग्राम binscenters ( binscenters ) के केंद्र हैं। फिट फ़ंक्शन का नाम, x मान और y मान को curve_fit से curve_fit करना curve_fit । इसके अलावा, फिट मापदंडों के लिए मोटे अनुमान वाले एक वैकल्पिक तर्क को p0 साथ दिया जा सकता है। curve_fit रिटर्न popt और pcov , जहां popt , मानकों के लिए फिट परिणाम होता है, जबकि pcov सहप्रसरण मैट्रिक्स है, विकर्ण तत्वों जिनमें से सज्जित मापदंडों के विचरण का प्रतिनिधित्व करते हैं।
# 1.) Necessary imports.
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# 2.) Define fit function.
def fit_function(x, A, beta, B, mu, sigma):
return (A * np.exp(-x/beta) + B * np.exp(-1.0 * (x - mu)**2 / (2 * sigma**2)))
# 3.) Generate exponential and gaussian data and histograms.
data = np.random.exponential(scale=2.0, size=100000)
data2 = np.random.normal(loc=3.0, scale=0.3, size=15000)
bins = np.linspace(0, 6, 61)
data_entries_1, bins_1 = np.histogram(data, bins=bins)
data_entries_2, bins_2 = np.histogram(data2, bins=bins)
# 4.) Add histograms of exponential and gaussian data.
data_entries = data_entries_1 + data_entries_2
binscenters = np.array([0.5 * (bins[i] + bins[i+1]) for i in range(len(bins)-1)])
# 5.) Fit the function to the histogram data.
popt, pcov = curve_fit(fit_function, xdata=binscenters, ydata=data_entries, p0=[20000, 2.0, 2000, 3.0, 0.3])
print(popt)
# 6.)
# Generate enough x values to make the curves look smooth.
xspace = np.linspace(0, 6, 100000)
# Plot the histogram and the fitted function.
plt.bar(binscenters, data_entries, width=bins[1] - bins[0], color='navy', label=r'Histogram entries')
plt.plot(xspace, fit_function(xspace, *popt), color='darkorange', linewidth=2.5, label=r'Fitted function')
# Make the plot nicer.
plt.xlim(0,6)
plt.xlabel(r'x axis')
plt.ylabel(r'Number of entries')
plt.title(r'Exponential decay with gaussian peak')
plt.legend(loc='best')
plt.show()
plt.clf()
