cs231n一次课程实践,python实现softmax线性分类器和二层神经网络
来源:互联网 发布:网络小额贷款平台 编辑:程序博客网 时间:2024/06/01 09:54
看了以后,对bp算法的实现有直观的认识,真的太棒了!
import numpy as npimport matplotlib.pyplot as pltnp.random.seed(0)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 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# lets visualize the data:#plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)#plt.show()# initialize parameters randomlyh = 100 # size of hidden layerW = 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 hyperparametersstep_size = 1e-0reg = 1e-3 # regularization strength# gradient descent loopnum_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) # add regularization gradient contribution 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# evaluate training set accuracyhidden_layer = np.maximum(0, np.dot(X, W) + b)scores = np.dot(hidden_layer, W2) + b2predicted_class = np.argmax(scores, axis=1)print 'training accuracy: %.2f' % (np.mean(predicted_class == y))# plot the resulting classifierh = 0.02x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))Z = np.dot(np.maximum(0, np.dot(np.c_[xx.ravel(), yy.ravel()], W) + b), W2) + b2Z = 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())plt.show()#fig.savefig('spiral_net.png')
线性分类器,loss为softmax loss,注意softmax的梯度形式
import numpy as npimport matplotlib.pyplot as pltnp.random.seed(0)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 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# lets visualize the data:#plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)#plt.show()# 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 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 accuracyscores = np.dot(X, W) + bpredicted_class = np.argmax(scores, axis=1)print 'training accuracy: %.2f' % (np.mean(predicted_class == y))# plot the resulting classifierh = 0.02x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1xx, 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) + bZ = 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())#plt.show()#fig.savefig('spiral_linear.png')
0 0
- cs231n一次课程实践,python实现softmax线性分类器和二层神经网络
- cs231n-(2)线性分类器:SVM和Softmax
- CS231n课程笔记3.1:线性分类器(SVM,softmax)的误差函数、正则化
- CS231n课程笔记2.2:线性分类器
- 20161206#cs231n#2.线性分类器 Assignment1--SVM&Softmax
- 斯坦福大学深度学习公开课cs231n学习笔记(9)softmax分类和神经网络分类代码实现
- 【Python 代码】CS231n中Softmax线性分类器、非线性分类器对比举例(含python绘图显示结果)
- CS231n课程笔记--线性分类
- 斯坦福CS231n 课程学习笔记--线性分类器(Assignment1代码实现)
- softmax分类器 python实现
- cs231n-线性分类器
- CS231n 课程笔记翻译:线性分类笔记
- CS231n课程笔记翻译:线性分类笔记
- cs231n assignment(1.3):softmax分类器
- [CS231n@Stanford] Assignment1-Q3 (python) Softmax实现
- cs231n:SVM线性分类器
- cs231学习笔记二 线性分类器、SVM、Softmax
- 线性分类器、SVM、Softmax
- ngx_queue_t
- openVR驱动接口之ICameraVideoSinkCallback简介
- html使用ajax+jsp更新网页部分信息
- python操作数据库之批量导入
- Linux内核分析(六):进程的描述和进程的创建
- cs231n一次课程实践,python实现softmax线性分类器和二层神经网络
- openVR驱动接口之IDriverLog简介
- 编程之法-第一章字符串
- Halcon学习(三) Halcon基本操作:获取时间与文本操作
- 第一个servlet
- 手势识别
- Sorted Union--多个数组按原顺序合并并去除重复值
- 2.6使用二维数组存储学生的数据,包括学号、姓名、操作系统成绩、Java成绩、高数成绩、总分;一行存储一个学生的数据;要求输入若干学生的数据,求出总分;然后按照总分由高到低重新排列;输出排序后的结果
- mysql获取月日相同的数据