def predict(x,theta): m,_ = x.shape p = np.zeros((m,1),dtype='uint8') for i in xrange(m): h = hypothesis(x[i],theta) s = np.sum(h) l = np.argmax(h) if (1-s)<h[l]: p[i][0] = l else: p[i][0] = 9 return p m,rows,cols,xTrain,yTrain = mnistData.getTrainData() mTest,_,_,xTest,yTest = mnistData.getTestData() k = 10 xTrain = xTrain.reshape((m,rows*cols)) xTrain = addColumn(xTrain) xTrain = xTrain/255 xTest = xTest.reshape((mTest,rows*cols)) xTest = addColumn(xTest) xTest = xTest/255 theta = np.zeros((k-1,rows*cols+1)) iterations = 250 alpha = .2 for i in xrange(iterations): theta = gradientAcsent(xTrain,yTrain,theta,alpha,m) print 'iteration = {}'.format(i+1) pTrain = predict(xTrain,theta)
import numpy as np import mnistData from neuralNetworks import NeuralNetwork def createY(y, k, m): Y = np.zeros((m, k), dtype=int) temp = np.array(range(m)) Y[temp, y[:, 0]] = 1 return Y m, rows, cols, x_train, y = mnistData.getTrainData() y_train = createY(y, 10, m) x_train = x_train.reshape((m, rows * cols)) mtest, rtest, ctest, x_test, y_t = mnistData.getTestData() y_test = createY(y_t, 10, mtest) x_test = x_test.reshape((mtest, rtest * ctest)) nn = NeuralNetwork('mnist', rows * cols, 1, [50], 10, .1) nn.train(x_train, y_train, 250, .1) count = 0 for x, y in zip(x_test, y_t): res = nn.predict(x) if res == y[0]: count += 1 print count
import numpy as np import mnistData from neuralNetworks import NeuralNetwork def createY(y,k,m): Y = np.zeros((m,k),dtype=int) temp = np.array(range(m)) Y[temp,y[:,0]] = 1 return Y m,rows,cols,x_train,y = mnistData.getTrainData() y_train = createY(y,10,m) x_train = x_train.reshape((m,rows*cols)) mtest,rtest,ctest,x_test,y_t = mnistData.getTestData() y_test = createY(y_t,10,mtest) x_test = x_test.reshape((mtest,rtest*ctest)) nn = NeuralNetwork('mnist',rows*cols,1,[50],10,.1) nn.train(x_train,y_train,250,.1) count = 0 for x,y in zip(x_test,y_t): res = nn.predict(x) if res==y[0]: count+=1 print count