Skip to content

Commit 3311b93

Browse files
author
xuming
committed
add scipy statistics 、curve and advanced operation. xuming 20170405
1 parent e37216b commit 3311b93

12 files changed

Lines changed: 1132 additions & 10 deletions

File tree

03.scipy/03.array.py

Lines changed: 0 additions & 10 deletions
This file was deleted.

03.scipy/03.stats.py

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
# -*- coding:utf-8 -*-
2+
from __future__ import absolute_import
3+
from __future__ import print_function
4+
5+
__author__ = 'XuMing'
6+
# Python 中常用的统计工具有 Numpy, Pandas, PyMC, StatsModels 等。
7+
# Scipy 中的子库 scipy.stats 中包含很多统计上的方法。
8+
from numpy import *
9+
from matplotlib import pyplot
10+
11+
# Numpy 自带简单的统计方法:
12+
heights = array([1.46, 1.79, 2.01, 1.75, 1.56, 1.69, 1.88, 1.76, 1.88, 1.78])
13+
print('mean,', heights.mean())
14+
print('min,', heights.min())
15+
print('max', heights.max())
16+
print('stand deviation,', heights.std())
17+
18+
# 导入 Scipy 的统计模块:
19+
import scipy.stats.stats as st
20+
21+
print('median, ', st.nanmedian(heights)) # 忽略nan值之后的中位数
22+
print('mode, ', st.mode(heights)) # 众数及其出现次数
23+
print('skewness, ', st.skew(heights)) # 偏度
24+
print('kurtosis, ', st.kurtosis(heights)) # 峰度
25+
26+
# 概率分布
27+
# 常见的连续概率分布有:
28+
# 均匀分布
29+
# 正态分布
30+
# 学生t分布
31+
# F分布
32+
# Gamma分布
33+
# ...
34+
35+
# 离散概率分布:
36+
# 伯努利分布
37+
# 几何分布
38+
# ...
39+
# 这些都可以在 scipy.stats 中找到。
40+
41+
# 正态分布
42+
from scipy.stats import norm
43+
44+
# 它包含四类常用的函数:
45+
#
46+
# norm.cdf 返回对应的累计分布函数值
47+
# norm.pdf 返回对应的概率密度函数值
48+
# norm.rvs 产生指定参数的随机变量
49+
# norm.fit 返回给定数据下,各参数的最大似然估计(MLE)值
50+
51+
# 从正态分布产生500个随机点:
52+
x_norm = norm.rvs(size=500)
53+
type(x_norm)
54+
# pyplot.ion() #开启interactive mode
55+
# 直方图:
56+
h = pyplot.hist(x_norm)
57+
print('counts, ', h[0])
58+
print('bin centers', h[1])
59+
figure = pyplot.figure(1) # 创建图表1
60+
pyplot.show()
61+
62+
# 归一化直方图(用出现频率代替次数),将划分区间变为 20(默认 10):
63+
h = pyplot.hist(x_norm, normed=True, bins=20)
64+
pyplot.show()
65+
# 在这组数据下,正态分布参数的最大似然估计值为:
66+
x_mean, x_std = norm.fit(x_norm)
67+
68+
print('mean, ', x_mean)
69+
print('x_std, ', x_std)
70+
71+
# 将真实的概率密度函数与直方图进行比较:
72+
h = pyplot.hist(x_norm, normed=True, bins=20)
73+
74+
x = linspace(-3, 3, 50)
75+
p = pyplot.plot(x, norm.pdf(x), 'r-')
76+
pyplot.show()
77+
78+
# 导入积分函数:
79+
from scipy.integrate import trapz
80+
81+
x1 = linspace(-2, 2, 108)
82+
p = trapz(norm.pdf(x1), x1)
83+
print('{:.2%} of the values lie between -2 and 2'.format(p))
84+
85+
pyplot.fill_between(x1, norm.pdf(x1), color='red')
86+
pyplot.plot(x, norm.pdf(x), 'k-')
87+
pyplot.show()
88+
89+
# 可以通过 loc 和 scale 来调整这些参数,一种方法是调用相关函数时进行输入:
90+
x = linspace(-3, 3, 50)
91+
p = pyplot.plot(x, norm.pdf(x, loc=0, scale=1))
92+
p = pyplot.plot(x, norm.pdf(x, loc=0.5, scale=2))
93+
p = pyplot.plot(x, norm.pdf(x, loc=-0.5, scale=.5))
94+
pyplot.show()
95+
96+
# 不同参数的对数正态分布:
97+
from scipy.stats import lognorm, t, dweibull
98+
99+
x = linspace(0.01, 3, 100)
100+
101+
pyplot.plot(x, lognorm.pdf(x, 1), label='s=1')
102+
pyplot.plot(x, lognorm.pdf(x, 2), label='s=2')
103+
pyplot.plot(x, lognorm.pdf(x, .1), label='s=0.1')
104+
105+
pyplot.legend()
106+
pyplot.show()
107+
108+
# 离散分布
109+
from scipy.stats import binom, poisson, randint
110+
111+
# 离散均匀分布的概率质量函数(PMF):
112+
high = 10
113+
low = -10
114+
115+
x = arange(low, high + 1, 0.5)
116+
p = pyplot.stem(x, randint(low, high).pmf(x)) # 杆状图
117+
pyplot.show()
118+
119+
# 假设检验
120+
# 导入相关的函数:
121+
#
122+
# 1.正态分布
123+
# 2.独立双样本 t 检验,配对样本 t 检验,单样本 t 检验
124+
# 3.学生 t 分布
125+
126+
from scipy.stats import norm
127+
from scipy.stats import ttest_ind, ttest_rel, ttest_1samp
128+
from scipy.stats import t
129+
130+
# 独立样本 t 检验
131+
# 两组参数不同的正态分布:
132+
n1 = norm(loc=0.3, scale=1.0)
133+
n2 = norm(loc=0, scale=1.0)
134+
# 从分布中产生两组随机样本:
135+
n1_samples = n1.rvs(size=100)
136+
n2_samples = n2.rvs(size=100)
137+
# 将两组样本混合在一起:
138+
samples = hstack((n1_samples, n2_samples))
139+
# 最大似然参数估计:
140+
loc, scale = norm.fit(samples)
141+
n = norm(loc=loc, scale=scale)
142+
# 比较:
143+
x = linspace(-3, 3, 100)
144+
145+
pyplot.hist([samples, n1_samples, n2_samples], normed=True)
146+
pyplot.plot(x, n.pdf(x), 'b-')
147+
pyplot.plot(x, n1.pdf(x), 'g-')
148+
pyplot.plot(x, n2.pdf(x), 'r-')
149+
pyplot.show()
150+
151+
# 独立双样本 t 检验的目的在于判断两组样本之间是否有显著差异:
152+
t_val, p = ttest_ind(n1_samples, n2_samples)
153+
154+
print('t = {}'.format(t_val))
155+
print('p-value = {}'.format(p))
156+
# t = 0.868384594123
157+
# p-value = 0.386235148899
158+
# p 值小,说明这两个样本有显著性差异。

03.scipy/04.curve.py

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
@description:
4+
@author:XuMing
5+
"""
6+
from __future__ import print_function # 兼容python3的print写法
7+
from __future__ import unicode_literals # 兼容python3的编码处理
8+
9+
import matplotlib.pyplot as plt
10+
# 曲线拟合
11+
# 导入基础包:
12+
import numpy as np
13+
# 多项式拟合
14+
from numpy import polyfit, poly1d
15+
16+
# 产生数据:
17+
x = np.linspace(-5, 5, 100)
18+
y = 4 * x + 1.5
19+
noise_y = y + np.random.randn(y.shape[-1]) * 2.5
20+
21+
p = plt.plot(x, noise_y, 'rx')
22+
p = plt.plot(x, y, 'b:')
23+
plt.show()
24+
25+
# 进行线性拟合,polyfit 是多项式拟合函数,线性拟合即一阶多项式:
26+
coeff = polyfit(x, noise_y, 1)
27+
print(coeff)
28+
29+
# 一阶多项式 y=a1x+a0y=a1x+a0 拟合,返回两个系数 [a1,a0][a1,a0]。
30+
31+
# 画出拟合曲线:
32+
p = plt.plot(x, noise_y, 'rx')
33+
p = plt.plot(x, coeff[0] * x + coeff[1], 'k-')
34+
p = plt.plot(x, y, 'b--')
35+
plt.show()
36+
37+
# 多项式拟合余弦函数
38+
# 余弦函数:
39+
x = np.linspace(-np.pi, np.pi, 100)
40+
y = np.cos(x)
41+
42+
# 用一阶到九阶多项式拟合,类似泰勒展开:
43+
# 可以用 poly1d 生成一个以传入的 coeff 为参数的多项式函数:
44+
y1 = poly1d(polyfit(x, y, 1))
45+
y3 = poly1d(polyfit(x, y, 3))
46+
y5 = poly1d(polyfit(x, y, 5))
47+
y7 = poly1d(polyfit(x, y, 7))
48+
y9 = poly1d(polyfit(x, y, 9))
49+
x = np.linspace(-3 * np.pi, 3 * np.pi, 100)
50+
51+
p = plt.plot(x, np.cos(x), 'k') # 黑色余弦
52+
p = plt.plot(x, y1(x))
53+
p = plt.plot(x, y3(x))
54+
p = plt.plot(x, y5(x))
55+
p = plt.plot(x, y7(x))
56+
p = plt.plot(x, y9(x))
57+
58+
a = plt.axis([-3 * np.pi, 3 * np.pi, -1.25, 1.25])
59+
plt.show()
60+
# 黑色为原始的图形,可以看到,随着多项式拟合的阶数的增加,
61+
# 曲线与拟合数据的吻合程度在逐渐增大。
62+
63+
64+
# 最小二乘拟合
65+
# 导入相关的模块:
66+
from scipy.linalg import lstsq
67+
from scipy.stats import linregress
68+
69+
x = np.linspace(0, 5, 100)
70+
y = 0.5 * x + np.random.randn(x.shape[-1]) * 0.35
71+
72+
plt.plot(x, y, 'x')
73+
plt.show()
74+
75+
# Scipy.linalg.lstsq 最小二乘解
76+
# 可以使用 scipy.linalg.lstsq 求最小二乘解。
77+
X = np.hstack((x[:, np.newaxis], np.ones((x.shape[-1], 1))))
78+
print(X[1:5])
79+
# 求解:
80+
C, resid, rank, s = lstsq(X, y)
81+
print(C, resid, rank, s)
82+
# 画图:
83+
p = plt.plot(x, y, 'rx')
84+
p = plt.plot(x, C[0] * x + C[1], 'k--')
85+
plt.show()
86+
print("sum squared residual = {:.3f}".format(resid))
87+
print("rank of the X matrix = {}".format(rank))
88+
print("singular values of X = {}".format(s))
89+
90+
# Scipy.stats.linregress 线性回归
91+
# 对于上面的问题,还可以使用线性回归进行求解:
92+
slope, intercept, r_value, p_value, stderr = linregress(x, y)
93+
p = plt.plot(x, y, 'rx')
94+
p = plt.plot(x, slope * x + intercept, 'k--')
95+
plt.show()
96+
print("R-value = {:.3f}".format(r_value))
97+
print("p-value (probability there is no correlation) = {:.3e}".format(p_value))
98+
print("Root mean squared error of the fit = {:.3f}".format(np.sqrt(stderr)))
99+
100+
101+
# 可以看到,两者求解的结果是一致的,但是出发的角度是不同的。
102+
103+
# 高级的拟合
104+
# 先定义这个非线性函数:y=ae^(−bsin(fx+ϕ))
105+
def function(x, a, b, f, phi):
106+
"""a function of x with four parameters"""
107+
result = a * np.exp(-b * np.sin(f * x + phi))
108+
return result
109+
110+
111+
# 画出原始曲线:
112+
x = np.linspace(0, 2 * np.pi, 50)
113+
actual_parameters = [3, 2, 1.25, np.pi / 4]
114+
y = function(x, *actual_parameters)
115+
p = plt.plot(x, y)
116+
plt.show()
117+
# 加入噪声:
118+
from scipy.stats import norm
119+
120+
y_noisy = y + 0.8 * norm.rvs(size=len(x))
121+
p = plt.plot(x, y, 'k-')
122+
p = plt.plot(x, y_noisy, 'rx')
123+
plt.show()
124+
# 高级的做法:
125+
from scipy.optimize import curve_fit
126+
127+
# 不需要定义误差函数,直接传入 function 作为参数:
128+
p_est, err_est = curve_fit(function, x, y_noisy)
129+
print(p_est)
130+
p = plt.plot(x, y_noisy, "rx")
131+
p = plt.plot(x, function(x, *p_est), "g--")
132+
plt.show()
133+
134+
# 这里第一个返回的是函数的参数,第二个返回值为各个参数的协方差矩阵:
135+
print(err_est)
136+
137+
# 协方差矩阵的对角线为各个参数的方差:
138+
print("normalized relative errors for each parameter")
139+
print(" a\t b\t f\t phi")
140+
print(np.sqrt(err_est.diagonal()) / p_est)

04.advanced/01.os.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
@description:
4+
@author:XuMing
5+
"""
6+
from __future__ import print_function # 兼容python3的print写法
7+
from __future__ import unicode_literals # 兼容python3的编码处理
8+
9+
# 与操作系统进行交互:os 模块
10+
import os
11+
12+
# 文件路径操作
13+
# os.remove(path) 或 os.unlink(path) :删除指定路径的文件。路径可以是全名,也可以是当前工作目录下的路径。
14+
# os.removedirs:删除文件,并删除中间路径中的空文件夹
15+
# os.chdir(path):将当前工作目录改变为指定的路径
16+
# os.getcwd():返回当前的工作目录
17+
# os.curdir:表示当前目录的符号
18+
# os.rename(old, new):重命名文件
19+
# os.renames(old, new):重命名文件,如果中间路径的文件夹不存在,则创建文件夹
20+
# os.listdir(path):返回给定目录下的所有文件夹和文件名,不包括 '.' 和 '..' 以及子文件夹下的目录。('.' 和 '..' 分别指当前目录和父目录)
21+
# os.mkdir(name):产生新文件夹
22+
# os.makedirs(name):产生新文件夹,如果中间路径的文件夹不存在,则创建文件夹
23+
24+
# 产生文件:
25+
f = open('test.file', 'w')
26+
f.close()
27+
print('test.file' in os.listdir(os.curdir))
28+
29+
# 重命名文件
30+
os.rename("test.file", "test.new.file")
31+
print("test.file" in os.listdir(os.curdir))
32+
print("test.new.file" in os.listdir(os.curdir))
33+
34+
# 删除文件
35+
os.remove("test.new.file")
36+
37+
# 系统常量
38+
# windows 为 \r\n
39+
# unix为 \n
40+
print(os.linesep)
41+
# 当前操作系统的路径分隔符:
42+
print(os.sep)
43+
# 当前操作系统的环境变量中的分隔符(';' 或 ':'):
44+
# windows 为 ;
45+
# unix 为:
46+
print(os.pathsep)
47+
48+
# os.environ 是一个存储所有环境变量的值的字典,可以修改。
49+
print(os.environ)
50+
51+
# os.path 模块
52+
import os.path
53+
54+
# os.path.isfile(path) :检测一个路径是否为普通文件
55+
# os.path.isdir(path):检测一个路径是否为文件夹
56+
# os.path.exists(path):检测路径是否存在
57+
# os.path.isabs(path):检测路径是否为绝对路径
58+
print(os.path.isfile("C:/Windows"))
59+
print(os.path.isdir("C:/Windows"))
60+
print(os.path.exists("C:/Windows"))
61+
print(os.path.isabs("C:/Windows"))
62+
# split 和 join
63+
# os.path.split(path):拆分一个路径为 (head, tail) 两部分
64+
# os.path.join(a, *p):使用系统的路径分隔符,将各个部分合成一个路径
65+
head, tail = os.path.split("c:/tem/b.txt")
66+
print(head, tail)
67+
a = "c:/tem"
68+
b = "b.txt"
69+
print(os.path.join(a, b))
70+
71+
72+
def get_files(dir_path):
73+
'''
74+
列出文件夹下的所有文件
75+
:param dir_path: 父文件夹路径
76+
:return:
77+
'''
78+
for parent, dirname, filenames in os.walk(dir_path):
79+
for filename in filenames:
80+
print("parent is:", parent)
81+
print("filename is:", filename)
82+
print("full name of the file is:", os.path.join(parent, filename))
83+
84+
85+
dir = "C:\Windows\System32\drivers\etc"
86+
get_files(dir)

0 commit comments

Comments
 (0)