scipy库 signal 导入_埃博拉病毒数据处理库清洗|EBOV_data|Notebook_1

埃博拉病毒库的数据结构

0ee473dff44a9d0c3756f212ac741c0a.png
ebov_data的数据结构

埃博拉病毒的数据依赖

6148b8837ad2d1cf51707d05d33eb19c.png
ebov_data的数据清洗

数据清洗相关专业知识

Scipy的模块:

501f9173ac2ef5247c8b547fca978c46.png
  • scipy.special: 特殊函数模块。里面有各种特殊的数学函数,可以直接调用,如贝塞尔函数
  • scipy.integrate: 积分模块。可以求多重积分,高斯积分,解常微分方程
  • scipy.optimize: 优化模块。 里面有各种优化算法,包括用来求有/ 无约束的多元标量函数最小值算法,最小二乘法,求有/无约束的单变量函数最小值算法,还有解各种复杂方程的算法
  • scipy.interpolation: 插值模块。提供各种一维、二维、N维插值算法,包括B样条插值、径向基函数插值等
  • scipy.fftpack: FFT(快速傅里叶变换)模块。可以进行FFT/ DCT/ DST
  • scipy.signal: 信号处理模块。包括样条插值,卷积,差分等滤波方法,还有FIR/IIR滤波,中值、排序、维纳、希尔伯特等滤波器,各种谱分析算法
  • scipy.linalg: 线代模块。提供各种线性代数中的常规操作
  • scipy.sparse: 稀疏矩阵模块。提供了大型稀疏矩阵计算中的各种算法
  • scipy.spatial: 空间结构模块。提供了一些空间相关的数据结构和算法,如Delaunay三角剖分,共面点,凸包,维诺图,Kd树等
  • scipy.stats: 统计模块。提供一些统计学上常用的函数
  • scipy.ndimage: 多维图像处理模块。提供一些多维图像处理上的常用算法
  • scipy.io: IO模块。提供与其他文件的接口,如matlab文件、IDL文件、Wav(音频)文件、ARFF文件

Scipy 应用场景

  1. 统计

2. 统计

2.1 分析随机数:

(1)生成服从指定分布的随机数

norm.rvs通过loc和scale参数可以指定随机变量的偏移和缩放参数,这里对应的是正态分布的期望和标准差。size得到随机数数组的形状参数。(也可以使用np.random.normal(loc=0.0, scale=1.0, size=None))

import scipy.stats as stats
generated = stats.norm.rvs(size = 900)
Mean, std = stats.norm.fit(generated)

偏度(skewnes)描述的是概率分布的偏斜程度,我们需要做一个偏度检验。该检验有两个返回值,其中第二个返回值是p-value,即观察到的数据服从正态分布的概率,取值为0-1

stats.skewtest(generated)

峰度(kurtosis)描述的是概率分布的陡峭程度。该检验和偏度检验类似。

stats.kurtosistest(generated)

正态性检验(normality test)可以检验数据服从正态分布的程度

stats.normaltest(generated)

使用Scipy我们很方便的得到数据所在区域中某一百分比处的数值

例如获取到95%处的值

stats.scoreatpercentile(generated, 95)

同样返过来也可以通过某一个数值获取其百分比

stats.percentileofscore(generated, 1)

(1) 求概率密度函数指定点的函数值

stats.norm.pdf正态分布概率密度函数

stats.norm.pdf(0,loc = 0,scale = 1) 

(2) 求累计分布函数指定点的函数值

stats.norm.cdf正态分布累计概率密度函数

stats.norm.cdf(0,loc=3,scale=1) 

(3) 累计分布函数的逆函数

stats.norm.ppf正态分布的累计分布函数的逆函数,即下分位点

z05 = stats.norm.ppf(0.05) 

2.2 通用函数

名称

备注

rvs

产生服从指定分布的随机数

pdf

概率密度函数

cdf

累计分布函数

sf

残存函数(1-CDF)

ppf

分位点函数(CDF的逆)

isf

逆残存函数(sf的逆)

fit

对一组随机取样进行拟合,最大似然估计方法找出最适合取样数据的概率密度函数系数。

2.3常见分布

名称

含义

beta

beta分布

f

F分布

gamma

gam分布

poisson

泊松分布

hypergeom

超几何分布

lognorm

对数正态分布

binom

二项分布

uniform

均匀分布

chi2

卡方分布

cauchy

柯西分布

laplace

拉普拉斯分布

rayleigh

瑞利分布

t

学生T分布

norm

正态分布

expon

指数分布

概率论中常见分布总结以及python的scipy库使用:两点分布、二项分布、几何分布、泊松分布、均匀分布、指数分布、正态分布 - 禅在心中 - 博客园​www.cnblogs.com
498fbdbb16d5eead812ce1be65e83fd7.png

2.4假设检验

(1)导入相关的函数:

·        正态分布:from scipy.stats import norm

· 独立双样本 t 检验,配对样本 t 检验,单样本 t 检验

from scipy.stats import ttest_ind, ttest_rel, ttest_1samp
·        学生 t 分布:from scipy.stats import t

(2) 独立样本 t 检验

两组参数不同的正态分布:

n1 = norm(loc=0.3, scale=1.0)
n2 = norm(loc=0, scale=1.0)

从分布中产生两组随机样本:

n1_samples = n1.rvs(size=100)
n2_samples = n2.rvs(size=100)

将两组样本混合在一起:

samples = hstack((n1_samples, n2_samples))

最大似然参数估计:

loc, scale = norm.fit(samples)
n = norm(loc=loc, scale=scale)

独立双样本 t 检验的目的在于判断两组样本之间是否有显著差异:

t_val, p = ttest_ind(n1_samples, n2_samples)

p 值小,说明这两个样本有显著性差异

(3) 配对样本 t 检验

配对样本指的是两组样本之间的元素一一对应,例如,假设我们有一组病人的数据:

pop_size = 35
pre_treat = norm(loc=0, scale=1)
n0 = pre_treat.rvs(size=pop_size)

经过某种治疗后,对这组病人得到一组新的数据:

effect = norm(loc=0.05, scale=0.2)
eff = effect.rvs(size=pop_size)
n1 = n0 + eff

新数据的最大似然估计:

loc, scale = norm.fit(n1)
post_treat = norm(loc=loc, scale=scale)

画图:

fig = figure(figsize=(10,4))
ax1 = fig.add_subplot(1,2,1)
h = ax1.hist([n0, n1], normed=True)
p = ax1.plot(x, pre_treat.pdf(x), 'b-')
p = ax1.plot(x, post_treat.pdf(x), 'g-')
ax2 = fig.add_subplot(1,2,2)
h = ax2.hist(eff, normed=True)

独立 t 检验:

t_val, p = ttest_ind(n0, n1)

高 p 值说明两组样本之间没有显著性差异。

配对 t 检验:

t_val, p = ttest_rel(n0, n1)

配对 t 检验的结果说明,配对样本之间存在显著性差异,说明治疗时有效的,符合我们的预期

3. 插值

插值是在直线或曲线上的两点之间找到值的过程

import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt
x = np.linspace(0, 4, 12)
y = np.cos(x**2/3+4)
print (x,y)

有两个数组。 假设这两个数组作为空间点的两个维度,使用下面的程序进行绘图,并看看它们的样子

plt.plot(x,y,'o')
plt.show()

(1) 一维插值

scipy.interpolate中的interp1d类是一种创建基于固定数据点的函数的便捷方法,可以使用线性插值在给定数据定义的域内的任意位置评估该函数。

from scipy import interpolate
from scipy.interpolate import interp1d
f1 = interp1d(x, y,kind = 'linear')
f2 = interp1d(x, y,kind = 'cubic')

创建更多长度的新输入以查看插值的明显区别。 对新数据使用旧数据的相同功能

xnew = np.linspace(0, 4,30)
plt.plot(x, y, 'o', xnew, f1(xnew), '-', xnew, f2(xnew), '--')
plt.legend(['data', 'linear', 'cubic','nearest'], loc = 'best')
plt.show()

(2)样条曲线

单变量样条

一维平滑样条拟合一组给定的数据点。 Scipy.interpolate中的UnivariateSpline类是创建基于固定数据点类的函数的便捷方法 –

scipy.interpolate.UnivariateSpline(x,y,w = None,bbox = [None,None],k = 3,s = None,ext = 0,check_finite = False)

下面来看看一个例子

import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
x = np.linspace(-3, 3, 50)
y = np.exp(-x**2) + 0.1 * np.random.randn(50)
plt.plot(x, y, 'ro', ms = 5)
plt.show()

使用平滑参数的默认值

spl = UnivariateSpline(x, y)
xs = np.linspace(-3, 3, 1000)
plt.plot(xs, spl(xs), 'g', lw = 3)
plt.show()

手动更改平滑量

spl.set_smoothing_factor(0.5)
plt.plot(xs, spl(xs), 'b', lw = 3)
plt.show()

4. 拟合

曲线拟合

导入基础包:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
AI 基础:Scipy(科学计算库) 简易入门​mp.weixin.qq.com
41af2f0ef212f521e8f32f903cf88c1f.png

2. scipy在金融领域的应用:

  1. 插值 (interpolation)
  2. 积分 (integration)
  3. 优化 (optimization)
Python小白数据科学教程:SciPy精讲​mp.weixin.qq.com
2f82bed114169c8d37104132db23a0a8.png
CSDN-专业IT技术社区-登录​blog.csdn.net https://github.com/zjgulai/BAP​github.com

