1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import numpy as np import pandas as pd import matplotlib.pyplot as plt
def computeCost(X, y, theta): inner = np.power(((X * theta.T) - y), 2) return np.sum(inner) / (2 * len(X))
def gradientDescent(X, y, theta, alpha, iters): temp = np.matrix(np.zeros(theta.shape)) parameters = int(theta.ravel().shape[1]) cost = np.zeros(iters)
for i in range(iters): error = (X * theta.T) - y
for j in range(parameters): term = np.multiply(error, X[:, j]) temp[0, j] = theta[0, j] - ((alpha / len(X)) * np.sum(term))
theta = temp cost[i] = computeCost(X, y, theta)
return theta, cost
path = "ex1data2.txt" data = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])
data = (data - data.mean()) / data.std()
data.insert(0, 'Ones', 1)
cols = data.shape[1] X = data.iloc[:, 0:cols - 1] y = data.iloc[:, cols - 1:cols] theta = np.matrix(np.array([0, 0, 0])) X = np.matrix(X.values) y = np.matrix(y.values)
alpha = 0.01 iters = 1000 g, cost = gradientDescent(X, y, theta, alpha, iters)
fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(111, projection='3d')
ax.scatter(data['Size'], data['Bedrooms'], data['Price'], c='r', marker='o')
size_vals = np.linspace(data['Size'].min(), data['Size'].max(), 100) bedroom_vals = np.linspace(data['Bedrooms'].min(), data['Bedrooms'].max(), 100) size_vals, bedroom_vals = np.meshgrid(size_vals, bedroom_vals) price_vals = g[0, 2] + g[0, 0] * size_vals + g[0, 1] * bedroom_vals ax.plot_surface(size_vals, bedroom_vals, price_vals, color='blue', alpha=0.5)
ax.set_xlabel('Size') ax.set_ylabel('Bedrooms') ax.set_zlabel('Price')
ax.set_title('Price vs. Size and Bedrooms')
plt.show()
|