【Python统计和建模】

简介: 【Python统计和建模】

1. 前言

统计学是数学领域的一个重要分支,几乎涉及科学和工程学的所有应用领域,也被广泛应用于商业、金融等需要依靠数据来获取知识和做出决策的领域。


本章将介绍使SciPy中的stats模块,包括描述性统计量、随机数、随机变量、分布以及假设检验等内容。


2. 导入模块

import numpy as np
import random
from scipy import stats
from scipy import optimize
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="whitegrid")


3. 描述性统计量

x = np.array([3.5, 1.1, 3.2, 2.8, 6.7, 4.4, 0.9, 2.2])
np.mean(x)
np.median(x)
x.min(), x.max()
x.var()
x.std()

3.1.png


参数ddof用于设置自由度的个数。如果计算方差的无偏估计以及样本的标准差,需要把ddof设置为1


x.var(ddof=1)
x.std(ddof=1)

3.2.png


4. 随机数

random.seed(123456789)
random.random()
random.randint(0, 10)  # 0 and 10 inclusive
np.random.seed(123456789)
np.random.rand()
np.random.randn()
np.random.rand(5)
np.random.randn(2, 4)

4.1.png

np.random.randint(10, size=10)
np.random.randint(low=10, high=20, size=(2, 10))

4.2.png

fig, axes = plt.subplots(1, 3, figsize=(12, 3))
axes[0].hist(np.random.rand(10000))
axes[0].set_title("rand")
axes[1].hist(np.random.randn(10000))
axes[1].set_title("randn")
axes[2].hist(np.random.randint(low=1, high=10, size=10000), bins=9, align='left')
axes[2].set_title("randint(low=1, high=10)")
fig.tight_layout()
fig.savefig("ch13-random-hist.pdf")

4.3.png

#random.sample(range(10), 5)
np.random.choice(10, 5, replace=False)
np.random.seed(123456789)
np.random.rand()
np.random.seed(123456789); np.random.rand()
np.random.seed(123456789); np.random.rand()
prng = np.random.RandomState(123456789)
prng.rand(2, 4)

4.4.png

prng.chisquare(1, size=(2, 2))
prng.standard_t(1, size=(2, 3))
prng.f(5, 2, size=(2, 4))
prng.binomial(10, 0.5, size=10)
prng.poisson(5, size=10)

4.5.png


4.1 随机变量及其分布

np.random.seed(123456789)
X = stats.norm(1, 0.5)
X.mean()
X.median()
X.std()
X.var()
[X.moment(n) for n in range(5)]
X.stats()

4.6.png

X.pdf([0, 1, 2])
X.cdf([0, 1, 2])
X.rvs(10)
stats.norm(1, 0.5).stats()
stats.norm.stats(loc=2, scale=0.5)
X.interval(0.95)
X.interval(0.99)

4.7.png

def plot_rv_distribution(X, axes=None):
    """Plot the PDF, CDF, SF and PPF of a given random variable"""
    if axes is None:
        fig, axes = plt.subplots(1, 3, figsize=(12, 3))
    x_min_999, x_max_999 = X.interval(0.999)
    x999 = np.linspace(x_min_999, x_max_999, 1000)
    x_min_95, x_max_95 = X.interval(0.95)
    x95 = np.linspace(x_min_95, x_max_95, 1000)
    if hasattr(X.dist, 'pdf'):
        axes[0].plot(x999, X.pdf(x999), label="PDF")
        axes[0].fill_between(x95, X.pdf(x95), alpha=0.25)
    else:
        x999_int = np.unique(x999.astype(int))
        axes[0].bar(x999_int, X.pmf(x999_int), label="PMF")
    axes[1].plot(x999, X.cdf(x999), label="CDF")
    axes[1].plot(x999, X.sf(x999), label="SF")
    axes[2].plot(x999, X.ppf(x999), label="PPF")
    for ax in axes:
        ax.legend()
    return axes
fig, axes = plt.subplots(3, 3, figsize=(12, 9))
X = stats.norm()
plot_rv_distribution(X, axes=axes[0, :])
axes[0, 0].set_ylabel("Normal dist.")
X = stats.f(2, 50)
plot_rv_distribution(X, axes=axes[1, :])
axes[1, 0].set_ylabel("F dist.")
X = stats.poisson(5)
plot_rv_distribution(X, axes=axes[2, :])
axes[2, 0].set_ylabel("Poisson dist.")
fig.tight_layout()

4.8.png

def plot_dist_samples(X, X_samples, title=None, ax=None):
    """ Plot the PDF and histogram of samples of a continuous random variable"""
    if ax is None:
        fig, ax = plt.subplots(1, 1, figsize=(8, 4))
    x_lim = X.interval(.99)
    x = np.linspace(*x_lim, num=100)
    ax.plot(x, X.pdf(x), label="PDF", lw=3)    
    ax.hist(X_samples, label="samples", bins=75)
    ax.set_xlim(*x_lim)
    ax.legend()
    if title:
        ax.set_title(title)
    return ax
