Skip to content

Commit 9f46fc7

Browse files
committed
:: coding
1 parent ce045fd commit 9f46fc7

File tree

2 files changed

+59
-1
lines changed

2 files changed

+59
-1
lines changed

AnomalyDetection/AnomalyDetection.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,61 @@
11
#-*- coding: utf-8 -*-
22
# Author: Bob
33
# Date: 2016.12.22
4+
import numpy as np
5+
from matplotlib import pyplot as plt
6+
from scipy import io as spio
7+
8+
'''异常检测主运行程序'''
9+
def anomalyDetection_example():
10+
'''加载并显示数据'''
11+
data = spio.loadmat('data1.mat')
12+
X = data['X']
13+
plt = display_2d_data(X, 'bx')
14+
plt.title("origin data")
15+
plt.show()
16+
17+
mu,sigma2 = estimateGaussian(X)
18+
print mu,sigma2
19+
p = multivariateGaussian(X,mu,sigma2)
20+
print p
21+
22+
visualizeFit(X,mu,sigma2)
23+
24+
25+
26+
# 显示二维数据
27+
def display_2d_data(X,marker):
28+
plt.plot(X[:,0],X[:,1],marker)
29+
plt.axis('square')
30+
return plt
31+
32+
# 参数估计函数(就是求均值和方差)
33+
def estimateGaussian(X):
34+
m,n = X.shape
35+
mu = np.zeros((n,1))
36+
sigma2 = np.zeros((n,1))
37+
38+
mu = np.mean(X, axis=0) # axis=0表示列,每列的均值
39+
sigma2 = np.var(X,axis=0) # 求每列的方差
40+
return mu,sigma2
41+
42+
# 多元高斯分布函数
43+
def multivariateGaussian(X,mu,Sigma2):
44+
k = len(mu)
45+
if (Sigma2.shape[0]>1):
46+
Sigma2 = np.diag(Sigma2)
47+
48+
X = X-mu
49+
argu = (2*np.pi)**(-k/2)*np.linalg.det(Sigma2)**(-0.5)
50+
p = argu*np.exp(-0.5*np.sum(np.dot(X,np.linalg.inv(Sigma2))*X,axis=1)) # axis表示每行
51+
return p
52+
53+
# 可视化边界
54+
def visualizeFit(X,mu,sigma2):
55+
X1,X2 = np.meshgrid(0,0.5,35)
56+
Z = multivariateGaussian(np.vstack((X1,X2)), mu, Sigma2)
57+
58+
59+
if __name__ == '__main__':
60+
anomalyDetection_example()
61+

PCA/PCA.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def featureNormalize(X):
8383
mu = np.zeros((1,n));
8484
sigma = np.zeros((1,n))
8585

86-
mu = np.mean(X,axis=0)
86+
mu = np.mean(X,axis=0) # axis=0表示列
8787
sigma = np.std(X,axis=0)
8888
for i in range(n):
8989
X[:,i] = (X[:,i]-mu[i])/sigma[i]

0 commit comments

Comments
 (0)