SHARE
TWEET

Untitled

a guest Oct 23rd, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3.  
  4. # In[3]:
  5.  
  6.  
  7. import numpy as np
  8. import pickle, gzip
  9.  
  10.  
  11. # In[4]:
  12.  
  13.  
  14. f = gzip.open('mnist.pkl.gz', 'rb')
  15. train_set, valid_set, test_set = pickle.load(f, encoding='latin1')
  16. f.close()
  17.  
  18.  
  19. # In[5]:
  20.  
  21.  
  22. def isNumber(x, y):
  23.     if(x == y):
  24.         return 1
  25.     else:
  26.         return 0
  27.    
  28. def func(x):
  29.     if(x >= 0):
  30.         return 1.0
  31.     else:
  32.         return 0.0
  33.  
  34.  
  35. # In[9]:
  36.  
  37.  
  38. train_set[1][:10]
  39.  
  40.  
  41. # In[7]:
  42.  
  43.  
  44. def perceptron(train_set, target_set, number):
  45.     image_set = train_set
  46.     target_set = target_set
  47.     target_set = np.vectorize(isNumber)(target_set, number)
  48.    
  49.     weight = np.zeros([785, ], dtype = float)
  50.     image_set = np.insert(image_set, 0, 1, axis = 1)
  51.     rate = 0.1
  52.    
  53.    
  54.     output_func = np.vectorize(func)
  55.    
  56.     for i in range(len(image_set)):
  57.         y = np.dot(image_set, weight)
  58.         predict = output_func(y)
  59.  
  60.         weight +=  rate * image_set[i] * (target_set[i] - predict[i])
  61.         if(i == 100):
  62.             break
  63.     return weight
  64.  
  65.  
  66. # In[17]:
  67.  
  68.  
  69. w0 = perceptron(train_set[0], train_set[1], 0)
  70. w1 = perceptron(train_set[0], train_set[1], 1)
  71. w2 = perceptron(train_set[0], train_set[1], 2)
  72. w3 = perceptron(train_set[0], train_set[1], 3)
  73. w4 = perceptron(train_set[0], train_set[1], 4)
  74. w5 = perceptron(train_set[0], train_set[1], 5)
  75. w6 = perceptron(train_set[0], train_set[1], 6)
  76. w7 = perceptron(train_set[0], train_set[1], 7)
  77. w8 = perceptron(train_set[0], train_set[1], 8)
  78. w9 = perceptron(train_set[0], train_set[1], 9)
  79.  
  80.  
  81. # In[16]:
  82.  
  83.  
  84. t = np.insert(train_set[0], 0, 1, axis = 1)
  85. func(np.dot(t[0], w0))
  86.  
  87.  
  88. # In[27]:
  89.  
  90.  
  91. def predictNumber(image):
  92.     weight = [w0, w1, w2, w3, w4, w5, w6, w7, w8, w9]
  93.     pred = []
  94.     for w in weight:
  95.         pred.append(func(np.dot(image, w)))
  96.         #print(func(np.dot(image, w)))
  97.     for j, i in enumerate(pred):
  98.         if(i == 1):
  99.             return j
  100.  
  101.  
  102. # In[32]:
  103.  
  104.  
  105. predictNumber(t[8])
  106.  
  107.  
  108. # In[26]:
  109.  
  110.  
  111. train_set[1][:20]
  112.  
  113.  
  114. # In[ ]:
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top