fig, axes = plt.subplots(1, 3, figsize=(12, 3))
X = stats.t(7.0)
plot_dist_samples(X, X.rvs(2000), "Student's t dist.", ax=axes[0])
X = stats.chi2(5.0)
plot_dist_samples(X, X.rvs(2000), r"$\chi^2$ dist.", ax=axes[1])
X = stats.expon(0.5)
plot_dist_samples(X, X.rvs(2000), "exponential dist.", ax=axes[2])
fig.tight_layout()

4.9.png


X = stats.chi2(df=5)
X_samples = X.rvs(500)
df, loc, scale = stats.chi2.fit(X_samples)
df, loc, scale
Y = stats.chi2(df=df, loc=loc, scale=scale)
fig, ax = plt.subplots(1, 1, figsize=(8, 3))
x_lim = X.interval(.99)
x = np.linspace(*x_lim, num=100)
ax.plot(x, X.pdf(x), label="original")
ax.plot(x, Y.pdf(x), label="recreated")
ax.legend()
fig.tight_layout()


5.0.png

fig, axes = plt.subplots(1, 2, figsize=(12, 4))
x_lim = X.interval(.99)
x = np.linspace(*x_lim, num=100)
axes[0].plot(x, X.pdf(x), label="original")
axes[0].plot(x, Y.pdf(x), label="recreated")
axes[0].legend()
axes[1].plot(x, X.pdf(x) - Y.pdf(x), label="error")
axes[1].legend()
fig.tight_layout()


5.1.png


4.2 假设检验

np.random.seed(123456789)
mu, sigma = 1.0, 0.5
X = stats.norm(mu-0.2, sigma)
n = 100
X_samples = X.rvs(n)
z = (X_samples.mean() - mu)/(sigma/np.sqrt(n))
z
t = (X_samples.mean() - mu)/(X_samples.std(ddof=1)/np.sqrt(n))
t
stats.norm().ppf(0.025)
2 * stats.norm().cdf(-abs(z))
2 * stats.t(df=(n-1)).cdf(-abs(t))
t, p = stats.ttest_1samp(X_samples, mu)
t
p
fig, ax = plt.subplots(figsize=(8, 3))
sns.distplot(X_samples, ax=ax)
x = np.linspace(*X.interval(0.999), num=100)
ax.plot(x, stats.norm(loc=mu, scale=sigma).pdf(x))
fig.tight_layout()

1.png

n = 50
mu1, mu2 = np.random.rand(2)
X1 = stats.norm(mu1, sigma)
X1_sample = X1.rvs(n)
X2 = stats.norm(mu2, sigma)
X2_sample = X2.rvs(n)
t, p = stats.ttest_ind(X1_sample, X2_sample)
t
p
mu1, mu2
sns.histplot(X1_sample)
sns.histplot(X2_sample)

2.png

非参数法


np.random.seed(0)
X = stats.chi2(df=5)
X_samples = X.rvs(100)
kde = stats.kde.gaussian_kde(X_samples)
kde_low_bw = stats.kde.gaussian_kde(X_samples, bw_method=0.25)
x = np.linspace(0, 20, 100)
fig, axes = plt.subplots(1, 3, figsize=(12, 3))
axes[0].hist(X_samples, alpha=0.5, bins=25)
axes[1].plot(x, kde(x), label="KDE")
axes[1].plot(x, kde_low_bw(x), label="KDE (low bw)")
axes[1].plot(x, X.pdf(x), label="True PDF")
axes[1].legend()
sns.histplot(X_samples, bins=25, ax=axes[2])
fig.tight_layout()

3.png

kde.resample(10)
def _kde_cdf(x):
    return kde.integrate_box_1d(-np.inf, x)
kde_cdf = np.vectorize(_kde_cdf)
fig, ax = plt.subplots(1, 1, figsize=(8, 3))
sns.histplot(X_samples, bins=25, ax=ax)
x = np.linspace(0, 20, 100)
ax.plot(x, kde_cdf(x))
fig.tight_layout()


4.png

def _kde_ppf(q):

return optimize.fsolve(lambda x, q: kde_cdf(x) - q, kde.dataset.mean(), args=(q,))[0]


kde_ppf = np.vectorize(_kde_ppf)


kde_ppf([0.05, 0.95])


X.ppf([0.05, 0.95])

目录
相关文章
|
1月前
|
数据采集 数据可视化 数据挖掘
金融波动率的多模型建模研究:GARCH族与HAR模型的Python实现与对比分析
本文探讨了金融资产波动率建模中的三种主流方法:GARCH、GJR-GARCH和HAR模型,基于SPY的实际交易数据进行实证分析。GARCH模型捕捉波动率聚类特征,GJR-GARCH引入杠杆效应,HAR整合多时间尺度波动率信息。通过Python实现模型估计与性能比较,展示了各模型在风险管理、衍生品定价等领域的应用优势。
300 66
金融波动率的多模型建模研究:GARCH族与HAR模型的Python实现与对比分析
|
2月前
|
数据可视化 算法 数据挖掘
Python量化投资实践:基于蒙特卡洛模拟的投资组合风险建模与分析
蒙特卡洛模拟是一种利用重复随机抽样解决确定性问题的计算方法,广泛应用于金融领域的不确定性建模和风险评估。本文介绍如何使用Python和EODHD API获取历史交易数据,通过模拟生成未来价格路径,分析投资风险与收益,包括VaR和CVaR计算,以辅助投资者制定合理决策。
139 15
|
5月前
|
机器学习/深度学习 算法 数据可视化
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
2024年中国研究生数学建模竞赛C题聚焦磁性元件磁芯损耗建模。题目背景介绍了电能变换技术的发展与应用,强调磁性元件在功率变换器中的重要性。磁芯损耗受多种因素影响,现有模型难以精确预测。题目要求通过数据分析建立高精度磁芯损耗模型。具体任务包括励磁波形分类、修正斯坦麦茨方程、分析影响因素、构建预测模型及优化设计条件。涉及数据预处理、特征提取、机器学习及优化算法等技术。适合电气、材料、计算机等多个专业学生参与。
1808 17
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
|
4月前
|
数据可视化 数据挖掘 Python
Seaborn 库创建吸引人的统计图表
【10月更文挑战第11天】本文介绍了如何使用 Seaborn 库创建多种统计图表,包括散点图、箱线图、直方图、线性回归图、热力图等。通过具体示例和代码,展示了 Seaborn 在数据可视化中的强大功能和灵活性,帮助读者更好地理解和应用这一工具。
64 3
|
5月前
|
机器学习/深度学习 数据采集 算法
【BetterBench博士】2024华为杯C题:数据驱动下磁性元件的磁芯损耗建模 Python代码实现
本文介绍了2024年中国研究生数学建模竞赛C题的详细分析,涵盖数据预处理、特征提取、模型训练及评估等多个方面。通过对磁通密度数据的处理,提取关键特征并应用多种分类算法进行波形分类。此外,还探讨了斯坦麦茨方程及其温度修正模型的应用,分析了温度、励磁波形和磁芯材料对磁芯损耗的影响,并提出了优化磁芯损耗与传输磁能的方法。最后,提供了B站视频教程链接,供进一步学习参考。
280 7
【BetterBench博士】2024华为杯C题:数据驱动下磁性元件的磁芯损耗建模 Python代码实现
|
4月前
|
JSON 数据格式 Python
Python实用记录(十四):python统计某个单词在TXT/JSON文件中出现的次数
这篇文章介绍了一个Python脚本,用于统计TXT或JSON文件中特定单词的出现次数。它包含两个函数,分别处理文本和JSON文件,并通过命令行参数接收文件路径、目标单词和文件格式。文章还提供了代码逻辑的解释和示例用法。
75 0
Python实用记录(十四):python统计某个单词在TXT/JSON文件中出现的次数
|
4月前
|
数据可视化 Serverless Python
Python小事例—质地不均匀的硬币的概率统计
Python小事例—质地不均匀的硬币的概率统计
91 0
|
4月前
|
开发者 Python
Python类和子类的小示例:建模农场
Python类和子类的小示例:建模农场
38 0
|
6月前
|
供应链 数据可视化 数据挖掘
【2023年第十一届泰迪杯数据挖掘挑战赛】B题:产品订单的数据分析与需求预测 建模及python代码详解 问题一
本文详细介绍了第十一届泰迪杯数据挖掘挑战赛B题的解决方案,涵盖了对产品订单数据的深入分析、多种因素对需求量影响的探讨,并建立了数学模型进行未来需求量的预测,同时提供了Python代码实现和结果可视化的方法。
198 3
【2023年第十一届泰迪杯数据挖掘挑战赛】B题:产品订单的数据分析与需求预测 建模及python代码详解 问题一
|
6月前
|
数据建模 大数据 数据库
【2023年4月美赛加赛】Y题:Understanding Used Sailboat Prices 建模思路、建模方案、数据来源、相关资料、Python代码
本文提供了2023年MCM问题Y的解题思路、建模方案、数据来源、相关资料以及Python代码,旨在建立数学模型解释二手帆船的挂牌价格,并分析地区对价格的影响,以及在香港(SAR)市场上的应用。
69 1
【2023年4月美赛加赛】Y题:Understanding Used Sailboat Prices 建模思路、建模方案、数据来源、相关资料、Python代码

热门文章

最新文章