软件工程统计方法机考复习


一、环境搭建与教程

1.环境搭建:pycharm + Anaconda
2.快速入门:Python十分钟入门
3.基础教程:菜鸟教程-Python

二、python语法

2.1 变量类型

五个标准的数据类型:Numbers、String、List(列表)、Tuple(元组)、Dictionary(字典)

1.Numbers-数字:int、long、float、complex(复数)
2.String-字符串:从左索引默认0开始,从右默认-1开始;可以使用List类似的[start:end]形式来截取
3.List-列表:[,,]的形式,使用[start:end]截取,可重新赋值
4.Tuple-元组:(,,)的形式,使用[start:end]截取,不可重新赋值——即可读的列表
5.Dictionary-字典:{,,}的形式,字典是无序的,使用key:value的key来存取元素

类型转换:将数据类型作为函数名即可。如int(x),将x转换成一个整数

2.1.1 Numbers

#Number类型转换:
    int(x[,base])、long(x[,base])、 float(x)、 complex(real[,imag])、 str(x)、 eval(str)、tuple(s)、list(s)、chr(x)、ord(x)...
#math/cmath模块
#math和cmath模块包含了数学运算常用的函数,math提供数学运算,cmath提供复数运算
    import math
    math.abs(x) #返回x的绝对值

#need import math: ceil(x),floor(x),exp(x),fabs(x),log(x[,base]),log10(x),modf(x),sqrt(x)
#don't need import math:abs(x),cmp(x,y),max(x1,x2...),min(x1,x2...),pow(x,y),round(x[,n])
#random模块
    choice(seq),randrange([start,]stop[,step]),random(),seed([x]),shuffle(lst),uniform(x,y)
#python数学常量
    math.pi表示π
    math.e表示自然常数e

2.1.2 String

三引号允许一个字符串跨多行,可以包括换行符、制表符和其他特殊字符;三引号的语法是一对连续的单引号或者双引号;——所见即所得,不需要使用转义字符了。

2.1.3 List

#python列表函数/方法
    cmp(list1,list2),len(list),max(list),min(list),list(seq)
#list方法
    list.append(obj),list.count(obj),list.extend(seq),list.index(obj),list.insert(index,obj),list.pop([index=-1]),list.remove(obj),list.reverse(),list.sort(cmp=None,key=None,reverse=False)

2.1.4 元组

与列表类似,区别在于元组的元素不能修改

2.1.5 字典

d = {key1 : value1, key2 : value2, key3 : value3}
#有很多内置的dic.function()

2.2 运算符

1.算术运算符:x**y表示x的y次幂;x//y表示取整除
2.逻辑运算符:x and y表示如果x为False,则返回false,否则返回y的值(不一定是布尔);
x or y表示如果x为非0,则返回x,否则返回y;not x表示若x为True,则返回False3.成员运算符:innot in
4.身份运算符:is 和 isnot;比较两个对象的存储单元;等价于id(a)==id(y);id()用于
获取对象内存地址

2.3 语句

2.3.1 条件语句

if 判断条件1:
    执行语句1……
elif 判断条件2:
    执行语句2……
elif 判断条件3:
    执行语句3……
else:
    执行语句4……

2.3.2 循环语句

#while循环
while expression:
    statement(s)
[else: ...]

#for循环
for iterating_var in sequence:
    statements(s)
[else: ...]

for i in range(0,x):
    print i # 注意:此处取0到x-1的循环

2.4 函数

#语法:
def functionname( parameters ):
    "函数_文档字符串"
    function_suite
    return [expression]

#参数:类型属于对象,String/tuples/numbers是不可变的,list/dict是可变的。不可变参数是值传递,可变参数是引用传递;

2.5 文件I/O

#输入/输出
print x #输出到屏幕
str = raw_input("请输入:") #读取键盘输入
str = input("请输入") #读取键盘输入,可以接受python表达式,计算后返回结果到str

#文件
file object = open(file_name[,access_mode][,buffering]) #打开文件
fo.write(str)
fo.read([count])
fo.close()

#File对象提供了操作文件的方法,OS对象提供了处理文件和目录的方法-使用OS中的方法需要import os;

2.6 面向对象

class ClassName:
    '类的帮助信息' #类文档字符串
    class_suite #类体
#实例
class Employee:
   '所有员工的基类'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1

   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

# _init_方法即构造函数
# empCount是类变量,相当于java里的静态变量,可通过Employee.empCount访问
# self代表类的实例,在定义类中的方法时必须有,虽然在调用时不必传入相应的参数

#创建实例对象
emp1 = Employee("z",10000)
emp1.displayEmployee()
print Employee.empCount #类似java的静态访问

三、统计学常用的库:Numpy、Scipy等


四、软统机考相关知识

4.1 置信区间

根据抽样参数来估计总体参数,范围由区间的形式给出,而实际参数位于这个区间的概率就是置信水平1-α(通常为95%,α称为显著水平);
置信水平是指总体参数值落在样本统计值某一区内的概率,而置信区间是指在某一置信水平下,样本统计值与总体参数值间的误差范围。置信区间越大,置信水平越高。

4.2 t检验

分为单总体均值检验和双总体均值差检验。注意总体必须符合正态分布。


五、题目

5.1 读文件

# 主要是csv文件
f = open(file)
lines = f.readlines
for line in lines:
    ...

5.2 pdf和cdf

# -*- coding:utf-8 -*-
from scipy.stats import norm
from scipy.stats import t as T
from scipy.stats import chi2

if __name__ == "__main__":
    # 计算标准正态分布,用于求置信区间,即x的范围
    a1 = 0.05  # 显著水平0.05,即置信水平95%
    print norm.ppf(1-a1/2)  # 约等于1.96

    # 计算t分布上分位数,用于求t检验test
    t_rv = T(16-1)  # n-1
    print t_rv.ppf(1-a1)  # 单侧检验   t>=test or t<= -test
    print t_rv.ppf(1-a1/2)  # 双侧检验 |t|>=test

    # 根据x计算正态分布的概率
    print norm.cdf(0.0)
    print norm.cdf(1.96)  # res = 0.975, a= (1-res)*2= 0.05 即x<1.96的标准正态分布积分

    # 根据n和z求t分布的分位点α
    t_rv = T(16-1)
    print t_rv.cdf(1.7530503556925547)  # 约等于0.95,即1-a=0.95,a=0.05

    # 卡方分布
    n = 26
    x_rv = chi2(n-1)
    x_test = x_rv.ppf(1-a1)  # 显著性水平0.05,根据n和显著性水平求卡方分布值
    print x_test
    print x_rv.cdf(x_test)  # 根据n和开发分布值求显著性水平a

5.3 置信区间

# -*- coding:UTF-8 -*-
'''
随着中国经济发展,人们!生活质量相应提升,但睡眠质量却并不乐观。据《2016中国睡眠指数报告》显示,
中国人平均睡眠时长为8.5小时,这是从3600份问卷统计得到的结果。另外报告指出,中国人睡眠时长符合
方差为25的正态分布,试写solve函数估计中国人睡眠时长的置信区间(置信水平为95%)
'''
import math
from scipy.stats import norm
class Solution:
    def solve(self):
        mean = 8.5
        var = 25
        n = 3600
        a = 1 - 0.95
        z = norm.ppf(1-a/2)
        return [round(mean - z * math.sqrt(var)/math.sqrt(n), 6), round(mean + z * math.sqrt(var)/math.sqrt(n), 6)]

if __name__ == "__main__":
    sol = Solution()
    print sol.solve()

5.4 t检验–单总体均值检验

#-*- coding:utf-8 -*-
'''
Georgianna claims that in a small city renowned for its music school, the average child takes at least 5 years of piano lessons.
We have a random sample of 20 children from the city with a mean of 4.6 years of piano lessons and a standard deviation of 2.2 years. Evaluate 'Georgianna's claims using a hypothesis test. alpha is 0.05.
Extra:
(1) Construct a 95% confidence interval for the number of years students in this city takes piano lessons and interpret it in context of the data.
(2) Do your results from the hypothesis test and the confidence interval agree? Explain your reasoning.
'''
from scipy.stats import t as T
import numpy as np
class Solution():
    def solve(self):
        u = 5  # 样本检验值,H0: μ<5, H1:μ>5
        mean = 4.6 #样本均值
        var = 2.2 #标准差
        n = 20 #样本数量
        a = 0.05 #显著性水平
        t = (mean-u) / (var/np.sqrt(n)) #t应该符合t分布
        rv = T(n-1) #建立一个t分布
        test = rv.ppf(1-a) #计算拒绝域的界限值,此处认为当t>=test的时候,样本落入拒绝域,即H0被拒绝
        return [n-1, round(t,2), not(t>=test)]

if __name__ == "__main__":
    sol = Solution()
    print sol.solve()

5.5 t检验–双总体均值差检验

#-*- coding:utf-8 -*-
'''
A group of researchers are interested in the possible effects of distracting stimuli during eating, such as an increase
\or decrease in the amount of food consumption. To test this hypothesis, they monitored food intake for a group of 44
atients who were randomised into two equal groups. The treatment group ate lunch while playing solitaire, and the
control group ate lunch without any added distractions. Patients in the treatment group ate 52.1 grams of biscuits,
with a standard deviation of 45.1 grams, and patients in the control group ate 27.1 grams of biscuits with a standard
deviation of 26.4 grams. Do these data provide convincing evidence that the average food intake is different for the
patients in the treatment group? Assume the conditions for inference are satisfied.
Null hypothesis is H0: u_t - u_c = 0, alpha is 0.05
'''
import numpy as np
from scipy.stats import t as T
class Solution():
    '双正太总体均值的检验'
    def solve(self):
        u = 0
        n1 = 22
        n2 = 22
        mean1 = 52.1
        s1 = 45.1
        mean2 = 27.1
        s2 = 26.4
        a = 0.05
        # H0:u1-u2=0, H1:u1-u2不等于0

        sw = np.sqrt(((n1-1)*s1*s1 + (n2-1)*s2*s2) / (n1+n2-2)) #校正的双样本标准差
        t = ((mean1-mean2) - u) / (sw * np.sqrt(1.0/n1 + 1.0/n2)) #检验统计量

        myT = T(n1+n2-2) #建立t分布,注意,两个正态分布的统计量t符合自由度为n1+n2-2的t分布
        test = myT.ppf(1-a/2) #计算t分布值,注意,此处为双边检验,所以要用a/2

        return [n1-1, round(t,2), not(np.abs(t) >= test)]


if __name__ == "__main__":
    sol = Solution()
    print sol.solve()

5.4 其他常见题型复习

'''
葡萄干问题(2018_exam):
    假定一块蛋糕上的葡萄干颗粒数服从泊松分布,如果想要每块蛋糕上至少有一粒葡萄干的概率大于等于0.98,蛋糕上的葡萄干的平均颗粒数应该是多少?
思路:
    根据题意知p(x=0)<=0.02,以极限值即等于的情况计算出泊松分布的参数λ=- math.log(0.02,math.e)≈4,然后根据泊松分布的数学期望E和Var都为λ,可得出结论:蛋糕上葡萄干的平均粒数应该是4
'''
# -*- coding:utf-8 -*-
import math
class Solution:
    def solve(self):
        r = - math.log(0.02,math.e)
        return int(round(r))


if __name__ == "__main__":
    sol = Solution()
    print sol.solve()

猜你喜欢

转载自blog.csdn.net/qq_28379809/article/details/80847887