Always prefer builtin functions and operators to for loops. They are much more efficient.
% matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
theta0 = 1
theta1 = 2
n = 20
x = np.random.rand(n)
y = theta0 + theta1*x + 0.1*np.random.randn(n)
plt.scatter(x,y)
# Compute the cost
pred = theta0 + theta1*x
residual = y - pred
cost = np.sum(residual**2)
cost2 = np.dot(residual, residual)
print cost
print cost2
print np.sum( (theta0 + theta1*x - y)**2 ) # one liner
There are many functions / operators available for elementwise and summary operations on arrays. Find them and use them!
Sometimes you can use linear algebra to compute what you want!
# Example
A = np.array([[1, 2, 3], [4, 5, 6], [7,8, 9]])
print A
print np.sum(A)
print A
print np.sum(A, axis=0)
print A
print np.sum(A, axis=1)
A = np.array([[1, 2, 3], [4, 5, 6], [7,8, 9]])
print A
# Get first row of A
print A[0, :]
# Get second column of A
print A[:, 1]
# Assign to third row of A
A[2,:] = [10, 11, 12]
print A
# Get lower right block of A
print A[1:3, 1:3]
x = np.array([1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1])
i = x >= 4 # elementwise comparison
print i
print x
print i
print x[i] # select entries of x for which i is true
print x[x>=4] # one-liner
a = np.array([1, 2, 3, 4, 5])
b = np.array([5, 4, 3, 2, 1])
print a[ a >= b ] # What does this print?