Advertisement
Guest User

Untitled

a guest
Nov 24th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import scipy.optimize as opt
  4.  
  5. sig = 1.0
  6.  
  7. X = np.linspace(0.0, 4.0 * np.pi, 100)
  8.  
  9. x1 = X * np.sin(X)
  10. x2 = X * np.cos(X)
  11.  
  12. x1 = x1[:, None]
  13. x2 = x2[:, None]
  14.  
  15. Xnon = np.concatenate((x1, x2), 1) #puts X_actual to matrix, f_non_lin
  16. A = np.random.randn(10, 2)
  17. Y = np.dot(Xnon, np.transpose(A)) # f_lin
  18.  
  19.  
  20. def L(w):
  21. w = np.reshape(w, (10, 2))
  22. C = np.dot(w, np.transpose(w)) + sig * np.eye(10)
  23. inv = np.linalg.inv(C)
  24. p1 = np.dot(np.dot(Y, inv), np.transpose(Y))
  25.  
  26. t1 = 0.5 * 100 * 10 * np.log(np.pi * 2)
  27. t2 = 0.5 * 100 * np.log(np.linalg.det(C))
  28. t3 = 0.5 * np.trace(p1)
  29. return t1 + t2 + t3
  30.  
  31.  
  32. def dL(w):
  33. w = np.reshape(w, (10, 2))
  34. C = np.dot(w, np.transpose(w)) + sig * np.eye(10)
  35. inv = np.linalg.inv(C)
  36. dLdW = np.zeros([10, 2])
  37. for i in range(10):
  38. for j in range(2):
  39. dW = np.zeros([10, 2])
  40. dW[i, j] = 1
  41. dWW = np.dot(dW, np.transpose(w)) + np.dot(w, np.transpose(dW))
  42. p1 = np.dot(inv, np.dot(dWW, inv))
  43. p2 = np.dot(Y, np.dot(p1, np.transpose(Y)))
  44.  
  45. t1 = 0.5 * 100 * np.trace(np.dot(inv, dWW))
  46. t2 = -0.5 * np.trace(p2)
  47. dLdW[i, j] = t1 + t2
  48.  
  49. dLdW = np.reshape(dLdW, (20,))
  50. return dLdW
  51.  
  52.  
  53. W0 = np.random.randn(20)
  54. W = opt.fmin_cg(L, W0, fprime=dL)
  55. W = np.reshape(W, (10, 2))
  56.  
  57. # Remember Y = X * A^T, but you cannot do X = Y * inv(A^T) because A is not a square matrix
  58. # Instead Y = X * A^T ... Y * A = X * (A^T * A) ... ((A^T)A) can be inverted giving X = Y*A*inv((A^T)A)
  59. WTW = np.dot(np.transpose(W), W)
  60. x_pred = np.dot(Y, np.dot(W, np.linalg.inv(WTW)))
  61.  
  62. fig1 = plt.figure()
  63. ax1 = fig1.add_subplot(111)
  64. ax1.plot(Xnon[:, 0], Xnon[:, 1], 'ro')
  65.  
  66. fig2 = plt.figure()
  67. ax2 = fig2.add_subplot(111)
  68. ax2.plot(x_pred[:, 0], x_pred[:, 1], 'bo')
  69.  
  70. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement