You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.py 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import nn
  2. class PerceptronModel(object):
  3. def __init__(self, dimensions):
  4. """
  5. Initialize a new Perceptron instance.
  6. A perceptron classifies data points as either belonging to a particular
  7. class (+1) or not (-1). `dimensions` is the dimensionality of the data.
  8. For example, dimensions=2 would mean that the perceptron must classify
  9. 2D points.
  10. """
  11. self.w = nn.Parameter(1, dimensions)
  12. def get_weights(self):
  13. """
  14. Return a Parameter instance with the current weights of the perceptron.
  15. """
  16. return self.w
  17. def run(self, x):
  18. """
  19. Calculates the score assigned by the perceptron to a data point x.
  20. Inputs:
  21. x: a node with shape (1 x dimensions)
  22. Returns: a node containing a single number (the score)
  23. """
  24. "*** YOUR CODE HERE ***"
  25. return nn.DotProduct(x, self.get_weights())
  26. def get_prediction(self, x):
  27. """
  28. Calculates the predicted class for a single data point `x`.
  29. Returns: 1 or -1
  30. """
  31. "*** YOUR CODE HERE ***"
  32. score = self.run(x)
  33. if nn.as_scalar(score) >= 0:
  34. return 1
  35. else:
  36. return -1
  37. def train(self, dataset):
  38. """
  39. Train the perceptron until convergence.
  40. """
  41. "*** YOUR CODE HERE ***"
  42. batch_size = 1
  43. while True:
  44. converged = True
  45. for x, y in dataset.iterate_once(batch_size):
  46. prediction = self.get_prediction(x)
  47. print(x, y)
  48. assert 0
  49. if prediction != nn.as_scalar(y):
  50. converged = False
  51. self.w.update(x, nn.as_scalar(y))
  52. if converged:
  53. break
  54. class RegressionModel(object):
  55. """
  56. A neural network model for approximating a function that maps from real
  57. numbers to real numbers. The network should be sufficiently large to be able
  58. to approximate sin(x) on the interval [-2pi, 2pi] to reasonable precision.
  59. """
  60. def __init__(self):
  61. # Initialize your model parameters here
  62. "*** YOUR CODE HERE ***"
  63. self.i = 1
  64. self.o = 1
  65. self.h = 50
  66. self.b = 10
  67. self.learning_rate = 0.01
  68. self.W1 = nn.Parameter(self.i, self.h)
  69. self.b1 = nn.Parameter(1, self.h)
  70. self.W2 = nn.Parameter(self.h, self.o)
  71. self.b2 = nn.Parameter(1, self.o)
  72. def run(self, x):
  73. """
  74. Runs the model for a batch of examples.
  75. Inputs:
  76. x: a node with shape (batch_size x 1)
  77. Returns:
  78. A node with shape (batch_size x 1) containing predicted y-values
  79. """
  80. "*** YOUR CODE HERE ***"
  81. layer_1 = nn.ReLU(nn.AddBias(nn.Linear(x, self.W1), self.b1))
  82. prediction = nn.AddBias(nn.Linear(layer_1, self.W2), self.b2)
  83. return prediction
  84. def get_loss(self, x, y):
  85. """
  86. Computes the loss for a batch of examples.
  87. Inputs:
  88. x: a node with shape (batch_size x 1)
  89. y: a node with shape (batch_size x 1), containing the true y-values
  90. to be used for training
  91. Returns: a loss node
  92. """
  93. "*** YOUR CODE HERE ***"
  94. return nn.SquareLoss(self.run(x), y)
  95. def train(self, dataset):
  96. """
  97. Trains the model.
  98. """
  99. "*** YOUR CODE HERE ***"
  100. for i in range(20):
  101. for x, y in dataset.iterate_once(self.b):
  102. loss = self.get_loss(x, y)
  103. print(loss.data)
  104. g_W1, g_b1, g_W2, g_b2 = nn.gradients(loss, [self.W1, self.b1, self.W2, self.b2])
  105. # print(g_W1.data)
  106. # print(g_b1.data)
  107. # print(g_W2.data)
  108. # print(g_b2.data)
  109. self.W1.update(g_W1, -self.learning_rate)
  110. self.b1.update(g_b1, -self.learning_rate)
  111. self.W2.update(g_W2, -self.learning_rate)
  112. self.b2.update(g_b2, -self.learning_rate)
  113. if loss.data < 0.01:
  114. break
  115. class DigitClassificationModel(object):
  116. """
  117. A model for handwritten digit classification using the MNIST dataset.
  118. Each handwritten digit is a 28x28 pixel grayscale image, which is flattened
  119. into a 784-dimensional vector for the purposes of this model. Each entry in
  120. the vector is a floating point number between 0 and 1.
  121. The goal is to sort each digit into one of 10 classes (number 0 through 9).
  122. (See RegressionModel for more information about the APIs of different
  123. methods here. We recommend that you implement the RegressionModel before
  124. working on this part of the project.)
  125. """
  126. def __init__(self):
  127. # Initialize your model parameters here
  128. "*** YOUR CODE HERE ***"
  129. self.input_features = 784
  130. self.h1 = 200
  131. self.h2 = 100
  132. self.output_features = 10
  133. self.lr = 0.01
  134. self.batch_size = 100
  135. self.w1 = nn.Parameter(self.input_features, self.h1)
  136. self.b1 = nn.Parameter(1, self.h1)
  137. self.w2 = nn.Parameter(self.h1, self.h2)
  138. self.b2 = nn.Parameter(1, self.h2)
  139. self.w3 = nn.Parameter(self.h2, self.output_features)
  140. self.b3 = nn.Parameter(1, self.output_features)
  141. def run(self, x):
  142. """
  143. Runs the model for a batch of examples.
  144. Your model should predict a node with shape (batch_size x 10),
  145. containing scores. Higher scores correspond to greater probability of
  146. the image belonging to a particular class.
  147. Inputs:
  148. x: a node with shape (batch_size x 784)
  149. Output:
  150. A node with shape (batch_size x 10) containing predicted scores
  151. (also called logits)
  152. """
  153. "*** YOUR CODE HERE ***"
  154. l1 = nn.ReLU(nn.AddBias(nn.Linear(x, self.w1), self.b1))
  155. l2 = nn.ReLU(nn.AddBias(nn.Linear(l1, self.w2), self.b2))
  156. l3 = nn.AddBias(nn.Linear(l2, self.w3), self.b3)
  157. return l3
  158. def get_loss(self, x, y):
  159. """
  160. Computes the loss for a batch of examples.
  161. The correct labels `y` are represented as a node with shape
  162. (batch_size x 10). Each row is a one-hot vector encoding the correct
  163. digit class (0-9).
  164. Inputs:
  165. x: a node with shape (batch_size x 784)
  166. y: a node with shape (batch_size x 10)
  167. Returns: a loss node
  168. """
  169. "*** YOUR CODE HERE ***"
  170. return nn.SoftmaxLoss(self.run(x), y)
  171. def train(self, dataset):
  172. """
  173. Trains the model.
  174. """
  175. "*** YOUR CODE HERE ***"
  176. while True:
  177. for x, y in dataset.iterate_once(self.batch_size):
  178. loss = self.get_loss(x, y)
  179. g_w1, g_b1, g_w2, g_b2, g_w3, g_b3 = nn.gradients(loss, [self.w1, self.b1, self.w2, self.b2, self.w3, self.b3])
  180. self.w1.update(g_w1, -self.lr)
  181. self.b1.update(g_b1, -self.lr)
  182. self.w2.update(g_w2, -self.lr)
  183. self.b2.update(g_b2, -self.lr)
  184. self.w3.update(g_w3, -self.lr)
  185. self.b3.update(g_b3, -self.lr)
  186. accuracy = dataset.get_validation_accuracy()
  187. print(accuracy)
  188. if accuracy > 0.95:
  189. break
  190. class LanguageIDModel(object):
  191. """
  192. A model for language identification at a single-word granularity.
  193. (See RegressionModel for more information about the APIs of different
  194. methods here. We recommend that you implement the RegressionModel before
  195. working on this part of the project.)
  196. """
  197. def __init__(self):
  198. # Our dataset contains words from five different languages, and the
  199. # combined alphabets of the five languages contain a total of 47 unique
  200. # characters.
  201. # You can refer to self.num_chars or len(self.languages) in your code
  202. self.num_chars = 47
  203. self.languages = ["English", "Spanish", "Finnish", "Dutch", "Polish"]
  204. # Initialize your model parameters here
  205. "*** YOUR CODE HERE ***"
  206. def run(self, xs):
  207. """
  208. Runs the model for a batch of examples.
  209. Although words have different lengths, our data processing guarantees
  210. that within a single batch, all words will be of the same length (L).
  211. Here `xs` will be a list of length L. Each element of `xs` will be a
  212. node with shape (batch_size x self.num_chars), where every row in the
  213. array is a one-hot vector encoding of a character. For example, if we
  214. have a batch of 8 three-letter words where the last word is "cat", then
  215. xs[1] will be a node that contains a 1 at position (7, 0). Here the
  216. index 7 reflects the fact that "cat" is the last word in the batch, and
  217. the index 0 reflects the fact that the letter "a" is the inital (0th)
  218. letter of our combined alphabet for this task.
  219. Your model should use a Recurrent Neural Network to summarize the list
  220. `xs` into a single node of shape (batch_size x hidden_size), for your
  221. choice of hidden_size. It should then calculate a node of shape
  222. (batch_size x 5) containing scores, where higher scores correspond to
  223. greater probability of the word originating from a particular language.
  224. Inputs:
  225. xs: a list with L elements (one per character), where each element
  226. is a node with shape (batch_size x self.num_chars)
  227. Returns:
  228. A node with shape (batch_size x 5) containing predicted scores
  229. (also called logits)
  230. """
  231. "*** YOUR CODE HERE ***"
  232. def get_loss(self, xs, y):
  233. """
  234. Computes the loss for a batch of examples.
  235. The correct labels `y` are represented as a node with shape
  236. (batch_size x 5). Each row is a one-hot vector encoding the correct
  237. language.
  238. Inputs:
  239. xs: a list with L elements (one per character), where each element
  240. is a node with shape (batch_size x self.num_chars)
  241. y: a node with shape (batch_size x 5)
  242. Returns: a loss node
  243. """
  244. "*** YOUR CODE HERE ***"
  245. def train(self, dataset):
  246. """
  247. Trains the model.
  248. """
  249. "*** YOUR CODE HERE ***"