Created
September 10, 2019 03:13
-
-
Save ortsed/e25d2d490d0dc152724d1b1020526b2d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def find_term_derivative(term): | |
constant = term[0]*term[1] | |
exponent = term[1] - 1 | |
return (constant, exponent) | |
def find_derivative(function_terms): | |
derivative_terms = list(map(lambda term: find_term_derivative(term),function_terms)) | |
return list(filter(lambda derivative_term: derivative_term[0] != 0, derivative_terms)) | |
def term_output(term, input_value): | |
return term[0]*input_value**term[1] | |
def output_at(list_of_terms, x_value): | |
outputs = list(map(lambda term: term_output(term, x_value), list_of_terms)) | |
return sum(outputs) | |
def derivative_at(terms, x): | |
derivative_fn = find_derivative(terms) | |
total = 0 | |
for term in derivative_fn: | |
total += term[0]*x**term[1] | |
return total | |
def errors(x_values, y_values, m, b): | |
y_line = (b + m*x_values) | |
return (y_values - y_line) | |
def squared_errors(x_values, y_values, m, b): | |
return errors(x_values, y_values, m, b)**2 | |
def residual_sum_squares(x_values, y_values, m, b): | |
return sum(squared_errors(x_values, y_values, m, b)) | |
def slope_at(x_values, y_values, m, b): | |
delta = .001 | |
base_rss = residual_sum_squares(x_values, y_values, m, b) | |
delta_rss = residual_sum_squares(x_values, y_values, m, b + delta) | |
numerator = delta_rss - base_rss | |
slope = numerator/delta | |
return {'b': b, 'slope': slope} | |
def gradient_descent(x_values, y_values, steps, current_b, learning_rate, m): | |
cost_curve = [] | |
for i in range(steps): | |
current_cost_slope = slope_at(x_values, y_values, m, current_b)['slope'] | |
current_rss = residual_sum_squares(x_values, y_values, m, current_b) | |
cost_curve.append({'b': current_b, 'rss': round(current_rss,2), 'slope': round(current_cost_slope,2)}) | |
current_b = updated_b(current_b, learning_rate, current_cost_slope) | |
return cost_curve |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment