2016-05-30

1. 实现线性分类器
2. 改变成神经网络

# 1 生成数据

``````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)在二维平面内的300个点
y = np.zeros(N*K, dtype=&#39;uint8&#39;) # class labels整数形式
for j in xrange(K):
ix = range(N*j,N*(j+1))
t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta第一个linspace意为产生100个数，random是为了让这些角度分开
X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]#c_合并列
y[ix] = j
# lets visualize the data:
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)#c代表颜色，s:scalar 大小 cmap:colormap改变了原始的颜色映射``````

# 3 训练Softmax线性分类器

## 3.1 初始化

``````# initialize parameters randomly
W = 0.01 * np.random.randn(D,K)#每一类需要两个w（因为在2维空间）2x3
b = np.zeros((1,K))#每一类需要一个b 1x3``````

## 3.2 计算类别得分

``````# compute class scores for a linear classifier
scores = np.dot(X, W) + b#300*2乘2*3得到300行3列的矩阵代表每个数据在三类中的得分``````

300x2的X乘2x3W得到300行3列的矩阵代表每个数据在三类中的得分

## 3.3 建立损失函数

Li=?log??efyi&sum;jefj??

L=1N&sum;iLi??????????data loss+12&lambda;&sum;k&sum;lW2k,l??????????????????regularization loss

``````# get unnormalized probabilities
exp_scores = np.exp(scores)#这个score就是前面计算的300*3的矩阵
# normalize them for each example
probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True)#注意这里面的参数axis和keepdims``````

``````corect_logprobs = -np.log(probs[range(num_examples),y])#这里是选择了正确的那一列的概率，然后进行了-log运算 得到300x1个概率
``````

``````# compute the loss: average cross-entropy loss and regularization
data_loss = np.sum(corect_logprobs)/num_examples#300个样本的得分平均值
reg_loss = 0.5*reg*np.sum(W*W)#reg是惩罚因子lambda
loss = data_loss + reg_loss``````

## 3.4 计算反向传播的梯度

pk=efk&sum;jefjLi=?log(pyi)

?L?w=?L?p?p?f?f?w+&lambda;w

?Li?fk=pk?1(yi=k)

``````dscores = probs
dscores[range(num_examples),y] -= 1
dscores /= num_examples#300&times;3的矩阵
dW = np.dot(X.T, dscores)#内积的形式得到的是2&times;3的矩阵
db = np.sum(dscores, axis=0, keepdims=True)
dW += reg*W # don&#39;t forget the regularization gradient``````

## 3.5 更新参数

``````# perform a parameter update
W += -step_size * dW
b += -step_size * db#注意要向着负梯度方向更新噢``````

## 3.6 整合

``````#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

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``````

``````iteration 0: loss 1.096956
iteration 10: loss 0.917265
...........
iteration 180: loss 0.786331
iteration 190: loss 0.786302``````

``````iteration 410: loss 0.762752
iteration 420: loss 0.762751``````

``````# evaluate training set accuracy
scores = np.dot(X, W) + b
predicted_class = np.argmax(scores, axis=1)#返回最大值的列标
print &#39;training accuracy: %.2f&#39; % (np.mean(predicted_class == y))``````

# 4 训练神经网络

## 4.1 初始化数据：

``````# initialize parameters randomly
h = 100 # size of hidden layer=100个神经单元
W = 0.01 * np.random.randn(D,h)#2*100个
b = np.zeros((1,h))#100个
W2 = 0.01 * np.random.randn(h,K)#100*3个
b2 = np.zeros((1,K))#3个``````

## 4.2 先前计算得分

S=max(0,wx+b)&times;w2+b2

``````# evaluate class scores with a 2-layer Neural Network
hidden_layer = np.maximum(0, np.dot(X, W) + b) # note, ReLU activation如果不理解画一个神经网络连接下就行了
scores = np.dot(hidden_layer, W2) + b2``````

## 4.3 计算反向梯度

w2和b2的梯度

``````# backpropate the gradient to the parameters
# first backprop into parameters W2 and b2
dW2 = np.dot(hidden_layer.T, dscores)
db2 = np.sum(dscores, axis=0, keepdims=True)``````

``````dhidden = np.dot(dscores, W2.T)
# backprop the ReLU non-linearity
dhidden[hidden_layer <= 0] = 0``````

``````# finally into W,b
dW = np.dot(X.T, dhidden)
db = np.sum(dhidden, axis=0, keepdims=True)``````

``````# initialize parameters randomly
h = 100 # size of hidden layer
W = 0.01 * np.random.randn(D,h)
b = np.zeros((1,h))
W2 = 0.01 * np.random.randn(h,K)
b2 = np.zeros((1,K))

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

num_examples = X.shape[0]
for i in xrange(10000):

# evaluate class scores, [N x K]
hidden_layer = np.maximum(0, np.dot(X, W) + b) # note, ReLU activation
scores = np.dot(hidden_layer, W2) + b2

# 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) + 0.5*reg*np.sum(W2*W2)
loss = data_loss + reg_loss
if i % 1000 == 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
# first backprop into parameters W2 and b2
dW2 = np.dot(hidden_layer.T, dscores)
db2 = np.sum(dscores, axis=0, keepdims=True)
# next backprop into hidden layer
dhidden = np.dot(dscores, W2.T)
# backprop the ReLU non-linearity
dhidden[hidden_layer <= 0] = 0
# finally into W,b
dW = np.dot(X.T, dhidden)
db = np.sum(dhidden, axis=0, keepdims=True)

dW2 += reg * W2
dW += reg * W

# perform a parameter update
W += -step_size * dW
b += -step_size * db
W2 += -step_size * dW2
b2 += -step_size * db2``````

``````iteration 0: loss 1.098744
iteration 1000: loss 0.294946
iteration 2000: loss 0.259301
iteration 3000: loss 0.248310
iteration 4000: loss 0.246170
iteration 5000: loss 0.245649
iteration 6000: loss 0.245491
iteration 7000: loss 0.245400
iteration 8000: loss 0.245335
iteration 9000: loss 0.245292``````

``````# evaluate training set accuracy
hidden_layer = np.maximum(0, np.dot(X, W) + b)
scores = np.dot(hidden_layer, W2) + b2
predicted_class = np.argmax(scores, axis=1)
print &#39;training accuracy: %.2f&#39; % (np.mean(predicted_class == y))``````