machinelearning

Machine learning code
git clone git://git.laack.co/machinelearning.git
Log | Files | Refs

GradientDescentThirdDegreePolynomialV2.py (1069B)


      1 import sys
      2 import random
      3 
      4 RECURSION_LIMIT = 1500
      5 
      6 
      7 sys.setrecursionlimit(RECURSION_LIMIT)
      8 print("ax^3 + bx^2 + cx + d")
      9 a = float(input("Enter a: "))
     10 b = float(input("Enter b: "))
     11 c = float(input("Enter c: "))
     12 d = float(input("Enter d: "))
     13 learningRate = float(input("Learning Rate: "))
     14 
     15 
     16 def calculateValue(x):
     17     return x**3 * a + x**2 * b + x * c + d
     18 
     19 
     20 def printResult(x, y):
     21     print("x: " + str(x) + "\ty: " + str(y))
     22 
     23 
     24 def limit(x):
     25     rightX = x + .00000001
     26     leftX = x - .00000001
     27 
     28     rightY = calculateValue(rightX)
     29     leftY = calculateValue(leftX)
     30 
     31     return ((rightY - leftY) / .00000002)
     32 
     33 
     34 def descend(x, depth):
     35     # Need - 15 because recursion includes other function calls...
     36     if depth >= RECURSION_LIMIT - 15:
     37         return x
     38     lim = limit(x)
     39     printResult(x, calculateValue(x))
     40     depth += 1
     41 
     42     if lim > 0:
     43         return descend(x - learningRate * lim, depth)
     44     else:
     45         return descend(x + learningRate * lim, depth)
     46 
     47 
     48 currSearch = random.random() * 10
     49 xVal = descend(currSearch, 0)
     50 
     51 printResult(xVal, calculateValue(xVal))