前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 单变量线性回归

python 单变量线性回归

作者头像
JadePeng
发布2018-03-12 16:17:58
1.6K0
发布2018-03-12 16:17:58
举报

单变量线性回归(Linear Regression with One Variable)

In [54]:

代码语言:javascript
复制
#初始化工作
import random
import numpy as np
import matplotlib.pyplot as plt

# This is a bit of magic to make matplotlib figures appear inline in the notebook
# rather than in a new window.
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

# Some more magic so that the notebook will reload external python modules;
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2

1、加载数据与可视化

In [55]:

代码语言:javascript
复制
print('Plotting Data ...')

def load_exdata(filename):
    data = []
    with open(filename, 'r') as f:
        for line in f.readlines(): 
            line = line.split(',')
            current = [float(item) for item in line]
            #5.5277,9.1302
            data.append(current)
    return data

data = load_exdata('ex1data1.txt');
data = np.array(data)
print(data.shape)

x = data[:, 0]; y = data[:,1]
m = data.shape[0] 
#number of training examples
plt.plot(x,y,'rx')
plt.ylabel('Profit in $10,000s');
plt.xlabel('Population of City in 10,000s');
plt.title("Training data")
代码语言:javascript
复制
Plotting Data ...
(97, 2)

Out[55]:

代码语言:javascript
复制
<matplotlib.text.Text at 0x2e663d888d0>

2、通过梯度下降求解theta

In [56]:

代码语言:javascript
复制
x = x.reshape(-1,1)
# 添加一列1
X = np.hstack([x,np.ones((x.shape[0], 1))])
theta = np.zeros((2, 1))
y = y.reshape(-1,1)

#计算损失
def computeCost(X, y, theta):
    m = y.shape[0]
    J = (np.sum((X.dot(theta) - y)**2)) / (2*m)  
    #X (m,2) theta (2,1) = m*1
    return J

#梯度下降
def gradientDescent(X, y, theta, alpha, num_iters):
    m = y.shape[0]
    # 存储历史误差
    J_history = np.zeros((num_iters, 1))
    
    for iter in range(num_iters):
        # 对J求导,得到 alpha/m * (WX - Y)*x(i),
        theta = theta - ( alpha/m) * X.T.dot(X.dot(theta) - y)
        J_history[iter] = computeCost(X, y, theta)
    return J_history,theta
    

iterations = 1500  #迭代次数
alpha = 0.01    #学习率
j = computeCost(X,y,theta)
J_history,theta = gradientDescent(X, y, theta, alpha, iterations)
print('Theta found by gradient descent: %f %f'%(theta[0][0],theta[1][0]))
plt.plot(J_history)
plt.ylabel('lost');
plt.xlabel('iter count')
代码语言:javascript
复制
Theta found by gradient descent: 1.166362 -3.630291

Out[56]:

代码语言:javascript
复制
<matplotlib.text.Text at 0x2e661194ac8>

3、训练结果可视化

In [57]:

代码语言:javascript
复制
#number of training examples
plt.plot(data[:,0],data[:,1],'rx')
plt.plot(X[:,0], X.dot(theta), '-')
plt.ylabel('Profit in $10,000s');
plt.xlabel('Population of City in 10,000s');
plt.title("Training data")

Out[57]:

代码语言:javascript
复制
<matplotlib.text.Text at 0x2e662155198>

4、可视化 J(theta_0, theta_1)

In [75]:

代码语言:javascript
复制
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter

theta0_vals = np.linspace(-10, 10, 100)
theta1_vals = np.linspace(-10, 10, 100)

J_vals = np.zeros((theta0_vals.shape[0], theta1_vals.shape[0]));


# 填充J_vals
for i in range(theta0_vals.shape[0]):
    for j in range(theta1_vals.shape[0]):
        t = [theta0_vals[i],theta1_vals[j]]
        J_vals[i,j] = computeCost(X, y, t)


fig = plt.figure()
ax = fig.gca(projection='3d')

theta0_vals, theta1_vals = np.meshgrid(theta0_vals, theta1_vals)
# Plot the surface.
surf = ax.plot_surface(theta0_vals, theta1_vals, J_vals, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)

# 定制Z轴.
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%d'))

# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

In [ ]:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-02-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 单变量线性回归(Linear Regression with One Variable)¶
    • 1、加载数据与可视化¶
    • 2、通过梯度下降求解theta¶
      • 3、训练结果可视化¶
        • 4、可视化 J(theta_0, theta_1)¶
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档