當前位置:首頁 » 密碼管理 » python統計iis訪問量

python統計iis訪問量

發布時間: 2023-06-08 16:35:49

『壹』 python 運維常用腳本

Python 批量遍歷目錄文件,並修改訪問時間

import os

path = "D:/UASM64/include/"
dirs = os.listdir(path)
temp=[];

for file in dirs:
temp.append(os.path.join(path, file))
for x in temp:
os.utime(x, (1577808000, 1577808000))
Python 實現的自動化伺服器管理

import sys
import os
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def ssh_cmd(user,passwd,port,userfile,cmd):

def ssh_put(user,passwd,source,target):

while True:
try:
shell=str(input("[Shell] # "))
if (shell == ""):
continue
elif (shell == "exit"):
exit()
elif (shell == "put"):
ssh_put("root","123123","./a.py","/root/a.py")
elif (shell =="cron"):
temp=input("輸入一個計劃任務: ")
temp1="(crontab -l; echo "+ temp + ") |crontab"
ssh_cmd("root","123123","22","./user_ip.conf",temp1)
elif (shell == "uncron"):
temp=input("輸入要刪除的計劃任務: ")
temp1="crontab -l | grep -v " "+ temp + "|crontab"
ssh_cmd("root","123123","22","./user_ip.conf",temp1)
else:
ssh_cmd("lyshark","123123","22","./user_ip.conf",shell)

遍歷目錄和文件

import os

def list_all_files(rootdir):
import os
_files = []
list = os.listdir(rootdir) #列出文件夾下所有的目錄與文件
for i in range(0,len(list)):
path = os.path.join(rootdir,list[i])
if os.path.isdir(path):
_files.extend(list_all_files(path))
if os.path.isfile(path):
_files.append(path)
return _files

a=list_all_files("C:/Users/LyShark/Desktop/a")
print(a)
python檢測指定埠狀態

import socket

sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sk.settimeout(1)

for ip in range(0,254):
try:
sk.connect(("192.168.1."+str(ip),443))
print("192.168.1.%d server open "%ip)
except Exception:
print("192.168.1.%d server not open"%ip)

sk.close()

python實現批量執行CMD命令

import sys
import os
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

print("------------------------------> ")
print("使用說明,在當前目錄創建ip.txt寫入ip地址")
print("------------------------------> ")

user=input("輸入用戶名:")
passwd=input("輸入密碼:")
port=input("輸入埠:")
cmd=input("輸入執行的命令:")

file = open("./ip.txt", "r")
line = file.readlines()

for i in range(len(line)):
print("對IP: %s 執行"%line[i].strip(' '))

python3-實現釘釘報警

import requests
import sys
import json

dingding_url = ' https://oapi.dingtalk.com/robot/send?access_token='

data = {"msgtype": "markdown","markdown": {"title": "監控","text": "apche異常"}}

headers = {'Content-Type':'application/json;charset=UTF-8'}

send_data = json.mps(data).encode('utf-8')
requests.post(url=dingding_url,data=send_data,headers=headers)

import psutil
import requests
import time
import os
import json

monitor_name = set(['httpd','cobblerd']) # 用戶指定監控的服務進程名稱

proc_dict = {}
proc_name = set() # 系統檢測的進程名稱
monitor_map = {
'httpd': 'systemctl restart httpd',
'cobblerd': 'systemctl restart cobblerd' # 系統在進程down掉後,自動重啟
}

dingding_url = ' https://oapi.dingtalk.com/robot/send?access_token='

while True:
for proc in psutil.process_iter(attrs=['pid','name']):
proc_dict[proc.info['pid']] = proc.info['name']
proc_name.add(proc.info['name'])

判斷指定埠是否開放

import socket

port_number = [135,443,80]

for index in port_number:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((飗.0.0.1', index))
if result == 0:
print("Port %d is open" % index)
else:
print("Port %d is not open" % index)
sock.close()

判斷指定埠並且實現釘釘輪詢報警

import requests
import sys
import json
import socket
import time

def dingding(title,text):
dingding_url = ' https://oapi.dingtalk.com/robot/send?access_token='
data = {"msgtype": "markdown","markdown": {"title": title,"text": text}}
headers = {'Content-Type':'application/json;charset=UTF-8'}
send_data = json.mps(data).encode('utf-8')
requests.post(url=dingding_url,data=send_data,headers=headers)

def net_scan():
port_number = [80,135,443]
for index in port_number:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((飗.0.0.1', index))
if result == 0:
print("Port %d is open" % index)
else:
return index
sock.close()

while True:
dingding("Warning",net_scan())
time.sleep(60)

python-實現SSH批量CMD執行命令

import sys
import os
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def ssh_cmd(user,passwd,port,userfile,cmd):
file = open(userfile, "r")
line = file.readlines()
for i in range(len(line)):
print("對IP: %s 執行"%line[i].strip(' '))
ssh.connect(hostname=line[i].strip(' '),port=port,username=user,password=passwd)
cmd=cmd
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read()

ssh_cmd("lyshark","123","22","./ip.txt","free -h |grep 'Mem:' |awk '{print $3}'")

用python寫一個列舉當前目錄以及所有子目錄下的文件,並列印出絕對路徑

import sys
import os

for root,dirs,files in os.walk("C://"):
for name in files:
print(os.path.join(root,name))
os.walk()

按照這樣的日期格式(xxxx-xx-xx)每日生成一個文件,例如今天生成的文件為2013-09-23.log, 並且把磁碟的使用情況寫到到這個文件中。

import os
import sys
import time

new_time = time.strftime("%Y-%m-%d")
disk_status = os.popen("df -h").readlines()

str1 = ''.join(disk_status)
f = open(new_time+'.log','w')
f.write("%s"%str1)

f.flush()
f.close()

統計出每個IP的訪問量有多少?(從日誌文件中查找)

import sys

list = []

f = open("/var/log/httpd/access_log","r")
str1 = f.readlines()
f.close()

for i in str1:
ip=i.split()[0]
list.append(ip)

list_num=set(list)

for j in list_num:
num=list.count(j)
print("%s -----> %s" %(num,j))

寫個程序,接受用戶輸入數字,並進行校驗,非數字給出錯誤提示,然後重新等待用戶輸入。

import tab
import sys

while True:
try:
num=int(input("輸入數字:").strip())
for x in range(2,num+1):
for y in range(2,x):
if x % y == 0:
break
else:
print(x)
except ValueError:
print("您輸入的不是數字")
except KeyboardInterrupt:
sys.exit(" ")

ps 可以查看進程的內存佔用大小,寫一個腳本計算一下所有進程所佔用內存大小的和。

import sys
import os

list=[]
sum=0

str1=os.popen("ps aux","r").readlines()

for i in str1:
str2=i.split()
new_rss=str2[5]
list.append(new_rss)
for i in list[1:-1]:
num=int(i)
sum=sum+num

print("%s ---> %s"%(list[0],sum))

關於Python 命令行參數argv

import sys

if len(sys.argv) < 2:
print ("沒有輸入任何參數")
sys.exit()

if sys.argv[1].startswith("-"):
option = sys.argv[1][1:]

利用random生成6位數字加字母隨機驗證碼

import sys
import random

rand=[]

for x in range(6):
y=random.randrange(0,5)
if y == 2 or y == 4:
num=random.randrange(0,9)
rand.append(str(num))
else:
temp=random.randrange(65,91)
c=chr(temp)
rand.append(c)
result="".join(rand)
print(result)

自動化-使用pexpect非交互登陸系統

import pexpect
import sys

ssh = pexpect.spawn('ssh [email protected]')
fout = file('sshlog.txt', 'w')
ssh.logfile = fout

ssh.expect("[email protected]'s password:")

ssh.sendline("密碼")
ssh.expect('#')

ssh.sendline('ls /home')
ssh.expect('#')

Python-取系統時間

import sys
import time

time_str = time.strftime("日期:%Y-%m-%d",time.localtime())
print(time_str)

time_str= time.strftime("時間:%H:%M",time.localtime())
print(time_str)

psutil-獲取內存使用情況

import sys
import os
import psutil

memory_convent = 1024 * 1024
mem =psutil.virtual_memory()

print("內存容量為:"+str(mem.total/(memory_convent))+"MB ")
print("已使用內存:"+str(mem.used/(memory_convent))+"MB ")
print("可用內存:"+str(mem.total/(memory_convent)-mem.used/(1024*1024))+"MB ")
print("buffer容量:"+str(mem.buffers/( memory_convent ))+"MB ")
print("cache容量:"+str(mem.cached/(memory_convent))+"MB ")

Python-通過SNMP協議監控CPU
注意:被監控的機器上需要支持snmp協議 yum install -y net-snmp*

import os

def getAllitems(host, oid):
sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid + '|grep Raw|grep Cpu|grep -v Kernel').read().split(' ')[:-1]
return sn1

def getDate(host):
items = getAllitems(host, '.1.3.6.1.4.1.2021.11')

if name == ' main ':

Python-通過SNMP協議監控系統負載
注意:被監控的機器上需要支持snmp協議 yum install -y net-snmp*

import os
import sys

def getAllitems(host, oid):
sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split(' ')
return sn1

def getload(host,loid):
load_oids = Ƈ.3.6.1.4.1.2021.10.1.3.' + str(loid)
return getAllitems(host,load_oids)[0].split(':')[3]

if name == ' main ':

Python-通過SNMP協議監控內存
注意:被監控的機器上需要支持snmp協議 yum install -y net-snmp*

import os

def getAllitems(host, oid):

def getSwapTotal(host):

def getSwapUsed(host):

def getMemTotal(host):

def getMemUsed(host):

if name == ' main ':

Python-通過SNMP協議監控磁碟
注意:被監控的機器上需要支持snmp協議 yum install -y net-snmp*

import re
import os

def getAllitems(host,oid):

def getDate(source,newitem):

def getRealDate(item1,item2,listname):

def caculateDiskUsedRate(host):

if name == ' main ':

Python-通過SNMP協議監控網卡流量
注意:被監控的機器上需要支持snmp協議 yum install -y net-snmp*

import re
import os

def getAllitems(host,oid):
sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split(' ')[:-1]
return sn1

def getDevices(host):
device_mib = getAllitems(host,'RFC1213-MIB::ifDescr')
device_list = []

def getDate(host,oid):
date_mib = getAllitems(host,oid)[1:]
date = []

if name == ' main ':

Python-實現多級菜單

import os
import sys

ps="[None]->"
ip=["192.168.1.1","192.168.1.2","192.168.1.3"]
flage=1

while True:
ps="[None]->"
temp=input(ps)
if (temp=="test"):
print("test page !!!!")
elif(temp=="user"):
while (flage == 1):
ps="[User]->"
temp1=input(ps)
if(temp1 =="exit"):
flage=0
break
elif(temp1=="show"):
for i in range(len(ip)):
print(i)

Python實現一個沒用的東西

import sys

ps="[root@localhost]# "
ip=["192.168.1.1","192.168.1.2","192.168.1.3"]

while True:
temp=input(ps)
temp1=temp.split()

檢查各個進程讀寫的磁碟IO

import sys
import os
import time
import signal
import re

class DiskIO:
def init (self, pname=None, pid=None, reads=0, writes=0):
self.pname = pname
self.pid = pid
self.reads = 0
self.writes = 0

def main():
argc = len(sys.argv)
if argc != 1:
print ("usage: please run this script like [./lyshark.py]")
sys.exit(0)
if os.getuid() != 0:
print ("Error: This script must be run as root")
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
os.system('echo 1 > /proc/sys/vm/block_mp')
print ("TASK PID READ WRITE")
while True:
os.system('dmesg -c > /tmp/diskio.log')
l = []
f = open('/tmp/diskio.log', 'r')
line = f.readline()
while line:
m = re.match(
'^(S+)(d+)(d+): (READ|WRITE) block (d+) on (S+)', line)
if m != None:
if not l:
l.append(DiskIO(m.group(1), m.group(2)))
line = f.readline()
continue
found = False
for item in l:
if item.pid == m.group(2):
found = True
if m.group(3) == "READ":
item.reads = item.reads + 1
elif m.group(3) == "WRITE":
item.writes = item.writes + 1
if not found:
l.append(DiskIO(m.group(1), m.group(2)))
line = f.readline()
time.sleep(1)
for item in l:
print ("%-10s %10s %10d %10d" %
(item.pname, item.pid, item.reads, item.writes))
def signal_handler(signal, frame):
os.system('echo 0 > /proc/sys/vm/block_mp')
sys.exit(0)

if name ==" main ":
main()

利用Pexpect實現自動非交互登陸linux

import pexpect
import sys

ssh = pexpect.spawn('ssh [email protected]')
fout = file('sshlog.log', 'w')
ssh.logfile = fout

ssh.expect("[email protected]'s password:")

ssh.sendline("密碼")

ssh.expect('#')
ssh.sendline('ls /home')
ssh.expect('#')

利用psutil模塊獲取系統的各種統計信息

import sys
import psutil
import time
import os

time_str = time.strftime( "%Y-%m-%d", time.localtime( ) )
file_name = "./" + time_str + ".log"

if os.path.exists ( file_name ) == False :
os.mknod( file_name )
handle = open ( file_name , "w" )
else :
handle = open ( file_name , "a" )

if len( sys.argv ) == 1 :
print_type = 1
else :
print_type = 2

def isset ( list_arr , name ) :
if name in list_arr :
return True
else :
return False

print_str = "";

if ( print_type == 1 ) or isset( sys.argv,"mem" ) :
memory_convent = 1024 * 1024
mem = psutil.virtual_memory()
print_str += " 內存狀態如下: "
print_str = print_str + " 系統的內存容量為: "+str( mem.total/( memory_convent ) ) + " MB "
print_str = print_str + " 系統的內存以使用容量為: "+str( mem.used/( memory_convent ) ) + " MB "
print_str = print_str + " 系統可用的內存容量為: "+str( mem.total/( memory_convent ) - mem.used/( 1024*1024 )) + "MB "
print_str = print_str + " 內存的buffer容量為: "+str( mem.buffers/( memory_convent ) ) + " MB "
print_str = print_str + " 內存的cache容量為:" +str( mem.cached/( memory_convent ) ) + " MB "

if ( print_type == 1 ) or isset( sys.argv,"cpu" ) :
print_str += " CPU狀態如下: "
cpu_status = psutil.cpu_times()
print_str = print_str + " user = " + str( cpu_status.user ) + " "
print_str = print_str + " nice = " + str( cpu_status.nice ) + " "
print_str = print_str + " system = " + str( cpu_status.system ) + " "
print_str = print_str + " idle = " + str ( cpu_status.idle ) + " "
print_str = print_str + " iowait = " + str ( cpu_status.iowait ) + " "
print_str = print_str + " irq = " + str( cpu_status.irq ) + " "
print_str = print_str + " softirq = " + str ( cpu_status.softirq ) + " "
print_str = print_str + " steal = " + str ( cpu_status.steal ) + " "
print_str = print_str + " guest = " + str ( cpu_status.guest ) + " "

if ( print_type == 1 ) or isset ( sys.argv,"disk" ) :
print_str += " 硬碟信息如下: "
disk_status = psutil.disk_partitions()
for item in disk_status :
print_str = print_str + " "+ str( item ) + " "

if ( print_type == 1 ) or isset ( sys.argv,"user" ) :
print_str += " 登錄用戶信息如下: "
user_status = psutil.users()
for item in user_status :
print_str = print_str + " "+ str( item ) + " "

print_str += "--------------------------------------------------------------- "
print ( print_str )
handle.write( print_str )
handle.close()

import psutil

mem = psutil.virtual_memory()
print mem.total,mem.used,mem
print psutil.swap_memory() # 輸出獲取SWAP分區信息

cpu = psutil.cpu_stats()
printcpu.interrupts,cpu.ctx_switches

psutil.cpu_times(percpu=True) # 輸出每個核心的詳細CPU信息
psutil.cpu_times().user # 獲取CPU的單項數據 [用戶態CPU的數據]
psutil.cpu_count() # 獲取CPU邏輯核心數,默認logical=True
psutil.cpu_count(logical=False) # 獲取CPU物理核心數

psutil.disk_partitions() # 列出全部的分區信息
psutil.disk_usage('/') # 顯示出指定的掛載點情況【位元組為單位】
psutil.disk_io_counters() # 磁碟總的IO個數
psutil.disk_io_counters(perdisk=True) # 獲取單個分區IO個數

psutil.net_io_counter() 獲取網路總的IO,默認參數pernic=False
psutil.net_io_counter(pernic=Ture)獲取網路各個網卡的IO

psutil.pids() # 列出所有進程的pid號
p = psutil.Process(2047)
p.name() 列出進程名稱
p.exe() 列出進程bin路徑
p.cwd() 列出進程工作目錄的絕對路徑
p.status()進程當前狀態[sleep等狀態]
p.create_time() 進程創建的時間 [時間戳格式]
p.uids()
p.gids()
p.cputimes() 【進程的CPU時間,包括用戶態、內核態】
p.cpu_affinity() # 顯示CPU親緣關系
p.memory_percent() 進程內存利用率
p.meminfo() 進程的RSS、VMS信息
p.io_counters() 進程IO信息,包括讀寫IO數及位元組數
p.connections() 返回打開進程socket的nametples列表
p.num_threads() 進程打開的線程數

import psutil
from subprocess import PIPE
p =psutil.Popen(["/usr/bin/python" ,"-c","print 'helloworld'"],stdout=PIPE)
p.name()
p.username()
p.communicate()
p.cpu_times()

psutil.users() # 顯示當前登錄的用戶,和Linux的who命令差不多

psutil.boot_time() 結果是個UNIX時間戳,下面我們來轉換它為標准時間格式,如下:
datetime.datetime.fromtimestamp(psutil.boot_time()) # 得出的結果不是str格式,繼續進行轉換 datetime.datetime.fromtimestamp(psutil.boot_time()).strftime('%Y-%m-%d%H:%M:%S')

Python生成一個隨機密碼

import random, string
def GenPassword(length):

if name == ' main ':
print (GenPassword(6))

『貳』 網站伺服器是怎麼統計訪問量的

用程序統計 也可以用軟體分析IIS流量

『叄』 如何知道伺服器IIS里每個網站的流量和訪問量!

IIS每個網站都有單獨的日誌,可以用這個軟體查看:

逆火web日誌分析器 v2.0
http://down.chinaz.com/s/4483.asp

『肆』 如何使用python做統計分析

Shape Parameters
形態參數
While a general continuous random variable can be shifted and scaled
with the loc and scale parameters, some distributions require additional
shape parameters. For instance, the gamma distribution, with density
γ(x,a)=λ(λx)a−1Γ(a)e−λx,
requires the shape parameter a. Observe that setting λ can be obtained by setting the scale keyword to 1/λ.
雖然一個一般的連續隨機變數可以被位移和伸縮通過loc和scale參數,但一些分布還需要額外的形態參數。作為例子,看到這個伽馬分布,這是它的密度函數
γ(x,a)=λ(λx)a−1Γ(a)e−λx,
要求一個形態參數a。注意到λ的設置可以通過設置scale關鍵字為1/λ進行。
Let』s check the number and name of the shape parameters of the gamma
distribution. (We know from the above that this should be 1.)
讓我們檢查伽馬分布的形態參數的名字的數量。(我們知道從上面知道其應該為1)
>>>
>>> from scipy.stats import gamma
>>> gamma.numargs
1
>>> gamma.shapes
'a'

Now we set the value of the shape variable to 1 to obtain the
exponential distribution, so that we compare easily whether we get the
results we expect.
現在我們設置形態變數的值為1以變成指數分布。所以我們可以容易的比較是否得到了我們所期望的結果。
>>>
>>> gamma(1, scale=2.).stats(moments="mv")
(array(2.0), array(4.0))

Notice that we can also specify shape parameters as keywords:
注意我們也可以以關鍵字的方式指定形態參數:
>>>
>>> gamma(a=1, scale=2.).stats(moments="mv")
(array(2.0), array(4.0))

Freezing a Distribution
凍結分布
Passing the loc and scale keywords time and again can become quite
bothersome. The concept of freezing a RV is used to solve such problems.
不斷地傳遞loc與scale關鍵字最終會讓人厭煩。而凍結RV的概念被用來解決這個問題。
>>>
>>> rv = gamma(1, scale=2.)

By using rv we no longer have to include the scale or the shape
parameters anymore. Thus, distributions can be used in one of two ways,
either by passing all distribution parameters to each method call (such
as we did earlier) or by freezing the parameters for the instance of the
distribution. Let us check this:
通過使用rv我們不用再更多的包含scale與形態參數在任何情況下。顯然,分布可以被多種方式使用,我們可以通過傳遞所有分布參數給對方法的每次調用(像我們之前做的那樣)或者可以對一個分布對象凍結參數。讓我們看看是怎麼回事:
>>>
>>> rv.mean(), rv.std()
(2.0, 2.0)

This is indeed what we should get.
這正是我們應該得到的。
Broadcasting
廣播
The basic methods pdf and so on satisfy the usual numpy broadcasting
rules. For example, we can calculate the critical values for the upper
tail of the t distribution for different probabilites and degrees of
freedom.
像pdf這樣的簡單方法滿足numpy的廣播規則。作為例子,我們可以計算t分布的右尾分布的臨界值對於不同的概率值以及自由度。
>>>
>>> stats.t.isf([0.1, 0.05, 0.01], [[10], [11]])
array([[ 1.37218364, 1.81246112, 2.76376946],
[ 1.36343032, 1.79588482, 2.71807918]])

Here, the first row are the critical values for 10 degrees of freedom
and the second row for 11 degrees of freedom (d.o.f.). Thus, the
broadcasting rules give the same result of calling isf twice:
這里,第一行是以10自由度的臨界值,而第二行是以11為自由度的臨界值。所以,廣播規則與下面調用了兩次isf產生的結果相同。
>>>
>>> stats.t.isf([0.1, 0.05, 0.01], 10)
array([ 1.37218364, 1.81246112, 2.76376946])
>>> stats.t.isf([0.1, 0.05, 0.01], 11)
array([ 1.36343032, 1.79588482, 2.71807918])

If the array with probabilities, i.e, [0.1, 0.05, 0.01] and the array of
degrees of freedom i.e., [10, 11, 12], have the same array shape, then
element wise matching is used. As an example, we can obtain the 10% tail
for 10 d.o.f., the 5% tail for 11 d.o.f. and the 1% tail for 12 d.o.f.
by calling
但是如果概率數組,如[0.1,0.05,0.01]與自由度數組,如[10,11,12]具有相同的數組形態,則元素對應捕捉被作用,我們可以分別得到10%,5%,1%尾的臨界值對於10,11,12的自由度。
>>>
>>> stats.t.isf([0.1, 0.05, 0.01], [10, 11, 12])
array([ 1.37218364, 1.79588482, 2.68099799])

Specific Points for Discrete Distributions
離散分布的特殊之處
Discrete distribution have mostly the same basic methods as the
continuous distributions. However pdf is replaced the probability mass
function pmf, no estimation methods, such as fit, are available, and
scale is not a valid keyword parameter. The location parameter, keyword
loc can still be used to shift the distribution.
離散分布的簡單方法大多數與連續分布很類似。當然像pdf被更換為密度函數pmf,沒有估計方法,像fit是可用的。而scale不是一個合法的關鍵字參數。Location參數,關鍵字loc則仍然可以使用用於位移。
The computation of the cdf requires some extra attention. In the case of
continuous distribution the cumulative distribution function is in most
standard cases strictly monotonic increasing in the bounds (a,b) and
has therefore a unique inverse. The cdf of a discrete distribution,
however, is a step function, hence the inverse cdf, i.e., the percent
point function, requires a different definition:
ppf(q) = min{x : cdf(x) >= q, x integer}

Cdf的計算要求一些額外的關注。在連續分布的情況下,累積分布函數在大多數標准情況下是嚴格遞增的,所以有唯一的逆。而cdf在離散分布,無論如何,是階躍函數,所以cdf的逆,分位點函數,要求一個不同的定義:
ppf(q) = min{x : cdf(x) >= q, x integer}
For further info, see the docs here.
為了更多信息可以看這里。
We can look at the hypergeometric distribution as an example
>>>
>>> from scipy.stats import hypergeom
>>> [M, n, N] = [20, 7, 12]

我們可以看這個超幾何分布的例子
>>>
>>> from scipy.stats import hypergeom
>>> [M, n, N] = [20, 7, 12]

If we use the cdf at some integer points and then evaluate the ppf at
those cdf values, we get the initial integers back, for example
如果我們使用在一些整數點使用cdf,它們的cdf值再作用ppf會回到開始的值。
>>>
>>> x = np.arange(4)*2
>>> x
array([0, 2, 4, 6])
>>> prb = hypergeom.cdf(x, M, n, N)
>>> prb
array([ 0.0001031991744066, 0.0521155830753351, 0.6083591331269301,
0.9897832817337386])
>>> hypergeom.ppf(prb, M, n, N)
array([ 0., 2., 4., 6.])

If we use values that are not at the kinks of the cdf step function, we get the next higher integer back:
如果我們使用的值不是cdf的函數值,則我們得到一個更高的值。
>>>
>>> hypergeom.ppf(prb + 1e-8, M, n, N)
array([ 1., 3., 5., 7.])
>>> hypergeom.ppf(prb - 1e-8, M, n, N)
array([ 0., 2., 4., 6.])

『伍』 python數據統計分析

1. 常用函數庫

  scipy包中的stats模塊和statsmodels包是python常用的數據分析工具,scipy.stats以前有一個models子模塊,後來被移除了。這個模塊被重寫並成為了現在獨立的statsmodels包。

 scipy的stats包含一些比較基本的工具,比如:t檢驗,正態性檢驗,卡方檢驗之類,statsmodels提供了更為系統的統計模型,包括線性模型,時序分析,還包含數據集,做圖工具等等。

2. 小樣本數據的正態性檢驗

(1) 用途

 夏皮羅維爾克檢驗法 (Shapiro-Wilk) 用於檢驗參數提供的一組小樣本數據線是否符合正態分布,統計量越大則表示數據越符合正態分布,但是在非正態分布的小樣本數據中也經常會出現較大的W值。需要查表來估計其概率。由於原假設是其符合正態分布,所以當P值小於指定顯著水平時表示其不符合正態分布。

 正態性檢驗是數據分析的第一步,數據是否符合正態性決定了後續使用不同的分析和預測方法,當數據不符合正態性分布時,我們可以通過不同的轉換方法把非正太態數據轉換成正態分布後再使用相應的統計方法進行下一步操作。

(2) 示例

(3) 結果分析

 返回結果 p-value=0.029035290703177452,比指定的顯著水平(一般為5%)小,則拒絕假設:x不服從正態分布。

3. 檢驗樣本是否服務某一分布

(1) 用途

 科爾莫戈羅夫檢驗(Kolmogorov-Smirnov test),檢驗樣本數據是否服從某一分布,僅適用於連續分布的檢驗。下例中用它檢驗正態分布。

(2) 示例

(3) 結果分析

 生成300個服從N(0,1)標准正態分布的隨機數,在使用k-s檢驗該數據是否服從正態分布,提出假設:x從正態分布。最終返回的結果,p-value=0.9260909172362317,比指定的顯著水平(一般為5%)大,則我們不能拒絕假設:x服從正態分布。這並不是說x服從正態分布一定是正確的,而是說沒有充分的證據證明x不服從正態分布。因此我們的假設被接受,認為x服從正態分布。如果p-value小於我們指定的顯著性水平,則我們可以肯定地拒絕提出的假設,認為x肯定不服從正態分布,這個拒絕是絕對正確的。

4.方差齊性檢驗

(1) 用途

 方差反映了一組數據與其平均值的偏離程度,方差齊性檢驗用以檢驗兩組或多組數據與其平均值偏離程度是否存在差異,也是很多檢驗和演算法的先決條件。

(2) 示例

(3) 結果分析

 返回結果 p-value=0.19337536323599344, 比指定的顯著水平(假設為5%)大,認為兩組數據具有方差齊性。

5. 圖形描述相關性

(1) 用途

 最常用的兩變數相關性分析,是用作圖描述相關性,圖的橫軸是一個變數,縱軸是另一變數,畫散點圖,從圖中可以直觀地看到相關性的方向和強弱,線性正相關一般形成由左下到右上的圖形;負面相關則是從左上到右下的圖形,還有一些非線性相關也能從圖中觀察到。

(2) 示例

(3) 結果分析

 從圖中可以看到明顯的正相關趨勢。

6. 正態資料的相關分析

(1) 用途

 皮爾森相關系數(Pearson correlation coefficient)是反應兩變數之間線性相關程度的統計量,用它來分析正態分布的兩個連續型變數之間的相關性。常用於分析自變數之間,以及自變數和因變數之間的相關性。

(2) 示例

(3) 結果分析

 返回結果的第一個值為相關系數表示線性相關程度,其取值范圍在[-1,1],絕對值越接近1,說明兩個變數的相關性越強,絕對值越接近0說明兩個變數的相關性越差。當兩個變數完全不相關時相關系數為0。第二個值為p-value,統計學上,一般當p-value<0.05時,可以認為兩變數存在相關性。

7. 非正態資料的相關分析

(1) 用途

 斯皮爾曼等級相關系數(Spearman』s correlation coefficient for ranked data ),它主要用於評價順序變數間的線性相關關系,在計算過程中,只考慮變數值的順序(rank, 值或稱等級),而不考慮變數值的大小。常用於計算類型變數的相關性。

(2) 示例

(3) 結果分析

 返回結果的第一個值為相關系數表示線性相關程度,本例中correlation趨近於1表示正相關。第二個值為p-value,p-value越小,表示相關程度越顯著。

8. 單樣本T檢驗

(1) 用途

 單樣本T檢驗,用於檢驗數據是否來自一致均值的總體,T檢驗主要是以均值為核心的檢驗。注意以下幾種T檢驗都是雙側T檢驗。

(2) 示例

(3) 結果分析

 本例中生成了2列100行的數組,ttest_1samp的第二個參數是分別對兩列估計的均值,p-value返回結果,第一列1.47820719e-06比指定的顯著水平(一般為5%)小,認為差異顯著,拒絕假設;第二列2.83088106e-01大於指定顯著水平,不能拒絕假設:服從正態分布。

9. 兩獨立樣本T檢驗

(1) 用途

 由於比較兩組數據是否來自於同一正態分布的總體。注意:如果要比較的兩組數據不滿足方差齊性, 需要在ttest_ind()函數中添加參數equal_var = False。

(2) 示例

(3) 結果分析

 返回結果的第一個值為統計量,第二個值為p-value,pvalue=0.19313343989106416,比指定的顯著水平(一般為5%)大,不能拒絕假設,兩組數據來自於同一總結,兩組數據之間無差異。

10. 配對樣本T檢驗

(1) 用途

 配對樣本T檢驗可視為單樣本T檢驗的擴展,檢驗的對象由一群來自正態分布獨立樣本更改為二群配對樣本觀測值之差。它常用於比較同一受試對象處理的前後差異,或者按照某一條件進行兩兩配對分別給與不同處理的受試對象之間是否存在差異。

(2) 示例

(3) 結果分析

 返回結果的第一個值為統計量,第二個值為p-value,pvalue=0.80964043445811551,比指定的顯著水平(一般為5%)大,不能拒絕假設。

11. 單因素方差分析

(1) 用途

 方差分析(Analysis of Variance,簡稱ANOVA),又稱F檢驗,用於兩個及兩個以上樣本均數差別的顯著性檢驗。方差分析主要是考慮各組之間的平均數差別。

 單因素方差分析(One-wayAnova),是檢驗由單一因素影響的多組樣本某因變數的均值是否有顯著差異。

 當因變數Y是數值型,自變數X是分類值,通常的做法是按X的類別把實例成分幾組,分析Y值在X的不同分組中是否存在差異。

(2) 示例

(3) 結果分析

 返回結果的第一個值為統計量,它由組間差異除以組間差異得到,上例中組間差異很大,第二個返回值p-value=6.2231520821576832e-19小於邊界值(一般為0.05),拒絕原假設, 即認為以上三組數據存在統計學差異,並不能判斷是哪兩組之間存在差異 。只有兩組數據時,效果同 stats.levene 一樣。

12. 多因素方差分析

(1) 用途

 當有兩個或者兩個以上自變數對因變數產生影響時,可以用多因素方差分析的方法來進行分析。它不僅要考慮每個因素的主效應,還要考慮因素之間的交互效應。

(2) 示例

(3) 結果分析

 上述程序定義了公式,公式中,"~"用於隔離因變數和自變數,」+「用於分隔各個自變數, ":"表示兩個自變數交互影響。從返回結果的P值可以看出,X1和X2的值組間差異不大,而組合後的T:G的組間有明顯差異。

13. 卡方檢驗

(1) 用途

 上面介紹的T檢驗是參數檢驗,卡方檢驗是一種非參數檢驗方法。相對來說,非參數檢驗對數據分布的要求比較寬松,並且也不要求太大數據量。卡方檢驗是一種對計數資料的假設檢驗方法,主要是比較理論頻數和實際頻數的吻合程度。常用於特徵選擇,比如,檢驗男人和女人在是否患有高血壓上有無區別,如果有區別,則說明性別與是否患有高血壓有關,在後續分析時就需要把性別這個分類變數放入模型訓練。

 基本數據有R行C列, 故通稱RC列聯表(contingency table), 簡稱RC表,它是觀測數據按兩個或更多屬性(定性變數)分類時所列出的頻數表。

(2) 示例

(3) 結果分析

 卡方檢驗函數的參數是列聯表中的頻數,返回結果第一個值為統計量值,第二個結果為p-value值,p-value=0.54543425102570975,比指定的顯著水平(一般5%)大,不能拒絕原假設,即相關性不顯著。第三個結果是自由度,第四個結果的數組是列聯表的期望值分布。

14. 單變數統計分析

(1) 用途

 單變數統計描述是數據分析中最簡單的形式,其中被分析的數據只包含一個變數,不處理原因或關系。單變數分析的主要目的是通過對數據的統計描述了解當前數據的基本情況,並找出數據的分布模型。

 單變數數據統計描述從集中趨勢上看,指標有:均值,中位數,分位數,眾數;從離散程度上看,指標有:極差、四分位數、方差、標准差、協方差、變異系數,從分布上看,有偏度,峰度等。需要考慮的還有極大值,極小值(數值型變數)和頻數,構成比(分類或等級變數)。

 此外,還可以用統計圖直觀展示數據分布特徵,如:柱狀圖、正方圖、箱式圖、頻率多邊形和餅狀圖。

15. 多元線性回歸

(1) 用途

 多元線性回歸模型(multivariable linear regression model ),因變數Y(計量資料)往往受到多個變數X的影響,多元線性回歸模型用於計算各個自變數對因變數的影響程度,可以認為是對多維空間中的點做線性擬合。

(2) 示例

(3) 結果分析

 直接通過返回結果中各變數的P值與0.05比較,來判定對應的解釋變數的顯著性,P<0.05則認為自變數具有統計學意義,從上例中可以看到收入INCOME最有顯著性。

16. 邏輯回歸

(1) 用途

 當因變數Y為2分類變數(或多分類變數時)可以用相應的logistic回歸分析各個自變數對因變數的影響程度。

(2) 示例

(3) 結果分析

 直接通過返回結果中各變數的P值與0.05比較,來判定對應的解釋變數的顯著性,P<0.05則認為自變數具有統計學意義。

熱點內容
怎樣防止sql注入 發布:2024-04-27 06:11:25 瀏覽:235
安卓為什麼不能登蘋果系統的游戲 發布:2024-04-27 06:11:23 瀏覽:600
編程日課 發布:2024-04-27 05:56:54 瀏覽:619
漏洞上傳工具 發布:2024-04-27 05:50:58 瀏覽:716
手機如何選擇存儲 發布:2024-04-27 05:40:25 瀏覽:799
機架式伺服器怎麼操作 發布:2024-04-27 05:19:02 瀏覽:815
我的世界minez網易伺服器 發布:2024-04-27 05:09:26 瀏覽:384
易網頁源碼 發布:2024-04-27 04:51:06 瀏覽:864
攜程伺服器是什麼牌子 發布:2024-04-27 04:31:50 瀏覽:745
醫院新冠肺炎疫情防控演練腳本 發布:2024-04-27 04:04:45 瀏覽:652