Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.46 KB | None | 0 0
  1. from sklearn.ensemble import RandomForestClassifier
  2. import numpy as np
  3. import pandas as pd
  4.  
  5. import matplotlib.pyplot as plt
  6. import matplotlib.cm as cm
  7.  
  8. #include neural net packages
  9. import lasagne
  10. from lasagne import layers
  11. from lasagne.updates import nesterov_momentum
  12. from nolearn.lasagne import NeuralNet
  13. from nolearn.lasagne import visualize
  14.  
  15. # create the training & test sets
  16. #not including header
  17. dataset = pd.read_csv("../input/train.csv")
  18. target = dataset[[0]].values.ravel()
  19. train = dataset.iloc[:,1:].values
  20. test = pd.read_csv("../input/test.csv").values
  21.  
  22. # create and train the random forest
  23. # multi-core CPUs can use: rf = RandomForestClassifier(n_estimators=100, n_jobs=2)
  24. rf = RandomForestClassifier(n_estimators=100)
  25. rf.fit(train, target)
  26. pred = rf.predict(test)
  27.  
  28. np.savetxt('submission_rand_forest.csv', np.c_[range(1,len(test)+1),pred], delimiter=',', header = 'ImageId,Label', comments = '', fmt='%d')
  29.  
  30. #random forest gave a really good accuracy. But when I was reading about image processing then the COnvolute neural networks give you the best ouput.
  31. #let me try
  32. #before that let us reshape the data
  33. #the image size is 28*28=784 columns
  34. #so each row has 784 columns indicating every pixel value
  35. # convert to array, specify data type, and reshape
  36. target = target.astype(np.uint8)
  37. train = np.array(train).reshape((-1, 1, 28, 28)).astype(np.uint8)
  38. test = np.array(test).reshape((-1, 1, 28, 28)).astype(np.uint8)
  39.  
  40. #plot every pixel and see what digit is coming out
  41.  
  42. plt.imshow(train[1729][0], cmap=cm.binary) # draw the picture
  43.  
  44.  
  45. net1 = NeuralNet(
  46. layers=[('input', layers.InputLayer),
  47. ('hidden', layers.DenseLayer),
  48. ('output', layers.DenseLayer),
  49. ],
  50. # layer parameters:
  51. input_shape=(None,1,28,28),
  52. hidden_num_units=1000, # number of units in 'hidden' layer
  53. output_nonlinearity=lasagne.nonlinearities.softmax,
  54. output_num_units=10, # 0,1,2,....,9 digits
  55.  
  56. # optimization paramters
  57. update=nesterov_momentum,
  58. update_learning_rate=0.0001,
  59. update_momentum=0.9,
  60.  
  61. max_epochs=15, #number of times iterate the samples
  62. verbose=1,
  63. )
  64.  
  65.  
  66. # Train the network
  67. net1.fit(train, target)
  68.  
  69. #advantage of CNN is you can use maxpooling, Conv layer, Dense layer.
  70.  
  71. def CNN(n_epochs):
  72. net1 = NeuralNet(
  73. layers=[
  74. ('input', layers.InputLayer),
  75. ('conv1', layers.Conv2DLayer),
  76. ('pool1', layers.MaxPool2DLayer),
  77. ('conv2', layers.Conv2DLayer),
  78. ('hidden3', layers.DenseLayer),
  79. ('output', layers.DenseLayer),
  80. ],
  81.  
  82. input_shape=(None, 1, 28, 28),
  83. conv1_num_filters=7,
  84. conv1_filter_size=(3, 3),
  85. conv1_nonlinearity=lasagne.nonlinearities.rectify,
  86.  
  87. pool1_pool_size=(2, 2),
  88.  
  89. conv2_num_filters=12,
  90. conv2_filter_size=(2, 2),
  91. conv2_nonlinearity=lasagne.nonlinearities.rectify,
  92.  
  93. hidden3_num_units=1000,
  94. output_num_units=10,
  95. output_nonlinearity=lasagne.nonlinearities.softmax,
  96.  
  97. update_learning_rate=0.0001,
  98. update_momentum=0.9,
  99.  
  100. max_epochs=n_epochs,
  101. verbose=1,
  102. )
  103. return net1
  104.  
  105. cnn = CNN(15).fit(train,target)
  106.  
  107. #though CNN took more time to run than NN but
  108. #CNN work better than just NN with same number of epoch and weights
  109.  
  110. # use the CNN model to classify test data
  111. pred = cnn.predict(test)
  112.  
  113. # save results
  114. np.savetxt('cnn_submission.csv', np.c_[range(1,len(test)+1),pred], delimiter=',', header = 'ImageId,Label', comments = '', fmt='%d')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement