lolamontes69

Ch10 Ex4- Programming Collective Intelligence

Sep 14th, 2013
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. """ Chapter 10 Exercise 4: Stopping criteria.
  2.  
  3.    The NMF algorithm in this chapter stops when the cost has dropped to 0 or when it reaches the maximum number of iterations.
  4.    Sometimes improvement will almost entirely stop once a very good though not perfect solution has been reached.
  5.    Modify the code so it stops when the cost is not improving by more than one percent per iteration
  6.  
  7. """
  8.  
  9. def factorize(v, pc=10, iter=50):
  10.     ic, fc = shape(v)
  11.     cost=0
  12.     previouscost = 9999999999999
  13.     w = matrix([[random.random() for j in range(pc)] for i in range(ic)])
  14.     h = matrix([[random.random() for i in range(fc)] for i in range(pc)])
  15.  
  16.     for i in range(iter):
  17.         wh = w * h
  18.  
  19.         cost = difcost(v, wh)
  20.         if i % 10 == 0:
  21.             print("%d: %f" % (i, cost))
  22.  
  23.         if cost == 0 or math.isnan(cost):
  24.             print("%d: %f" % (i, cost))       # nan means not a number
  25.             break
  26.  
  27.         hn = transpose(w) * v
  28.         hd = transpose(w) * w * h
  29.         h = matrix(array(h) * array(hn) / array(hd))
  30.  
  31.         wn = v * transpose(h)
  32.         wd = w * h * transpose(h)
  33.  
  34.         # RuntimeWarning: invalid value encountered in divide
  35.         wn = [[1e-20 if (x - 1e-20 < 0) else x for x in lst] for lst in wn.tolist()]
  36.         wd = [[1e-20 if (x - 1e-20 < 0) else x for x in lst] for lst in wd.tolist()]
  37.  
  38.         w = matrix(array(w) * array(wn) / array(wd))
  39.  
  40.         if i == 0: pass
  41.         else:
  42.             if (previouscost-cost)/previouscost < 0.01:
  43.                 print("%d: %f" % (i, cost)),'\nCost improved by less than 1%'
  44.                 break
  45.         previouscost=cost
  46.  
  47.     return w, h
Advertisement
Add Comment
Please, Sign In to add comment