原文:

埃博拉病毒数据处理库清洗|EBOV_data​mp.weixin.qq.com
4c3bd5c6602bf371c62f7af46f56ada5.png

代码:

def loadData():
    for fname in filenames:  ## iterate through country files
        # handle = pd.json.load(open(map_path + fname, 'r'))  ## load data
        # 参看 https://blog.csdn.net/qq_24499417/article/details/81428594
        # https://stackoverflow.com/questions/36837663/reading-json-file-as-pandas-dataframe-error
        # handle =gpd.read_file(fname)  ## load data
        openfile = open(fname)
        jsondata = json.load(openfile)
        handle = pd.DataFrame(jsondata)
        openfile.close()
        # print(handle)
        # 81个行政区的地理位置信息
        features = handle['features']
        # print(features)
        for loc in features:  ## iterate through features (locations)
            poly = np.array(loc['geometry']['coordinates'])  ## get coordinates

            country = loc['properties']['ISO']
            location = loc['properties']['location']  ## standardised location name
            location_to_country[location] = country
            # print("location_to_country{}: {}".format(location, country))
            locations.append(location)
            if country not in countries:
                countries.append(country)


            location_points[location] = []
            if loc['geometry']['type'] == 'MultiPolygon':  ## multiple parts detected
                # 这种n维数组的遍历是层层剥开的,从最外层到最内层
                # np.array for vector in vectors
                # 四维数组剥开两层
                for part in poly:
                    for coords in part:
                        xs = column(coords, 0)
                        ys = column(coords, 1)
                        location_points[location].append(np.vstack(zip(xs, ys)))
            if loc['geometry']['type'] == 'Polygon':  ## location is single part
                # 3维数组剥开一层
                for coords in poly:
                    xs = column(coords, 0)
                    ys = column(coords, 1)
                    location_points[location].append(np.vstack(zip(xs, ys)))
            # 存放所有多边形的list,是把location_points[location]的集成
            complete_location = []
            # 每个location的循环清零
            polygons[location] = []
            # 如果多边形补丁,在做面积图的时候使用
            # class matplotlib.patches.Polygon(xy, closed=True, **kwargs)
            for part in location_points[location]:
                complete_location.append(Polygon(part, True))
            # 做了每个地理位置的多边形集合的键值对 polygons={location: Polygon}
            polygons[location] = complete_location
    # 这里涉及到fix的问题
    location_to_country['WesternArea'] = 'SLE'
    # print("countrys number: {}, {}".format(len(countries), countries))
    # print("locations number: {}".format(len(locations)))

    ## Load actual names of locations
    # ref: https://weibo.com/p/2304187f5d1e820102wozy
    for line in open(standard, 'r'):
        l = line.strip('n').split('t')
        ## map parts of a district name to its standard name(去异常字符)
        # split by space, keep last word in lower case(让最后一个单词小些)
        # e.g River Gee = gee, Grand Cape Mount = mount.
        # --l[0]:country、 l[1]:actual name 、 l[2]:diacritics removed 、 l[3]:standardised
        actual = l[1]
        # 这里是判断一下是否是第一行,如果不是就直接取最后的一个字符作为修正后的地区名字
        if 'actual' not in actual:
            # actual = actual.decode('utf8')
            # 这里是map_to_actual = {修正后的地区名字:修正前的地区名字}
            map_to_actual[l[-1]] = actual

    ## Load text tinkering文字修正 ????
    for line in open(textpath, 'r'):
        location, t, r = line.strip('n').split('t')
        textCorrection[location] = (int(t), int(r))
    ## ------------cases_byCountry={country:{时间(某日):病例数}}------ ###
    ## Load case numbers
    for line in open(cases_path, 'r'):
        l = line.strip('n').split(',')
        # 如果是第一行,就转化日期列到标准阿拉伯数字日期
        if l[0] == 'country':
            for d in l[3:]:
                # 将d从已知的'%Y-%b-%d'格式转化为'%Y-%m-%d'
                # 这里是eg: Dec->12
                dates.append(convertDate(d, '%Y-%b-%d', '%Y-%m-%d'))
        else:
            # 如果是其他行就开始按照国家统计累计病例数量
            if '%s' % (l[0]) not in cases_byCountry:
            # if cases_byCountry.has_key('%s' % (l[0])) == False:
            # 如果国家不在列表中就建立键值对:国家:
                cases_byCountry['%s' % (l[0])] = {}

            for i, x in enumerate(dates):
                if x  not in cases_byCountry['%s' % (l[0])]:
                # if cases_byCountry['%s' % (l[0])].has_key(x) == False:
                    cases_byCountry['%s' % (l[0])][x] = 0
                # 这里是只要日期对应的列上值不为空,就把当日的累计病例加上去
                if l[3 + i] != '':
                    cases_byCountry['%s' % (l[0])][x] += int(l[3 + i])
                else:
                    cases_byCountry['%s' % (l[0])][x] += 0

            ## ------------cases_byLocation={location:{时间(某日):病例数}}------ ###
            # d在这里代表标准化名字后的位置
            d = '%s' % (l[2])
            if '%s' % (d) not in cases_byLocation:
            # if cases_byLocation.has_key('%s' % (d)) == False:
                cases_byLocation['%s' % (d)] = {}

            for i, x in enumerate(dates):
                if x not in cases_byLocation['%s' % (d)]:
                # if cases_byLocation['%s' % (d)].has_key(x) == False:
                    cases_byLocation['%s' % (d)][x] = 0

                if l[3 + i] != '':
                    cases_byLocation['%s' % (d)][x] += int(l[3 + i])
                else:
                    cases_byLocation['%s' % (d)][x] += 0
    # 如果没有统计到的国家,就直接代表没有传染病例直接设置为零
    for loc in locations:
        if loc not in cases_byLocation:
        # if cases_byLocation.has_key(loc) == False:
            cases_byLocation[loc] = {d: 0 for d in dates}

    # 总累计病例数:当前日期date的所有国家的病例数之和,每天的累计病例数
    totalCaseCounts = {x: sum(cases_byCountry[x].values()) for x in cases_byCountry.keys()}

    ## Load PCA coordinates of population centroids
    for line in open(PCA_path, 'r'):
        l = line.strip('n').split('t')
        # 忽略第一行的标题index
        if l[0] == 'location':
            pass
        else:
            # PCA[地区名字]=(normPC1, normPC2)
            # PCA coordinates already normalized
            PCA[l[0]] = (float(l[-2]), float(l[-1]))

    # normalization =(((value - l_min) * newRange) / float(oldRange)) + n_min
    # normalization是关于value的函数,value的取值范围oldRange【0.2, 1.0】,转到newRange[0,1]的归一化的值
    normalization = create_normalization([0, 1], 0.2, 1.0)

    for loc in locations:
        if normalize_by == 'PCA1':
            normalized_coords[loc] = normalization(PCA[loc][0])
        elif normalize_by == 'PCA2':
            normalized_coords[loc] = normalization(PCA[loc][1])

    # 处理一个特例那就是一个地方的农村与城市的归一化坐标轴取为他们的均值
    fix = {'WesternArea': ('WesternRural', 'WesternUrban')}

    for f in fix.keys():
        being_fixed = f
        fixed_with = fix[being_fixed]

        aggregate = []

        for f2 in fixed_with:
            if normalize_by == 'PCA1':
                aggregate.append(PCA[f2][0])
            elif normalize_by == 'PCA2':
                aggregate.append(PCA[f2][1])

        normalized_coords[being_fixed] = normalization(np.mean(aggregate))

    ## import population centroids
    for line in open(loc_path, 'r'):
        # 如果出现没有Location字符串的行,开始赋值
        if 'Location' not in line:
            # (x, y)->(纬度lat, 经度lon)
            location, lon, lat = line.strip('n').split('t')
            # 经度,纬度划分
            popCentres[location] = (float(lon), float(lat))
            # print("popCentres[location]: {}, {}".format(location, popCentres[location]))

    ## import coordinates of the international borders
    for line in open(border_path, 'r'):
        cerberus = re.findall('([0-9.- ,]+)', line.strip('n'))
        # global_border.append([map(float, x[1:-1].split(',')) for x in cerberus])

        global_border.append([list(map(float, x[1:-1].split(','))) for x in cerberus])
        # print("global_border: {}".format(global_border))
    # for local_border in global_border:
    #     print("local_border: {}".format(local_border))
    #     print(column(local_border, 0))
        # plt.plot(column(local_border, 0), column(local_border, 1), color='k', lw=2, zorder=99)

    ## set up dictionary of border sharing
    for line in open(border_sharing, 'r'):
        l = line.strip('n').split('t')
        if l[0] == 'locA':
            pass
        else:
            locA, locB, share, international = l
            if int(share) == 0:
                s = False
            else:
                s = True

            if locA not in shared_border:
            # if shared_border.has_key(locA) == False:
                shared_border[locA] = {locB: s}

            if locB not in shared_border:
            # if shared_border.has_key(locB) == False:
                shared_border[locB] = {locA: s}

            shared_border[locA][locB] = s
            shared_border[locB][locA] = s

# loadData()

#最后祝大家女神节快乐

a24ba13b0912211cf8f3ccdd78270c36.png
女神节快乐

b7f793218611156f267c1458a649659e.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值