گرادیان کاهشی ( Gradient descent) یک الگوریتم برای پیدا کردن کمینه ی یک تابع می باشد.

اساس الگوریتم
الگوریتم گرادیان کاهشی
این الگوریتم از الگوریتم بهینهسازی مرتبهٔ اول از نوع الگوریتمهای تکرار شونده است. برای یافتن کمینهٔ محلی یک تابع با استفاده از این الگوریتم، گامهایی متناسب با منفی گرادیان (یا گرادیان تخمینی) تابع در محل فعلی برداشته خواهد شد. اگر در استفاده از این الگوریتم، گامهایی متناسب با جهت مثبت گرادیان برداشته شود، به بیشینهٔ محلی تابع نزدیک میشویم که به این فرایند افزایش گرادیان گفته میشود. اگر تابع محدب یا مقعر باشه به بیشینه و کمینه جهانی میرسیم.
کد پایتون الگورتیم
#!\bin\py\Midya print(""" _____ _ _ _ _ | ___| | (_) | | (_) | |__ ___| |_ _ __ | |_ _ ___ | __|/ __| | | '_ \| __| |/ __| | |__| (__| | | |_) | |_| | (__ \____/\___|_|_| .__/ \__|_|\___| | | |_| """) print("\a This Program calculate the Gradient Descent \n Just Fallow the Instruction to run the Algorithm\n") print("If you Have eny Quastion or opinion Call me : midyalab@gmail.com or visit: Ecliptic. \n Programmer::Midya Rostami:: ") fx = input("Enter df/dx Function: ") df = lambda x: eval(fx) #main function (definition) curx = int(input("please enter The algorithm start point: ")) #The algorithm start point rate = float(input("Enter the Learning Rate(eg=0.01): ")) # Learning rate precision = float(input("Enter the Digit's Aaccuracy (means when to stop the algorithm eg=0.000001): ")) #This tells us when to stop the algorithm maxit = float(input("Enter maximum number of iterations(eg=10000): ")) # maximum number of iterations previousstepsize = 1 # iters= 0 #iteration counter while previousstepsize > precision and iters < maxit: prevx = curx #Store current x value in prev_x curx = curx - rate * df(prevx) #Grad descent previousstepsize = abs(curx - prevx) #Change in x iters = iters+1 #iteration count print("Iteration",iters,"\nX value is",curx) #Print iterations print("The minimum occurs at", curx) quit = input()