emwmunmf.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import numpy as np
  2. import time
  3. import matplotlib.pyplot as plt
  4. def emwmunmf(data, G, F, r, Tmax):
  5. delta_measure = 1
  6. em_iter_max = round(Tmax / delta_measure) + 1 #
  7. T = np.empty(shape=(em_iter_max + 1))
  8. T.fill(np.nan)
  9. RMSE = np.empty(shape=(2, em_iter_max + 1))
  10. RMSE.fill(np.nan)
  11. # RRE = np.empty(shape=(em_iter_max + 1))
  12. # RRE.fill(np.nan)
  13. secu = 1e-12
  14. M_loop = 5
  15. np.put(F, data.idxOF, data.sparsePhi_F)
  16. np.put(G, data.idxOG, data.sparsePhi_G)
  17. delta_G = G
  18. delta_F = F
  19. # Iterative updating
  20. k = 0
  21. RMSE[:, k] = np.linalg.norm(F[:, 0:-1] - data.F[:, 0:-1], 2, axis=1) / np.sqrt(F.shape[1] - 1)
  22. T[k] = 0
  23. t = time.time()
  24. # Main loop
  25. while time.time() - t <= Tmax + delta_measure:
  26. # Estimation step
  27. X = data.X + np.multiply(data.nW, np.dot(G, F))
  28. # Maximisation step
  29. for _ in range(M_loop):
  30. # Optimize F with fixed G
  31. np.put(delta_G, data.idxOG, 0)
  32. delta_G = np.divide(
  33. np.multiply(
  34. delta_G,
  35. np.dot(
  36. secu_plus(X - data.Phi_G.dot(F), secu),
  37. F.T
  38. )
  39. ),
  40. np.dot(
  41. delta_G.dot(F),
  42. F.T
  43. )
  44. )
  45. delta_G[np.isnan(delta_G)] = 0
  46. G = delta_G
  47. np.put(G, data.idxOG, data.sparsePhi_G)
  48. # Optimize G with fixed F
  49. np.put(F, data.idxOF, 0)
  50. delta_F = np.divide(
  51. np.multiply(
  52. delta_F,
  53. np.dot(
  54. G.T,
  55. secu_plus(X - G.dot(data.Phi_F), secu)
  56. )
  57. ),
  58. np.dot(
  59. G.T,
  60. G.dot(delta_F)
  61. )
  62. )
  63. delta_F[np.isnan(delta_F)] = 0
  64. F = delta_F
  65. np.put(F, data.idxOF, data.sparsePhi_F)
  66. if time.time() - t - k * delta_measure >= delta_measure:
  67. k = k + 1
  68. if k >= em_iter_max + 1:
  69. break
  70. RMSE[:, k] = np.linalg.norm(F[:, 0:-1] - data.F[:, 0:-1], 2, axis=1) / np.sqrt(F.shape[1] - 1)
  71. T[k] = time.time() - t
  72. # RRE[k] = nmf_norm_fro(data.Xtheo, G.T, F, data.W)
  73. # if k%100==0:
  74. # print(str(k)+' '+str(RMSE[0,k])+' '+str(RMSE[1,k]))
  75. # plt.semilogy(RRE)
  76. # plt.show()
  77. return {'RMSE': RMSE, 'T': T}
  78. def secu_plus(tutu, s):
  79. toto = np.maximum(tutu, s)
  80. toto[np.isnan(tutu)] = 0
  81. return toto
  82. def nmf_norm_fro(X, G, F, *args):
  83. W = args
  84. if len(W) == 0:
  85. f = np.square(np.linalg.norm(X - np.dot(G, F), 'fro')) / np.square(np.linalg.norm(X, 'fro'))
  86. else:
  87. W = W[0]
  88. f = np.square(np.linalg.norm(X - np.multiply(W, np.dot(G, F)), 'fro')) / np.square(np.linalg.norm(X, 'fro'))
  89. return f