#### 目录

3. 训练一个Softmax线性分类器

3.2 计算分类分数（class scores）

3.4 计算交叉熵损失函数

3.7 组装到一起进行训练

## 1. 前言

CS231n Convolutional Neural Networks for Visual Recognition

CS231n-2022 Module1: 神经网络1：Setting Up the Architecture

CS231n-2022 Module1: 神经网络2

CS231n-2022 Module1: 神经网络3：Learning and Evaluation

## 3.1 参数初始化

W通常用零均值、小方差的高斯分布进行初始化，而b则初始化为全0即可。

## 3.4 计算交叉熵损失函数

Softmax分类器使用的损失函数为交叉熵损失函数（softmax loss, cross-entropy loss）。给定一个分布P和一个分布Q，交叉熵定义为([1])：

​​​​​​​

```dscores = probs
dscores[range(num_examples),y] -= 1
dscores /= num_examples
dW = np.dot(X.T, dscores)
db = np.sum(dscores, axis=0, keepdims=True)
dW += reg*W # don't forget the regularization gradient```

​​​​​​​

## 3.7 组装到一起进行训练

### 3.7.2 代码

```# A bit of setup
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# 2.数据生成
M = 100 # number of points per class。原示例中用N，容易混淆。通常用N表示数据集总的样本数。
D = 2   # dimensionality
K = 3   # number of classes
N = M*K # 总样本数
X = np.zeros((N,D)) # data matrix (each row = single example)
y = np.zeros(N, dtype='uint8') # class labels
for j in range(K):
ix = range(M*j,M*(j+1))
t = np.linspace(j*4,(j+1)*4,M) + np.random.randn(M)*0.2 # theta
X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
y[ix] = j
# lets visualize the data:
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
plt.show()
# 3.0 some hyperparameters
step_size = 1e-0
reg = 1e-3 # regularization strength
# 3.1 initialize parameters randomly
W = 0.01 * np.random.randn(D,K)
b = np.zeros((1,K))
num_examples = X.shape[0]
for i in range(200): # Each iteration corresponding to one epoch.
# 3.2 evaluate class scores, [N x K]
scores = np.dot(X, W) + b
# 3.3 compute the class probabilities
exp_scores = np.exp(scores)
probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K]
# 3.4 compute the loss: average cross-entropy loss and regularization
correct_logprobs = -np.log(probs[range(num_examples),y])
data_loss = np.sum(correct_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))
# 3.5 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)))```

。。。

```iteration 170: loss 0.785329
iteration 180: loss 0.785282
iteration 190: loss 0.785249```

`training accuracy: 0.52`

50%的准确度当然不能说好，但是考虑到数据集本来是非线性可分的，现在强行用一个线性分类器来分类，结果不好也是意料之内的事情。为了更直观地看到训练效果，用以下代码将所训练好的分类器的分类边界画出来，如下所示：

```# plot the resulting classifier
h = 0.02
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = np.dot(np.c_[xx.ravel(), yy.ravel()], W) + b
Z = np.argmax(Z, axis=1)
Z = Z.reshape(xx.shape)
fig = plt.figure()
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8)
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
#fig.savefig('spiral_linear.png')```