Как построить доверительный интервал в Python
Доверительный интервал — это диапазон значений, который может содержать параметр генеральной совокупности с определенным уровнем достоверности.
В этом руководстве объясняется, как построить доверительный интервал для набора данных в Python с помощью библиотеки визуализации Seaborn .
Построение доверительных интервалов с использованием lineplot()
Первый способ построить доверительный интервал — использоватьфункцию lineplot() , которая соединяет все точки данных в наборе данных линией и отображает доверительный интервал вокруг каждой точки:
import numpy as np import seaborn as sns import matplotlib.pyplot as plt #create some random data np.random.seed(0) x = np.random.randint(1, 10, 30) y = x+np.random.normal(0, 1, 30) #create lineplot ax = sns.lineplot(x, y)
По умолчанию функция lineplot() использует доверительный интервал 95%, но может указать уровень достоверности для использования с командой ci .
Чем меньше уровень достоверности, тем более узким будет доверительный интервал вокруг линии. Например, вот как выглядит доверительный интервал 80% для точно такого же набора данных:
#create lineplot ax = sns.lineplot(x, y, ci= 80 )
Построение доверительных интервалов с использованием regplot()
Вы также можете построить доверительные интервалы с помощью функции regplot() , которая отображает диаграмму рассеяния набора данных с доверительными диапазонами вокруг оценочной линии регрессии:
import numpy as np import seaborn as sns import matplotlib.pyplot as plt #create some random data np.random.seed(0) x = np.random.randint(1, 10, 30) y = x+np.random.normal(0, 1, 30) #create regplot ax = sns.regplot(x, y)
Подобно функции lineplot(), функция regplot() по умолчанию использует доверительный интервал 95%, но может указать уровень достоверности для использования с командой ci .
Опять же, чем меньше уровень достоверности, тем более узким будет доверительный интервал вокруг линии регрессии. Например, вот как выглядит доверительный интервал 80% для точно такого же набора данных:
#create regplot ax = sns.regplot(x, y, ci= 80 )
How to Plot the Confidence Interval in Python?
Problem Formulation: How to plot the confidence interval in Python?
To plot a filled interval with the width ci and interval boundaries from y-ci to y+ci around function values y , use the plt.fill_between(x, (y-ci), (y+ci), color=’blue’, alpha=0.1) function call on the Matplotlib plt module.
- The first argument x defines the x values of the filled curve. You can use the same values as for the original plot.
- The second argument y-ci defines the lower interval boundary.
- The third argument y+ci defines the upper interval boundary.
- The fourth argument color=’blue’ defines the color of the shaded interval.
- The fifth argument alpha=0.1 defines the transparency to allow for layered intervals.
from matplotlib import pyplot as plt import numpy as np # Create the data set x = np.arange(0, 10, 0.05) y = np.sin(x) Define the confidence interval ci = 0.1 * np.std(y) / np.mean(y) # Plot the sinus function plt.plot(x, y) # Plot the confidence interval plt.fill_between(x, (y-ci), (y+ci), color='blue', alpha=0.1) plt.show()
You can also plot two layered confidence intervals by calling the plt.fill_between() function twice with different interval boundaries:
from matplotlib import pyplot as plt import numpy as np # Create the data set x = np.arange(0, 10, 0.05) y = np.sin(x) # Define the confidence interval ci = 0.1 * np.std(y) / np.mean(y) # Plot the sinus function plt.plot(x, y) # Plot the confidence interval plt.fill_between(x, (y-ci), (y+ci), color='blue', alpha=0.1) plt.fill_between(x, (y-2*ci), (y+2*ci), color='yellow', alpha=.1) plt.show()
The resulting plot shows two confidence intervals in blue and yellow:
You can run this in our interactive Jupyter Notebook:
You can also use Seaborn’s regplot() function that does it for you, given a scattered data set of (x,y) tuples.
import numpy as np import seaborn as sns import matplotlib.pyplot as plt #create some random data x = np.random.randint(1, 10, 20) y = x + np.random.normal(0, 1, 20) #create regplot ax = sns.regplot(x, y)
This results in the convenient output:
Note that the 95% confidence interval is calculated automatically. An alternative third ci argument in the sns.regplot(x, y, ci=80) allows you to define another confidence interval (e.g., 80%).
To boost your skills in Python, Matplotlib and data science, join our free email academy and download your Python cheat sheets now!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
Be on the Right Side of Change 🚀
- The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
- Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
- Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.
Learning Resources 🧑💻
⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!
Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.
New Finxter Tutorials:
Finxter Categories: