首页 > 代码库 > Python: Soft_max 分类器

Python: Soft_max 分类器

我们能够建立例如以下的loss function:

Li=?log(pyi)=?log??efyijefj??
<script type="math/tex; mode=display" id="MathJax-Element-11"> L_{i}=-log(p_{y_{i}}) = -log \left( \frac{e^{f_{y_{i}}}}{\sum_{j}e^{f_{j}}} \right) </script>

L=1NiLi+12λklW2k,l
<script type="math/tex; mode=display" id="MathJax-Element-2"> L=\frac{1}{N}\sum_{i}L_{i}+\frac{1}{2}\lambda \sum_{k}\sum_{l}W_{k,l}^{2} </script>

以下我们推导loss对W,b<script type="math/tex" id="MathJax-Element-3">W,b</script>的偏导数,我们能够先计算loss对f<script type="math/tex" id="MathJax-Element-4">f</script>的偏导数,利用链式法则。我们能够得到:

?Li?fk=?Li?pk?pk?fk?pi?fk=pi(1?pk)i=k?pi?fk=?pipkik?Li?fk=?1pyi?pyi?fk=(pk?1{yi=k})
<script type="math/tex; mode=display" id="MathJax-Element-5">\begin{equation*} \begin{split} & \frac{\partial L_{i}}{\partial f_{k}}= \frac{\partial L_{i}}{\partial p_{k}} \frac{\partial p_{k}}{\partial f_{k}} \& \frac{\partial p_{i}}{\partial f_{k}}=p_{i}(1-p_{k}) \quad i=k \& \frac{\partial p_{i}}{\partial f_{k}}=-p_{i}p_{k} \quad i \neq k \& \frac{\partial L_{i}}{\partial f_{k}}=-\frac{1}{p_{y_{i}}} \frac{\partial p_{y_{i}}}{\partial f_{k}}= \left(p_{k}-1\{y_{i}=k \}\right) \end{split} \end{equation*}</script>

进一步,由f=XW+b<script type="math/tex" id="MathJax-Element-6">f=XW+b</script>,可知?f?W=XT,?f?b=1<script type="math/tex" id="MathJax-Element-7">\frac{\partial f}{\partial W}=X^{T}, \frac{\partial f}{\partial b}=1</script>,我们能够得到:

ΔW=?L?W=1N?Li?W+λW=1N?Li?p?p?f?f?W+λWΔb=?L?b=1N?Li?b=1N?Li?p?p?f?f?bW=W?αΔWb=b?αΔb
<script type="math/tex; mode=display" id="MathJax-Element-16">\begin{equation*} \begin{split} & \Delta W=\frac{\partial L}{\partial W} =\frac{1}{N} \frac{\partial L_{i}}{\partial W} + \lambda W =\frac{1}{N} \frac{\partial L_{i}}{\partial p} \frac{\partial p}{\partial f} \frac{\partial f}{\partial W} +\lambda W \& \Delta b=\frac{\partial L}{\partial b} =\frac{1}{N} \frac{\partial L_{i}}{\partial b} =\frac{1}{N} \frac{\partial L_{i}}{\partial p} \frac{\partial p}{\partial f} \frac{\partial f}{\partial b} \& W=W-\alpha \Delta W \& b=b-\alpha \Delta b \end{split} \end{equation*}</script>

以下是用Python实现的soft max 分类器,基于Python 2.7.9, numpy, matplotlib.
代码来源于斯坦福大学的课程: http://cs231n.github.io/neural-networks-case-study/
基本是照搬过来,通过这个程序有助于了解python的语法。

import numpy as np
import matplotlib.pyplot as plt

N = 100  # number of points per class
D = 2    # dimensionality
K = 3    # number of classes
X = np.zeros((N*K,D))    #data matrix (each row = single example)
y = np.zeros(N*K, dtype=‘uint8‘)  # class labels

for j in xrange(K):
  ix = range(N*j,N*(j+1))
  r = np.linspace(0.0,1,N)            # radius
  t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta
  X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
  y[ix] = j

# print y

# lets visualize the data:
plt.scatter(X[:,0], X[:,1], s=40, c=y, alpha=0.5)
plt.show()
#Train a Linear Classifier

# initialize parameters randomly
W = 0.01 * np.random.randn(D,K)
b = np.zeros((1,K))

# some hyperparameters
step_size = 1e-0
reg = 1e-3 # regularization strength

# gradient descent loop
num_examples = X.shape[0]

for i in xrange(200):

  # evaluate class scores, [N x K]
  scores = np.dot(X, W) + b 

  # compute the class probabilities
  exp_scores = np.exp(scores)
  probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K]

  # compute the loss: average cross-entropy loss and regularization
  corect_logprobs = -np.log(probs[range(num_examples),y])
  data_loss = np.sum(corect_logprobs)/num_examples
  reg_loss = 0.5*reg*np.sum(W*W)
  loss = data_loss + reg_loss
  if i % 10 == 0:
    print "iteration %d: loss %f" % (i, loss)

  # compute the gradient on scores
  dscores = probs
  dscores[range(num_examples),y] -= 1
  dscores /= num_examples

  # backpropate the gradient to the parameters (W,b)
  dW = np.dot(X.T, dscores)
  db = np.sum(dscores, axis=0, keepdims=True)

  dW += reg*W     #regularization gradient

  # perform a parameter update
  W += -step_size * dW
  b += -step_size * db

# evaluate training set accuracy
scores = np.dot(X, W) + b
predicted_class = np.argmax(scores, axis=1)
print ‘training accuracy: %.2f‘ % (np.mean(predicted_class == y))

生成的随机数据

技术分享

执行结果

技术分享

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

Python: Soft_max 分类器