full_code.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # View more python tutorials on my Youtube and Youku channel!!!
  2. # Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
  3. # Youku video tutorial: http://i.youku.com/pythontutorial
  4. # 13 - save and reload
  5. """
  6. Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
  7. """
  8. from __future__ import print_function
  9. import numpy as np
  10. import theano
  11. import theano.tensor as T
  12. import pickle
  13. def compute_accuracy(y_target, y_predict):
  14. correct_prediction = np.equal(y_predict, y_target)
  15. accuracy = np.sum(correct_prediction)/len(correct_prediction)
  16. return accuracy
  17. rng = np.random
  18. # set random seed
  19. np.random.seed(100)
  20. N = 400
  21. feats = 784
  22. # generate a dataset: D = (input_values, target_class)
  23. D = (rng.randn(N, feats), rng.randint(size=N, low=0, high=2))
  24. # Declare Theano symbolic variables
  25. x = T.dmatrix("x")
  26. y = T.dvector("y")
  27. # initialize the weights and biases
  28. w = theano.shared(rng.randn(feats), name="w")
  29. b = theano.shared(0., name="b")
  30. # Construct Theano expression graph
  31. p_1 = 1 / (1 + T.exp(-T.dot(x, w) - b))
  32. prediction = p_1 > 0.5
  33. xent = -y * T.log(p_1) - (1-y) * T.log(1-p_1)
  34. cost = xent.mean() + 0.01 * (w ** 2).sum()
  35. gw, gb = T.grad(cost, [w, b])
  36. # Compile
  37. learning_rate = 0.1
  38. train = theano.function(
  39. inputs=[x, y],
  40. updates=((w, w - learning_rate * gw), (b, b - learning_rate * gb)))
  41. predict = theano.function(inputs=[x], outputs=prediction)
  42. # Training
  43. for i in range(500):
  44. train(D[0], D[1])
  45. # save model
  46. with open('save/model.pickle', 'wb') as file:
  47. model = [w.get_value(), b.get_value()]
  48. pickle.dump(model, file)
  49. print(model[0][:10])
  50. print("accuracy:", compute_accuracy(D[1], predict(D[0])))
  51. # load model
  52. with open('save/model.pickle', 'rb') as file:
  53. model = pickle.load(file)
  54. w.set_value(model[0])
  55. b.set_value(model[1])
  56. print(w.get_value()[:10])
  57. print("accuracy:", compute_accuracy(D[1], predict(D[0])))