Skip to content

Instantly share code, notes, and snippets.

@Tan-Moy
Tan-Moy / wild_west.svg
Last active January 22, 2017 13:59
Wild West
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@Tan-Moy
Tan-Moy / desert.svg
Created January 22, 2017 14:23
Desert
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
function sum (number1, number2){ //We defined a function with a name of sum and it takes 2 parameters
console.log (number1+number2); //Then it adds up the parameters and console.logs it
}
sum(2,1); //We invoke the function here and it prints out 3
//the function from before
function sum(number1, number2) {
console.log(number1 + number2);
}
//sum(2, 1); //3
//new function that takes 3 parameters
function doesSomething(parameter1, parameter2, parameter3) { //again we define a function with 3 parameters
console.log('This is parameter 1: ',parameter1); //print parameter 1
console.log('This is parameter 2: ',parameter2);//print parameter 2
import matplotlib.pyplot as plt
import numpy as np
my_data = np.genfromtxt('data.csv', delimiter=',') # read the data
X = my_data[:, 0].reshape(-1,1) # -1 tells numpy to figure out the dimension by itself
ones = np.ones([X.shape[0], 1]) # create a array containing only ones
X = np.concatenate([ones, X],1) # cocatenate the ones to X matrix
y = my_data[:, 1].reshape(-1,1) # create the y matrix
# notice small alpha value
alpha = 0.0001
iters = 1000
# theta is a row vector
theta = np.array([[1.0, 1.0]])
def computeCost(X, y, theta):
inner = np.power(((X @ theta.T) - y), 2) # @ means matrix multiplication of arrays. If we want to use * for multiplication we will have to convert all arrays to matrices
return np.sum(inner) / (2 * len(X))
def gradientDescent(X, y, theta, alpha, iters):
for i in range(iters):
theta = theta - (alpha/len(X)) * np.sum((X @ theta.T - y) * X, axis=0)
cost = computeCost(X, y, theta)
# if i % 10 == 0: # just look at cost every ten loops for debugging
# print(cost)
return (theta, cost)
plt.scatter(my_data[:, 0].reshape(-1,1), y)
axes = plt.gca()
x_vals = np.array(axes.get_xlim())
y_vals = g[0][0] + g[0][1]* x_vals #the line equation
plt.plot(x_vals, y_vals, '--')