├── LICENSE ├── README.md ├── bias_variance ├── bias_variance.py ├── ex5data1.mat └── test1.py ├── formula ├── AnomalyDetection.wmf ├── K-Means.wmf ├── LinearRegression_01.wmf ├── LogisticRegression_01.wmf ├── NeuralNetwork.wmf ├── PCA.wmf └── SVM.wmf ├── images ├── AnomalyDetection_01.png ├── AnomalyDetection_02.png ├── AnomalyDetection_03.png ├── AnomalyDetection_04.png ├── AnomalyDetection_05.png ├── AnomalyDetection_06.png ├── AnomalyDetection_07.png ├── AnomalyDetection_08.png ├── AnomalyDetection_09.png ├── AnomalyDetection_10.png ├── IMG_2759.JPG ├── K-Means_01.png ├── K-Means_02.png ├── K-Means_03.png ├── K-Means_04.png ├── K-Means_05.png ├── K-Means_06.png ├── K-Means_07.png ├── LinearRegression_01.png ├── LogisticRegression_01.png ├── LogisticRegression_02.png ├── LogisticRegression_03.jpg ├── LogisticRegression_04.png ├── LogisticRegression_05.png ├── LogisticRegression_06.png ├── LogisticRegression_07.png ├── LogisticRegression_08.png ├── LogisticRegression_09.png ├── LogisticRegression_10.png ├── LogisticRegression_11.png ├── LogisticRegression_12.png ├── LogisticRegression_13.png ├── NeuralNetwork_01.png ├── NeuralNetwork_02.png ├── NeuralNetwork_03.jpg ├── NeuralNetwork_04.png ├── NeuralNetwork_05.png ├── NeuralNetwork_06.png ├── NeuralNetwork_07.png ├── NeuralNetwork_08.png ├── NeuralNetwork_09.png ├── PCA_01.png ├── PCA_02.png ├── PCA_03.png ├── PCA_04.png ├── PCA_05.png ├── PCA_06.png ├── PCA_07.png ├── PCA_08.png ├── SVM_01.png ├── SVM_02.png ├── SVM_03.png ├── SVM_04.png ├── SVM_05.png ├── SVM_06.png ├── SVM_07.png ├── SVM_08.png ├── SVM_09.png └── SVM_10.png ├── linear ├── ex1data1.txt ├── ex1data2.txt ├── linear.py ├── linear_multi.py └── linear_scikit ├── logistic ├── README.md ├── ex2data1.txt ├── ex2data2.txt ├── logistic.py ├── logistic_scikit.py ├── output_0_1.png ├── output_0_2.png └── output_0_3.png ├── multi_class_logistic ├── 111.html ├── class_y.csv ├── ex3data1.mat ├── multi_class.py └── running_process.html └── neural_network ├── ex3data1.mat ├── ex3weights.mat ├── ex4data1.mat ├── ex4weights.mat ├── nn.py └── nn_ex4.py /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 JSen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 机器学习算法Python实现 2 | ========= 3 | 4 | [![MIT license](https://img.shields.io/dub/l/vibe-d.svg)](https://github.com/lawlite19/MachineLearning_Python/blob/master/LICENSE) 5 | 6 | 7 | ## 目录 8 | * [机器学习算法Python实现](#机器学习算法python实现) 9 | * [一、线性回归](#一-线性回归) 10 | * [1、代价函数](#1-代价函数) 11 | * [2、梯度下降算法](#2-梯度下降算法) 12 | * [3、均值归一化](#3-均值归一化) 13 | * [4、最终运行结果](#4-最终运行结果) 14 | * [5、使用scikit-learn库中的线性模型实现](#5-使用scikit-learn库中的线性模型实现) 15 | * [二、逻辑回归](#二-逻辑回归) 16 | * [1、代价函数](#1-代价函数) 17 | * [2、梯度](#2-梯度) 18 | * [3、正则化](#3-正则化) 19 | * [4、S型函数(即)](#4-s型函数即) 20 | * [5、映射为多项式](#5-映射为多项式) 21 | * [6、使用的优化方法](#6-使用的优化方法) 22 | * [7、运行结果](#7-运行结果) 23 | * [8、使用scikit-learn库中的逻辑回归模型实现](#8-使用scikit-learn库中的逻辑回归模型实现) 24 | * [逻辑回归_手写数字识别_OneVsAll](#逻辑回归_手写数字识别_onevsall) 25 | * [1、随机显示100个数字](#1-随机显示100个数字) 26 | * [2、OneVsAll](#2-onevsall) 27 | * [3、手写数字识别](#3-手写数字识别) 28 | * [4、预测](#4-预测) 29 | * [5、运行结果](#5-运行结果) 30 | * [6、使用scikit-learn库中的逻辑回归模型实现](#6-使用scikit-learn库中的逻辑回归模型实现) 31 | * [三、BP神经网络](#三-bp神经网络) 32 | * [1、神经网络model](#1-神经网络model) 33 | * [2、代价函数](#2-代价函数) 34 | * [3、正则化](#3-正则化) 35 | * [4、反向传播BP](#4-反向传播bp) 36 | * [5、BP可以求梯度的原因](#5-bp可以求梯度的原因) 37 | * [6、梯度检查](#6-梯度检查) 38 | * [7、权重的随机初始化](#7-权重的随机初始化) 39 | * [8、预测](#8-预测) 40 | * [9、输出结果](#9-输出结果) 41 | * [四、SVM支持向量机](#四-svm支持向量机) 42 | * [1、代价函数](#1-代价函数) 43 | * [2、Large Margin](#2-large-margin) 44 | * [3、SVM Kernel(核函数)](#3-svm-kernel核函数) 45 | * [4、使用中的模型代码](#4-使用中的模型代码) 46 | * [5、运行结果](#5-运行结果) 47 | * [五、K-Means聚类算法](#五-k-means聚类算法) 48 | * [1、聚类过程](#1-聚类过程) 49 | * [2、目标函数](#2-目标函数) 50 | * [3、聚类中心的选择](#3-聚类中心的选择) 51 | * [4、聚类个数K的选择](#4-聚类个数k的选择) 52 | * [5、应用——图片压缩](#5-应用图片压缩) 53 | * [6、使用scikit-learn库中的线性模型实现聚类](#6-使用scikit-learn库中的线性模型实现聚类) 54 | * [7、运行结果](#7-运行结果) 55 | * [六、PCA主成分分析(降维)](#六-pca主成分分析降维) 56 | * [1、用处](#1-用处) 57 | * [2、2D-->1D,nD-->kD](#2-2d-1dnd-kd) 58 | * [3、主成分分析PCA与线性回归的区别](#3-主成分分析pca与线性回归的区别) 59 | * [4、PCA降维过程](#4-pca降维过程) 60 | * [5、数据恢复](#5-数据恢复) 61 | * [6、主成分个数的选择(即要降的维度)](#6-主成分个数的选择即要降的维度) 62 | * [7、使用建议](#7-使用建议) 63 | * [8、运行结果](#8-运行结果) 64 | * [9、使用scikit-learn库中的PCA实现降维](#9-使用scikit-learn库中的pca实现降维) 65 | * [七、异常检测 Anomaly Detection](#七-异常检测-anomaly-detection) 66 | * [1、高斯分布(正态分布)](#1-高斯分布正态分布) 67 | * [2、异常检测算法](#2-异常检测算法) 68 | * [3、评价的好坏,以及的选取](#3-评价的好坏以及的选取) 69 | * [4、选择使用什么样的feature(单元高斯分布)](#4-选择使用什么样的feature单元高斯分布) 70 | * [5、多元高斯分布](#5-多元高斯分布) 71 | * [6、单元和多元高斯分布特点](#6-单元和多元高斯分布特点) 72 | * [7、程序运行结果](#7-程序运行结果) 73 | 74 | [注]:吴恩达(Andrew Ng)在coursera的机器学习课程习题的python实现, 目前包括ex1, ex2, ex3, ex4, ex5,ex6.python代码是完全根据matlib代码修改而来,几乎一一对应。 75 | 76 | 77 | 78 | ## 一、[线性回归](/LinearRegression) 79 | 80 | - [全部代码](/LinearRegression/LinearRegression.py) 81 | 82 | ### 1、代价函数 83 | - ![J(\theta ) = \frac{1}{{2{\text{m}}}}\sum\limits_{i = 1}^m {{{({h_\theta }({x^{(i)}}) - {y^{(i)}})}^2}} ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=J%28%5Ctheta%20%29%20%3D%20%5Cfrac%7B1%7D%7B%7B2%7B%5Ctext%7Bm%7D%7D%7D%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%7B%7B%28%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%20-%20%7By%5E%7B%28i%29%7D%7D%29%7D%5E2%7D%7D%20) 84 | - 其中: 85 | ![{h_\theta }(x) = {\theta _0} + {\theta _1}{x_1} + {\theta _2}{x_2} + ...](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bh_%5Ctheta%20%7D%28x%29%20%3D%20%7B%5Ctheta%20_0%7D%20%2B%20%7B%5Ctheta%20_1%7D%7Bx_1%7D%20%2B%20%7B%5Ctheta%20_2%7D%7Bx_2%7D%20%2B%20...) 86 | 87 | - 下面就是要求出theta,使代价最小,即代表我们拟合出来的方程距离真实值最近 88 | - 共有m条数据,其中![{{{({h_\theta }({x^{(i)}}) - {y^{(i)}})}^2}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%7B%7B%28%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%20-%20%7By%5E%7B%28i%29%7D%7D%29%7D%5E2%7D%7D)代表我们要拟合出来的方程到真实值距离的平方,平方的原因是因为可能有负值,正负可能会抵消 89 | - 前面有系数`2`的原因是下面求梯度是对每个变量求偏导,`2`可以消去 90 | 91 | - 实现代码: 92 | ``` 93 | # 计算代价函数 94 | def computerCost(X,y,theta): 95 | m = len(y) 96 | J = 0 97 | 98 | J = (np.transpose(X*theta-y))*(X*theta-y)/(2*m) #计算代价J 99 | return J 100 | ``` 101 | - 注意这里的X是真实数据前加了一列1,因为有theta(0) 102 | 103 | ### 2、梯度下降算法 104 | - 代价函数对![{{\theta _j}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%7B%5Ctheta%20_j%7D%7D)求偏导得到: 105 | ![\frac{{\partial J(\theta )}}{{\partial {\theta _j}}} = \frac{1}{m}\sum\limits_{i = 1}^m {[({h_\theta }({x^{(i)}}) - {y^{(i)}})x_j^{(i)}]} ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Cfrac%7B%7B%5Cpartial%20J%28%5Ctheta%20%29%7D%7D%7B%7B%5Cpartial%20%7B%5Ctheta%20_j%7D%7D%7D%20%3D%20%5Cfrac%7B1%7D%7Bm%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%5B%28%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%20-%20%7By%5E%7B%28i%29%7D%7D%29x_j%5E%7B%28i%29%7D%5D%7D%20) 106 | - 所以对theta的更新可以写为: 107 | ![{\theta _j} = {\theta _j} - \alpha \frac{1}{m}\sum\limits_{i = 1}^m {[({h_\theta }({x^{(i)}}) - {y^{(i)}})x_j^{(i)}]} ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Ctheta%20_j%7D%20%3D%20%7B%5Ctheta%20_j%7D%20-%20%5Calpha%20%5Cfrac%7B1%7D%7Bm%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%5B%28%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%20-%20%7By%5E%7B%28i%29%7D%7D%29x_j%5E%7B%28i%29%7D%5D%7D%20) 108 | - 其中![\alpha ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Calpha%20)为学习速率,控制梯度下降的速度,一般取**0.01,0.03,0.1,0.3.....** 109 | - 为什么梯度下降可以逐步减小代价函数 110 | - 假设函数`f(x)` 111 | - 泰勒展开:`f(x+△x)=f(x)+f'(x)*△x+o(△x)` 112 | - 令:`△x=-α*f'(x)` ,即负梯度方向乘以一个很小的步长`α` 113 | - 将`△x`代入泰勒展开式中:`f(x+△x)=f(x)-α*[f'(x)]²+o(△x)` 114 | - 可以看出,`α`是取得很小的正数,`[f'(x)]²`也是正数,所以可以得出:`f(x+△x)<=f(x)` 115 | - 所以沿着**负梯度**放下,函数在减小,多维情况一样。 116 | - 实现代码 117 | ``` 118 | # 梯度下降算法 119 | def gradientDescent(X,y,theta,alpha,num_iters): 120 | m = len(y) 121 | n = len(theta) 122 | 123 | temp = np.matrix(np.zeros((n,num_iters))) # 暂存每次迭代计算的theta,转化为矩阵形式 124 | 125 | 126 | J_history = np.zeros((num_iters,1)) #记录每次迭代计算的代价值 127 | 128 | for i in range(num_iters): # 遍历迭代次数 129 | h = np.dot(X,theta) # 计算内积,matrix可以直接乘 130 | temp[:,i] = theta - ((alpha/m)*(np.dot(np.transpose(X),h-y))) #梯度的计算 131 | theta = temp[:,i] 132 | J_history[i] = computerCost(X,y,theta) #调用计算代价函数 133 | print '.', 134 | return theta,J_history 135 | ``` 136 | 137 | ### 3、均值归一化 138 | - 目的是使数据都缩放到一个范围内,便于使用梯度下降算法 139 | - ![{x_i} = \frac{{{x_i} - {\mu _i}}}{{{s_i}}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bx_i%7D%20%3D%20%5Cfrac%7B%7B%7Bx_i%7D%20-%20%7B%5Cmu%20_i%7D%7D%7D%7B%7B%7Bs_i%7D%7D%7D) 140 | - 其中 ![{{\mu _i}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%7B%5Cmu%20_i%7D%7D) 为所有此feture数据的平均值 141 | - ![{{s_i}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%7Bs_i%7D%7D)可以是**最大值-最小值**,也可以是这个feature对应的数据的**标准差** 142 | - 实现代码: 143 | ``` 144 | # 归一化feature 145 | def featureNormaliza(X): 146 | X_norm = np.array(X) #将X转化为numpy数组对象,才可以进行矩阵的运算 147 | #定义所需变量 148 | mu = np.zeros((1,X.shape[1])) 149 | sigma = np.zeros((1,X.shape[1])) 150 | 151 | mu = np.mean(X_norm,0) # 求每一列的平均值(0指定为列,1代表行) 152 | sigma = np.std(X_norm,0) # 求每一列的标准差 153 | for i in range(X.shape[1]): # 遍历列 154 | X_norm[:,i] = (X_norm[:,i]-mu[i])/sigma[i] # 归一化 155 | 156 | return X_norm,mu,sigma 157 | ``` 158 | - 注意预测的时候也需要均值归一化数据 159 | 160 | ### 4、最终运行结果 161 | - 代价随迭代次数的变化 162 | ![enter description here][1] 163 | 164 | 165 | ### 5、[使用scikit-learn库中的线性模型实现](/LinearRegression/LinearRegression_scikit-learn.py) 166 | - 导入包 167 | ``` 168 | from sklearn import linear_model 169 | from sklearn.preprocessing import StandardScaler #引入缩放的包 170 | ``` 171 | - 归一化 172 | ``` 173 | # 归一化操作 174 | scaler = StandardScaler() 175 | scaler.fit(X) 176 | x_train = scaler.transform(X) 177 | x_test = scaler.transform(np.array([1650,3])) 178 | ``` 179 | - 线性模型拟合 180 | ``` 181 | # 线性模型拟合 182 | model = linear_model.LinearRegression() 183 | model.fit(x_train, y) 184 | ``` 185 | - 预测 186 | ``` 187 | #预测结果 188 | result = model.predict(x_test) 189 | ``` 190 | 191 | ------------------- 192 | 193 | 194 | ## 二、[逻辑回归](/LogisticRegression) 195 | - [全部代码](/LogisticRegression/LogisticRegression.py) 196 | 197 | ### 1、代价函数 198 | - ![\left\{ \begin{gathered} 199 | J(\theta ) = \frac{1}{m}\sum\limits_{i = 1}^m {\cos t({h_\theta }({x^{(i)}}),{y^{(i)}})} \hfill \\ 200 | \cos t({h_\theta }(x),y) = \left\{ {\begin{array}{c} { - \log ({h_\theta }(x))} \\ { - \log (1 - {h_\theta }(x))} \end{array} \begin{array}{c} {y = 1} \\ {y = 0} \end{array} } \right. \hfill \\ 201 | \end{gathered} \right.](http://latex.codecogs.com/gif.latex?%5Clarge%20%5Cleft%5C%7B%20%5Cbegin%7Bgathered%7D%20J%28%5Ctheta%20%29%20%3D%20%5Cfrac%7B1%7D%7Bm%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%5Ccos%20t%28%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%2C%7By%5E%7B%28i%29%7D%7D%29%7D%20%5Chfill%20%5C%5C%20%5Ccos%20t%28%7Bh_%5Ctheta%20%7D%28x%29%2Cy%29%20%3D%20%5Cleft%5C%7B%20%7B%5Cbegin%7Barray%7D%7Bc%7D%20%7B%20-%20%5Clog%20%28%7Bh_%5Ctheta%20%7D%28x%29%29%7D%20%5C%5C%20%7B%20-%20%5Clog%20%281%20-%20%7Bh_%5Ctheta%20%7D%28x%29%29%7D%20%5Cend%7Barray%7D%20%5Cbegin%7Barray%7D%7Bc%7D%20%7By%20%3D%201%7D%20%5C%5C%20%7By%20%3D%200%7D%20%5Cend%7Barray%7D%20%7D%20%5Cright.%20%5Chfill%20%5C%5C%20%5Cend%7Bgathered%7D%20%5Cright.) 202 | - 可以综合起来为: 203 | ![J(\theta ) = - \frac{1}{m}\sum\limits_{i = 1}^m {[{y^{(i)}}\log ({h_\theta }({x^{(i)}}) + (1 - } {y^{(i)}})\log (1 - {h_\theta }({x^{(i)}})]](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=J%28%5Ctheta%20%29%20%3D%20%20-%20%5Cfrac%7B1%7D%7Bm%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%5B%7By%5E%7B%28i%29%7D%7D%5Clog%20%28%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%20%2B%20%281%20-%20%7D%20%7By%5E%7B%28i%29%7D%7D%29%5Clog%20%281%20-%20%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%5D) 204 | 其中: 205 | ![{h_\theta }(x) = \frac{1}{{1 + {e^{ - x}}}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bh_%5Ctheta%20%7D%28x%29%20%3D%20%5Cfrac%7B1%7D%7B%7B1%20%2B%20%7Be%5E%7B%20-%20x%7D%7D%7D%7D) 206 | - 为什么不用线性回归的代价函数表示,因为线性回归的代价函数可能是非凸的,对于分类问题,使用梯度下降很难得到最小值,上面的代价函数是凸函数 207 | - ![{ - \log ({h_\theta }(x))}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%20-%20%5Clog%20%28%7Bh_%5Ctheta%20%7D%28x%29%29%7D)的图像如下,即`y=1`时: 208 | ![enter description here][2] 209 | 210 | 可以看出,当![{{h_\theta }(x)}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%7Bh_%5Ctheta%20%7D%28x%29%7D)趋于`1`,`y=1`,与预测值一致,此时付出的代价`cost`趋于`0`,若![{{h_\theta }(x)}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%7Bh_%5Ctheta%20%7D%28x%29%7D)趋于`0`,`y=1`,此时的代价`cost`值非常大,我们最终的目的是最小化代价值 211 | - 同理![{ - \log (1 - {h_\theta }(x))}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%20-%20%5Clog%20%281%20-%20%7Bh_%5Ctheta%20%7D%28x%29%29%7D)的图像如下(`y=0`): 212 | ![enter description here][3] 213 | 214 | ### 2、梯度 215 | - 同样对代价函数求偏导: 216 | ![\frac{{\partial J(\theta )}}{{\partial {\theta _j}}} = \frac{1}{m}\sum\limits_{i = 1}^m {[({h_\theta }({x^{(i)}}) - {y^{(i)}})x_j^{(i)}]} ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Cfrac%7B%7B%5Cpartial%20J%28%5Ctheta%20%29%7D%7D%7B%7B%5Cpartial%20%7B%5Ctheta%20_j%7D%7D%7D%20%3D%20%5Cfrac%7B1%7D%7Bm%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%5B%28%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%20-%20%7By%5E%7B%28i%29%7D%7D%29x_j%5E%7B%28i%29%7D%5D%7D%20) 217 | 可以看出与线性回归的偏导数一致 218 | - 推导过程 219 | ![enter description here][4] 220 | 221 | ![IMG_2759](images/IMG_2759.JPG) 222 | 223 | ### 3、正则化 224 | 225 | - 目的是为了防止过拟合 226 | - 在代价函数中加上一项![J(\theta ) = - \frac{1}{m}\sum\limits_{i = 1}^m {[{y^{(i)}}\log ({h_\theta }({x^{(i)}}) + (1 - } {y^{(i)}})\log (1 - {h_\theta }({x^{(i)}})] + \frac{\lambda }{{2m}}\sum\limits_{j = 1}^n {\theta _j^2} ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=J%28%5Ctheta%20%29%20%3D%20%20-%20%5Cfrac%7B1%7D%7Bm%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%5B%7By%5E%7B%28i%29%7D%7D%5Clog%20%28%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%20%2B%20%281%20-%20%7D%20%7By%5E%7B%28i%29%7D%7D%29%5Clog%20%281%20-%20%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%5D%20%2B%20%5Cfrac%7B%5Clambda%20%7D%7B%7B2m%7D%7D%5Csum%5Climits_%7Bj%20%3D%201%7D%5En%20%7B%5Ctheta%20_j%5E2%7D%20) 227 | - 注意j是重1开始的,因为theta(0)为一个常数项,X中最前面一列会加上1列1,所以乘积还是theta(0),feature没有关系,没有必要正则化 228 | - 正则化后的代价: 229 | ``` 230 | # 代价函数 231 | def costFunction(initial_theta,X,y,inital_lambda): 232 | m = len(y) 233 | J = 0 234 | 235 | h = sigmoid(np.dot(X,initial_theta)) # 计算h(z) 236 | theta1 = initial_theta.copy() # 因为正则化j=1从1开始,不包含0,所以复制一份,前theta(0)值为0 237 | theta1[0] = 0 238 | 239 | temp = np.dot(np.transpose(theta1),theta1) 240 | J = (-np.dot(np.transpose(y),np.log(h))-np.dot(np.transpose(1-y),np.log(1-h))+temp*inital_lambda/2)/m # 正则化的代价方程 241 | return J 242 | ``` 243 | - 正则化后的代价的梯度 244 | ``` 245 | # 计算梯度 246 | def gradient(initial_theta,X,y,inital_lambda): 247 | m = len(y) 248 | grad = np.zeros((initial_theta.shape[0])) 249 | 250 | h = sigmoid(np.dot(X,initial_theta))# 计算h(z) 251 | theta1 = initial_theta.copy() 252 | theta1[0] = 0 253 | 254 | grad = np.dot(np.transpose(X),h-y)/m+inital_lambda/m*theta1 #正则化的梯度 255 | return grad 256 | ``` 257 | 258 | ### 4、S型函数(即![{{h_\theta }(x)}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%7Bh_%5Ctheta%20%7D%28x%29%7D)) 259 | - 实现代码: 260 | ``` 261 | # S型函数 262 | def sigmoid(z): 263 | h = np.zeros((len(z),1)) # 初始化,与z的长度一置 264 | 265 | h = 1.0/(1.0+np.exp(-z)) 266 | return h 267 | ``` 268 | 269 | ### 5、映射为多项式 270 | - 因为数据的feture可能很少,导致偏差大,所以创造出一些feture结合 271 | - eg:映射为2次方的形式:![1 + {x_1} + {x_2} + x_1^2 + {x_1}{x_2} + x_2^2](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=1%20%2B%20%7Bx_1%7D%20%2B%20%7Bx_2%7D%20%2B%20x_1%5E2%20%2B%20%7Bx_1%7D%7Bx_2%7D%20%2B%20x_2%5E2) 272 | - 实现代码: 273 | ``` 274 | # 映射为多项式 275 | def mapFeature(X1,X2): 276 | degree = 3; # 映射的最高次方 277 | out = np.ones((X1.shape[0],1)) # 映射后的结果数组(取代X) 278 | ''' 279 | 这里以degree=2为例,映射为1,x1,x2,x1^2,x1,x2,x2^2 280 | ''' 281 | for i in np.arange(1,degree+1): 282 | for j in range(i+1): 283 | temp = X1**(i-j)*(X2**j) #矩阵直接乘相当于matlab中的点乘.* 284 | out = np.hstack((out, temp.reshape(-1,1))) 285 | return out 286 | ``` 287 | 288 | ### 6、使用`scipy`的优化方法 289 | - 梯度下降使用`scipy`中`optimize`中的`fmin_bfgs`函数 290 | - 调用scipy中的优化算法fmin_bfgs(拟牛顿法Broyden-Fletcher-Goldfarb-Shanno 291 | - costFunction是自己实现的一个求代价的函数, 292 | - initial_theta表示初始化的值, 293 | - fprime指定costFunction的梯度 294 | - args是其余测参数,以元组的形式传入,最后会将最小化costFunction的theta返回 295 | ``` 296 | result = optimize.fmin_bfgs(costFunction, initial_theta, fprime=gradient, args=(X,y,initial_lambda)) 297 | ``` 298 | 299 | ### 7、运行结果 300 | - data1决策边界和准确度 301 | ![enter description here][5] 302 | ![enter description here][6] 303 | - data2决策边界和准确度 304 | ![enter description here][7] 305 | ![enter description here][8] 306 | 307 | ### 8、[使用scikit-learn库中的逻辑回归模型实现](/LogisticRegression/LogisticRegression_scikit-learn.py) 308 | - 导入包 309 | ``` 310 | from sklearn.linear_model import LogisticRegression 311 | from sklearn.preprocessing import StandardScaler 312 | from sklearn.cross_validation import train_test_split 313 | import numpy as np 314 | ``` 315 | - 划分训练集和测试集 316 | ``` 317 | # 划分为训练集和测试集 318 | x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.2) 319 | ``` 320 | - 归一化 321 | ``` 322 | # 归一化 323 | scaler = StandardScaler() 324 | x_train = scaler.fit_transform(x_train) 325 | x_test = scaler.fit_transform(x_test) 326 | ``` 327 | - 逻辑回归 328 | ``` 329 | #逻辑回归 330 | model = LogisticRegression() 331 | model.fit(x_train,y_train) 332 | ``` 333 | - 预测 334 | ``` 335 | # 预测 336 | predict = model.predict(x_test) 337 | right = sum(predict == y_test) 338 | 339 | predict = np.hstack((predict.reshape(-1,1),y_test.reshape(-1,1))) # 将预测值和真实值放在一块,好观察 340 | print predict 341 | print ('测试集准确率:%f%%'%(right*100.0/predict.shape[0])) #计算在测试集上的准确度 342 | ``` 343 | 344 | ------------- 345 | 346 | ## [逻辑回归_手写数字识别_OneVsAll](/LogisticRegression) 347 | - [全部代码](/LogisticRegression/LogisticRegression_OneVsAll.py) 348 | 349 | ### 1、随机显示100个数字 350 | - 我没有使用scikit-learn中的数据集,像素是20*20px,彩色图如下 351 | ![enter description here][9] 352 | 灰度图: 353 | ![enter description here][10] 354 | - 实现代码: 355 | ``` 356 | # 显示100个数字 357 | def display_data(imgData): 358 | sum = 0 359 | ''' 360 | 显示100个数(若是一个一个绘制将会非常慢,可以将要画的数字整理好,放到一个矩阵中,显示这个矩阵即可) 361 | - 初始化一个二维数组 362 | - 将每行的数据调整成图像的矩阵,放进二维数组 363 | - 显示即可 364 | ''' 365 | pad = 1 366 | display_array = -np.ones((pad+10*(20+pad),pad+10*(20+pad))) 367 | for i in range(10): 368 | for j in range(10): 369 | display_array[pad+i*(20+pad):pad+i*(20+pad)+20,pad+j*(20+pad):pad+j*(20+pad)+20] = (imgData[sum,:].reshape(20,20,order="F")) # order=F指定以列优先,在matlab中是这样的,python中需要指定,默认以行 370 | sum += 1 371 | 372 | plt.imshow(display_array,cmap='gray') #显示灰度图像 373 | plt.axis('off') 374 | plt.show() 375 | ``` 376 | 377 | ### 2、OneVsAll 378 | - 如何利用逻辑回归解决多分类的问题,OneVsAll就是把当前某一类看成一类,其他所有类别看作一类,这样有成了二分类的问题了 379 | - 如下图,把途中的数据分成三类,先把红色的看成一类,把其他的看作另外一类,进行逻辑回归,然后把蓝色的看成一类,其他的再看成一类,以此类推... 380 | ![enter description here][11] 381 | - 可以看出大于2类的情况下,有多少类就要进行多少次的逻辑回归分类 382 | 383 | ### 3、手写数字识别 384 | - 共有0-9,10个数字,需要10次分类 385 | - 由于**数据集y**给出的是`0,1,2...9`的数字,而进行逻辑回归需要`0/1`的label标记,所以需要对y处理 386 | - 说一下数据集,前`500`个是`0`,`500-1000`是`1`,`...`,所以如下图,处理后的`y`,**前500行的第一列是1,其余都是0,500-1000行第二列是1,其余都是0....** 387 | ![enter description here][12] 388 | - 然后调用**梯度下降算法**求解`theta` 389 | - 实现代码: 390 | ``` 391 | # 求每个分类的theta,最后返回所有的all_theta 392 | def oneVsAll(X,y,num_labels,Lambda): 393 | # 初始化变量 394 | m,n = X.shape 395 | all_theta = np.zeros((n+1,num_labels)) # 每一列对应相应分类的theta,共10列 396 | X = np.hstack((np.ones((m,1)),X)) # X前补上一列1的偏置bias 397 | class_y = np.zeros((m,num_labels)) # 数据的y对应0-9,需要映射为0/1的关系 398 | initial_theta = np.zeros((n+1,1)) # 初始化一个分类的theta 399 | 400 | # 映射y 401 | for i in range(num_labels): 402 | class_y[:,i] = np.int32(y==i).reshape(1,-1) # 注意reshape(1,-1)才可以赋值 403 | 404 | #np.savetxt("class_y.csv", class_y[0:600,:], delimiter=',') 405 | 406 | '''遍历每个分类,计算对应的theta值''' 407 | for i in range(num_labels): 408 | result = optimize.fmin_bfgs(costFunction, initial_theta, fprime=gradient, args=(X,class_y[:,i],Lambda)) # 调用梯度下降的优化方法 409 | all_theta[:,i] = result.reshape(1,-1) # 放入all_theta中 410 | 411 | all_theta = np.transpose(all_theta) 412 | return all_theta 413 | ``` 414 | 415 | ### 4、预测 416 | - 之前说过,预测的结果是一个**概率值**,利用学习出来的`theta`代入预测的**S型函数**中,每行的最大值就是是某个数字的最大概率,所在的**列号**就是预测的数字的真实值,因为在分类时,所有为`0`的将`y`映射在第一列,为1的映射在第二列,依次类推 417 | - 实现代码: 418 | ``` 419 | # 预测 420 | def predict_oneVsAll(all_theta,X): 421 | m = X.shape[0] 422 | num_labels = all_theta.shape[0] 423 | p = np.zeros((m,1)) 424 | X = np.hstack((np.ones((m,1)),X)) #在X最前面加一列1 425 | 426 | h = sigmoid(np.dot(X,np.transpose(all_theta))) #预测 427 | 428 | ''' 429 | 返回h中每一行最大值所在的列号 430 | - np.max(h, axis=1)返回h中每一行的最大值(是某个数字的最大概率) 431 | - 最后where找到的最大概率所在的列号(列号即是对应的数字) 432 | ''' 433 | p = np.array(np.where(h[0,:] == np.max(h, axis=1)[0])) 434 | for i in np.arange(1, m): 435 | t = np.array(np.where(h[i,:] == np.max(h, axis=1)[i])) 436 | p = np.vstack((p,t)) 437 | return p 438 | ``` 439 | 440 | ### 5、运行结果 441 | - 10次分类,在训练集上的准确度: 442 | ![enter description here][13] 443 | 444 | ### 6、[使用scikit-learn库中的逻辑回归模型实现](/LogisticRegression/LogisticRegression_OneVsAll_scikit-learn.py) 445 | - 1、导入包 446 | ``` 447 | from scipy import io as spio 448 | import numpy as np 449 | from sklearn import svm 450 | from sklearn.linear_model import LogisticRegression 451 | ``` 452 | - 2、加载数据 453 | ``` 454 | data = loadmat_data("data_digits.mat") 455 | X = data['X'] # 获取X数据,每一行对应一个数字20x20px 456 | y = data['y'] # 这里读取mat文件y的shape=(5000, 1) 457 | y = np.ravel(y) # 调用sklearn需要转化成一维的(5000,) 458 | ``` 459 | - 3、拟合模型 460 | ``` 461 | model = LogisticRegression() 462 | model.fit(X, y) # 拟合 463 | ``` 464 | - 4、预测 465 | ``` 466 | predict = model.predict(X) #预测 467 | 468 | print u"预测准确度为:%f%%"%np.mean(np.float64(predict == y)*100) 469 | ``` 470 | - 5、输出结果(在训练集上的准确度) 471 | ![enter description here][14] 472 | 473 | ---------- 474 | 475 | ## 三、BP神经网络 476 | - [全部代码](/NeuralNetwok/NeuralNetwork.py) 477 | 478 | ### 1、神经网络model 479 | - 先介绍个三层的神经网络,如下图所示 480 | - 输入层(input layer)有三个units(![{x_0}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bx_0%7D)为补上的bias,通常设为`1`) 481 | - ![a_i^{(j)}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=a_i%5E%7B%28j%29%7D)表示第`j`层的第`i`个激励,也称为为单元unit 482 | - ![{\theta ^{(j)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Ctheta%20%5E%7B%28j%29%7D%7D)为第`j`层到第`j+1`层映射的权重矩阵,就是每条边的权重 483 | ![enter description here][15] 484 | 485 | - 所以可以得到: 486 | - 隐含层: 487 | ![a_1^{(2)} = g(\theta _{10}^{(1)}{x_0} + \theta _{11}^{(1)}{x_1} + \theta _{12}^{(1)}{x_2} + \theta _{13}^{(1)}{x_3})](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=a_1%5E%7B%282%29%7D%20%3D%20g%28%5Ctheta%20_%7B10%7D%5E%7B%281%29%7D%7Bx_0%7D%20%2B%20%5Ctheta%20_%7B11%7D%5E%7B%281%29%7D%7Bx_1%7D%20%2B%20%5Ctheta%20_%7B12%7D%5E%7B%281%29%7D%7Bx_2%7D%20%2B%20%5Ctheta%20_%7B13%7D%5E%7B%281%29%7D%7Bx_3%7D%29) 488 | ![a_2^{(2)} = g(\theta _{20}^{(1)}{x_0} + \theta _{21}^{(1)}{x_1} + \theta _{22}^{(1)}{x_2} + \theta _{23}^{(1)}{x_3})](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=a_2%5E%7B%282%29%7D%20%3D%20g%28%5Ctheta%20_%7B20%7D%5E%7B%281%29%7D%7Bx_0%7D%20%2B%20%5Ctheta%20_%7B21%7D%5E%7B%281%29%7D%7Bx_1%7D%20%2B%20%5Ctheta%20_%7B22%7D%5E%7B%281%29%7D%7Bx_2%7D%20%2B%20%5Ctheta%20_%7B23%7D%5E%7B%281%29%7D%7Bx_3%7D%29) 489 | ![a_3^{(2)} = g(\theta _{30}^{(1)}{x_0} + \theta _{31}^{(1)}{x_1} + \theta _{32}^{(1)}{x_2} + \theta _{33}^{(1)}{x_3})](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=a_3%5E%7B%282%29%7D%20%3D%20g%28%5Ctheta%20_%7B30%7D%5E%7B%281%29%7D%7Bx_0%7D%20%2B%20%5Ctheta%20_%7B31%7D%5E%7B%281%29%7D%7Bx_1%7D%20%2B%20%5Ctheta%20_%7B32%7D%5E%7B%281%29%7D%7Bx_2%7D%20%2B%20%5Ctheta%20_%7B33%7D%5E%7B%281%29%7D%7Bx_3%7D%29) 490 | - 输出层 491 | ![{h_\theta }(x) = a_1^{(3)} = g(\theta _{10}^{(2)}a_0^{(2)} + \theta _{11}^{(2)}a_1^{(2)} + \theta _{12}^{(2)}a_2^{(2)} + \theta _{13}^{(2)}a_3^{(2)})](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bh_%5Ctheta%20%7D%28x%29%20%3D%20a_1%5E%7B%283%29%7D%20%3D%20g%28%5Ctheta%20_%7B10%7D%5E%7B%282%29%7Da_0%5E%7B%282%29%7D%20%2B%20%5Ctheta%20_%7B11%7D%5E%7B%282%29%7Da_1%5E%7B%282%29%7D%20%2B%20%5Ctheta%20_%7B12%7D%5E%7B%282%29%7Da_2%5E%7B%282%29%7D%20%2B%20%5Ctheta%20_%7B13%7D%5E%7B%282%29%7Da_3%5E%7B%282%29%7D%29) 其中,**S型函数**![g(z) = \frac{1}{{1 + {e^{ - z}}}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=g%28z%29%20%3D%20%5Cfrac%7B1%7D%7B%7B1%20%2B%20%7Be%5E%7B%20-%20z%7D%7D%7D%7D),也成为**激励函数** 492 | - 可以看出![{\theta ^{(1)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Ctheta%20%5E%7B%281%29%7D%7D) 为3x4的矩阵,![{\theta ^{(2)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Ctheta%20%5E%7B%282%29%7D%7D)为1x4的矩阵 493 | - ![{\theta ^{(j)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Ctheta%20%5E%7B%28j%29%7D%7D) ==》`j+1`的单元数x(`j`层的单元数+1) 494 | 495 | ### 2、代价函数 496 | - 假设最后输出的![{h_\Theta }(x) \in {R^K}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bh_%5CTheta%20%7D%28x%29%20%5Cin%20%7BR%5EK%7D),即代表输出层有K个单元 497 | - ![J(\Theta ) = - \frac{1}{m}\sum\limits_{i = 1}^m {\sum\limits_{k = 1}^K {[y_k^{(i)}\log {{({h_\Theta }({x^{(i)}}))}_k}} } + (1 - y_k^{(i)})\log {(1 - {h_\Theta }({x^{(i)}}))_k}]](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=J%28%5CTheta%20%29%20%3D%20%20-%20%5Cfrac%7B1%7D%7Bm%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%5Csum%5Climits_%7Bk%20%3D%201%7D%5EK%20%7B%5By_k%5E%7B%28i%29%7D%5Clog%20%7B%7B%28%7Bh_%5CTheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%29%7D_k%7D%7D%20%7D%20%20%2B%20%281%20-%20y_k%5E%7B%28i%29%7D%29%5Clog%20%7B%281%20-%20%7Bh_%5CTheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%29_k%7D%5D) 其中,![{({h_\Theta }(x))_i}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%28%7Bh_%5CTheta%20%7D%28x%29%29_i%7D)代表第`i`个单元输出 498 | - 与逻辑回归的代价函数![J(\theta ) = - \frac{1}{m}\sum\limits_{i = 1}^m {[{y^{(i)}}\log ({h_\theta }({x^{(i)}}) + (1 - } {y^{(i)}})\log (1 - {h_\theta }({x^{(i)}})]](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=J%28%5Ctheta%20%29%20%3D%20%20-%20%5Cfrac%7B1%7D%7Bm%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%5B%7By%5E%7B%28i%29%7D%7D%5Clog%20%28%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%20%2B%20%281%20-%20%7D%20%7By%5E%7B%28i%29%7D%7D%29%5Clog%20%281%20-%20%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%5D)差不多,就是累加上每个输出(共有K个输出) 499 | 500 | 501 | 502 | ### 3、正则化 503 | - `L`-->所有层的个数 504 | - ![{S_l}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7BS_l%7D)-->第`l`层unit的个数 505 | - 正则化后的**代价函数**为 506 | ![enter description here][16] 507 | - ![\theta ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Ctheta%20)共有`L-1`层, 508 | - 然后是累加对应每一层的theta矩阵,注意不包含加上偏置项对应的theta(0) 509 | - 正则化后的代价函数实现代码: 510 | ``` 511 | # 代价函数 512 | def nnCostFunction(nn_params,input_layer_size,hidden_layer_size,num_labels,X,y,Lambda): 513 | length = nn_params.shape[0] # theta的中长度 514 | # 还原theta1和theta2 515 | Theta1 = nn_params[0:hidden_layer_size*(input_layer_size+1)].reshape(hidden_layer_size,input_layer_size+1) 516 | Theta2 = nn_params[hidden_layer_size*(input_layer_size+1):length].reshape(num_labels,hidden_layer_size+1) 517 | 518 | # np.savetxt("Theta1.csv",Theta1,delimiter=',') 519 | 520 | m = X.shape[0] 521 | class_y = np.zeros((m,num_labels)) # 数据的y对应0-9,需要映射为0/1的关系 522 | # 映射y 523 | for i in range(num_labels): 524 | class_y[:,i] = np.int32(y==i).reshape(1,-1) # 注意reshape(1,-1)才可以赋值 525 | 526 | '''去掉theta1和theta2的第一列,因为正则化时从1开始''' 527 | Theta1_colCount = Theta1.shape[1] 528 | Theta1_x = Theta1[:,1:Theta1_colCount] 529 | Theta2_colCount = Theta2.shape[1] 530 | Theta2_x = Theta2[:,1:Theta2_colCount] 531 | # 正则化向theta^2 532 | term = np.dot(np.transpose(np.vstack((Theta1_x.reshape(-1,1),Theta2_x.reshape(-1,1)))),np.vstack((Theta1_x.reshape(-1,1),Theta2_x.reshape(-1,1)))) 533 | 534 | '''正向传播,每次需要补上一列1的偏置bias''' 535 | a1 = np.hstack((np.ones((m,1)),X)) 536 | z2 = np.dot(a1,np.transpose(Theta1)) 537 | a2 = sigmoid(z2) 538 | a2 = np.hstack((np.ones((m,1)),a2)) 539 | z3 = np.dot(a2,np.transpose(Theta2)) 540 | h = sigmoid(z3) 541 | '''代价''' 542 | J = -(np.dot(np.transpose(class_y.reshape(-1,1)),np.log(h.reshape(-1,1)))+np.dot(np.transpose(1-class_y.reshape(-1,1)),np.log(1-h.reshape(-1,1)))-Lambda*term/2)/m 543 | 544 | return np.ravel(J) 545 | ``` 546 | 547 | ### 4、反向传播BP 548 | - 上面正向传播可以计算得到`J(θ)`,使用梯度下降法还需要求它的梯度 549 | - BP反向传播的目的就是求代价函数的梯度 550 | - 假设4层的神经网络,![\delta _{\text{j}}^{(l)}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Cdelta%20_%7B%5Ctext%7Bj%7D%7D%5E%7B%28l%29%7D)记为-->`l`层第`j`个单元的误差 551 | - ![\delta _{\text{j}}^{(4)} = a_j^{(4)} - {y_i}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Cdelta%20_%7B%5Ctext%7Bj%7D%7D%5E%7B%284%29%7D%20%3D%20a_j%5E%7B%284%29%7D%20-%20%7By_i%7D)《===》![{\delta ^{(4)}} = {a^{(4)}} - y](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Cdelta%20%5E%7B%284%29%7D%7D%20%3D%20%7Ba%5E%7B%284%29%7D%7D%20-%20y)(向量化) 552 | - ![{\delta ^{(3)}} = {({\theta ^{(3)}})^T}{\delta ^{(4)}}.*{g^}({a^{(3)}})](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Cdelta%20%5E%7B%283%29%7D%7D%20%3D%20%7B%28%7B%5Ctheta%20%5E%7B%283%29%7D%7D%29%5ET%7D%7B%5Cdelta%20%5E%7B%284%29%7D%7D.%2A%7Bg%5E%7D%28%7Ba%5E%7B%283%29%7D%7D%29) 553 | - ![{\delta ^{(2)}} = {({\theta ^{(2)}})^T}{\delta ^{(3)}}.*{g^}({a^{(2)}})](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Cdelta%20%5E%7B%282%29%7D%7D%20%3D%20%7B%28%7B%5Ctheta%20%5E%7B%282%29%7D%7D%29%5ET%7D%7B%5Cdelta%20%5E%7B%283%29%7D%7D.%2A%7Bg%5E%7D%28%7Ba%5E%7B%282%29%7D%7D%29) 554 | - 没有![{\delta ^{(1)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Cdelta%20%5E%7B%281%29%7D%7D),因为对于输入没有误差 555 | - 因为S型函数![{\text{g(z)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Ctext%7Bg%28z%29%7D%7D)的导数为:![{g^}(z){\text{ = g(z)(1 - g(z))}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bg%5E%7D%28z%29%7B%5Ctext%7B%20%3D%20g%28z%29%281%20-%20g%28z%29%29%7D%7D),所以上面的![{g^}({a^{(3)}})](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bg%5E%7D%28%7Ba%5E%7B%283%29%7D%7D%29)和![{g^}({a^{(2)}})](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bg%5E%7D%28%7Ba%5E%7B%282%29%7D%7D%29)可以在前向传播中计算出来 556 | 557 | - 反向传播计算梯度的过程为: 558 | - ![\Delta _{ij}^{(l)} = 0](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5CDelta%20_%7Bij%7D%5E%7B%28l%29%7D%20%3D%200)(![\Delta ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5CDelta%20)是大写的![\delta ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Cdelta%20)) 559 | - for i=1-m: 560 | -![{a^{(1)}} = {x^{(i)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Ba%5E%7B%281%29%7D%7D%20%3D%20%7Bx%5E%7B%28i%29%7D%7D) 561 | -正向传播计算![{a^{(l)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Ba%5E%7B%28l%29%7D%7D)(l=2,3,4...L) 562 | -反向计算![{\delta ^{(L)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Cdelta%20%5E%7B%28L%29%7D%7D)、![{\delta ^{(L - 1)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Cdelta%20%5E%7B%28L%20-%201%29%7D%7D)...![{\delta ^{(2)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Cdelta%20%5E%7B%282%29%7D%7D); 563 | -![\Delta _{ij}^{(l)} = \Delta _{ij}^{(l)} + a_j^{(l)}{\delta ^{(l + 1)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5CDelta%20_%7Bij%7D%5E%7B%28l%29%7D%20%3D%20%5CDelta%20_%7Bij%7D%5E%7B%28l%29%7D%20%2B%20a_j%5E%7B%28l%29%7D%7B%5Cdelta%20%5E%7B%28l%20%2B%201%29%7D%7D) 564 | -![D_{ij}^{(l)} = \frac{1}{m}\Delta _{ij}^{(l)} + \lambda \theta _{ij}^l\begin{array}{c} {}& {(j \ne 0)} \end{array} ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=D_%7Bij%7D%5E%7B%28l%29%7D%20%3D%20%5Cfrac%7B1%7D%7Bm%7D%5CDelta%20_%7Bij%7D%5E%7B%28l%29%7D%20%2B%20%5Clambda%20%5Ctheta%20_%7Bij%7D%5El%5Cbegin%7Barray%7D%7Bc%7D%20%20%20%20%7B%7D%26%20%7B%28j%20%5Cne%200%29%7D%20%20%5Cend%7Barray%7D%20) 565 | ![D_{ij}^{(l)} = \frac{1}{m}\Delta _{ij}^{(l)} + \lambda \theta _{ij}^lj = 0\begin{array}{c} {}& {j = 0} \end{array} ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=D_%7Bij%7D%5E%7B%28l%29%7D%20%3D%20%5Cfrac%7B1%7D%7Bm%7D%5CDelta%20_%7Bij%7D%5E%7B%28l%29%7D%20%2B%20%5Clambda%20%5Ctheta%20_%7Bij%7D%5Elj%20%3D%200%5Cbegin%7Barray%7D%7Bc%7D%20%20%20%20%7B%7D%26%20%7Bj%20%3D%200%7D%20%20%5Cend%7Barray%7D%20) 566 | 567 | - 最后![\frac{{\partial J(\Theta )}}{{\partial \Theta _{ij}^{(l)}}} = D_{ij}^{(l)}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Cfrac%7B%7B%5Cpartial%20J%28%5CTheta%20%29%7D%7D%7B%7B%5Cpartial%20%5CTheta%20_%7Bij%7D%5E%7B%28l%29%7D%7D%7D%20%3D%20D_%7Bij%7D%5E%7B%28l%29%7D),即得到代价函数的梯度 568 | - 实现代码: 569 | ``` 570 | # 梯度 571 | def nnGradient(nn_params,input_layer_size,hidden_layer_size,num_labels,X,y,Lambda): 572 | length = nn_params.shape[0] 573 | Theta1 = nn_params[0:hidden_layer_size*(input_layer_size+1)].reshape(hidden_layer_size,input_layer_size+1).copy() # 这里使用copy函数,否则下面修改Theta的值,nn_params也会一起修改 574 | Theta2 = nn_params[hidden_layer_size*(input_layer_size+1):length].reshape(num_labels,hidden_layer_size+1).copy() 575 | m = X.shape[0] 576 | class_y = np.zeros((m,num_labels)) # 数据的y对应0-9,需要映射为0/1的关系 577 | # 映射y 578 | for i in range(num_labels): 579 | class_y[:,i] = np.int32(y==i).reshape(1,-1) # 注意reshape(1,-1)才可以赋值 580 | 581 | '''去掉theta1和theta2的第一列,因为正则化时从1开始''' 582 | Theta1_colCount = Theta1.shape[1] 583 | Theta1_x = Theta1[:,1:Theta1_colCount] 584 | Theta2_colCount = Theta2.shape[1] 585 | Theta2_x = Theta2[:,1:Theta2_colCount] 586 | 587 | Theta1_grad = np.zeros((Theta1.shape)) #第一层到第二层的权重 588 | Theta2_grad = np.zeros((Theta2.shape)) #第二层到第三层的权重 589 | 590 | 591 | '''正向传播,每次需要补上一列1的偏置bias''' 592 | a1 = np.hstack((np.ones((m,1)),X)) 593 | z2 = np.dot(a1,np.transpose(Theta1)) 594 | a2 = sigmoid(z2) 595 | a2 = np.hstack((np.ones((m,1)),a2)) 596 | z3 = np.dot(a2,np.transpose(Theta2)) 597 | h = sigmoid(z3) 598 | 599 | 600 | '''反向传播,delta为误差,''' 601 | delta3 = np.zeros((m,num_labels)) 602 | delta2 = np.zeros((m,hidden_layer_size)) 603 | for i in range(m): 604 | #delta3[i,:] = (h[i,:]-class_y[i,:])*sigmoidGradient(z3[i,:]) # 均方误差的误差率 605 | delta3[i,:] = h[i,:]-class_y[i,:] # 交叉熵误差率 606 | Theta2_grad = Theta2_grad+np.dot(np.transpose(delta3[i,:].reshape(1,-1)),a2[i,:].reshape(1,-1)) 607 | delta2[i,:] = np.dot(delta3[i,:].reshape(1,-1),Theta2_x)*sigmoidGradient(z2[i,:]) 608 | Theta1_grad = Theta1_grad+np.dot(np.transpose(delta2[i,:].reshape(1,-1)),a1[i,:].reshape(1,-1)) 609 | 610 | Theta1[:,0] = 0 611 | Theta2[:,0] = 0 612 | '''梯度''' 613 | grad = (np.vstack((Theta1_grad.reshape(-1,1),Theta2_grad.reshape(-1,1)))+Lambda*np.vstack((Theta1.reshape(-1,1),Theta2.reshape(-1,1))))/m 614 | return np.ravel(grad) 615 | ``` 616 | 617 | ### 5、BP可以求梯度的原因 618 | - 实际是利用了`链式求导`法则 619 | - 因为下一层的单元利用上一层的单元作为输入进行计算 620 | - 大体的推导过程如下,最终我们是想预测函数与已知的`y`非常接近,求均方差的梯度沿着此梯度方向可使代价函数最小化。可对照上面求梯度的过程。 621 | ![enter description here][17] 622 | - 求误差更详细的推导过程: 623 | ![enter description here][18] 624 | 625 | ### 6、梯度检查 626 | - 检查利用`BP`求的梯度是否正确 627 | - 利用导数的定义验证: 628 | ![\frac{{dJ(\theta )}}{{d\theta }} \approx \frac{{J(\theta + \varepsilon ) - J(\theta - \varepsilon )}}{{2\varepsilon }}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Cfrac%7B%7BdJ%28%5Ctheta%20%29%7D%7D%7B%7Bd%5Ctheta%20%7D%7D%20%5Capprox%20%5Cfrac%7B%7BJ%28%5Ctheta%20%20%2B%20%5Cvarepsilon%20%29%20-%20J%28%5Ctheta%20%20-%20%5Cvarepsilon%20%29%7D%7D%7B%7B2%5Cvarepsilon%20%7D%7D) 629 | - 求出来的数值梯度应该与BP求出的梯度非常接近 630 | - 验证BP正确后就不需要再执行验证梯度的算法了 631 | - 实现代码: 632 | ``` 633 | # 检验梯度是否计算正确 634 | # 检验梯度是否计算正确 635 | def checkGradient(Lambda = 0): 636 | '''构造一个小型的神经网络验证,因为数值法计算梯度很浪费时间,而且验证正确后之后就不再需要验证了''' 637 | input_layer_size = 3 638 | hidden_layer_size = 5 639 | num_labels = 3 640 | m = 5 641 | initial_Theta1 = debugInitializeWeights(input_layer_size,hidden_layer_size); 642 | initial_Theta2 = debugInitializeWeights(hidden_layer_size,num_labels) 643 | X = debugInitializeWeights(input_layer_size-1,m) 644 | y = 1+np.transpose(np.mod(np.arange(1,m+1), num_labels))# 初始化y 645 | 646 | y = y.reshape(-1,1) 647 | nn_params = np.vstack((initial_Theta1.reshape(-1,1),initial_Theta2.reshape(-1,1))) #展开theta 648 | '''BP求出梯度''' 649 | grad = nnGradient(nn_params, input_layer_size, hidden_layer_size, 650 | num_labels, X, y, Lambda) 651 | '''使用数值法计算梯度''' 652 | num_grad = np.zeros((nn_params.shape[0])) 653 | step = np.zeros((nn_params.shape[0])) 654 | e = 1e-4 655 | for i in range(nn_params.shape[0]): 656 | step[i] = e 657 | loss1 = nnCostFunction(nn_params-step.reshape(-1,1), input_layer_size, hidden_layer_size, 658 | num_labels, X, y, 659 | Lambda) 660 | loss2 = nnCostFunction(nn_params+step.reshape(-1,1), input_layer_size, hidden_layer_size, 661 | num_labels, X, y, 662 | Lambda) 663 | num_grad[i] = (loss2-loss1)/(2*e) 664 | step[i]=0 665 | # 显示两列比较 666 | res = np.hstack((num_grad.reshape(-1,1),grad.reshape(-1,1))) 667 | print res 668 | ``` 669 | 670 | ### 7、权重的随机初始化 671 | - 神经网络不能像逻辑回归那样初始化`theta`为`0`,因为若是每条边的权重都为0,每个神经元都是相同的输出,在反向传播中也会得到同样的梯度,最终只会预测一种结果。 672 | - 所以应该初始化为接近0的数 673 | - 实现代码 674 | ``` 675 | # 随机初始化权重theta 676 | def randInitializeWeights(L_in,L_out): 677 | W = np.zeros((L_out,1+L_in)) # 对应theta的权重 678 | epsilon_init = (6.0/(L_out+L_in))**0.5 679 | W = np.random.rand(L_out,1+L_in)*2*epsilon_init-epsilon_init # np.random.rand(L_out,1+L_in)产生L_out*(1+L_in)大小的随机矩阵 680 | return W 681 | ``` 682 | 683 | ### 8、预测 684 | - 正向传播预测结果 685 | - 实现代码 686 | ``` 687 | # 预测 688 | def predict(Theta1,Theta2,X): 689 | m = X.shape[0] 690 | num_labels = Theta2.shape[0] 691 | #p = np.zeros((m,1)) 692 | '''正向传播,预测结果''' 693 | X = np.hstack((np.ones((m,1)),X)) 694 | h1 = sigmoid(np.dot(X,np.transpose(Theta1))) 695 | h1 = np.hstack((np.ones((m,1)),h1)) 696 | h2 = sigmoid(np.dot(h1,np.transpose(Theta2))) 697 | 698 | ''' 699 | 返回h中每一行最大值所在的列号 700 | - np.max(h, axis=1)返回h中每一行的最大值(是某个数字的最大概率) 701 | - 最后where找到的最大概率所在的列号(列号即是对应的数字) 702 | ''' 703 | #np.savetxt("h2.csv",h2,delimiter=',') 704 | p = np.array(np.where(h2[0,:] == np.max(h2, axis=1)[0])) 705 | for i in np.arange(1, m): 706 | t = np.array(np.where(h2[i,:] == np.max(h2, axis=1)[i])) 707 | p = np.vstack((p,t)) 708 | return p 709 | ``` 710 | 711 | ### 9、输出结果 712 | - 梯度检查: 713 | ![enter description here][19] 714 | - 随机显示100个手写数字 715 | ![enter description here][20] 716 | - 显示theta1权重 717 | ![enter description here][21] 718 | - 训练集预测准确度 719 | ![enter description here][22] 720 | - 归一化后训练集预测准确度 721 | ![enter description here][23] 722 | 723 | -------------------- 724 | 725 | ## 四、SVM支持向量机 726 | 727 | ### 1、代价函数 728 | - 在逻辑回归中,我们的代价为: 729 | ![\cos t({h_\theta }(x),y) = \left\{ {\begin{array}{c} { - \log ({h_\theta }(x))} \\ { - \log (1 - {h_\theta }(x))} \end{array} \begin{array}{c} {y = 1} \\ {y = 0} \end{array} } \right.](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Ccos%20t%28%7Bh_%5Ctheta%20%7D%28x%29%2Cy%29%20%3D%20%5Cleft%5C%7B%20%7B%5Cbegin%7Barray%7D%7Bc%7D%20%20%20%20%7B%20-%20%5Clog%20%28%7Bh_%5Ctheta%20%7D%28x%29%29%7D%20%5C%5C%20%20%20%20%7B%20-%20%5Clog%20%281%20-%20%7Bh_%5Ctheta%20%7D%28x%29%29%7D%20%20%5Cend%7Barray%7D%20%5Cbegin%7Barray%7D%7Bc%7D%20%20%20%20%7By%20%3D%201%7D%20%5C%5C%20%20%20%20%7By%20%3D%200%7D%20%20%5Cend%7Barray%7D%20%7D%20%5Cright.), 730 | 其中:![{h_\theta }({\text{z}}) = \frac{1}{{1 + {e^{ - z}}}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bh_%5Ctheta%20%7D%28%7B%5Ctext%7Bz%7D%7D%29%20%3D%20%5Cfrac%7B1%7D%7B%7B1%20%2B%20%7Be%5E%7B%20-%20z%7D%7D%7D%7D),![z = {\theta ^T}x](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=z%20%3D%20%7B%5Ctheta%20%5ET%7Dx) 731 | - 如图所示,如果`y=1`,`cost`代价函数如图所示 732 | ![enter description here][24] 733 | 我们想让![{\theta ^T}x > > 0](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%5Ctheta%20%5ET%7Dx%20%3E%20%20%3E%200),即`z>>0`,这样的话`cost`代价函数才会趋于最小(这是我们想要的),所以用途中**红色**的函数![\cos {t_1}(z)](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Ccos%20%7Bt_1%7D%28z%29)代替逻辑回归中的cost 734 | - 当`y=0`时同样,用![\cos {t_0}(z)](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Ccos%20%7Bt_0%7D%28z%29)代替 735 | ![enter description here][25] 736 | - 最终得到的代价函数为: 737 | ![J(\theta ) = C\sum\limits_{i = 1}^m {[{y^{(i)}}\cos {t_1}({\theta ^T}{x^{(i)}}) + (1 - {y^{(i)}})\cos {t_0}({\theta ^T}{x^{(i)}})} ] + \frac{1}{2}\sum\limits_{j = 1}^{\text{n}} {\theta _j^2} ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=J%28%5Ctheta%20%29%20%3D%20C%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%5B%7By%5E%7B%28i%29%7D%7D%5Ccos%20%7Bt_1%7D%28%7B%5Ctheta%20%5ET%7D%7Bx%5E%7B%28i%29%7D%7D%29%20%2B%20%281%20-%20%7By%5E%7B%28i%29%7D%7D%29%5Ccos%20%7Bt_0%7D%28%7B%5Ctheta%20%5ET%7D%7Bx%5E%7B%28i%29%7D%7D%29%7D%20%5D%20%2B%20%5Cfrac%7B1%7D%7B2%7D%5Csum%5Climits_%7Bj%20%3D%201%7D%5E%7B%5Ctext%7Bn%7D%7D%20%7B%5Ctheta%20_j%5E2%7D%20) 738 | 最后我们想要![\mathop {\min }\limits_\theta J(\theta )](http://latex.codecogs.com/gif.latex?%5Clarge%20%5Cmathop%20%7B%5Cmin%20%7D%5Climits_%5Ctheta%20J%28%5Ctheta%20%29) 739 | - 之前我们逻辑回归中的代价函数为: 740 | ![J(\theta ) = - \frac{1}{m}\sum\limits_{i = 1}^m {[{y^{(i)}}\log ({h_\theta }({x^{(i)}}) + (1 - } {y^{(i)}})\log (1 - {h_\theta }({x^{(i)}})] + \frac{\lambda }{{2m}}\sum\limits_{j = 1}^n {\theta _j^2} ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=J%28%5Ctheta%20%29%20%3D%20%20-%20%5Cfrac%7B1%7D%7Bm%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%5B%7By%5E%7B%28i%29%7D%7D%5Clog%20%28%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%20%2B%20%281%20-%20%7D%20%7By%5E%7B%28i%29%7D%7D%29%5Clog%20%281%20-%20%7Bh_%5Ctheta%20%7D%28%7Bx%5E%7B%28i%29%7D%7D%29%5D%20%2B%20%5Cfrac%7B%5Clambda%20%7D%7B%7B2m%7D%7D%5Csum%5Climits_%7Bj%20%3D%201%7D%5En%20%7B%5Ctheta%20_j%5E2%7D%20) 741 | 可以认为这里的![C = \frac{m}{\lambda }](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=C%20%3D%20%5Cfrac%7Bm%7D%7B%5Clambda%20%7D),只是表达形式问题,这里`C`的值越大,SVM的决策边界的`margin`也越大,下面会说明 742 | 743 | ### 2、Large Margin 744 | - 如下图所示,SVM分类会使用最大的`margin`将其分开 745 | ![enter description here][26] 746 | - 先说一下向量内积 747 | - ![u = \left[ {\begin{array}{c} {{u_1}} \\ {{u_2}} \end{array} } \right]](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=u%20%3D%20%5Cleft%5B%20%7B%5Cbegin%7Barray%7D%7Bc%7D%20%20%20%20%7B%7Bu_1%7D%7D%20%5C%5C%20%20%20%20%7B%7Bu_2%7D%7D%20%20%5Cend%7Barray%7D%20%7D%20%5Cright%5D),![v = \left[ {\begin{array}{c} {{v_1}} \\ {{v_2}} \end{array} } \right]](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=v%20%3D%20%5Cleft%5B%20%7B%5Cbegin%7Barray%7D%7Bc%7D%20%20%20%20%7B%7Bv_1%7D%7D%20%5C%5C%20%20%20%20%7B%7Bv_2%7D%7D%20%20%5Cend%7Barray%7D%20%7D%20%5Cright%5D) 748 | - ![||u||](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7C%7Cu%7C%7C)表示`u`的**欧几里得范数**(欧式范数),![||u||{\text{ = }}\sqrt {{\text{u}}_1^2 + u_2^2} ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7C%7Cu%7C%7C%7B%5Ctext%7B%20%3D%20%7D%7D%5Csqrt%20%7B%7B%5Ctext%7Bu%7D%7D_1%5E2%20%2B%20u_2%5E2%7D%20) 749 | - `向量V`在`向量u`上的投影的长度记为`p`,则:向量内积: 750 | ![{{\text{u}}^T}v = p||u|| = {u_1}{v_1} + {u_2}{v_2}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7B%7B%5Ctext%7Bu%7D%7D%5ET%7Dv%20%3D%20p%7C%7Cu%7C%7C%20%3D%20%7Bu_1%7D%7Bv_1%7D%20%2B%20%7Bu_2%7D%7Bv_2%7D) 751 | ![enter description here][27] 752 | 根据向量夹角公式推导一下即可,![\cos \theta = \frac{{\overrightarrow {\text{u}} \overrightarrow v }}{{|\overrightarrow {\text{u}} ||\overrightarrow v |}}](http://latex.codecogs.com/gif.latex?%5Clarge%20%5Ccos%20%5Ctheta%20%3D%20%5Cfrac%7B%7B%5Coverrightarrow%20%7B%5Ctext%7Bu%7D%7D%20%5Coverrightarrow%20v%20%7D%7D%7B%7B%7C%5Coverrightarrow%20%7B%5Ctext%7Bu%7D%7D%20%7C%7C%5Coverrightarrow%20v%20%7C%7D%7D) 753 | 754 | - 前面说过,当`C`越大时,`margin`也就越大,我们的目的是最小化代价函数`J(θ)`,当`margin`最大时,`C`的乘积项![\sum\limits_{i = 1}^m {[{y^{(i)}}\cos {t_1}({\theta ^T}{x^{(i)}}) + (1 - {y^{(i)}})\cos {t_0}({\theta ^T}{x^{(i)}})} ]](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%5B%7By%5E%7B%28i%29%7D%7D%5Ccos%20%7Bt_1%7D%28%7B%5Ctheta%20%5ET%7D%7Bx%5E%7B%28i%29%7D%7D%29%20%2B%20%281%20-%20%7By%5E%7B%28i%29%7D%7D%29%5Ccos%20%7Bt_0%7D%28%7B%5Ctheta%20%5ET%7D%7Bx%5E%7B%28i%29%7D%7D%29%7D%20%5D)要很小,所以近似为: 755 | ![J(\theta ) = C0 + \frac{1}{2}\sum\limits_{j = 1}^{\text{n}} {\theta _j^2} = \frac{1}{2}\sum\limits_{j = 1}^{\text{n}} {\theta _j^2} = \frac{1}{2}(\theta _1^2 + \theta _2^2) = \frac{1}{2}{\sqrt {\theta _1^2 + \theta _2^2} ^2}](http://latex.codecogs.com/gif.latex?%5Clarge%20J%28%5Ctheta%20%29%20%3D%20C0%20+%20%5Cfrac%7B1%7D%7B2%7D%5Csum%5Climits_%7Bj%20%3D%201%7D%5E%7B%5Ctext%7Bn%7D%7D%20%7B%5Ctheta%20_j%5E2%7D%20%3D%20%5Cfrac%7B1%7D%7B2%7D%5Csum%5Climits_%7Bj%20%3D%201%7D%5E%7B%5Ctext%7Bn%7D%7D%20%7B%5Ctheta%20_j%5E2%7D%20%3D%20%5Cfrac%7B1%7D%7B2%7D%28%5Ctheta%20_1%5E2%20+%20%5Ctheta%20_2%5E2%29%20%3D%20%5Cfrac%7B1%7D%7B2%7D%7B%5Csqrt%20%7B%5Ctheta%20_1%5E2%20+%20%5Ctheta%20_2%5E2%7D%20%5E2%7D), 756 | 我们最后的目的就是求使代价最小的`θ` 757 | - 由 758 | ![\left\{ {\begin{array}{c} {{\theta ^T}{x^{(i)}} \geqslant 1} \\ {{\theta ^T}{x^{(i)}} \leqslant - 1} \end{array} } \right.\begin{array}{c} {({y^{(i)}} = 1)} \\ {({y^{(i)}} = 0)} \end{array} ](http://latex.codecogs.com/gif.latex?%5Clarge%20%5Cleft%5C%7B%20%7B%5Cbegin%7Barray%7D%7Bc%7D%20%7B%7B%5Ctheta%20%5ET%7D%7Bx%5E%7B%28i%29%7D%7D%20%5Cgeqslant%201%7D%20%5C%5C%20%7B%7B%5Ctheta%20%5ET%7D%7Bx%5E%7B%28i%29%7D%7D%20%5Cleqslant%20-%201%7D%20%5Cend%7Barray%7D%20%7D%20%5Cright.%5Cbegin%7Barray%7D%7Bc%7D%20%7B%28%7By%5E%7B%28i%29%7D%7D%20%3D%201%29%7D%20%5C%5C%20%7B%28%7By%5E%7B%28i%29%7D%7D%20%3D%200%29%7D%20%5Cend%7Barray%7D)可以得到: 759 | ![\left\{ {\begin{array}{c} {{p^{(i)}}||\theta || \geqslant 1} \\ {{p^{(i)}}||\theta || \leqslant - 1} \end{array} } \right.\begin{array}{c} {({y^{(i)}} = 1)} \\ {({y^{(i)}} = 0)} \end{array} ](http://latex.codecogs.com/gif.latex?%5Clarge%20%5Cleft%5C%7B%20%7B%5Cbegin%7Barray%7D%7Bc%7D%20%7B%7Bp%5E%7B%28i%29%7D%7D%7C%7C%5Ctheta%20%7C%7C%20%5Cgeqslant%201%7D%20%5C%5C%20%7B%7Bp%5E%7B%28i%29%7D%7D%7C%7C%5Ctheta%20%7C%7C%20%5Cleqslant%20-%201%7D%20%5Cend%7Barray%7D%20%7D%20%5Cright.%5Cbegin%7Barray%7D%7Bc%7D%20%7B%28%7By%5E%7B%28i%29%7D%7D%20%3D%201%29%7D%20%5C%5C%20%7B%28%7By%5E%7B%28i%29%7D%7D%20%3D%200%29%7D%20%5Cend%7Barray%7D),`p`即为`x`在`θ`上的投影 760 | - 如下图所示,假设决策边界如图,找其中的一个点,到`θ`上的投影为`p`,则![p||\theta || \geqslant 1](http://latex.codecogs.com/gif.latex?%5Clarge%20p%7C%7C%5Ctheta%20%7C%7C%20%5Cgeqslant%201)或者![p||\theta || \leqslant - 1](http://latex.codecogs.com/gif.latex?%5Clarge%20p%7C%7C%5Ctheta%20%7C%7C%20%5Cleqslant%20-%201),若是`p`很小,则需要![||\theta ||](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7C%7C%5Ctheta%20%7C%7C)很大,这与我们要求的`θ`使![||\theta || = \frac{1}{2}\sqrt {\theta _1^2 + \theta _2^2} ](http://latex.codecogs.com/gif.latex?%5Clarge%20%7C%7C%5Ctheta%20%7C%7C%20%3D%20%5Cfrac%7B1%7D%7B2%7D%5Csqrt%20%7B%5Ctheta%20_1%5E2%20+%20%5Ctheta%20_2%5E2%7D)最小相违背,**所以**最后求的是`large margin` 761 | ![enter description here][28] 762 | 763 | ### 3、SVM Kernel(核函数) 764 | - 对于线性可分的问题,使用**线性核函数**即可 765 | - 对于线性不可分的问题,在逻辑回归中,我们是将`feature`映射为使用多项式的形式![1 + {x_1} + {x_2} + x_1^2 + {x_1}{x_2} + x_2^2](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=1%20%2B%20%7Bx_1%7D%20%2B%20%7Bx_2%7D%20%2B%20x_1%5E2%20%2B%20%7Bx_1%7D%7Bx_2%7D%20%2B%20x_2%5E2),`SVM`中也有**多项式核函数**,但是更常用的是**高斯核函数**,也称为**RBF核** 766 | - 高斯核函数为:![f(x) = {e^{ - \frac{{||x - u|{|^2}}}{{2{\sigma ^2}}}}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=f%28x%29%20%3D%20%7Be%5E%7B%20-%20%5Cfrac%7B%7B%7C%7Cx%20-%20u%7C%7B%7C%5E2%7D%7D%7D%7B%7B2%7B%5Csigma%20%5E2%7D%7D%7D%7D%7D) 767 | 假设如图几个点, 768 | ![enter description here][29] 769 | 令: 770 | ![{f_1} = similarity(x,{l^{(1)}}) = {e^{ - \frac{{||x - {l^{(1)}}|{|^2}}}{{2{\sigma ^2}}}}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bf_1%7D%20%3D%20similarity%28x%2C%7Bl%5E%7B%281%29%7D%7D%29%20%3D%20%7Be%5E%7B%20-%20%5Cfrac%7B%7B%7C%7Cx%20-%20%7Bl%5E%7B%281%29%7D%7D%7C%7B%7C%5E2%7D%7D%7D%7B%7B2%7B%5Csigma%20%5E2%7D%7D%7D%7D%7D) 771 | ![{f_2} = similarity(x,{l^{(2)}}) = {e^{ - \frac{{||x - {l^{(2)}}|{|^2}}}{{2{\sigma ^2}}}}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bf_2%7D%20%3D%20similarity%28x%2C%7Bl%5E%7B%282%29%7D%7D%29%20%3D%20%7Be%5E%7B%20-%20%5Cfrac%7B%7B%7C%7Cx%20-%20%7Bl%5E%7B%282%29%7D%7D%7C%7B%7C%5E2%7D%7D%7D%7B%7B2%7B%5Csigma%20%5E2%7D%7D%7D%7D%7D) 772 | . 773 | . 774 | . 775 | - 可以看出,若是`x`与![{l^{(1)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bl%5E%7B%281%29%7D%7D)距离较近,==》![{f_1} \approx {e^0} = 1](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bf_1%7D%20%5Capprox%20%7Be%5E0%7D%20%3D%201),(即相似度较大) 776 | 若是`x`与![{l^{(1)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bl%5E%7B%281%29%7D%7D)距离较远,==》![{f_2} \approx {e^{ - \infty }} = 0](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bf_2%7D%20%5Capprox%20%7Be%5E%7B%20-%20%5Cinfty%20%7D%7D%20%3D%200),(即相似度较低) 777 | - 高斯核函数的`σ`越小,`f`下降的越快 778 | ![enter description here][30] 779 | ![enter description here][31] 780 | 781 | - 如何选择初始的![{l^{(1)}}{l^{(2)}}{l^{(3)}}...](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bl%5E%7B%281%29%7D%7D%7Bl%5E%7B%282%29%7D%7D%7Bl%5E%7B%283%29%7D%7D...) 782 | - 训练集:![(({x^{(1)}},{y^{(1)}}),({x^{(2)}},{y^{(2)}}),...({x^{(m)}},{y^{(m)}}))](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%28%28%7Bx%5E%7B%281%29%7D%7D%2C%7By%5E%7B%281%29%7D%7D%29%2C%28%7Bx%5E%7B%282%29%7D%7D%2C%7By%5E%7B%282%29%7D%7D%29%2C...%28%7Bx%5E%7B%28m%29%7D%7D%2C%7By%5E%7B%28m%29%7D%7D%29%29) 783 | - 选择:![{l^{(1)}} = {x^{(1)}},{l^{(2)}} = {x^{(2)}}...{l^{(m)}} = {x^{(m)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bl%5E%7B%281%29%7D%7D%20%3D%20%7Bx%5E%7B%281%29%7D%7D%2C%7Bl%5E%7B%282%29%7D%7D%20%3D%20%7Bx%5E%7B%282%29%7D%7D...%7Bl%5E%7B%28m%29%7D%7D%20%3D%20%7Bx%5E%7B%28m%29%7D%7D) 784 | - 对于给出的`x`,计算`f`,令:![f_0^{(i)} = 1](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=f_0%5E%7B%28i%29%7D%20%3D%201)所以:![{f^{(i)}} \in {R^{m + 1}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bf%5E%7B%28i%29%7D%7D%20%5Cin%20%7BR%5E%7Bm%20%2B%201%7D%7D) 785 | - 最小化`J`求出`θ`, 786 | ![J(\theta ) = C\sum\limits_{i = 1}^m {[{y^{(i)}}\cos {t_1}({\theta ^T}{f^{(i)}}) + (1 - {y^{(i)}})\cos {t_0}({\theta ^T}{f^{(i)}})} ] + \frac{1}{2}\sum\limits_{j = 1}^{\text{n}} {\theta _j^2} ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=J%28%5Ctheta%20%29%20%3D%20C%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%5B%7By%5E%7B%28i%29%7D%7D%5Ccos%20%7Bt_1%7D%28%7B%5Ctheta%20%5ET%7D%7Bf%5E%7B%28i%29%7D%7D%29%20%2B%20%281%20-%20%7By%5E%7B%28i%29%7D%7D%29%5Ccos%20%7Bt_0%7D%28%7B%5Ctheta%20%5ET%7D%7Bf%5E%7B%28i%29%7D%7D%29%7D%20%5D%20%2B%20%5Cfrac%7B1%7D%7B2%7D%5Csum%5Climits_%7Bj%20%3D%201%7D%5E%7B%5Ctext%7Bn%7D%7D%20%7B%5Ctheta%20_j%5E2%7D%20) 787 | - 如果![{\theta ^T}f \geqslant 0](http://latex.codecogs.com/gif.latex?%5Clarge%20%7B%5Ctheta%20%5ET%7Df%20%5Cgeqslant%200),==》预测`y=1` 788 | 789 | ### 4、使用`scikit-learn`中的`SVM`模型代码 790 | - [全部代码](/SVM/SVM_scikit-learn.py) 791 | - 线性可分的,指定核函数为`linear`: 792 | ``` 793 | '''data1——线性分类''' 794 | data1 = spio.loadmat('data1.mat') 795 | X = data1['X'] 796 | y = data1['y'] 797 | y = np.ravel(y) 798 | plot_data(X,y) 799 | 800 | model = svm.SVC(C=1.0,kernel='linear').fit(X,y) # 指定核函数为线性核函数 801 | ``` 802 | - 非线性可分的,默认核函数为`rbf` 803 | ``` 804 | '''data2——非线性分类''' 805 | data2 = spio.loadmat('data2.mat') 806 | X = data2['X'] 807 | y = data2['y'] 808 | y = np.ravel(y) 809 | plt = plot_data(X,y) 810 | plt.show() 811 | 812 | model = svm.SVC(gamma=100).fit(X,y) # gamma为核函数的系数,值越大拟合的越好 813 | ``` 814 | ### 5、运行结果 815 | - 线性可分的决策边界: 816 | ![enter description here][32] 817 | - 线性不可分的决策边界: 818 | ![enter description here][33] 819 | 820 | -------------------------- 821 | 822 | ## 五、K-Means聚类算法 823 | - [全部代码](/K-Means/K-Menas.py) 824 | 825 | ### 1、聚类过程 826 | - 聚类属于无监督学习,不知道y的标记分为K类 827 | - K-Means算法分为两个步骤 828 | - 第一步:簇分配,随机选`K`个点作为中心,计算到这`K`个点的距离,分为`K`个簇 829 | - 第二步:移动聚类中心:重新计算每个**簇**的中心,移动中心,重复以上步骤。 830 | - 如下图所示: 831 | - 随机分配的聚类中心 832 | ![enter description here][34] 833 | - 重新计算聚类中心,移动一次 834 | ![enter description here][35] 835 | - 最后`10`步之后的聚类中心 836 | ![enter description here][36] 837 | 838 | - 计算每条数据到哪个中心最近实现代码: 839 | ``` 840 | # 找到每条数据距离哪个类中心最近 841 | def findClosestCentroids(X,initial_centroids): 842 | m = X.shape[0] # 数据条数 843 | K = initial_centroids.shape[0] # 类的总数 844 | dis = np.zeros((m,K)) # 存储计算每个点分别到K个类的距离 845 | idx = np.zeros((m,1)) # 要返回的每条数据属于哪个类 846 | 847 | '''计算每个点到每个类中心的距离''' 848 | for i in range(m): 849 | for j in range(K): 850 | dis[i,j] = np.dot((X[i,:]-initial_centroids[j,:]).reshape(1,-1),(X[i,:]-initial_centroids[j,:]).reshape(-1,1)) 851 | 852 | '''返回dis每一行的最小值对应的列号,即为对应的类别 853 | - np.min(dis, axis=1)返回每一行的最小值 854 | - np.where(dis == np.min(dis, axis=1).reshape(-1,1)) 返回对应最小值的坐标 855 | - 注意:可能最小值对应的坐标有多个,where都会找出来,所以返回时返回前m个需要的即可(因为对于多个最小值,属于哪个类别都可以) 856 | ''' 857 | dummy,idx = np.where(dis == np.min(dis, axis=1).reshape(-1,1)) 858 | return idx[0:dis.shape[0]] # 注意截取一下 859 | ``` 860 | - 计算类中心实现代码: 861 | ``` 862 | # 计算类中心 863 | def computerCentroids(X,idx,K): 864 | n = X.shape[1] 865 | centroids = np.zeros((K,n)) 866 | for i in range(K): 867 | centroids[i,:] = np.mean(X[np.ravel(idx==i),:], axis=0).reshape(1,-1) # 索引要是一维的,axis=0为每一列,idx==i一次找出属于哪一类的,然后计算均值 868 | return centroids 869 | ``` 870 | 871 | ### 2、目标函数 872 | - 也叫做**失真代价函数** 873 | - ![J({c^{(1)}}, \cdots ,{c^{(m)}},{u_1}, \cdots ,{u_k}) = \frac{1}{m}\sum\limits_{i = 1}^m {||{x^{(i)}} - {u_{{c^{(i)}}}}|{|^2}} ](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=J%28%7Bc%5E%7B%281%29%7D%7D%2C%20%5Ccdots%20%2C%7Bc%5E%7B%28m%29%7D%7D%2C%7Bu_1%7D%2C%20%5Ccdots%20%2C%7Bu_k%7D%29%20%3D%20%5Cfrac%7B1%7D%7Bm%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%7C%7C%7Bx%5E%7B%28i%29%7D%7D%20-%20%7Bu_%7B%7Bc%5E%7B%28i%29%7D%7D%7D%7D%7C%7B%7C%5E2%7D%7D%20) 874 | - 最后我们想得到: 875 | ![enter description here][37] 876 | - 其中![{c^{(i)}}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bc%5E%7B%28i%29%7D%7D)表示第`i`条数据距离哪个类中心最近, 877 | - 其中![{u_i}](http://chart.apis.google.com/chart?cht=tx&chs=1x0&chf=bg,s,FFFFFF00&chco=000000&chl=%7Bu_i%7D)即为聚类的中心 878 | 879 | ### 3、聚类中心的选择 880 | - 随机初始化,从给定的数据中随机抽取K个作为聚类中心 881 | - 随机一次的结果可能不好,可以随机多次,最后取使代价函数最小的作为中心 882 | - 实现代码:(这里随机一次) 883 | ``` 884 | # 初始化类中心--随机取K个点作为聚类中心 885 | def kMeansInitCentroids(X,K): 886 | m = X.shape[0] 887 | m_arr = np.arange(0,m) # 生成0-m-1 888 | centroids = np.zeros((K,X.shape[1])) 889 | np.random.shuffle(m_arr) # 打乱m_arr顺序 890 | rand_indices = m_arr[:K] # 取前K个 891 | centroids = X[rand_indices,:] 892 | return centroids 893 | ``` 894 | 895 | ### 4、聚类个数K的选择 896 | - 聚类是不知道y的label的,所以不知道真正的聚类个数 897 | - 肘部法则(Elbow method) 898 | - 作代价函数`J`和`K`的图,若是出现一个拐点,如下图所示,`K`就取拐点处的值,下图此时`K=3` 899 | ![enter description here][38] 900 | - 若是很平滑就不明确,人为选择。 901 | - 第二种就是人为观察选择 902 | 903 | ### 5、应用——图片压缩 904 | - 将图片的像素分为若干类,然后用这个类代替原来的像素值 905 | - 执行聚类的算法代码: 906 | > 这里要解释下为什么可以用作图像压缩。压缩其实就是减少了表示每像素的字节数,比如RGB32使用32位来表示一个像素,如果将像素值换成16位表示,则可以图片存储大小减少一半。如何做到呢?KMeans设置聚类中心为16个点,将图片像素聚类为16个簇,聚类完成后每个簇都可以用对应的聚类中心来表示,这个每个像素只占了2个字节。 907 | ``` 908 | # 聚类算法 909 | def runKMeans(X,initial_centroids,max_iters,plot_process): 910 | m,n = X.shape # 数据条数和维度 911 | K = initial_centroids.shape[0] # 类数 912 | centroids = initial_centroids # 记录当前类中心 913 | previous_centroids = centroids # 记录上一次类中心 914 | idx = np.zeros((m,1)) # 每条数据属于哪个类 915 | 916 | for i in range(max_iters): # 迭代次数 917 | print u'迭代计算次数:%d'%(i+1) 918 | idx = findClosestCentroids(X, centroids) 919 | if plot_process: # 如果绘制图像 920 | plt = plotProcessKMeans(X,centroids,previous_centroids) # 画聚类中心的移动过程 921 | previous_centroids = centroids # 重置 922 | centroids = computerCentroids(X, idx, K) # 重新计算类中心 923 | if plot_process: # 显示最终的绘制结果 924 | plt.show() 925 | return centroids,idx # 返回聚类中心和数据属于哪个类 926 | ``` 927 | 928 | ### 6、[使用scikit-learn库中的线性模型实现聚类](/K-Means/K-Means_scikit-learn.py) 929 | 930 | - 导入包 931 | ``` 932 | from sklearn.cluster import KMeans 933 | ``` 934 | - 使用模型拟合数据 935 | ``` 936 | model = KMeans(n_clusters=3).fit(X) # n_clusters指定3类,拟合数据 937 | ``` 938 | - 聚类中心 939 | ``` 940 | centroids = model.cluster_centers_ # 聚类中心 941 | ``` 942 | 943 | ### 7、运行结果 944 | - 二维数据类中心的移动 945 | ![enter description here][39] 946 | - 图片压缩 947 | ![enter description here][40] 948 | 949 | ---------------------- 950 | 951 | ## 六、PCA主成分分析(降维) 952 | - [全部代码](/PCA/PCA.py) 953 | 954 | ### 1、用处 955 | - 数据压缩(Data Compression),使程序运行更快 956 | - 可视化数据,例如`3D-->2D`等 957 | - ...... 958 | 959 | ### 2、2D-->1D,nD-->kD 960 | - 如下图所示,所有数据点可以投影到一条直线,是**投影距离的平方和**(投影误差)最小 961 | ![enter description here][41] 962 | - 注意数据需要`归一化`处理 963 | - 思路是找`1`个`向量u`,所有数据投影到上面使投影距离最小 964 | - 那么`nD-->kD`就是找`k`个向量![$${u^{(1)}},{u^{(2)}} \ldots {u^{(k)}}$$](http://latex.codecogs.com/gif.latex?%24%24%7Bu%5E%7B%281%29%7D%7D%2C%7Bu%5E%7B%282%29%7D%7D%20%5Cldots%20%7Bu%5E%7B%28k%29%7D%7D%24%24),所有数据投影到上面使投影误差最小 965 | - eg:3D-->2D,2个向量![$${u^{(1)}},{u^{(2)}}$$](http://latex.codecogs.com/gif.latex?%24%24%7Bu%5E%7B%281%29%7D%7D%2C%7Bu%5E%7B%282%29%7D%7D%24%24)就代表一个平面了,所有点投影到这个平面的投影误差最小即可 966 | 967 | ### 3、主成分分析PCA与线性回归的区别 968 | - 线性回归是找`x`与`y`的关系,然后用于预测`y` 969 | - `PCA`是找一个投影面,最小化data到这个投影面的投影误差 970 | 971 | ### 4、PCA降维过程 972 | - 数据预处理(均值归一化) 973 | - 公式:![$${\rm{x}}_j^{(i)} = {{{\rm{x}}_j^{(i)} - {u_j}} \over {{s_j}}}$$](http://latex.codecogs.com/gif.latex?%24%24%7B%5Crm%7Bx%7D%7D_j%5E%7B%28i%29%7D%20%3D%20%7B%7B%7B%5Crm%7Bx%7D%7D_j%5E%7B%28i%29%7D%20-%20%7Bu_j%7D%7D%20%5Cover%20%7B%7Bs_j%7D%7D%7D%24%24) 974 | - 就是减去对应feature的均值,然后除以对应特征的标准差(也可以是最大值-最小值) 975 | - 实现代码: 976 | ``` 977 | # 归一化数据 978 | def featureNormalize(X): 979 | '''(每一个数据-当前列的均值)/当前列的标准差''' 980 | n = X.shape[1] 981 | mu = np.zeros((1,n)); 982 | sigma = np.zeros((1,n)) 983 | 984 | mu = np.mean(X,axis=0) 985 | sigma = np.std(X,axis=0) 986 | for i in range(n): 987 | X[:,i] = (X[:,i]-mu[i])/sigma[i] 988 | return X,mu,sigma 989 | ``` 990 | - 计算`协方差矩阵Σ`(Covariance Matrix):![$$\Sigma = {1 \over m}\sum\limits_{i = 1}^n {{x^{(i)}}{{({x^{(i)}})}^T}} $$](http://latex.codecogs.com/gif.latex?%24%24%5CSigma%20%3D%20%7B1%20%5Cover%20m%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5En%20%7B%7Bx%5E%7B%28i%29%7D%7D%7B%7B%28%7Bx%5E%7B%28i%29%7D%7D%29%7D%5ET%7D%7D%20%24%24) 991 | - 注意这里的`Σ`和求和符号不同 992 | - 协方差矩阵`对称正定`(不理解正定的看看线代) 993 | - 大小为`nxn`,`n`为`feature`的维度 994 | - 实现代码: 995 | ``` 996 | Sigma = np.dot(np.transpose(X_norm),X_norm)/m # 求Sigma 997 | ``` 998 | - 计算`Σ`的特征值和特征向量 999 | - 可以是用`svd`奇异值分解函数:`U,S,V = svd(Σ)` 1000 | - 返回的是与`Σ`同样大小的对角阵`S`(由`Σ`的特征值组成)[**注意**:`matlab`中函数返回的是对角阵,在`python`中返回的是一个向量,节省空间] 1001 | - 还有两个**酉矩阵**U和V,且![$$\Sigma = US{V^T}$$](http://latex.codecogs.com/gif.latex?%24%24%5CSigma%20%3D%20US%7BV%5ET%7D%24%24) 1002 | - ![enter description here][42] 1003 | - **注意**:`svd`函数求出的`S`是按特征值降序排列的,若不是使用`svd`,需要按**特征值**大小重新排列`U` 1004 | - 降维 1005 | - 选取`U`中的前`K`列(假设要降为`K`维) 1006 | - ![enter description here][43] 1007 | - `Z`就是对应降维之后的数据 1008 | - 实现代码: 1009 | ``` 1010 | # 映射数据 1011 | def projectData(X_norm,U,K): 1012 | Z = np.zeros((X_norm.shape[0],K)) 1013 | 1014 | U_reduce = U[:,0:K] # 取前K个 1015 | Z = np.dot(X_norm,U_reduce) 1016 | return Z 1017 | ``` 1018 | - 过程总结: 1019 | - `Sigma = X'*X/m` 1020 | - `U,S,V = svd(Sigma)` 1021 | - `Ureduce = U[:,0:k]` 1022 | - `Z = Ureduce'*x` 1023 | 1024 | ### 5、数据恢复 1025 | - 因为:![$${Z^{(i)}} = U_{reduce}^T*{X^{(i)}}$$](http://latex.codecogs.com/gif.latex?%5Cfn_cm%20%24%24%7BZ%5E%7B%28i%29%7D%7D%20%3D%20U_%7Breduce%7D%5ET*%7BX%5E%7B%28i%29%7D%7D%24%24) 1026 | - 所以:![$${X_{approx}} = {(U_{reduce}^T)^{ - 1}}Z$$](http://latex.codecogs.com/gif.latex?%5Cfn_cm%20%24%24%7BX_%7Bapprox%7D%7D%20%3D%20%7B%28U_%7Breduce%7D%5ET%29%5E%7B%20-%201%7D%7DZ%24%24) (注意这里是X的近似值) 1027 | - 又因为`Ureduce`为正定矩阵,【正定矩阵满足:![$$A{A^T} = {A^T}A = E$$](http://latex.codecogs.com/gif.latex?%5Cfn_cm%20%24%24A%7BA%5ET%7D%20%3D%20%7BA%5ET%7DA%20%3D%20E%24%24),所以:![$${A^{ - 1}} = {A^T}$$](http://latex.codecogs.com/gif.latex?%5Cfn_cm%20%24%24%7BA%5E%7B%20-%201%7D%7D%20%3D%20%7BA%5ET%7D%24%24)】,所以这里: 1028 | - ![$${X_{approx}} = {(U_{reduce}^{ - 1})^{ - 1}}Z = {U_{reduce}}Z$$](http://latex.codecogs.com/gif.latex?%5Cfn_cm%20%24%24%7BX_%7Bapprox%7D%7D%20%3D%20%7B%28U_%7Breduce%7D%5E%7B%20-%201%7D%29%5E%7B%20-%201%7D%7DZ%20%3D%20%7BU_%7Breduce%7D%7DZ%24%24) 1029 | - 实现代码: 1030 | ``` 1031 | # 恢复数据 1032 | def recoverData(Z,U,K): 1033 | X_rec = np.zeros((Z.shape[0],U.shape[0])) 1034 | U_recude = U[:,0:K] 1035 | X_rec = np.dot(Z,np.transpose(U_recude)) # 还原数据(近似) 1036 | return X_rec 1037 | ``` 1038 | 1039 | ### 6、主成分个数的选择(即要降的维度) 1040 | - 如何选择 1041 | - **投影误差**(project error):![$${1 \over m}\sum\limits_{i = 1}^m {||{x^{(i)}} - x_{approx}^{(i)}|{|^2}} $$](http://latex.codecogs.com/gif.latex?%5Cfn_cm%20%24%24%7B1%20%5Cover%20m%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%7C%7C%7Bx%5E%7B%28i%29%7D%7D%20-%20x_%7Bapprox%7D%5E%7B%28i%29%7D%7C%7B%7C%5E2%7D%7D%20%24%24) 1042 | - **总变差**(total variation):![$${1 \over m}\sum\limits_{i = 1}^m {||{x^{(i)}}|{|^2}} $$](http://latex.codecogs.com/gif.latex?%5Cfn_cm%20%24%24%7B1%20%5Cover%20m%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%7C%7C%7Bx%5E%7B%28i%29%7D%7D%7C%7B%7C%5E2%7D%7D%20%24%24) 1043 | - 若**误差率**(error ratio):![$${{{1 \over m}\sum\limits_{i = 1}^m {||{x^{(i)}} - x_{approx}^{(i)}|{|^2}} } \over {{1 \over m}\sum\limits_{i = 1}^m {||{x^{(i)}}|{|^2}} }} \le 0.01$$](http://latex.codecogs.com/gif.latex?%5Cfn_cm%20%24%24%7B%7B%7B1%20%5Cover%20m%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%7C%7C%7Bx%5E%7B%28i%29%7D%7D%20-%20x_%7Bapprox%7D%5E%7B%28i%29%7D%7C%7B%7C%5E2%7D%7D%20%7D%20%5Cover%20%7B%7B1%20%5Cover%20m%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%7C%7C%7Bx%5E%7B%28i%29%7D%7D%7C%7B%7C%5E2%7D%7D%20%7D%7D%20%5Cle%200.01%24%24),则称`99%`保留差异性 1044 | - 误差率一般取`1%,5%,10%`等 1045 | - 如何实现 1046 | - 若是一个个试的话代价太大 1047 | - 之前`U,S,V = svd(Sigma)`,我们得到了`S`,这里误差率error ratio: 1048 | ![$$error{\kern 1pt} \;ratio = 1 - {{\sum\limits_{i = 1}^k {{S_{ii}}} } \over {\sum\limits_{i = 1}^n {{S_{ii}}} }} \le threshold$$](http://latex.codecogs.com/gif.latex?%5Cfn_cm%20%24%24error%7B%5Ckern%201pt%7D%20%5C%3Bratio%20%3D%201%20-%20%7B%7B%5Csum%5Climits_%7Bi%20%3D%201%7D%5Ek%20%7B%7BS_%7Bii%7D%7D%7D%20%7D%20%5Cover%20%7B%5Csum%5Climits_%7Bi%20%3D%201%7D%5En%20%7B%7BS_%7Bii%7D%7D%7D%20%7D%7D%20%5Cle%20threshold%24%24) 1049 | - 可以一点点增加`K`尝试。 1050 | 1051 | ### 7、使用建议 1052 | - 不要使用PCA去解决过拟合问题`Overfitting`,还是使用正则化的方法(如果保留了很高的差异性还是可以的) 1053 | - 只有在原数据上有好的结果,但是运行很慢,才考虑使用PCA 1054 | 1055 | ### 8、运行结果 1056 | - 2维数据降为1维 1057 | - 要投影的方向 1058 | ![enter description here][44] 1059 | - 2D降为1D及对应关系 1060 | ![enter description here][45] 1061 | - 人脸数据降维 1062 | - 原始数据 1063 | ![enter description here][46] 1064 | - 可视化部分`U`矩阵信息 1065 | ![enter description here][47] 1066 | - 恢复数据 1067 | ![enter description here][48] 1068 | 1069 | ### 9、[使用scikit-learn库中的PCA实现降维](/PCA/PCA.py_scikit-learn.py) 1070 | - 导入需要的包: 1071 | ``` 1072 | #-*- coding: utf-8 -*- 1073 | # Author:bob 1074 | # Date:2016.12.22 1075 | import numpy as np 1076 | from matplotlib import pyplot as plt 1077 | from scipy import io as spio 1078 | from sklearn.decomposition import pca 1079 | from sklearn.preprocessing import StandardScaler 1080 | ``` 1081 | - 归一化数据 1082 | ``` 1083 | '''归一化数据并作图''' 1084 | scaler = StandardScaler() 1085 | scaler.fit(X) 1086 | x_train = scaler.transform(X) 1087 | ``` 1088 | - 使用PCA模型拟合数据,并降维 1089 | - `n_components`对应要将的维度 1090 | ``` 1091 | '''拟合数据''' 1092 | K=1 # 要降的维度 1093 | model = pca.PCA(n_components=K).fit(x_train) # 拟合数据,n_components定义要降的维度 1094 | Z = model.transform(x_train) # transform就会执行降维操作 1095 | ``` 1096 | 1097 | - 数据恢复 1098 | - `model.components_`会得到降维使用的`U`矩阵 1099 | ``` 1100 | '''数据恢复并作图''' 1101 | Ureduce = model.components_ # 得到降维用的Ureduce 1102 | x_rec = np.dot(Z,Ureduce) # 数据恢复 1103 | ``` 1104 | 1105 | 1106 | 1107 | --------------------------------------------------------------- 1108 | 1109 | 1110 | ## 七、异常检测 Anomaly Detection 1111 | - [全部代码](/AnomalyDetection/AnomalyDetection.py) 1112 | 1113 | ### 1、高斯分布(正态分布)`Gaussian distribution` 1114 | - 分布函数:![$$p(x) = {1 \over {\sqrt {2\pi } \sigma }}{e^{ - {{{{(x - u)}^2}} \over {2{\sigma ^2}}}}}$$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24p%28x%29%20%3D%20%7B1%20%5Cover%20%7B%5Csqrt%20%7B2%5Cpi%20%7D%20%5Csigma%20%7D%7D%7Be%5E%7B%20-%20%7B%7B%7B%7B%28x%20-%20u%29%7D%5E2%7D%7D%20%5Cover%20%7B2%7B%5Csigma%20%5E2%7D%7D%7D%7D%7D%24%24) 1115 | - 其中,`u`为数据的**均值**,`σ`为数据的**标准差** 1116 | - `σ`越**小**,对应的图像越**尖** 1117 | - 参数估计(`parameter estimation`) 1118 | - ![$$u = {1 \over m}\sum\limits_{i = 1}^m {{x^{(i)}}} $$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24u%20%3D%20%7B1%20%5Cover%20m%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%7Bx%5E%7B%28i%29%7D%7D%7D%20%24%24) 1119 | - ![$${\sigma ^2} = {1 \over m}\sum\limits_{i = 1}^m {{{({x^{(i)}} - u)}^2}} $$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24%7B%5Csigma%20%5E2%7D%20%3D%20%7B1%20%5Cover%20m%7D%5Csum%5Climits_%7Bi%20%3D%201%7D%5Em%20%7B%7B%7B%28%7Bx%5E%7B%28i%29%7D%7D%20-%20u%29%7D%5E2%7D%7D%20%24%24) 1120 | 1121 | ### 2、异常检测算法 1122 | - 例子 1123 | - 训练集:![$$\{ {x^{(1)}},{x^{(2)}}, \cdots {x^{(m)}}\} $$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24%5C%7B%20%7Bx%5E%7B%281%29%7D%7D%2C%7Bx%5E%7B%282%29%7D%7D%2C%20%5Ccdots%20%7Bx%5E%7B%28m%29%7D%7D%5C%7D%20%24%24),其中![$$x \in {R^n}$$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24x%20%5Cin%20%7BR%5En%7D%24%24) 1124 | - 假设![$${x_1},{x_2} \cdots {x_n}$$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24%7Bx_1%7D%2C%7Bx_2%7D%20%5Ccdots%20%7Bx_n%7D%24%24)相互独立,建立model模型:![$$p(x) = p({x_1};{u_1},\sigma _1^2)p({x_2};{u_2},\sigma _2^2) \cdots p({x_n};{u_n},\sigma _n^2) = \prod\limits_{j = 1}^n {p({x_j};{u_j},\sigma _j^2)} $$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24p%28x%29%20%3D%20p%28%7Bx_1%7D%3B%7Bu_1%7D%2C%5Csigma%20_1%5E2%29p%28%7Bx_2%7D%3B%7Bu_2%7D%2C%5Csigma%20_2%5E2%29%20%5Ccdots%20p%28%7Bx_n%7D%3B%7Bu_n%7D%2C%5Csigma%20_n%5E2%29%20%3D%20%5Cprod%5Climits_%7Bj%20%3D%201%7D%5En%20%7Bp%28%7Bx_j%7D%3B%7Bu_j%7D%2C%5Csigma%20_j%5E2%29%7D%20%24%24) 1125 | - 过程 1126 | - 选择具有代表异常的`feature`:xi 1127 | - 参数估计:![$${u_1},{u_2}, \cdots ,{u_n};\sigma _1^2,\sigma _2^2 \cdots ,\sigma _n^2$$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24%7Bu_1%7D%2C%7Bu_2%7D%2C%20%5Ccdots%20%2C%7Bu_n%7D%3B%5Csigma%20_1%5E2%2C%5Csigma%20_2%5E2%20%5Ccdots%20%2C%5Csigma%20_n%5E2%24%24) 1128 | - 计算`p(x)`,若是`P(x)<ε`则认为异常,其中`ε`为我们要求的概率的临界值`threshold` 1129 | - 这里只是**单元高斯分布**,假设了`feature`之间是独立的,下面会讲到**多元高斯分布**,会自动捕捉到`feature`之间的关系 1130 | - **参数估计**实现代码 1131 | ``` 1132 | # 参数估计函数(就是求均值和方差) 1133 | def estimateGaussian(X): 1134 | m,n = X.shape 1135 | mu = np.zeros((n,1)) 1136 | sigma2 = np.zeros((n,1)) 1137 | 1138 | mu = np.mean(X, axis=0) # axis=0表示列,每列的均值 1139 | sigma2 = np.var(X,axis=0) # 求每列的方差 1140 | return mu,sigma2 1141 | ``` 1142 | 1143 | ### 3、评价`p(x)`的好坏,以及`ε`的选取 1144 | - 对**偏斜数据**的错误度量 1145 | - 因为数据可能是非常**偏斜**的(就是`y=1`的个数非常少,(`y=1`表示异常)),所以可以使用`Precision/Recall`,计算`F1Score`(在**CV交叉验证集**上) 1146 | - 例如:预测癌症,假设模型可以得到`99%`能够预测正确,`1%`的错误率,但是实际癌症的概率很小,只有`0.5%`,那么我们始终预测没有癌症y=0反而可以得到更小的错误率。使用`error rate`来评估就不科学了。 1147 | - 如下图记录: 1148 | ![enter description here][49] 1149 | - ![$$\Pr ecision = {{TP} \over {TP + FP}}$$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24%5CPr%20ecision%20%3D%20%7B%7BTP%7D%20%5Cover%20%7BTP%20+%20FP%7D%7D%24%24) ,即:**正确预测正样本/所有预测正样本** 1150 | - ![$${\mathop{\rm Re}\nolimits} {\rm{call}} = {{TP} \over {TP + FN}}$$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24%7B%5Cmathop%7B%5Crm%20Re%7D%5Cnolimits%7D%20%7B%5Crm%7Bcall%7D%7D%20%3D%20%7B%7BTP%7D%20%5Cover%20%7BTP%20+%20FN%7D%7D%24%24) ,即:**正确预测正样本/真实值为正样本** 1151 | - 总是让`y=1`(较少的类),计算`Precision`和`Recall` 1152 | - ![$${F_1}Score = 2{{PR} \over {P + R}}$$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24%7BF_1%7DScore%20%3D%202%7B%7BPR%7D%20%5Cover%20%7BP%20+%20R%7D%7D%24%24) 1153 | - 还是以癌症预测为例,假设预测都是no-cancer,TN=199,FN=1,TP=0,FP=0,所以:Precision=0/0,Recall=0/1=0,尽管accuracy=199/200=99.5%,但是不可信。 1154 | 1155 | - `ε`的选取 1156 | - 尝试多个`ε`值,使`F1Score`的值高 1157 | - 实现代码 1158 | ``` 1159 | # 选择最优的epsilon,即:使F1Score最大 1160 | def selectThreshold(yval,pval): 1161 | '''初始化所需变量''' 1162 | bestEpsilon = 0. 1163 | bestF1 = 0. 1164 | F1 = 0. 1165 | step = (np.max(pval)-np.min(pval))/1000 1166 | '''计算''' 1167 | for epsilon in np.arange(np.min(pval),np.max(pval),step): 1168 | cvPrecision = pval bestF1: # 修改最优的F1 Score 1176 | bestF1 = F1 1177 | bestEpsilon = epsilon 1178 | return bestEpsilon,bestF1 1179 | ``` 1180 | 1181 | ### 4、选择使用什么样的feature(单元高斯分布) 1182 | - 如果一些数据不是满足高斯分布的,可以变化一下数据,例如`log(x+C),x^(1/2)`等 1183 | - 如果`p(x)`的值无论异常与否都很大,可以尝试组合多个`feature`,(因为feature之间可能是有关系的) 1184 | 1185 | ### 5、多元高斯分布 1186 | - 单元高斯分布存在的问题 1187 | - 如下图,红色的点为异常点,其他的都是正常点(比如CPU和memory的变化) 1188 | ![enter description here][50] 1189 | - x1对应的高斯分布如下: 1190 | ![enter description here][51] 1191 | - x2对应的高斯分布如下: 1192 | ![enter description here][52] 1193 | - 可以看出对应的p(x1)和p(x2)的值变化并不大,就不会认为异常 1194 | - 因为我们认为feature之间是相互独立的,所以如上图是以**正圆**的方式扩展 1195 | - 多元高斯分布 1196 | - ![$$x \in {R^n}$$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24x%20%5Cin%20%7BR%5En%7D%24%24),并不是建立`p(x1),p(x2)...p(xn)`,而是统一建立`p(x)` 1197 | - 其中参数:![$$\mu \in {R^n},\Sigma \in {R^{n \times {\rm{n}}}}$$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24%5Cmu%20%5Cin%20%7BR%5En%7D%2C%5CSigma%20%5Cin%20%7BR%5E%7Bn%20%5Ctimes%20%7B%5Crm%7Bn%7D%7D%7D%7D%24%24),`Σ`为**协方差矩阵** 1198 | - ![$$p(x) = {1 \over {{{(2\pi )}^{{n \over 2}}}|\Sigma {|^{{1 \over 2}}}}}{e^{ - {1 \over 2}{{(x - u)}^T}{\Sigma ^{ - 1}}(x - u)}}$$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24p%28x%29%20%3D%20%7B1%20%5Cover%20%7B%7B%7B%282%5Cpi%20%29%7D%5E%7B%7Bn%20%5Cover%202%7D%7D%7D%7C%5CSigma%20%7B%7C%5E%7B%7B1%20%5Cover%202%7D%7D%7D%7D%7D%7Be%5E%7B%20-%20%7B1%20%5Cover%202%7D%7B%7B%28x%20-%20u%29%7D%5ET%7D%7B%5CSigma%20%5E%7B%20-%201%7D%7D%28x%20-%20u%29%7D%7D%24%24) 1199 | - 同样,`|Σ|`越小,`p(x)`越尖 1200 | - 例如: 1201 | ![enter description here][53], 1202 | 表示x1,x2**正相关**,即x1越大,x2也就越大,如下图,也就可以将红色的异常点检查出了 1203 | ![enter description here][54] 1204 | 若: 1205 | ![enter description here][55], 1206 | 表示x1,x2**负相关** 1207 | - 实现代码: 1208 | ``` 1209 | # 多元高斯分布函数 1210 | def multivariateGaussian(X,mu,Sigma2): 1211 | k = len(mu) 1212 | if (Sigma2.shape[0]>1): 1213 | Sigma2 = np.diag(Sigma2) 1214 | '''多元高斯分布函数''' 1215 | X = X-mu 1216 | argu = (2*np.pi)**(-k/2)*np.linalg.det(Sigma2)**(-0.5) 1217 | p = argu*np.exp(-0.5*np.sum(np.dot(X,np.linalg.inv(Sigma2))*X,axis=1)) # axis表示每行 1218 | return p 1219 | ``` 1220 | ### 6、单元和多元高斯分布特点 1221 | - 单元高斯分布 1222 | - 人为可以捕捉到`feature`之间的关系时可以使用 1223 | - 计算量小 1224 | - 多元高斯分布 1225 | - 自动捕捉到相关的feature 1226 | - 计算量大,因为:![$$\Sigma \in {R^{n \times {\rm{n}}}}$$](http://latex.codecogs.com/png.latex?%5Cfn_cm%20%24%24%5CSigma%20%5Cin%20%7BR%5E%7Bn%20%5Ctimes%20%7B%5Crm%7Bn%7D%7D%7D%7D%24%24) 1227 | - `m>n`或`Σ`可逆时可以使用。(若不可逆,可能有冗余的x,因为线性相关,不可逆,或者就是m 2 | 3 | 4 | 7 |

Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct 6 2017, 12:04:38)

8 |

Type "copyright", "credits" or "license" for more information.

9 |


10 |

IPython 6.1.0 -- An enhanced Interactive Python.

11 |


Restarting kernel...

12 |
13 |


14 |


15 |

In [1]: runfile('/Users/JSen/Documents/multi_class_logistic/multi_class.py', wdir='/Users/JSen/Documents/multi_class_logistic')

16 |


17 |

949 |

Optimization terminated successfully.

950 |

Current function value: 0.004379

951 |

Iterations: 412

952 |

Function evaluations: 413

953 |

Gradient evaluations: 413

954 |

Optimization terminated successfully.

955 |

Current function value: 0.037992

956 |

Iterations: 762

957 |

Function evaluations: 763

958 |

Gradient evaluations: 763

959 |

Optimization terminated successfully.

960 |

Current function value: 0.047234

961 |

Iterations: 765

962 |

Function evaluations: 766

963 |

Gradient evaluations: 766

964 |

Optimization terminated successfully.

965 |

Current function value: 0.018973

966 |

Iterations: 669

967 |

Function evaluations: 670

968 |

Gradient evaluations: 670

969 |

Optimization terminated successfully.

970 |

Current function value: 0.041008

971 |

Iterations: 797

972 |

Function evaluations: 798

973 |

Gradient evaluations: 798

974 |

Optimization terminated successfully.

975 |

Current function value: 0.006572

976 |

Iterations: 489

977 |

Function evaluations: 490

978 |

Gradient evaluations: 490

979 |

/Users/JSen/Documents/multi_class_logistic/multi_class.py:63: RuntimeWarning: divide by zero encountered in log

980 |

J =( np.dot(np.transpose(-y), np.log(h)) - np.dot(np.transpose(1-y), np.log(1-h)) )/m + lambda_coe/(2*m) * np.dot(temp.T, temp)

981 |

/Users/JSen/Documents/multi_class_logistic/multi_class.py:63: RuntimeWarning: divide by zero encountered in log

982 |

J =( np.dot(np.transpose(-y), np.log(h)) - np.dot(np.transpose(1-y), np.log(1-h)) )/m + lambda_coe/(2*m) * np.dot(temp.T, temp)

983 |

Warning: Desired error not necessarily achieved due to precision loss.

984 |

Current function value: nan

985 |

Iterations: 203

986 |

Function evaluations: 214

987 |

Gradient evaluations: 214

988 |

Optimization terminated successfully.

989 |

Current function value: 0.070613

990 |

Iterations: 816

991 |

Function evaluations: 817

992 |

Gradient evaluations: 817

993 |

Optimization terminated successfully.

994 |

Current function value: 0.061042

995 |

Iterations: 757

996 |

Function evaluations: 758

997 |

Gradient evaluations: 758

998 |

Warning: Desired error not necessarily achieved due to precision loss.

999 |

Current function value: nan

1000 |

Iterations: 126

1001 |

Function evaluations: 139

1002 |

Gradient evaluations: 139

1003 |

0.9738

1004 |

/Users/JSen/Documents/multi_class_logistic/multi_class.py:63: RuntimeWarning: divide by zero encountered in log

1005 |

J =( np.dot(np.transpose(-y), np.log(h)) - np.dot(np.transpose(1-y), np.log(1-h)) )/m + lambda_coe/(2*m) * np.dot(temp.T, temp)

1006 |

/Users/JSen/Documents/multi_class_logistic/multi_class.py:63: RuntimeWarning: divide by zero encountered in log

1007 |

J =( np.dot(np.transpose(-y), np.log(h)) - np.dot(np.transpose(1-y), np.log(1-h)) )/m + lambda_coe/(2*m) * np.dot(temp.T, temp)

1008 |


1009 |

In [2]:

-------------------------------------------------------------------------------- /neural_network/ex3data1.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hujinsen/python-machine-learning/dad29ab0811a4ec54a099ffc8261c184e10843dc/neural_network/ex3data1.mat -------------------------------------------------------------------------------- /neural_network/ex3weights.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hujinsen/python-machine-learning/dad29ab0811a4ec54a099ffc8261c184e10843dc/neural_network/ex3weights.mat -------------------------------------------------------------------------------- /neural_network/ex4data1.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hujinsen/python-machine-learning/dad29ab0811a4ec54a099ffc8261c184e10843dc/neural_network/ex4data1.mat -------------------------------------------------------------------------------- /neural_network/ex4weights.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hujinsen/python-machine-learning/dad29ab0811a4ec54a099ffc8261c184e10843dc/neural_network/ex4weights.mat -------------------------------------------------------------------------------- /neural_network/nn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Feb 20 17:03:20 2018 5 | 6 | @author: JSen 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | from numpy import loadtxt, load 12 | import os 13 | from scipy import optimize 14 | from scipy.optimize import minimize 15 | from sklearn import linear_model 16 | import scipy.io as spio 17 | import random 18 | 19 | os.chdir(os.path.realpath('.')) 20 | 21 | #load weights 22 | theta = spio.loadmat('ex3weights.mat') 23 | 24 | theta1 = theta['Theta1'] #25x401 25 | theta2 = theta['Theta2'] #10x26 26 | 27 | #load training data 28 | data = spio.loadmat('ex3data1.mat') 29 | 30 | #X 5000x400 y 5000x1 31 | X = data['X'] 32 | y = data['y'] 33 | 34 | # 显示100个数字,拿某位仁兄代码过来用 35 | def display_data(imgData): 36 | sum = 0 37 | ''' 38 | 显示100个数(若是一个一个绘制将会非常慢,可以将要画的数字整理好,放到一个矩阵中,显示这个矩阵即可) 39 | - 初始化一个二维数组 40 | - 将每行的数据调整成图像的矩阵,放进二维数组 41 | - 显示即可 42 | ''' 43 | pad = 1 44 | display_array = -np.ones((pad+10*(20+pad), pad+10*(20+pad))) 45 | for i in range(10): 46 | for j in range(10): 47 | display_array[pad+i*(20+pad):pad+i*(20+pad)+20, pad+j*(20+pad):pad+j*(20+pad)+20] = (imgData[sum,:].reshape(20,20,order="F")) # order=F指定以列优先,在matlab中是这样的,python中需要指定,默认以行 48 | sum += 1 49 | 50 | plt.imshow(display_array,cmap='gray') #显示灰度图像 51 | plt.axis('off') 52 | plt.show() 53 | 54 | #随机选取100个数字 55 | rand_indices = random.choices(range(X.shape[0]), k=100) 56 | display_data(X[rand_indices,:]) # 显示100个数字 57 | 58 | input_layer_size = 400; # 20x20 Input Images of Digits 59 | hidden_layer_size = 25; # 25 hidden units 60 | num_labels = 10; 61 | 62 | def predict(theta1, theta2, X): 63 | m = X.shape[0] 64 | num_labels = theta2.shape[0] 65 | p = np.zeros((m, 1)) 66 | 67 | X = np.hstack((np.ones((m,1)), X)) 68 | h1 = np.dot(X, theta1.T) #隐层 5000x25 69 | #为隐层结点添加偏置1 70 | ones = np.ones((h1.shape[0], 1)) 71 | h1 = np.hstack((ones, h1)) #5000x26 72 | out = np.dot(h1, theta2.T) #5000x10 本预测可以不用sigmoid函数,因为是比大小,而sigmoid是单调增加函数,故省了 73 | row_max_index = np.argmax(out, axis=1) 74 | row_max_index = row_max_index + 1 75 | return row_max_index 76 | 77 | pre = predict(theta1, theta2, X) 78 | print('accurate:', np.mean(np.float32(pre.reshape(-1,1)==y))) -------------------------------------------------------------------------------- /neural_network/nn_ex4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Feb 20 17:47:40 2018 5 | 6 | @author: JSen 7 | """ 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | from numpy import loadtxt, load 12 | import os 13 | from scipy import optimize 14 | from scipy.optimize import minimize 15 | from sklearn import linear_model 16 | import scipy.io as spio 17 | import random 18 | 19 | os.chdir(os.path.realpath('.')) 20 | 21 | #load weights 22 | theta = spio.loadmat('ex4weights.mat') 23 | 24 | theta1 = theta['Theta1'] #25x401 25 | theta2 = theta['Theta2'] #10x26 26 | 27 | #load training data 28 | data = spio.loadmat('ex4data1.mat') 29 | 30 | #X 5000x400 y 5000x1 31 | X = data['X'] 32 | y = data['y'] 33 | 34 | # 显示100个数字,拿某位仁兄代码过来用 35 | def display_data(imgData): 36 | sum = 0 37 | ''' 38 | 显示100个数(若是一个一个绘制将会非常慢,可以将要画的数字整理好,放到一个矩阵中,显示这个矩阵即可) 39 | - 初始化一个二维数组 40 | - 将每行的数据调整成图像的矩阵,放进二维数组 41 | - 显示即可 42 | ''' 43 | pad = 1 44 | display_array = -np.ones((pad+10*(20+pad), pad+10*(20+pad))) 45 | for i in range(10): 46 | for j in range(10): 47 | display_array[pad+i*(20+pad):pad+i*(20+pad)+20, pad+j*(20+pad):pad+j*(20+pad)+20] = (imgData[sum,:].reshape(20,20,order="F")) # order=F指定以列优先,在matlab中是这样的,python中需要指定,默认以行 48 | sum += 1 49 | 50 | plt.imshow(display_array,cmap='gray') #显示灰度图像 51 | plt.axis('off') 52 | plt.show() 53 | 54 | #随机选取100个数字 55 | rand_indices = random.choices(range(X.shape[0]), k=100) 56 | display_data(X[rand_indices,:]) # 显示100个数字 57 | 58 | def sigmoid(z): 59 | s = 1.0/(1.0 + np.exp(-z)) 60 | return s 61 | 62 | input_layer_size = 400; # 20x20 Input Images of Digits 63 | hidden_layer_size = 25; # 25 hidden units 64 | num_labels = 10; 65 | 66 | def compress_theta_in_one_column(theta1, theta2): 67 | t1 = theta1.reshape(-1, 1) 68 | t2 = theta2.reshape(-1, 1) 69 | t3 = np.vstack((t1, t2)) 70 | return t3 71 | 72 | def decompress_theta_from_cloumn(one_column_theta, input_layer_size, hidden_layer_size, num_labels): 73 | one_column_theta = one_column_theta.reshape(-1, 1) #确保是nx1向量 74 | 75 | t1 = one_column_theta[0:hidden_layer_size*(input_layer_size+1), :] 76 | t1 = t1.reshape((hidden_layer_size, input_layer_size+1)) 77 | t2 = one_column_theta[hidden_layer_size*(input_layer_size+1):, :] 78 | t2 = t2.reshape(((num_labels, hidden_layer_size+1))) 79 | return t1, t2 80 | 81 | def decompress_theta_from_row(one_row_theta, input_layer_size, hidden_layer_size, num_labels): 82 | one_row_theta = one_row_theta.reshape(1, -1) #确保是1xn向量 83 | 84 | t1 = one_row_theta[:, 0:hidden_layer_size*(input_layer_size+1)] 85 | t1 = t1.reshape((hidden_layer_size, input_layer_size+1)) 86 | t2 = one_row_theta[:, hidden_layer_size*(input_layer_size+1):] 87 | t2 = t2.reshape(((num_labels, hidden_layer_size+1))) 88 | return t1, t2 89 | 90 | def nnCostFunction(nn_parms, input_layer_size, hidden_layer_size, num_labels, X, y): 91 | '''不带正则化的损失函数''' 92 | theta_t1, theta_t2 = decompress_theta_from_cloumn(nn_parms, input_layer_size, hidden_layer_size, num_labels) 93 | 94 | m = X.shape[0] 95 | X = np.hstack((np.ones((m,1)), X)) 96 | h1 = np.dot(X, theta_t1.T) #隐层 5000x25 97 | h1 = sigmoid(h1) #隐层输出 98 | #为隐层结点添加偏置1 99 | ones = np.ones((m, 1)) 100 | h1 = np.hstack((ones, h1)) #5000x26 101 | h2 = np.dot(h1, theta_t2.T) #5000x10 102 | h = sigmoid(h2) #结果映射到0-1,之间,后面才可以计算损失 103 | 104 | #将y转化为5000x10矩阵 105 | y_mat = np.zeros((m, num_labels),dtype=int) 106 | for i in range(m): 107 | y_mat[i, y[i]-1] = 1 #1->y(1)=1, 2->y(2)=1,...9->y(9)=1,10->y(10)=1,但python数组从0开始,故每个减一,注意10代表0 108 | 109 | #计算损失 110 | A = np.dot(y_mat.T, np.log(h)) + np.dot((1-y_mat).T , np.log(1-h)) #10 by 10 matrix 111 | J = -1/m * np.trace(A) 112 | 113 | return J 114 | 115 | 116 | theta_in_one_col = compress_theta_in_one_column(theta1, theta2) 117 | loss = nnCostFunction(theta_in_one_col, input_layer_size, hidden_layer_size, num_labels, X, y) 118 | print('loss:', loss) 119 | 120 | def nnCostFunction_with_regularization(nn_parms, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_coe): 121 | '''带正则化的损失函数''' 122 | theta_t1, theta_t2 = decompress_theta_from_cloumn(nn_parms, input_layer_size, hidden_layer_size, num_labels) 123 | 124 | m = X.shape[0] 125 | X = np.hstack((np.ones((m,1)), X)) 126 | h1 = np.dot(X, theta_t1.T) #隐层 5000x25 127 | h1 = sigmoid(h1) #隐层输出 128 | #为隐层结点添加偏置1 129 | ones = np.ones((m, 1)) 130 | h1 = np.hstack((ones, h1)) #5000x26 131 | h2 = np.dot(h1, theta_t2.T) #5000x10 132 | h = sigmoid(h2) #结果映射到0-1,之间,后面才可以计算损失 133 | 134 | #将y转化为5000x10矩阵 135 | y_mat = np.zeros((m, num_labels),dtype=int) 136 | for i in range(m): 137 | y_mat[i, y[i]-1] = 1 #1->y(1)=1, 2->y(2)=1,...9->y(9)=1,10->y(10)=1,但python数组从0开始,故每个减一,注意10代表0 138 | 139 | #计算损失 140 | A = np.dot(y_mat.T, np.log(h)) + np.dot((1-y_mat).T , np.log(1-h)) #10 by 10 matrix 141 | J = -1/m * np.trace(A) 142 | #正则化,所有theta第一列不用正则化 143 | theta_t1_r1 = theta_t1[:, 1:] 144 | theta_t2_r2 = theta_t2[:, 1:] 145 | B = np.dot(theta_t1_r1, theta_t1_r1.T) + np.dot(theta_t2_r2.T, theta_t2_r2)#25x25 146 | reg =lambda_coe/(2*m) * np.trace(B) 147 | 148 | J = J + reg 149 | 150 | return J 151 | 152 | loss = nnCostFunction_with_regularization(theta_in_one_col, input_layer_size, hidden_layer_size, num_labels, X, y, 1) 153 | print('loss with regularization:', loss) 154 | 155 | def sigmoid_gradient(z): 156 | '''假设z是经过sigmoid函数处理过得''' 157 | # gz = sigmoid(z) 158 | g = z * (1-z) 159 | return g 160 | 161 | def randInitializeWeights(input_layer_size, hidden_layer_size): 162 | epsilon_init = 0.12 163 | rand_matrix = np.random.rand(hidden_layer_size, input_layer_size+1) #得到[0,1)之间均匀分布的数字 164 | W = rand_matrix * 2 * epsilon_init - epsilon_init #得到(-epsilon_init, epsilon_init)之间的数字 165 | return W 166 | 167 | def compress_theta_in_one_row(theta1, theta2): 168 | t1 = np.matrix.flatten(theta1) 169 | t2 = np.matrix.flatten(theta2) 170 | t3 = np.hstack((t1, t2)).reshape(1, -1) #连接起来 171 | return t3 172 | 173 | 174 | def compute_gradient(nn_parms: np.ndarray, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_coe=0): 175 | '''计算参数为nn_parms,梯度''' 176 | theta_t1, theta_t2 = decompress_theta_from_cloumn(nn_parms, input_layer_size, hidden_layer_size, num_labels) 177 | 178 | m = X.shape[0] 179 | X = np.hstack((np.ones((m,1)), X)) 180 | h1 = np.dot(X, theta_t1.T) #隐层 5000x25 181 | h1 = sigmoid(h1) #隐层输出 182 | #为隐层结点添加偏置1 183 | ones = np.ones((m, 1)) 184 | h1 = np.hstack((ones, h1)) #5000x26 185 | h2 = np.dot(h1, theta_t2.T) #5000x10 186 | h = sigmoid(h2) #结果映射到0-1,之间,后面才可以计算损失 187 | 188 | #将y转化为5000x10矩阵 189 | y_mat = np.zeros((m, num_labels),dtype=int) 190 | for i in range(m): 191 | y_mat[i, y[i]-1] = 1 #1->y(1)=1, 2->y(2)=1,...9->y(9)=1,10->y(10)=1,但python数组从0开始,故每个减一,注意10代表0 192 | '''BP算法''' 193 | big_delta1 = np.zeros((theta_t1.shape)) #25x401 194 | big_delta2 = np.zeros((theta_t2.shape)) #10x26 195 | for i in range(m): 196 | out = h[i, :] 197 | y_current = y_mat[i, :] 198 | 199 | delta3 = (out - y_current).reshape(1, -1) #1x10 200 | 201 | delta2 = np.dot(delta3, theta_t2) * sigmoid_gradient(h1[i, :]) #1x26 202 | delta2 = delta2.reshape(1, -1) 203 | 204 | big_delta2 = big_delta2 + np.dot(delta3.T, h1[i, :].reshape(1, -1)) #10x26 205 | 206 | #此处tricky,分开写 207 | t1 = delta2[:, 1:].T 208 | t2 = X[i,:].reshape(1,-1) 209 | big_delta1 = big_delta1 + np.dot(t1, t2) #25x401 210 | 211 | B1 = np.hstack((np.zeros((theta_t1.shape[0], 1)), theta_t1[:, 1:])) #25x401 212 | theta1_grad = 1/m * big_delta1 + lambda_coe/m * B1 213 | 214 | B2 = np.hstack((np.zeros((theta_t2.shape[0], 1)), theta_t2[:, 1:])) #10x26 215 | theta2_grad = 1/m * big_delta2 + lambda_coe/m * B2 216 | #返回展平的参数 217 | r = compress_theta_in_one_column(theta1_grad, theta2_grad) 218 | 219 | return r.ravel() #将返回值展成(n,)形式,不能写成(n,1),因为报维度出错:deltak = numpy.dot(gfk, gfk) 220 | 221 | def debugInitializeWeights(fan_out, fan_in): 222 | '''随机创建一组根据fan_out, fan_in确定的权重''' 223 | arr = np.arange(1, fan_out*(fan_in + 1) + 1) 224 | W = np.sin(arr).reshape(fan_out, fan_in + 1) 225 | return W 226 | test_pram = debugInitializeWeights(3,3) 227 | 228 | def computeNumericalGradient(nn_param, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_coe): 229 | '''由导数定义计算对每一个theta的偏导数''' 230 | numgrad = np.zeros((nn_param.shape)) 231 | perturb = np.zeros((nn_param.shape)) 232 | 233 | e = 1e-4 234 | for p in range(np.size(nn_param)): 235 | perturb[p, :] = e 236 | loss1 = nnCostFunction_with_regularization(nn_param - perturb, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_coe) 237 | loss2 = nnCostFunction_with_regularization(nn_param + perturb, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_coe) 238 | 239 | numgrad[p, :] = (loss2 - loss1) / (2 * e) 240 | perturb[p, :] = 0 241 | 242 | return numgrad 243 | 244 | def checkNNGradients(lambda_coe = 0): 245 | '''创建一个小型网络,验证梯度计算是正确的''' 246 | input_layer_size = 3; 247 | hidden_layer_size = 5; 248 | num_labels = 3; 249 | m = 5; 250 | 251 | # We generate some 'random' test data 252 | Theta1 = debugInitializeWeights(hidden_layer_size, input_layer_size); 253 | Theta2 = debugInitializeWeights(num_labels, hidden_layer_size); 254 | # Reusing debugInitializeWeights to generate X 255 | X = debugInitializeWeights(m, input_layer_size - 1); 256 | #生成对应的label 257 | y = 1 + np.mod(np.arange(1, m+1), num_labels).reshape(-1,1) 258 | 259 | param = compress_theta_in_one_column(Theta1, Theta2) 260 | 261 | cost = nnCostFunction_with_regularization(param, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_coe) 262 | grad = compute_gradient(param, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_coe) 263 | 264 | numgrad = computeNumericalGradient(param, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_coe) 265 | #相对误差小于1e-9 特别注意:numgrad和grad相减,一定要确保他们的shape是一样的 266 | diff = np.linalg.norm(numgrad-grad) / np.linalg.norm(numgrad+grad) 267 | print(f'Relative Difference:{diff}') 268 | checkNNGradients() 269 | 270 | 271 | 272 | lambda_coe = 0.6 273 | 274 | initial_theta1 = randInitializeWeights(input_layer_size, hidden_layer_size); 275 | initial_theta2 = randInitializeWeights(hidden_layer_size, num_labels); 276 | initial_theta_in_one_col = compress_theta_in_one_column(initial_theta1, initial_theta2) 277 | 278 | t1, t2 = decompress_theta_from_cloumn(initial_theta_in_one_col, input_layer_size, hidden_layer_size, num_labels) 279 | 280 | 281 | nnCostFunction_with_regularization(initial_theta_in_one_col, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_coe) 282 | g = compute_gradient(initial_theta_in_one_col, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_coe) 283 | 284 | '''最小化损失''' 285 | result = optimize.fmin_cg(nnCostFunction_with_regularization, initial_theta_in_one_col, fprime=compute_gradient, args=(input_layer_size, hidden_layer_size, num_labels, X, y, lambda_coe), maxiter=100) 286 | #最终结果 287 | res_theta1, res_theta2 = decompress_theta_from_cloumn(result, input_layer_size, hidden_layer_size, num_labels) 288 | 289 | def predict(theta1, theta2, X): 290 | m = X.shape[0] 291 | 292 | #forward propagation 293 | X = np.hstack((np.ones((m,1)), X)) 294 | h1 = np.dot(X, theta1.T) #隐层 5000x25 295 | h1 = sigmoid(h1) #隐层输出 296 | #为隐层结点添加偏置1 297 | ones = np.ones((m, 1)) 298 | h1 = np.hstack((ones, h1)) #5000x26 299 | h2 = np.dot(h1, theta2.T) #5000x10 300 | h = sigmoid(h2) #结果映射到0-1,之间,后面才可以计算损失 301 | 302 | #找出每行最大值得下标,因为下标从0开始,而预测结果从1开始,故加一, 303 | row_max_index = np.argmax(h, axis=1) 304 | row_max_index = row_max_index + 1 305 | return row_max_index 306 | 307 | pre = predict(res_theta1, res_theta2, X) 308 | print('accuracy:', np.mean(np.float32(pre.reshape(-1,1)==y))) --------------------------------------------------------------------------------