Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- __author__ = 'shagas'
- import numpy as np
- # Get cost of the solution
- def cost(y):
- # Turn into a list so that we can use the 'count()' function
- x = list(y)
- # Error sum
- err = np.zeros((len(x)))
- for i in range(len(x)):
- err[i] = 0.5*(x[i] - x.count(i))**2 # J_i = 0.5*( x_i - z_i )^2
- return sum(err)
- # Get vector of partial derivatives of the cost function
- def getGrad(y):
- # Turn into a list so that we can use the 'count()' function
- x = list(y)
- z = np.zeros((len(x)))
- grad = np.zeros((len(x)))
- for i in range(len(x)):
- z[i] = x.count(i)
- grad[i] = (x[i] - z[i]) # dJ/dx_i = ( x_i - z_i )
- return grad
- # Initialize the solution to either random or all zeros or custom
- sol = np.zeros((10))
- #sol = np.random.rand(10)*10
- #sol = np.array([0,2,0,4,5,2,1,0,4,2])
- # Parameters
- iters = 800
- alpha = 0.01
- # Optimize
- for i in range(iters):
- # Error of solution
- err = cost(np.round(sol))
- # Update
- sol -= alpha*getGrad(np.round(sol))*err
- # Print out current solution every so often
- if i % (iters/30) == 0:
- print 'Solution: ' + str(np.round(sol)) + ' cost: ' + str(err)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement