軟件工程統計方法機考複習


一、環境搭建與教程

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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章