python 单变量线性回归
时间:2022-05-04
本文章向大家介绍python 单变量线性回归,主要内容包括单变量线性回归(Linear Regression with One Variable)¶、2、通过梯度下降求解theta¶、4、可视化 J(theta_0, theta_1)¶、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。
单变量线性回归(Linear Regression with One Variable)¶
In [54]:
#初始化工作
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]:
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")
Plotting Data ...
(97, 2)
Out[55]:
<matplotlib.text.Text at 0x2e663d888d0>
2、通过梯度下降求解theta¶
In [56]:
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')
Theta found by gradient descent: 1.166362 -3.630291
Out[56]:
<matplotlib.text.Text at 0x2e661194ac8>
3、训练结果可视化¶
In [57]:
#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]:
<matplotlib.text.Text at 0x2e662155198>
4、可视化 J(theta_0, theta_1)¶
In [75]:
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 [ ]:
- Silverlight学习(二)
- Silverlight学习(三)
- ArcGIS for Android学习(一)
- Arcgis for Silverlight学习(一)
- ImageButton与Button
- RadioButton、CheckBox与ToggleButton
- Silverlight学习(五)图形标绘
- radio与checkbox
- JavaScript之cookie
- Silverlight学习(四) domainservice动态多条件查询
- Android学习Tabhost、gallery、listview、imageswitcher
- ProgressBar、RatingBar和Spinner控件
- TimePicker控件、帧动画、补间动画
- Android学习之简单的数据存储
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- Linux硬盘合并的实现代码
- 虚拟机Linux桥接模式下设置静态IP详解
- Linux平台安装redis及redis扩展的方法
- Linux环境下快速搭建ftp服务器方法介绍
- Linux通过匿名管道进行进程间通信
- shell判断一个变量是否为空方法总结
- 基于ubuntu16 Python3 tensorflow(TensorFlow环境搭建)
- Linux中的iostat命令使用教程
- 深入解读Linux进程函数fork(),vfork(),execX()
- Linux centos下设置定时备份任务的方法步骤
- Linux 中如何切换相同程序的不同版本
- Linux中查看指定文件夹内各个子文件夹内的文件数量
- Linux系统中 /etc/fstab 文件的深入解读
- bash命令使用详解
- 实例详解Linux 中的命令链接操作符