Advertisement
Guest User

Self-descriptive number

a guest
Feb 7th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. __author__ = 'shagas'
  2.  
  3. import numpy as np
  4.  
  5. # Get cost of the solution
  6. def cost(y):
  7.  
  8.     # Turn into a list so that we can use the 'count()' function
  9.     x = list(y)
  10.  
  11.     # Error sum
  12.     err = np.zeros((len(x)))
  13.     for i in range(len(x)):
  14.         err[i] = 0.5*(x[i] - x.count(i))**2 # J_i = 0.5*( x_i - z_i )^2
  15.  
  16.     return sum(err)
  17.  
  18. # Get vector of partial derivatives of the cost function
  19. def getGrad(y):
  20.  
  21.     # Turn into a list so that we can use the 'count()' function
  22.     x = list(y)
  23.  
  24.     z = np.zeros((len(x)))
  25.     grad = np.zeros((len(x)))
  26.  
  27.     for i in range(len(x)):
  28.         z[i] = x.count(i)
  29.         grad[i] = (x[i] - z[i])  # dJ/dx_i = ( x_i - z_i )
  30.  
  31.     return grad
  32.  
  33.  
  34. # Initialize the solution to either random or all zeros or custom
  35. sol = np.zeros((10))
  36. #sol = np.random.rand(10)*10
  37. #sol = np.array([0,2,0,4,5,2,1,0,4,2])
  38.  
  39. # Parameters
  40. iters = 800
  41. alpha = 0.01
  42.  
  43. # Optimize
  44. for i in range(iters):
  45.  
  46.     # Error of solution
  47.     err = cost(np.round(sol))
  48.  
  49.     # Update
  50.     sol -= alpha*getGrad(np.round(sol))*err
  51.  
  52.     # Print out current solution every so often
  53.     if i % (iters/30) == 0:
  54.         print 'Solution: ' + str(np.round(sol)) + ' cost: ' + str(err)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement