incal.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import numpy as np
  2. import time
  3. import matplotlib.pyplot as plt
  4. def incal(data, G, F, r, Tmax):
  5. W2 = np.square(data.W)
  6. delta_measure = 1
  7. iter_max = round(Tmax / delta_measure) + 1
  8. secu = 1e-12
  9. T = np.empty(shape=(iter_max + 1))
  10. T.fill(np.nan)
  11. RMSE = np.empty(shape=(2, iter_max + 1))
  12. RMSE.fill(np.nan)
  13. # RRE = np.empty(shape=(iter_max + 1))
  14. # RRE.fill(np.nan)
  15. dataX = data.X
  16. dataF = data.F
  17. dataPhi_G = data.Phi_G
  18. dataPhi_F = data.Phi_F
  19. dataidxOF = data.idxOF
  20. dataidxOG = data.idxOG
  21. datasparsePhi_F = data.sparsePhi_F
  22. datasparsePhi_G = data.sparsePhi_G
  23. delta_G = G
  24. delta_F = F
  25. t = time.time()
  26. T[0] = time.time() - t
  27. RMSE[:, 0] = np.linalg.norm(F[:, 0:-1] - dataF[:, 0:-1], 2, axis=1) / np.sqrt(F.shape[1] - 1)
  28. i = 0
  29. niter = 0
  30. while time.time() - t <= Tmax + delta_measure:
  31. # Updating G
  32. np.put(delta_G, dataidxOG, 0)
  33. delta_G = np.divide(
  34. np.multiply(
  35. delta_G,
  36. np.dot(
  37. np.multiply(
  38. W2,
  39. secu_plus(dataX - dataPhi_G.dot(F), secu)
  40. ),
  41. F.T
  42. )
  43. ),
  44. np.dot(
  45. np.multiply(
  46. W2,
  47. delta_G.dot(F)
  48. ),
  49. F.T
  50. )
  51. )
  52. delta_G[np.isnan(delta_G)] = 0
  53. G = delta_G
  54. np.put(G, dataidxOG, datasparsePhi_G)
  55. # Updating F
  56. np.put(F, dataidxOF, 0)
  57. delta_F = np.divide(
  58. np.multiply(
  59. delta_F,
  60. np.dot(
  61. G.T,
  62. np.multiply(
  63. W2,
  64. secu_plus(dataX - G.dot(dataPhi_F), secu)
  65. )
  66. )
  67. ),
  68. np.dot(
  69. G.T,
  70. np.multiply(
  71. W2,
  72. G.dot(delta_F)
  73. )
  74. )
  75. )
  76. delta_F[np.isnan(delta_F)] = 0
  77. F = delta_F
  78. np.put(F, dataidxOF, datasparsePhi_F)
  79. # Saving results for this iteration
  80. if time.time() - t - i * delta_measure >= delta_measure:
  81. i = i + 1
  82. RMSE[:, i] = np.linalg.norm(F[:, 0:-1] - dataF[:, 0:-1], 2, axis=1) / np.sqrt(F.shape[1] - 1)
  83. T[i] = time.time() - t
  84. niter = niter + 1
  85. print(niter)
  86. return {'RMSE': RMSE, 'T': T}
  87. def secu_plus(tutu, s):
  88. toto = np.maximum(tutu, s)
  89. toto[np.isnan(tutu)] = 0
  90. return toto
  91. def nmf_norm_fro(X, G, F, *args):
  92. W = args
  93. if len(W) == 0:
  94. f = np.square(np.linalg.norm(X - np.dot(G, F), 'fro')) / np.square(np.linalg.norm(X, 'fro'))
  95. else:
  96. W = W[0]
  97. f = np.square(np.linalg.norm(X - np.multiply(W, np.dot(G, F)), 'fro')) / np.square(np.linalg.norm(X, 'fro'))
  98. return f