<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Preparation (Based on Linear Regression)
Prepare train and test data.
Step1:  Define some necessary functions.
Step2:  Gradient Checking
Define "step size" (don't set it too low to avoid numerical precision issues).
Step3:  Prepare theta step values (making use of numpy broadcasting).
Step4:  Compute diffs between theta's gradient as mathematically defined and the gradient as defined by our function above.
Step5:  Lookin' good! The smaller the values, the better.<br>
(Any value significantly larger than 1e-4 indicates a problem.)
<ASSISTANT_TASK:>
Python Code:
data_original = np.loadtxt('stanford_dl_ex/ex1/housing.data')
data = np.insert(data_original, 0, 1, axis=1)
np.random.shuffle(data)
train_X = data[:400, :-1]
train_y = data[:400, -1]
m, n = train_X.shape
theta = np.random.rand(n)
Explanation: Preparation (Based on Linear Regression)
Prepare train and test data.
End of explanation
def cost_function(theta, X, y): 
    squared_errors = (X.dot(theta) - y) ** 2
    J = 0.5 * squared_errors.sum()
    return J
def gradient(theta, X, y):
    errors = X.dot(theta) - y
    return errors.dot(X)
Explanation: Define some necessary functions.
End of explanation
epsilon = 1e-4
Explanation: Gradient Checking
Define "step size" (don't set it too low to avoid numerical precision issues).
End of explanation
mask = np.identity(theta.size)
theta_plus = theta + epsilon * mask
theta_minus = theta - epsilon * mask
Explanation: Prepare theta step values (making use of numpy broadcasting).
End of explanation
diffs = np.empty_like(theta)
for i in range(theta_plus.shape[0]):
    gradient_def = (
        (cost_function(theta_plus[i], train_X, train_y) - cost_function(theta_minus[i], train_X, train_y)) /
        (2 * epsilon)
    )
    gradient_lin_reg = gradient(theta, train_X, train_y)[i]
    diffs[i] = np.absolute(gradient_def - gradient_lin_reg)
diffs
Explanation: Compute diffs between theta's gradient as mathematically defined and the gradient as defined by our function above.
End of explanation
assert all(np.less(diffs, 1e-4))
Explanation: Lookin' good! The smaller the values, the better.<br>
(Any value significantly larger than 1e-4 indicates a problem.)
End of explanation
<END_TASK>