TVP

# 手把手教你用Python解决单一变量的线性回归问题

“如果你是一家特许经营餐厅的CEO，你正在考虑在某座城市开设一家新的奥莱店，现在你手上有各城市已开设的加盟餐厅的营业利润以及该城市的人口数据，你想知道在某一人口规模的城市中开设的新餐厅的营业利润将会是多少。”

import numpy as npimport pandas as pdimport matplotlib.pyplot as plt

path = 'C:\machine learning\ex1data1.txt'data = pd.read_csv(path,names=['Population', 'Profit'])data.plot(kind='scatter',x='Population', y='Profit', figsize=(12,8))plt.show()

def computeCost(X, y, theta): inner = np.power(((X * theta.T) - y), 2) return np.sum(inner) / (2 * len(X))

data.insert(0, 'Ones', 1)

cols = data.shape[1]X = data.iloc[:,0:cols-1]y = data.iloc[:,cols-1:cols]

X = np.matrix(X.values)y = np.matrix(y.values)theta = np.matrix(np.array([0,0]))

X.shape, theta.shape, y.shape

computeCost(X, y, theta)

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

alpha = 0.01iters = 1000

g,cost = gradientDescent(X, y, theta, alpha, iters)

computeCost(X, y, g)

#变量的定义域和取样的个数x = np.linspace(data.Population.min(), data.Population.max(), 100)#输出predictionf = g[0, 0] + (g[0, 1] * x)fig, ax = plt.subplots(figsize=(12,8))ax.plot(x, f, 'r', label='Prediction')ax.scatter(data.Population, data.Profit, label='Traning Data')ax.legend(loc=2)ax.set_xlabel('Population')ax.set_ylabel('Profit')ax.set_title('Predicted Profit vs. Population Size')plt.show()

fig, ax = plt.subplots(figsize=(12,8))ax.plot(np.arange(iters), cost, 'r')ax.set_xlabel('Iterations')ax.set_ylabel('Cost')ax.set_title('Error vs. Training Epoch')plt.show()

• 发表于:
• 原文链接http://kuaibao.qq.com/s/20180109G04BIY00?refer=cp_1026
• 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 cloudcommunity@tencent.com 删除。

2023-04-02

2023-04-02

2023-04-02

2023-04-02

2023-04-02

10元无门槛代金券