softmax_linear_classifier

来源:互联网 发布:左右删失数据 编辑:程序博客网 时间:2024/05/20 08:22
import numpy as np%matplotlib inlineimport matplotlib.pyplot as plt
N = 100 # number of points per classD = 2 # dimensionalityK = 3 # number of classesX = np.zeros((N*K,D)) # data matrix (each row = single example)y = np.zeros(N*K, dtype='uint8') # class labelsfor j in range(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# lets visualize the data:plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
<matplotlib.collections.PathCollection at 0x7fe2759eadd8>

这里写图片描述

#Train a Linear Classifier# initialize parameters randomlyW = 0.01 * np.random.randn(D,K)b = np.zeros((1,K))# some hyperparametersstep_size = 1e-0reg = 1e-3 # regularization strength# gradient descent loopnum_examples = X.shape[0]for i in range(150):  # 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.094959iteration 10: loss 0.910807iteration 20: loss 0.842313iteration 30: loss 0.811167iteration 40: loss 0.794949iteration 50: loss 0.785715iteration 60: loss 0.780126iteration 70: loss 0.776590iteration 80: loss 0.774279iteration 90: loss 0.772730iteration 100: loss 0.771672iteration 110: loss 0.770938iteration 120: loss 0.770421iteration 130: loss 0.770055iteration 140: loss 0.769793
# evaluate training set accuracyscores = np.dot(X, W) + bpredicted_class = np.argmax(scores, axis=1)print ('training accuracy: %.2f' % (np.mean(predicted_class == y)))
training accuracy: 0.49
1 0