机器学习算法 Python 实现

nengdu1 6年前
   <h2>机器学习算法Python实现</h2>    <h2>目录</h2>    <ul>     <li>机器学习算法Python实现      <ul>       <li>逻辑回归_手写数字识别_OneVsAll</li>       <li>六、PCA主成分分析(降维)        <ul>         <li>3、主成分分析PCA与线性回归的区别</li>         <li>6、主成分个数的选择(即要降的维度)</li>         <li>9、使用scikit-learn库中的PCA实现降维</li>        </ul> </li>       <li>七、异常检测 Anomaly Detection        <ul>         <li>1、高斯分布(正态分布)</li>         <li>3、评价的好坏,以及的选取</li>         <li>4、选择使用什么样的feature(单元高斯分布)</li>         <li>6、单元和多元高斯分布特点</li>        </ul> </li>      </ul> </li>    </ul>    <h2>一、 <a href="/misc/goto?guid=4959756254656719013" rel="nofollow,noindex">线性回归</a></h2>    <ul>     <li><a href="/misc/goto?guid=4959756254763344781" rel="nofollow,noindex">全部代码</a></li>    </ul>    <h3>1、代价函数</h3>    <ul>     <li> <p> </p> </li>     <li> <p>其中:</p> </li>     <li> <p>下面就是要求出theta,使代价最小,即代表我们拟合出来的方程距离真实值最近</p> </li>     <li> <p>共有m条数据,其中 代表我们要拟合出来的方程到真实值距离的平方,平方的原因是因为可能有负值,正负可能会抵消</p> </li>     <li> <p>前面有系数 2 的原因是下面求梯度是对每个变量求偏导, 2 可以消去</p> </li>     <li> <p>实现代码:</p> </li>    </ul>    <pre>  <code class="language-python"># 计算代价函数  def computerCost(X,y,theta):      m = len(y)      J = 0            J = (np.transpose(X*theta-y))*(X*theta-y)/(2*m) #计算代价J      return J</code></pre>    <ul>     <li>注意这里的X是真实数据前加了一列1,因为有theta(0)</li>    </ul>    <h3>2、梯度下降算法</h3>    <ul>     <li>代价函数对 求偏导得到:</li>     <li>所以对theta的更新可以写为:</li>     <li>其中 为学习速率,控制梯度下降的速度,一般取 <strong>0.01,0.03,0.1,0.3.....</strong></li>     <li>为什么梯度下降可以逐步减小代价函数</li>     <li>假设函数 f(x)</li>     <li>泰勒展开: f(x+△x)=f(x)+f'(x)*△x+o(△x)</li>     <li>令: △x=-α*f'(x) ,即负梯度方向乘以一个很小的步长 α</li>     <li>将 △x 代入泰勒展开式中: f(x+x)=f(x)-α*[f'(x)]²+o(△x)</li>     <li>可以看出, α 是取得很小的正数, [f'(x)]² 也是正数,所以可以得出: f(x+△x)<=f(x)</li>     <li>所以沿着 <strong>负梯度</strong> 放下,函数在减小,多维情况一样。</li>     <li>实现代码</li>    </ul>    <pre>  <code class="language-python"># 梯度下降算法  def gradientDescent(X,y,theta,alpha,num_iters):      m = len(y)            n = len(theta)            temp = np.matrix(np.zeros((n,num_iters)))   # 暂存每次迭代计算的theta,转化为矩阵形式                  J_history = np.zeros((num_iters,1)) #记录每次迭代计算的代价值            for i in range(num_iters):  # 遍历迭代次数              h = np.dot(X,theta)     # 计算内积,matrix可以直接乘          temp[:,i] = theta - ((alpha/m)*(np.dot(np.transpose(X),h-y)))   #梯度的计算          theta = temp[:,i]          J_history[i] = computerCost(X,y,theta)      #调用计算代价函数          print '.',            return theta,J_history</code></pre>    <h3>3、均值归一化</h3>    <ul>     <li>目的是使数据都缩放到一个范围内,便于使用梯度下降算法</li>     <li> </li>     <li>其中 为所有此feture数据的平均值</li>     <li>可以是 <strong>最大值-最小值</strong> ,也可以是这个feature对应的数据的 <strong>标准差</strong></li>     <li>实现代码:</li>    </ul>    <pre>  <code class="language-python"># 归一化feature  def featureNormaliza(X):      X_norm = np.array(X)            #将X转化为numpy数组对象,才可以进行矩阵的运算      #定义所需变量      mu = np.zeros((1,X.shape[1]))         sigma = np.zeros((1,X.shape[1]))            mu = np.mean(X_norm,0)          # 求每一列的平均值(0指定为列,1代表行)      sigma = np.std(X_norm,0)        # 求每一列的标准差      for i in range(X.shape[1]):     # 遍历列          X_norm[:,i] = (X_norm[:,i]-mu[i])/sigma[i]  # 归一化            return X_norm,mu,sigma</code></pre>    <ul>     <li>注意预测的时候也需要均值归一化数据</li>    </ul>    <h3>4、最终运行结果</h3>    <ul>     <li> <p>代价随迭代次数的变化</p> <img src="https://simg.open-open.com/show/a5d7273ff447f2d8f0441366bf0ddd73.png"></li>    </ul>    <h3>5、 <a href="/misc/goto?guid=4959756254841889626" rel="nofollow,noindex">使用scikit-learn库中的线性模型实现</a></h3>    <ul>     <li>导入包</li>    </ul>    <pre>  <code class="language-python">from sklearn import linear_model  from sklearn.preprocessing import StandardScaler    #引入缩放的包</code></pre>    <ul>     <li>归一化</li>    </ul>    <pre>  <code class="language-python"># 归一化操作      scaler = StandardScaler()         scaler.fit(X)      x_train = scaler.transform(X)      x_test = scaler.transform(np.array([1650,3]))</code></pre>    <ul>     <li>线性模型拟合</li>    </ul>    <pre>  <code class="language-python"># 线性模型拟合      model = linear_model.LinearRegression()      model.fit(x_train, y)</code></pre>    <ul>     <li>预测</li>    </ul>    <pre>  <code class="language-python">#预测结果      result = model.predict(x_test)</code></pre>    <h2>二、 <a href="/misc/goto?guid=4959756254924884654" rel="nofollow,noindex">逻辑回归</a></h2>    <ul>     <li><a href="/misc/goto?guid=4959756255010311794" rel="nofollow,noindex">全部代码</a></li>    </ul>    <h3>1、代价函数</h3>    <ul>     <li> </li>     <li>可以综合起来为: 其中:</li>     <li>为什么不用线性回归的代价函数表示,因为线性回归的代价函数可能是非凸的,对于分类问题,使用梯度下降很难得到最小值,上面的代价函数是凸函数</li>     <li>的图像如下,即 y=1 时: <img src="https://simg.open-open.com/show/cdbfa67ab63fc37324518dc53e07270a.png"></li>    </ul>    <p>可以看出,当 趋于 1 , y=1 ,与预测值一致,此时付出的代价 cost 趋于 0 ,若 趋于 0 , y=1 ,此时的代价 cost 值非常大,我们最终的目的是最小化代价值</p>    <ul>     <li> <p>同理 的图像如下( y=0 ):</p> <img src="https://simg.open-open.com/show/842ff321fcd3c66d860a121acd5a596f.png"></li>    </ul>    <h3>2、梯度</h3>    <ul>     <li>同样对代价函数求偏导:<br> 可以看出与线性回归的偏导数一致</li>     <li>推到过程 <img src="https://simg.open-open.com/show/96e7c074d7691a24b91119689f96e2da.jpg"></li>    </ul>    <h3>3、正则化</h3>    <ul>     <li>目的是为了防止过拟合</li>     <li>在代价函数中加上一项</li>     <li>注意j是重1开始的,因为theta(0)为一个常数项,X中最前面一列会加上1列1,所以乘积还是theta(0),feature没有关系,没有必要正则化</li>     <li>正则化后的代价:</li>    </ul>    <pre>  <code class="language-python"># 代价函数  def costFunction(initial_theta,X,y,inital_lambda):      m = len(y)      J = 0            h = sigmoid(np.dot(X,initial_theta))    # 计算h(z)      theta1 = initial_theta.copy()           # 因为正则化j=1从1开始,不包含0,所以复制一份,前theta(0)值为0       theta1[0] = 0               temp = np.dot(np.transpose(theta1),theta1)      J = (-np.dot(np.transpose(y),np.log(h))-np.dot(np.transpose(1-y),np.log(1-h))+temp*inital_lambda/2)/m   # 正则化的代价方程      return J</code></pre>    <ul>     <li>正则化后的代价的梯度</li>    </ul>    <pre>  <code class="language-python"># 计算梯度  def gradient(initial_theta,X,y,inital_lambda):      m = len(y)      grad = np.zeros((initial_theta.shape[0]))            h = sigmoid(np.dot(X,initial_theta))# 计算h(z)      theta1 = initial_theta.copy()      theta1[0] = 0        grad = np.dot(np.transpose(X),h-y)/m+inital_lambda/m*theta1 #正则化的梯度      return grad</code></pre>    <h3>4、S型函数(即 )</h3>    <ul>     <li>实现代码:</li>    </ul>    <pre>  <code class="language-python"># S型函数      def sigmoid(z):      h = np.zeros((len(z),1))    # 初始化,与z的长度一置            h = 1.0/(1.0+np.exp(-z))      return h</code></pre>    <h3>5、映射为多项式</h3>    <ul>     <li>因为数据的feture可能很少,导致偏差大,所以创造出一些feture结合</li>     <li>eg:映射为2次方的形式:</li>     <li>实现代码:</li>    </ul>    <pre>  <code class="language-python"># 映射为多项式   def mapFeature(X1,X2):      degree = 3;                     # 映射的最高次方      out = np.ones((X1.shape[0],1))  # 映射后的结果数组(取代X)      '''      这里以degree=2为例,映射为1,x1,x2,x1^2,x1,x2,x2^2      '''      for i in np.arange(1,degree+1):           for j in range(i+1):              temp = X1**(i-j)*(X2**j)    #矩阵直接乘相当于matlab中的点乘.*              out = np.hstack((out, temp.reshape(-1,1)))      return out</code></pre>    <h3>6、使用 scipy 的优化方法</h3>    <ul>     <li>梯度下降使用 scipy 中 optimize 中的 fmin_bfgs 函数</li>     <li>调用scipy中的优化算法fmin_bfgs(拟牛顿法Broyden-Fletcher-Goldfarb-Shanno</li>     <li>costFunction是自己实现的一个求代价的函数,</li>     <li>initial_theta表示初始化的值,</li>     <li>fprime指定costFunction的梯度</li>     <li>args是其余测参数,以元组的形式传入,最后会将最小化costFunction的theta返回</li>    </ul>    <pre>  <code class="language-python">result = optimize.fmin_bfgs(costFunction, initial_theta, fprime=gradient, args=(X,y,initial_lambda))</code></pre>    <h3>7、运行结果</h3>    <ul>     <li>data1决策边界和准确度<br> <img src="https://simg.open-open.com/show/d20f4bdd313aa64c1717fab98d970ce8.png"> <img src="https://simg.open-open.com/show/b1e66fa3afe305bb0b39f0c29c40931b.png"></li>     <li>data2决策边界和准确度<br> <img src="https://simg.open-open.com/show/fed49b332cda822aff7561aca849fadd.png"> <img src="https://simg.open-open.com/show/f9f4562b29ca47b62913b65db701dd87.png"></li>    </ul>    <h3>8、 <a href="/misc/goto?guid=4959756255087270326" rel="nofollow,noindex">使用scikit-learn库中的逻辑回归模型实现</a></h3>    <ul>     <li>导入包</li>    </ul>    <pre>  <code class="language-python">from sklearn.linear_model import LogisticRegression  from sklearn.preprocessing import StandardScaler  from sklearn.cross_validation import train_test_split  import numpy as np</code></pre>    <ul>     <li>划分训练集和测试集</li>    </ul>    <pre>  <code class="language-python"># 划分为训练集和测试集      x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.2)</code></pre>    <ul>     <li>归一化</li>    </ul>    <pre>  <code class="language-python"># 归一化      scaler = StandardScaler()      scaler.fit(x_train)      x_train = scaler.fit_transform(x_train)      x_test = scaler.fit_transform(x_test)</code></pre>    <ul>     <li>逻辑回归</li>    </ul>    <pre>  <code class="language-python">#逻辑回归      model = LogisticRegression()      model.fit(x_train,y_train)</code></pre>    <ul>     <li>预测</li>    </ul>    <pre>  <code class="language-python"># 预测      predict = model.predict(x_test)      right = sum(predict == y_test)            predict = np.hstack((predict.reshape(-1,1),y_test.reshape(-1,1)))   # 将预测值和真实值放在一块,好观察      print predict      print ('测试集准确率:%f%%'%(right*100.0/predict.shape[0]))          #计算在测试集上的准确度</code></pre>    <h2><a href="/misc/goto?guid=4959756254924884654" rel="nofollow,noindex">逻辑回归_手写数字识别_OneVsAll</a></h2>    <ul>     <li><a href="/misc/goto?guid=4959756255171578039" rel="nofollow,noindex">全部代码</a></li>    </ul>    <h3>1、随机显示100个数字</h3>    <ul>     <li>我没有使用scikit-learn中的数据集,像素是20*20px,彩色图如下 <img src="https://simg.open-open.com/show/3e04aaf8354a5959bde9821314dd1bbf.png"> 灰度图: <img src="https://simg.open-open.com/show/22ce9e90c9ee51d212bd78b1be3d0222.png"></li>     <li>实现代码:</li>    </ul>    <pre>  <code class="language-python"># 显示100个数字  def display_data(imgData):      sum = 0      '''      显示100个数(若是一个一个绘制将会非常慢,可以将要画的数字整理好,放到一个矩阵中,显示这个矩阵即可)      - 初始化一个二维数组      - 将每行的数据调整成图像的矩阵,放进二维数组      - 显示即可      '''      pad = 1      display_array = -np.ones((pad+10*(20+pad),pad+10*(20+pad)))      for i in range(10):          for j in range(10):              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中需要指定,默认以行              sum += 1                    plt.imshow(display_array,cmap='gray')   #显示灰度图像      plt.axis('off')      plt.show()</code></pre>    <h3>2、OneVsAll</h3>    <ul>     <li>如何利用逻辑回归解决多分类的问题,OneVsAll就是把当前某一类看成一类,其他所有类别看作一类,这样有成了二分类的问题了</li>     <li>如下图,把途中的数据分成三类,先把红色的看成一类,把其他的看作另外一类,进行逻辑回归,然后把蓝色的看成一类,其他的再看成一类,以此类推... <img src="https://simg.open-open.com/show/3307b3247a0d0b4f2a1f88deee95589e.png"></li>     <li>可以看出大于2类的情况下,有多少类就要进行多少次的逻辑回归分类</li>    </ul>    <h3>3、手写数字识别</h3>    <ul>     <li>共有0-9,10个数字,需要10次分类</li>     <li>由于 <strong>数据集y</strong> 给出的是 0,1,2...9 的数字,而进行逻辑回归需要 0/1 的label标记,所以需要对y处理</li>     <li>说一下数据集,前 500 个是 0 , 500-1000 是 1 , ... ,所以如下图,处理后的 y , 前500行的第一列是1,其余都是0,500-1000行第二列是1,其余都是0.... <img src="https://simg.open-open.com/show/d34b6c1d1f9a0685c48b627362550070.png"></li>     <li>然后调用 <strong>梯度下降算法</strong> 求解 theta</li>     <li>实现代码:</li>    </ul>    <pre>  <code class="language-python"># 求每个分类的theta,最后返回所有的all_theta      def oneVsAll(X,y,num_labels,Lambda):      # 初始化变量      m,n = X.shape      all_theta = np.zeros((n+1,num_labels))  # 每一列对应相应分类的theta,共10列      X = np.hstack((np.ones((m,1)),X))       # X前补上一列1的偏置bias      class_y = np.zeros((m,num_labels))      # 数据的y对应0-9,需要映射为0/1的关系      initial_theta = np.zeros((n+1,1))       # 初始化一个分类的theta            # 映射y      for i in range(num_labels):          class_y[:,i] = np.int32(y==i).reshape(1,-1) # 注意reshape(1,-1)才可以赋值            #np.savetxt("class_y.csv", class_y[0:600,:], delimiter=',')                '''遍历每个分类,计算对应的theta值'''      for i in range(num_labels):          result = optimize.fmin_bfgs(costFunction, initial_theta, fprime=gradient, args=(X,class_y[:,i],Lambda)) # 调用梯度下降的优化方法          all_theta[:,i] = result.reshape(1,-1)   # 放入all_theta中                all_theta = np.transpose(all_theta)       return all_theta</code></pre>    <h3>4、预测</h3>    <ul>     <li>之前说过,预测的结果是一个 <strong>概率值</strong> ,利用学习出来的 theta 代入预测的 <strong>S型函数</strong> 中,每行的最大值就是是某个数字的最大概率,所在的 <strong>列号</strong> 就是预测的数字的真实值,因为在分类时,所有为 0 的将 y 映射在第一列,为1的映射在第二列,依次类推</li>     <li>实现代码:</li>    </ul>    <pre>  <code class="language-python"># 预测  def predict_oneVsAll(all_theta,X):      m = X.shape[0]      num_labels = all_theta.shape[0]      p = np.zeros((m,1))      X = np.hstack((np.ones((m,1)),X))   #在X最前面加一列1            h = sigmoid(np.dot(X,np.transpose(all_theta)))  #预测        '''      返回h中每一行最大值所在的列号      - np.max(h, axis=1)返回h中每一行的最大值(是某个数字的最大概率)      - 最后where找到的最大概率所在的列号(列号即是对应的数字)      '''      p = np.array(np.where(h[0,:] == np.max(h, axis=1)[0]))        for i in np.arange(1, m):          t = np.array(np.where(h[i,:] == np.max(h, axis=1)[i]))          p = np.vstack((p,t))      return p</code></pre>    <h3>5、运行结果</h3>    <ul>     <li> <p>10次分类,在训练集上的准确度:</p> <img src="https://simg.open-open.com/show/1a870508dec2df8f28597f3eca6ba3ec.png"></li>    </ul>    <h3>6、 <a href="/misc/goto?guid=4959756255261724477" rel="nofollow,noindex">使用scikit-learn库中的逻辑回归模型实现</a></h3>    <ul>     <li>1、导入包</li>    </ul>    <pre>  <code class="language-python">from scipy import io as spio  import numpy as np  from sklearn import svm  from sklearn.linear_model import LogisticRegression</code></pre>    <ul>     <li>2、加载数据</li>    </ul>    <pre>  <code class="language-python">data = loadmat_data("data_digits.mat")       X = data['X']   # 获取X数据,每一行对应一个数字20x20px      y = data['y']   # 这里读取mat文件y的shape=(5000, 1)      y = np.ravel(y) # 调用sklearn需要转化成一维的(5000,)</code></pre>    <ul>     <li>3、拟合模型</li>    </ul>    <pre>  <code class="language-python">model = LogisticRegression()      model.fit(X, y) # 拟合</code></pre>    <ul>     <li>4、预测</li>    </ul>    <pre>  <code class="language-python">predict = model.predict(X) #预测            print u"预测准确度为:%f%%"%np.mean(np.float64(predict == y)*100)</code></pre>    <ul>     <li>5、输出结果(在训练集上的准确度) <img src="https://simg.open-open.com/show/0eacea05a289079e353330fdbaeb7dd8.png"></li>    </ul>    <h2>三、BP神经网络</h2>    <ul>     <li><a href="/misc/goto?guid=4959756255331212327" rel="nofollow,noindex">全部代码</a></li>    </ul>    <h3>1、神经网络model</h3>    <ul>     <li> <p>先介绍个三层的神经网络,如下图所示</p> </li>     <li> <p>输入层(input layer)有三个units( 为补上的bias,通常设为 1 )</p> </li>     <li> <p>表示第 j 层的第 i 个激励,也称为为单元unit</p> </li>     <li> <p>为第 j 层到第 j+1 层映射的权重矩阵,就是每条边的权重 <img src="https://simg.open-open.com/show/8d789a8ef24d025009f6374ef45611b4.png"></p> </li>     <li> <p>所以可以得到:</p> </li>     <li> <p>隐含层:</p> <p> </p> <p> </p> </li>     <li> <p>输出层</p> <p>其中, <strong>S型函数</strong> ,也成为 <strong>激励函数</strong></p> </li>     <li> <p>可以看出 为3x4的矩阵, 为1x4的矩阵</p> </li>     <li> <p>==》 j+1 的单元数x( j 层的单元数+1)</p> </li>    </ul>    <h3>2、代价函数</h3>    <ul>     <li>假设最后输出的 ,即代表输出层有K个单元</li>     <li>其中, 代表第 i 个单元输出</li>     <li>与逻辑回归的代价函数 差不多,就是累加上每个输出(共有K个输出)</li>    </ul>    <h3>3、正则化</h3>    <ul>     <li>L -->所有层的个数</li>     <li>-->第 l 层unit的个数</li>     <li>正则化后的 <strong>代价函数</strong> 为<br> <img src="https://simg.open-open.com/show/a78133a29b0ff945c2d79df8ec128c19.png"></li>     <li>共有 L-1 层,</li>     <li>然后是累加对应每一层的theta矩阵,注意不包含加上偏置项对应的theta(0)</li>     <li>正则化后的代价函数实现代码:</li>    </ul>    <pre>  <code class="language-python"># 代价函数  def nnCostFunction(nn_params,input_layer_size,hidden_layer_size,num_labels,X,y,Lambda):      length = nn_params.shape[0] # theta的中长度      # 还原theta1和theta2      Theta1 = nn_params[0:hidden_layer_size*(input_layer_size+1)].reshape(hidden_layer_size,input_layer_size+1)      Theta2 = nn_params[hidden_layer_size*(input_layer_size+1):length].reshape(num_labels,hidden_layer_size+1)            # np.savetxt("Theta1.csv",Theta1,delimiter=',')            m = X.shape[0]      class_y = np.zeros((m,num_labels))      # 数据的y对应0-9,需要映射为0/1的关系      # 映射y      for i in range(num_labels):          class_y[:,i] = np.int32(y==i).reshape(1,-1) # 注意reshape(1,-1)才可以赋值             '''去掉theta1和theta2的第一列,因为正则化时从1开始'''          Theta1_colCount = Theta1.shape[1]          Theta1_x = Theta1[:,1:Theta1_colCount]      Theta2_colCount = Theta2.shape[1]          Theta2_x = Theta2[:,1:Theta2_colCount]      # 正则化向theta^2      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))))            '''正向传播,每次需要补上一列1的偏置bias'''      a1 = np.hstack((np.ones((m,1)),X))            z2 = np.dot(a1,np.transpose(Theta1))          a2 = sigmoid(z2)      a2 = np.hstack((np.ones((m,1)),a2))      z3 = np.dot(a2,np.transpose(Theta2))      h  = sigmoid(z3)          '''代价'''          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               return np.ravel(J)</code></pre>    <h3>4、反向传播BP</h3>    <ul>     <li> <p>上面正向传播可以计算得到 J(θ) ,使用梯度下降法还需要求它的梯度</p> </li>     <li> <p>BP反向传播的目的就是求代价函数的梯度</p> </li>     <li> <p>假设4层的神经网络, 记为--> l 层第 j 个单元的误差</p> </li>     <li> <p>《===》 (向量化)</p> </li>     <li> <p> </p> </li>     <li> <p> </p> </li>     <li> <p>没有 ,因为对于输入没有误差</p> </li>     <li> <p>因为S型函数 的导数为: ,所以上面的 和 可以在前向传播中计算出来</p> </li>     <li> <p>反向传播计算梯度的过程为:</p> </li>     <li> <p>( 是大写的 )</p> </li>     <li> <p>for i=1-m:</p> <p>-</p> <p>-正向传播计算 (l=2,3,4...L)</p> <p>-反向计算 、 ... ;</p> <p>-</p> <p>-</p> </li>     <li> <p>最后 ,即得到代价函数的梯度</p> </li>     <li> <p>实现代码:</p> </li>    </ul>    <pre>  <code class="language-python"># 梯度  def nnGradient(nn_params,input_layer_size,hidden_layer_size,num_labels,X,y,Lambda):      length = nn_params.shape[0]      Theta1 = nn_params[0:hidden_layer_size*(input_layer_size+1)].reshape(hidden_layer_size,input_layer_size+1).copy()   # 这里使用copy函数,否则下面修改Theta的值,nn_params也会一起修改      Theta2 = nn_params[hidden_layer_size*(input_layer_size+1):length].reshape(num_labels,hidden_layer_size+1).copy()      m = X.shape[0]      class_y = np.zeros((m,num_labels))      # 数据的y对应0-9,需要映射为0/1的关系          # 映射y      for i in range(num_labels):          class_y[:,i] = np.int32(y==i).reshape(1,-1) # 注意reshape(1,-1)才可以赋值             '''去掉theta1和theta2的第一列,因为正则化时从1开始'''      Theta1_colCount = Theta1.shape[1]          Theta1_x = Theta1[:,1:Theta1_colCount]      Theta2_colCount = Theta2.shape[1]          Theta2_x = Theta2[:,1:Theta2_colCount]            Theta1_grad = np.zeros((Theta1.shape))  #第一层到第二层的权重      Theta2_grad = np.zeros((Theta2.shape))  #第二层到第三层的权重                   '''正向传播,每次需要补上一列1的偏置bias'''      a1 = np.hstack((np.ones((m,1)),X))      z2 = np.dot(a1,np.transpose(Theta1))      a2 = sigmoid(z2)      a2 = np.hstack((np.ones((m,1)),a2))      z3 = np.dot(a2,np.transpose(Theta2))      h  = sigmoid(z3)                  '''反向传播,delta为误差,'''      delta3 = np.zeros((m,num_labels))      delta2 = np.zeros((m,hidden_layer_size))      for i in range(m):          #delta3[i,:] = (h[i,:]-class_y[i,:])*sigmoidGradient(z3[i,:])  # 均方误差的误差率          delta3[i,:] = h[i,:]-class_y[i,:]                              # 交叉熵误差率          Theta2_grad = Theta2_grad+np.dot(np.transpose(delta3[i,:].reshape(1,-1)),a2[i,:].reshape(1,-1))          delta2[i,:] = np.dot(delta3[i,:].reshape(1,-1),Theta2_x)*sigmoidGradient(z2[i,:])          Theta1_grad = Theta1_grad+np.dot(np.transpose(delta2[i,:].reshape(1,-1)),a1[i,:].reshape(1,-1))            Theta1[:,0] = 0      Theta2[:,0] = 0                '''梯度'''      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      return np.ravel(grad)</code></pre>    <h3>5、BP可以求梯度的原因</h3>    <ul>     <li>实际是利用了 链式求导 法则</li>     <li>因为下一层的单元利用上一层的单元作为输入进行计算</li>     <li>大体的推导过程如下,最终我们是想预测函数与已知的 y 非常接近,求均方差的梯度沿着此梯度方向可使代价函数最小化。可对照上面求梯度的过程。 <img src="https://simg.open-open.com/show/a3d18494dbd0ca1bb6d87dda5ec7f296.jpg"></li>     <li>求误差更详细的推导过程: <img src="https://simg.open-open.com/show/b027e7d4281eb88a3b81b07266c6856e.png"></li>    </ul>    <h3>6、梯度检查</h3>    <ul>     <li>检查利用 BP 求的梯度是否正确</li>     <li>利用导数的定义验证:</li>     <li>求出来的数值梯度应该与BP求出的梯度非常接近</li>     <li>验证BP正确后就不需要再执行验证梯度的算法了</li>     <li>实现代码:</li>    </ul>    <pre>  <code class="language-python"># 检验梯度是否计算正确  # 检验梯度是否计算正确  def checkGradient(Lambda = 0):      '''构造一个小型的神经网络验证,因为数值法计算梯度很浪费时间,而且验证正确后之后就不再需要验证了'''      input_layer_size = 3      hidden_layer_size = 5      num_labels = 3      m = 5      initial_Theta1 = debugInitializeWeights(input_layer_size,hidden_layer_size);       initial_Theta2 = debugInitializeWeights(hidden_layer_size,num_labels)      X = debugInitializeWeights(input_layer_size-1,m)      y = 1+np.transpose(np.mod(np.arange(1,m+1), num_labels))# 初始化y            y = y.reshape(-1,1)      nn_params = np.vstack((initial_Theta1.reshape(-1,1),initial_Theta2.reshape(-1,1)))  #展开theta       '''BP求出梯度'''      grad = nnGradient(nn_params, input_layer_size, hidden_layer_size,                        num_labels, X, y, Lambda)        '''使用数值法计算梯度'''      num_grad = np.zeros((nn_params.shape[0]))      step = np.zeros((nn_params.shape[0]))      e = 1e-4      for i in range(nn_params.shape[0]):          step[i] = e          loss1 = nnCostFunction(nn_params-step.reshape(-1,1), input_layer_size, hidden_layer_size,                                 num_labels, X, y,                                 Lambda)          loss2 = nnCostFunction(nn_params+step.reshape(-1,1), input_layer_size, hidden_layer_size,                                 num_labels, X, y,                                 Lambda)          num_grad[i] = (loss2-loss1)/(2*e)          step[i]=0      # 显示两列比较      res = np.hstack((num_grad.reshape(-1,1),grad.reshape(-1,1)))      print res</code></pre>    <h3>7、权重的随机初始化</h3>    <ul>     <li>神经网络不能像逻辑回归那样初始化 theta 为 0 ,因为若是每条边的权重都为0,每个神经元都是相同的输出,在反向传播中也会得到同样的梯度,最终只会预测一种结果。</li>     <li>所以应该初始化为接近0的数</li>     <li>实现代码</li>    </ul>    <pre>  <code class="language-python"># 随机初始化权重theta  def randInitializeWeights(L_in,L_out):      W = np.zeros((L_out,1+L_in))    # 对应theta的权重      epsilon_init = (6.0/(L_out+L_in))**0.5      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)大小的随机矩阵      return W</code></pre>    <h3>8、预测</h3>    <ul>     <li>正向传播预测结果</li>     <li>实现代码</li>    </ul>    <pre>  <code class="language-python"># 预测  def predict(Theta1,Theta2,X):      m = X.shape[0]      num_labels = Theta2.shape[0]      #p = np.zeros((m,1))      '''正向传播,预测结果'''      X = np.hstack((np.ones((m,1)),X))      h1 = sigmoid(np.dot(X,np.transpose(Theta1)))      h1 = np.hstack((np.ones((m,1)),h1))      h2 = sigmoid(np.dot(h1,np.transpose(Theta2)))            '''      返回h中每一行最大值所在的列号      - np.max(h, axis=1)返回h中每一行的最大值(是某个数字的最大概率)      - 最后where找到的最大概率所在的列号(列号即是对应的数字)      '''      #np.savetxt("h2.csv",h2,delimiter=',')      p = np.array(np.where(h2[0,:] == np.max(h2, axis=1)[0]))        for i in np.arange(1, m):          t = np.array(np.where(h2[i,:] == np.max(h2, axis=1)[i]))          p = np.vstack((p,t))      return p</code></pre>    <h3>9、输出结果</h3>    <ul>     <li>梯度检查:<br> <img src="https://simg.open-open.com/show/6e2648a57a400f2c688f00183cbfc428.png"></li>     <li>随机显示100个手写数字<br> <img src="https://simg.open-open.com/show/31bfb5fb0beac745c9ce418955dc4860.png"></li>     <li>显示theta1权重<br> <img src="https://simg.open-open.com/show/f5d2e6545fe0146d3c6d017a385d4fe3.png"></li>     <li>训练集预测准确度<br> <img src="https://simg.open-open.com/show/0e6c7f49f0742b295deb24214e2cb3c6.png"></li>     <li>归一化后训练集预测准确度<br> <img src="https://simg.open-open.com/show/57a267afd5bba33ab6a065a2e209b949.png"></li>    </ul>    <h2>四、SVM支持向量机</h2>    <h3>1、代价函数</h3>    <ul>     <li>在逻辑回归中,我们的代价为:<br> ,<br> 其中: ,</li>     <li>如图所示,如果 y=1 , cost 代价函数如图所示<br> <img src="https://simg.open-open.com/show/ee66b71fc0a2cad395bcb7ff8674f315.png"><br> 我们想让 ,即 z>>0 ,这样的话 cost 代价函数才会趋于最小(这是我们想要的),所以用途中 <strong>红色</strong> 的函数 代替逻辑回归中的cost</li>     <li>当 y=0 时同样,用 代替 <img src="https://simg.open-open.com/show/35a975b800bb3565ec0a210c096e56a3.png"></li>     <li>最终得到的代价函数为:<br> <br> 最后我们想要</li>     <li>之前我们逻辑回归中的代价函数为:<br> <br> 可以认为这里的 ,只是表达形式问题,这里 C 的值越大,SVM的决策边界的 margin 也越大,下面会说明</li>    </ul>    <h3>2、Large Margin</h3>    <ul>     <li> <p>如下图所示,SVM分类会使用最大的 margin 将其分开</p> <img src="https://simg.open-open.com/show/c55502123f459a01e068ddc0d47b3d34.png"></li>     <li> <p>先说一下向量内积</p> </li>     <li> <p>,</p> </li>     <li> <p>表示 u 的 <strong>欧几里得范数</strong> (欧式范数),</p> </li>     <li> <p>向量V 在 向量u 上的投影的长度记为 p ,则:向量内积:</p> <p> </p> <p><img src="https://simg.open-open.com/show/d02425c722dea1c4e956556ba43af994.png"></p> <p>根据向量夹角公式推导一下即可,</p> </li>     <li> <p>前面说过,当 C 越大时, margin 也就越大,我们的目的是最小化代价函数 J(θ) ,当 margin 最大时, C 的乘积项 要很小,所以近似为:</p> <p>,</p> <p>我们最后的目的就是求使代价最小的 θ</p> </li>     <li> <p>由</p> <p>可以得到:</p> <p>, p 即为 x 在 θ 上的投影</p> </li>     <li> <p>如下图所示,假设决策边界如图,找其中的一个点,到 θ 上的投影为 p ,则 或者 ,若是 p 很小,则需要 很大,这与我们要求的 θ 使 <img src="https://simg.open-open.com/show/20dd44cad304b90f49e7198af5c978d7.gif"> 最小相违背, <strong>所以</strong> 最后求的是 large margin<br> <img src="https://simg.open-open.com/show/692c545b006bc60d55f6f0795d12f314.png"></p> </li>    </ul>    <h3>3、SVM Kernel(核函数)</h3>    <ul>     <li> <p>对于线性可分的问题,使用 <strong>线性核函数</strong> 即可</p> </li>     <li> <p>对于线性不可分的问题,在逻辑回归中,我们是将 feature 映射为使用多项式的形式 , SVM 中也有 <strong>多项式核函数</strong> ,但是更常用的是 <strong>高斯核函数</strong> ,也称为 <strong>RBF核</strong></p> </li>     <li> <p>高斯核函数为:</p> <p>假设如图几个点, <img src="https://simg.open-open.com/show/a2ff179d5177a14c32811be21cddcb2c.png"> 令:</p> <p> </p> <p>. . .</p> </li>     <li> <p>可以看出,若是 x 与 距离较近,==》 ,(即相似度较大)</p> <p>若是 x 与 距离较远,==》 ,(即相似度较低)</p> </li>     <li> <p>高斯核函数的 σ 越小, f 下降的越快</p> <img src="https://simg.open-open.com/show/25d47f66495be6662547f3f10844b725.png"> <img src="https://simg.open-open.com/show/49e2fadf6c5edbc03b6fea6e9ba33a04.png"></li>     <li> <p>如何选择初始的</p> </li>     <li> <p>训练集:</p> </li>     <li> <p>选择:</p> </li>     <li> <p>对于给出的 x ,计算 f ,令: 所以:</p> </li>     <li> <p>最小化 J 求出 θ ,</p> </li>     <li> <p>如果 ,==》预测 y=1</p> </li>    </ul>    <h3>4、使用 scikit-learn 中的 SVM 模型代码</h3>    <ul>     <li><a href="/misc/goto?guid=4959756255422627128" rel="nofollow,noindex">全部代码</a></li>     <li>线性可分的,指定核函数为 linear :</li>    </ul>    <pre>  <code class="language-python">'''data1——线性分类'''      data1 = spio.loadmat('data1.mat')      X = data1['X']      y = data1['y']      y = np.ravel(y)      plot_data(X,y)            model = svm.SVC(C=1.0,kernel='linear').fit(X,y) # 指定核函数为线性核函数</code></pre>    <ul>     <li>非线性可分的,默认核函数为 rbf</li>    </ul>    <pre>  <code class="language-python">'''data2——非线性分类'''      data2 = spio.loadmat('data2.mat')      X = data2['X']      y = data2['y']      y = np.ravel(y)      plt = plot_data(X,y)      plt.show()            model = svm.SVC(gamma=100).fit(X,y)     # gamma为核函数的系数,值越大拟合的越好</code></pre>    <h3>5、运行结果</h3>    <ul>     <li>线性可分的决策边界:<br> <img src="https://simg.open-open.com/show/3b1bfa14742ad9553fdd53e654ef38f9.png"></li>     <li>线性不可分的决策边界:<br> <img src="https://simg.open-open.com/show/f7af6d12917a17d683a2dce71576eb93.png"></li>    </ul>    <h2>五、K-Means聚类算法</h2>    <ul>     <li><a href="/misc/goto?guid=4959756255503928278" rel="nofollow,noindex">全部代码</a></li>    </ul>    <h3>1、聚类过程</h3>    <ul>     <li> <p>聚类属于无监督学习,不知道y的标记分为K类</p> </li>     <li> <p>K-Means算法分为两个步骤</p> </li>     <li> <p>第一步:簇分配,随机选 K 个点作为中心,计算到这 K 个点的距离,分为 K 个簇</p> </li>     <li> <p>第二步:移动聚类中心:重新计算每个 <strong>簇</strong> 的中心,移动中心,重复以上步骤。</p> </li>     <li> <p>如下图所示:</p> </li>     <li> <p>随机分配的聚类中心</p> <img src="https://simg.open-open.com/show/9c7b6aa20e2f11406a9a26af53f55b4f.png"></li>     <li> <p>重新计算聚类中心,移动一次</p> <img src="https://simg.open-open.com/show/53dc889491a4eb3fd5a3a7cba20d5000.png"></li>     <li> <p>最后 10 步之后的聚类中心</p> <img src="https://simg.open-open.com/show/764ac9bae487e55a3730d4e3267a30d3.png"></li>     <li> <p>计算每条数据到哪个中心最近实现代码:</p> </li>    </ul>    <pre>  <code class="language-python"># 找到每条数据距离哪个类中心最近      def findClosestCentroids(X,initial_centroids):      m = X.shape[0]                  # 数据条数      K = initial_centroids.shape[0]  # 类的总数      dis = np.zeros((m,K))           # 存储计算每个点分别到K个类的距离      idx = np.zeros((m,1))           # 要返回的每条数据属于哪个类            '''计算每个点到每个类中心的距离'''      for i in range(m):          for j in range(K):              dis[i,j] = np.dot((X[i,:]-initial_centroids[j,:]).reshape(1,-1),(X[i,:]-initial_centroids[j,:]).reshape(-1,1))            '''返回dis每一行的最小值对应的列号,即为对应的类别      - np.min(dis, axis=1)返回每一行的最小值      - np.where(dis == np.min(dis, axis=1).reshape(-1,1)) 返回对应最小值的坐标       - 注意:可能最小值对应的坐标有多个,where都会找出来,所以返回时返回前m个需要的即可(因为对于多个最小值,属于哪个类别都可以)      '''        dummy,idx = np.where(dis == np.min(dis, axis=1).reshape(-1,1))      return idx[0:dis.shape[0]]  # 注意截取一下</code></pre>    <ul>     <li>计算类中心实现代码:</li>    </ul>    <pre>  <code class="language-python"># 计算类中心  def computerCentroids(X,idx,K):      n = X.shape[1]      centroids = np.zeros((K,n))      for i in range(K):          centroids[i,:] = np.mean(X[np.ravel(idx==i),:], axis=0).reshape(1,-1)   # 索引要是一维的,axis=0为每一列,idx==i一次找出属于哪一类的,然后计算均值      return centroids</code></pre>    <h3>2、目标函数</h3>    <ul>     <li>也叫做 <strong>失真代价函数</strong></li>     <li> </li>     <li>最后我们想得到:<br> <img src="https://simg.open-open.com/show/0b64abb1021dd21522cf499adae8bbad.png"></li>     <li>其中 表示第 i 条数据距离哪个类中心最近,</li>     <li>其中 即为聚类的中心</li>    </ul>    <h3>3、聚类中心的选择</h3>    <ul>     <li>随机初始化,从给定的数据中随机抽取K个作为聚类中心</li>     <li>随机一次的结果可能不好,可以随机多次,最后取使代价函数最小的作为中心</li>     <li>实现代码:(这里随机一次)</li>    </ul>    <pre>  <code class="language-python"># 初始化类中心--随机取K个点作为聚类中心  def kMeansInitCentroids(X,K):      m = X.shape[0]      m_arr = np.arange(0,m)      # 生成0-m-1      centroids = np.zeros((K,X.shape[1]))      np.random.shuffle(m_arr)    # 打乱m_arr顺序          rand_indices = m_arr[:K]    # 取前K个      centroids = X[rand_indices,:]      return centroids</code></pre>    <h3>4、聚类个数K的选择</h3>    <ul>     <li>聚类是不知道y的label的,所以不知道真正的聚类个数</li>     <li>肘部法则(Elbow method)</li>     <li>作代价函数 J 和 K 的图,若是出现一个拐点,如下图所示, K 就取拐点处的值,下图此时 K=3 <img src="https://simg.open-open.com/show/7a16ea5b8762257bd59f7e3782a6ed07.png"></li>     <li>若是很平滑就不明确,人为选择。</li>     <li>第二种就是人为观察选择</li>    </ul>    <h3>5、应用——图片压缩</h3>    <ul>     <li>将图片的像素分为若干类,然后用这个类代替原来的像素值</li>     <li>执行聚类的算法代码:</li>    </ul>    <pre>  <code class="language-python"># 聚类算法  def runKMeans(X,initial_centroids,max_iters,plot_process):      m,n = X.shape                   # 数据条数和维度      K = initial_centroids.shape[0]  # 类数      centroids = initial_centroids   # 记录当前类中心      previous_centroids = centroids  # 记录上一次类中心      idx = np.zeros((m,1))           # 每条数据属于哪个类            for i in range(max_iters):      # 迭代次数          print u'迭代计算次数:%d'%(i+1)          idx = findClosestCentroids(X, centroids)          if plot_process:    # 如果绘制图像              plt = plotProcessKMeans(X,centroids,previous_centroids) # 画聚类中心的移动过程              previous_centroids = centroids  # 重置          centroids = computerCentroids(X, idx, K)    # 重新计算类中心      if plot_process:    # 显示最终的绘制结果          plt.show()      return centroids,idx    # 返回聚类中心和数据属于哪个类</code></pre>    <h3>6、 <a href="/misc/goto?guid=4959756255577508373" rel="nofollow,noindex">使用scikit-learn库中的线性模型实现聚类</a></h3>    <ul>     <li>导入包</li>    </ul>    <pre>  <code class="language-python">from sklearn.cluster import KMeans</code></pre>    <ul>     <li>使用模型拟合数据</li>    </ul>    <pre>  <code class="language-python">model = KMeans(n_clusters=3).fit(X) # n_clusters指定3类,拟合数据</code></pre>    <ul>     <li>聚类中心</li>    </ul>    <pre>  <code class="language-python">centroids = model.cluster_centers_  # 聚类中心</code></pre>    <h3>7、运行结果</h3>    <ul>     <li>二维数据类中心的移动<br> <img src="https://simg.open-open.com/show/d2921ff46010a431cf27b29e8b68c57a.png"></li>     <li>图片压缩<br> <img src="https://simg.open-open.com/show/c335e64d7057ce6cf7cab7e8961d2e71.png"></li>    </ul>    <h2>六、PCA主成分分析(降维)</h2>    <ul>     <li><a href="/misc/goto?guid=4959756255665358038" rel="nofollow,noindex">全部代码</a></li>    </ul>    <h3>1、用处</h3>    <ul>     <li>数据压缩(Data Compression),使程序运行更快</li>     <li>可视化数据,例如 3D-->2D 等</li>     <li>......</li>    </ul>    <h3>2、2D-->1D,nD-->kD</h3>    <ul>     <li>如下图所示,所有数据点可以投影到一条直线,是 <strong>投影距离的平方和</strong> (投影误差)最小 <img src="https://simg.open-open.com/show/edce605f7fe47551cccd798f9d883bb8.png"></li>     <li>注意数据需要 归一化 处理</li>     <li>思路是找 1 个 向量u ,所有数据投影到上面使投影距离最小</li>     <li>那么 nD-->kD 就是找 k 个向量 ,所有数据投影到上面使投影误差最小</li>     <li>eg:3D-->2D,2个向量 就代表一个平面了,所有点投影到这个平面的投影误差最小即可</li>    </ul>    <h3>3、主成分分析PCA与线性回归的区别</h3>    <ul>     <li>线性回归是找 x 与 y 的关系,然后用于预测 y</li>     <li>PCA 是找一个投影面,最小化data到这个投影面的投影误差</li>    </ul>    <h3>4、PCA降维过程</h3>    <ul>     <li>数据预处理(均值归一化)</li>     <li>公式:</li>     <li>就是减去对应feature的均值,然后除以对应特征的标准差(也可以是最大值-最小值)</li>     <li>实现代码:</li>    </ul>    <pre>  <code class="language-python"># 归一化数据     def featureNormalize(X):         '''(每一个数据-当前列的均值)/当前列的标准差'''         n = X.shape[1]         mu = np.zeros((1,n));         sigma = np.zeros((1,n))                  mu = np.mean(X,axis=0)         sigma = np.std(X,axis=0)         for i in range(n):             X[:,i] = (X[:,i]-mu[i])/sigma[i]         return X,mu,sigma</code></pre>    <ul>     <li>计算 协方差矩阵Σ (Covariance Matrix):</li>     <li>注意这里的 Σ 和求和符号不同</li>     <li>协方差矩阵 对称正定 (不理解正定的看看线代)</li>     <li>大小为 nxn , n 为 feature 的维度</li>     <li>实现代码:</li>    </ul>    <pre>  <code class="language-python">Sigma = np.dot(np.transpose(X_norm),X_norm)/m  # 求Sigma</code></pre>    <ul>     <li>计算 Σ 的特征值和特征向量</li>     <li>可以是用 svd 奇异值分解函数: U,S,V = svd(Σ)</li>     <li>返回的是与 Σ 同样大小的对角阵 S (由 Σ 的特征值组成)[ <strong>注意</strong> : matlab 中函数返回的是对角阵,在 python 中返回的是一个向量,节省空间]</li>     <li>还有两个 <strong>酉矩阵</strong> U和V,且</li>     <li><img src="https://simg.open-open.com/show/6c7d1c8cf08bb745dde82ca5d67b5974.png"></li>     <li><strong>注意</strong> : svd 函数求出的 S 是按特征值降序排列的,若不是使用 svd ,需要按 <strong>特征值</strong> 大小重新排列 U</li>     <li>降维</li>     <li>选取 U 中的前 K 列(假设要降为 K 维)</li>     <li><img src="https://simg.open-open.com/show/c42f7ade26da3ad2d06d7fd2fcb3d0e0.png"></li>     <li>Z 就是对应降维之后的数据</li>     <li>实现代码:</li>    </ul>    <pre>  <code class="language-python"># 映射数据     def projectData(X_norm,U,K):         Z = np.zeros((X_norm.shape[0],K))                  U_reduce = U[:,0:K]          # 取前K个         Z = np.dot(X_norm,U_reduce)          return Z</code></pre>    <ul>     <li>过程总结:</li>     <li>Sigma = X'*X/m</li>     <li>U,S,V = svd(Sigma)</li>     <li>Ureduce = U[:,0:k]</li>     <li>Z = Ureduce'*x</li>    </ul>    <h3>5、数据恢复</h3>    <ul>     <li>因为:</li>     <li>所以: (注意这里是X的近似值)</li>     <li>又因为 Ureduce 为正定矩阵,【正定矩阵满足: ,所以: 】,所以这里:</li>     <li> </li>     <li>实现代码:</li>    </ul>    <pre>  <code class="language-python"># 恢复数据       def recoverData(Z,U,K):          X_rec = np.zeros((Z.shape[0],U.shape[0]))          U_recude = U[:,0:K]          X_rec = np.dot(Z,np.transpose(U_recude))  # 还原数据(近似)          return X_rec</code></pre>    <h3>6、主成分个数的选择(即要降的维度)</h3>    <ul>     <li>如何选择</li>     <li><strong>投影误差</strong> (project error):</li>     <li><strong>总变差</strong> (total variation):</li>     <li>若 <strong>误差率</strong> (error ratio): ,则称 99% 保留差异性</li>     <li>误差率一般取 1%,5%,10% 等</li>     <li>如何实现</li>     <li>若是一个个试的话代价太大</li>     <li>之前 U,S,V = svd(Sigma) ,我们得到了 S ,这里误差率error ratio:</li>     <li>可以一点点增加 K 尝试。</li>    </ul>    <h3>7、使用建议</h3>    <ul>     <li>不要使用PCA去解决过拟合问题 Overfitting ,还是使用正则化的方法(如果保留了很高的差异性还是可以的)</li>     <li>只有在原数据上有好的结果,但是运行很慢,才考虑使用PCA</li>    </ul>    <h3>8、运行结果</h3>    <ul>     <li>2维数据降为1维</li>     <li>要投影的方向<br> <img src="https://simg.open-open.com/show/fa850c56bab6c82c39aa5523cc6bd074.png"></li>     <li>2D降为1D及对应关系<br> <img src="https://simg.open-open.com/show/6042dda7be4c07595a8f3a57f126cd1e.png"></li>     <li>人脸数据降维</li>     <li>原始数据<br> <img src="https://simg.open-open.com/show/1f976e74de3187766fc3ef9c577fe807.png"></li>     <li>可视化部分 U 矩阵信息<br> <img src="https://simg.open-open.com/show/96348f3a2fdb3099b2f0a78a0a15de90.png"></li>     <li>恢复数据<br> <img src="https://simg.open-open.com/show/7eabf1acb9918651905394faae0fbf1a.png"></li>    </ul>    <h3>9、 <a href="/misc/goto?guid=4959756255744986819" rel="nofollow,noindex">使用scikit-learn库中的PCA实现降维</a></h3>    <ul>     <li>导入需要的包:</li>    </ul>    <pre>  <code class="language-python">#-*- coding: utf-8 -*-  # Author:bob  # Date:2016.12.22  import numpy as np  from matplotlib import pyplot as plt  from scipy import io as spio  from sklearn.decomposition import pca  from sklearn.preprocessing import StandardScaler</code></pre>    <ul>     <li>归一化数据</li>    </ul>    <pre>  <code class="language-python">'''归一化数据并作图'''      scaler = StandardScaler()      scaler.fit(X)      x_train = scaler.transform(X)</code></pre>    <ul>     <li>使用PCA模型拟合数据,并降维</li>     <li>n_components 对应要将的维度</li>    </ul>    <pre>  <code class="language-python">'''拟合数据'''      K=1 # 要降的维度      model = pca.PCA(n_components=K).fit(x_train)   # 拟合数据,n_components定义要降的维度      Z = model.transform(x_train)    # transform就会执行降维操作</code></pre>    <ul>     <li>数据恢复</li>     <li>model.components_ 会得到降维使用的 U 矩阵</li>    </ul>    <pre>  <code class="language-python">'''数据恢复并作图'''      Ureduce = model.components_     # 得到降维用的Ureduce      x_rec = np.dot(Z,Ureduce)       # 数据恢复</code></pre>    <h2>七、异常检测 Anomaly Detection</h2>    <ul>     <li><a href="/misc/goto?guid=4959756255820987636" rel="nofollow,noindex">全部代码</a></li>    </ul>    <h3>1、高斯分布(正态分布) Gaussian distribution</h3>    <ul>     <li>分布函数:</li>     <li>其中, u 为数据的 <strong>均值</strong> , σ 为数据的 <strong>标准差</strong></li>     <li>σ 越 <strong>小</strong> ,对应的图像越 <strong>尖</strong></li>     <li>参数估计( parameter estimation )</li>     <li><img src="https://simg.open-open.com/show/66207c6d6d50546ea7dbe49ad82a0b8a.png"></li>     <li> </li>    </ul>    <h3>2、异常检测算法</h3>    <ul>     <li>例子</li>     <li>训练集: ,其中</li>     <li>假设 相互独立,建立model模型:</li>     <li>过程</li>     <li>选择具有代表异常的 feature :xi</li>     <li>参数估计:</li>     <li>计算 p(x) ,若是 P(x)<ε 则认为异常,其中 ε 为我们要求的概率的临界值 threshold</li>     <li>这里只是 <strong>单元高斯分布</strong> ,假设了 feature 之间是独立的,下面会讲到 <strong>多元高斯分布</strong> ,会自动捕捉到 feature 之间的关系</li>     <li><strong>参数估计</strong> 实现代码</li>    </ul>    <pre>  <code class="language-python"># 参数估计函数(就是求均值和方差)  def estimateGaussian(X):      m,n = X.shape      mu = np.zeros((n,1))      sigma2 = np.zeros((n,1))            mu = np.mean(X, axis=0) # axis=0表示列,每列的均值      sigma2 = np.var(X,axis=0) # 求每列的方差      return mu,sigma2</code></pre>    <h3>3、评价 p(x) 的好坏,以及 ε 的选取</h3>    <ul>     <li> <p>对 <strong>偏斜数据</strong> 的错误度量</p> </li>     <li> <p>因为数据可能是非常 <strong>偏斜</strong> 的(就是 y=1 的个数非常少,( y=1 表示异常)),所以可以使用 Precision/Recall ,计算 F1Score (在 <strong>CV交叉验证集</strong> 上)</p> </li>     <li> <p>例如:预测癌症,假设模型可以得到 99% 能够预测正确, 1% 的错误率,但是实际癌症的概率很小,只有 0.5% ,那么我们始终预测没有癌症y=0反而可以得到更小的错误率。使用 error rate 来评估就不科学了。</p> </li>     <li> <p>如下图记录:</p> <img src="https://simg.open-open.com/show/299fe51bc7de6ac4b9f715245cc4858f.png"></li>     <li> <p><img src="https://simg.open-open.com/show/dcd79f08a3490f3caede90054a70b331.png"> ,即: <strong>正确预测正样本/所有预测正样本</strong></p> </li>     <li> <p>,即: <strong>正确预测正样本/真实值为正样本</strong></p> </li>     <li> <p>总是让 y=1 (较少的类),计算 Precision 和 Recall</p> </li>     <li> <p><img src="https://simg.open-open.com/show/4db5a314024ccf59bed9eae97ee7b07b.png"></p> </li>     <li> <p>还是以癌症预测为例,假设预测都是no-cancer,TN=199,FN=1,TP=0,FP=0,所以:Precision=0/0,Recall=0/1=0,尽管accuracy=199/200=99.5%,但是不可信。</p> </li>     <li> <p>ε 的选取</p> </li>     <li> <p>尝试多个 ε 值,使 F1Score 的值高</p> </li>     <li> <p>实现代码</p> </li>    </ul>    <pre>  <code class="language-python"># 选择最优的epsilon,即:使F1Score最大      def selectThreshold(yval,pval):      '''初始化所需变量'''      bestEpsilon = 0.      bestF1 = 0.      F1 = 0.      step = (np.max(pval)-np.min(pval))/1000      '''计算'''      for epsilon in np.arange(np.min(pval),np.max(pval),step):          cvPrecision = pval<epsilon          tp = np.sum((cvPrecision == 1) & (yval == 1)).astype(float)  # sum求和是int型的,需要转为float          fp = np.sum((cvPrecision == 1) & (yval == 0)).astype(float)          fn = np.sum((cvPrecision == 1) & (yval == 0)).astype(float)          precision = tp/(tp+fp)  # 精准度          recision = tp/(tp+fn)   # 召回率          F1 = (2*precision*recision)/(precision+recision)  # F1Score计算公式          if F1 > bestF1:  # 修改最优的F1 Score              bestF1 = F1              bestEpsilon = epsilon      return bestEpsilon,bestF1</code></pre>    <h3>4、选择使用什么样的feature(单元高斯分布)</h3>    <ul>     <li>如果一些数据不是满足高斯分布的,可以变化一下数据,例如 log(x+C),x^(1/2) 等</li>     <li>如果 p(x) 的值无论异常与否都很大,可以尝试组合多个 feature ,(因为feature之间可能是有关系的)</li>    </ul>    <h3>5、多元高斯分布</h3>    <ul>     <li>单元高斯分布存在的问题</li>     <li>如下图,红色的点为异常点,其他的都是正常点(比如CPU和memory的变化)<br> <img src="https://simg.open-open.com/show/c9f958308ad27e69d62df410c070ed15.png"></li>     <li>x1对应的高斯分布如下:<br> <img src="https://simg.open-open.com/show/676d32948bd8704e0a6604709cd95f72.png"></li>     <li>x2对应的高斯分布如下:<br> <img src="https://simg.open-open.com/show/321722f501b205fabc35310f15636f90.png"></li>     <li>可以看出对应的p(x1)和p(x2)的值变化并不大,就不会认为异常</li>     <li>因为我们认为feature之间是相互独立的,所以如上图是以 <strong>正圆</strong> 的方式扩展</li>     <li>多元高斯分布</li>     <li>,并不是建立 p(x1),p(x2)...p(xn) ,而是统一建立 p(x)</li>     <li>其中参数: , Σ 为 <strong>协方差矩阵</strong></li>     <li> </li>     <li>同样, |Σ| 越小, p(x) 越尖</li>     <li>例如:<br> <img src="https://simg.open-open.com/show/f1258a0544c41c3f612999b964b07612.png"> ,<br> 表示x1,x2 <strong>正相关</strong> ,即x1越大,x2也就越大,如下图,也就可以将红色的异常点检查出了 <img src="https://simg.open-open.com/show/56215229a2066598e66c3925c5b46344.png"><br> 若:<br> <img src="https://simg.open-open.com/show/e7e2ce5f6cbfe8b7911b4df56d8c9001.png"> ,<br> 表示x1,x2 <strong>负相关</strong></li>     <li>实现代码:</li>    </ul>    <pre>  <code class="language-python"># 多元高斯分布函数      def multivariateGaussian(X,mu,Sigma2):      k = len(mu)      if (Sigma2.shape[0]>1):          Sigma2 = np.diag(Sigma2)      '''多元高斯分布函数'''          X = X-mu      argu = (2*np.pi)**(-k/2)*np.linalg.det(Sigma2)**(-0.5)      p = argu*np.exp(-0.5*np.sum(np.dot(X,np.linalg.inv(Sigma2))*X,axis=1))  # axis表示每行      return p</code></pre>    <h3>6、单元和多元高斯分布特点</h3>    <ul>     <li>单元高斯分布</li>     <li>人为可以捕捉到 feature 之间的关系时可以使用</li>     <li>计算量小</li>     <li>多元高斯分布</li>     <li>自动捕捉到相关的feature</li>     <li>计算量大,因为:</li>     <li>m>n 或 Σ 可逆时可以使用。(若不可逆,可能有冗余的x,因为线性相关,不可逆,或者就是m<n)</li>    </ul>    <h3>7、程序运行结果</h3>    <ul>     <li>显示数据<br> <img src="https://simg.open-open.com/show/140feff8700f9bab6318164da0d93e38.png"></li>     <li>等高线<br> <img src="https://simg.open-open.com/show/586761b5fd35ac00e85653adf6413967.png"></li>     <li>异常点标注<br> <img src="https://simg.open-open.com/show/7284e6f51715498fb95aa72c28848fa0.png"></li>    </ul>    <p> </p>    <p> </p>