提交 436ebbf6 编写于 作者: J jacquesqiao 提交者: GitHub

Merge pull request #268 from jacquesqiao/draw

Draw figure in event_handler
此差异已折叠。
......@@ -163,40 +163,31 @@ feeding={'x': 0, 'y': 1}
Moreover, an event handler is provided to print the training progress:
```python
import matplotlib.pyplot as plt
from IPython import display
import cPickle
# event_handler to print training and testing info
from paddle.v2.plot import Ploter
step=0
train_title = "Train cost"
test_title = "Test cost"
plot_cost = Ploter(train_title, test_title)
train_costs=[],[]
test_costs=[],[]
step = 0
def event_handler(event):
global step
global train_costs
global test_costs
if isinstance(event, paddle.event.EndIteration):
need_plot = False
if step % 10 == 0: # every 10 batches, record a train cost
train_costs[0].append(step)
train_costs[1].append(event.cost)
plot_cost.append(train_title, step, event.cost)
if step % 1000 == 0: # every 1000 batches, record a test cost
if step % 100 == 0: # every 100 batches, record a test cost
result = trainer.test(
reader=paddle.batch(
uci_housing.test(), batch_size=2),
feeding=feeding)
test_costs[0].append(step)
test_costs[1].append(result.cost)
plot_cost.append(test_title, step, result.cost)
if step % 100 == 0: # every 100 batches, update cost plot
plt.plot(*train_costs)
plt.plot(*test_costs)
plt.legend(['Train Cost', 'Test Cost'], loc='upper left')
display.clear_output(wait=True)
display.display(plt.gcf())
plt.gcf().clear()
plot_cost.plot()
step += 1
```
......@@ -213,7 +204,7 @@ trainer.train(
num_passes=30)
```
![png](./image/train-and-test.png)
![png](./image/train_and_test.png)
## Summary
This chapter introduces *Linear Regression* and how to train and test this model with PaddlePaddle, using the UCI Housing Data Set. Because a large number of more complex models and techniques are derived from linear regression, it is important to understand its underlying theory and limitation.
......
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 线性回归\n",
"让我们从经典的线性回归(Linear Regression \\[[1](#参考文献)\\])模型开始这份教程。在这一章里,你将使用真实的数据集建立起一个房价预测模型,并且了解到机器学习中的若干重要概念。\n",
"\n",
"本教程源代码目录在[book/fit_a_line](https://github.com/PaddlePaddle/book/tree/develop/01.fit_a_line), 初次使用请参考PaddlePaddle[安装教程](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_cn.rst)。\n",
"\n",
"## 背景介绍\n",
"给定一个大小为$n$的数据集 ${\\{y_{i}, x_{i1}, ..., x_{id}\\}}_{i=1}^{n}$,其中$x_{i1}, \\ldots, x_{id}$是第$i$个样本$d$个属性上的取值,$y_i$是该样本待预测的目标。线性回归模型假设目标$y_i$可以被属性间的线性组合描述,即\n",
"\n",
"$$y_i = \\omega_1x_{i1} + \\omega_2x_{i2} + \\ldots + \\omega_dx_{id} + b, i=1,\\ldots,n$$\n",
"\n",
"例如,在我们将要建模的房价预测问题里,$x_{ij}$是描述房子$i$的各种属性(比如房间的个数、周围学校和医院的个数、交通状况等),而 $y_i$是房屋的价格。\n",
"\n",
"初看起来,这个假设实在过于简单了,变量间的真实关系很难是线性的。但由于线性回归模型有形式简单和易于建模分析的优点,它在实际问题中得到了大量的应用。很多经典的统计学习、机器学习书籍\\[[2,3,4](#参考文献)\\]也选择对线性模型独立成章重点讲解。\n",
"\n",
"## 效果展示\n",
"我们使用从[UCI Housing Data Set](https://archive.ics.uci.edu/ml/datasets/Housing)获得的波士顿房价数据集进行模型的训练和预测。下面的散点图展示了使用模型对部分房屋价格进行的预测。其中,每个点的横坐标表示同一类房屋真实价格的中位数,纵坐标表示线性回归模型根据特征预测的结果,当二者值完全相等的时候就会落在虚线上。所以模型预测得越准确,则点离虚线越近。\n",
"\u003cp align=\"center\"\u003e\n",
" \u003cimg src = \"image/predictions.png\" width=400\u003e\u003cbr/\u003e\n",
" 图1. 预测值 V.S. 真实值\n",
"\u003c/p\u003e\n",
"\n",
"## 模型概览\n",
"\n",
"### 模型定义\n",
"\n",
"在波士顿房价数据集中,和房屋相关的值共有14个:前13个用来描述房屋相关的各种信息,即模型中的 $x_i$;最后一个值为我们要预测的该类房屋价格的中位数,即模型中的 $y_i$。因此,我们的模型就可以表示成:\n",
"\n",
"$$\\hat{Y} = \\omega_1X_{1} + \\omega_2X_{2} + \\ldots + \\omega_{13}X_{13} + b$$\n",
"\n",
"$\\hat{Y}$ 表示模型的预测结果,用来和真实值$Y$区分。模型要学习的参数即:$\\omega_1, \\ldots, \\omega_{13}, b$。\n",
"\n",
"建立模型后,我们需要给模型一个优化目标,使得学到的参数能够让预测值$\\hat{Y}$尽可能地接近真实值$Y$。这里我们引入损失函数([Loss Function](https://en.wikipedia.org/wiki/Loss_function),或Cost Function)这个概念。 输入任意一个数据样本的目标值$y_{i}$和模型给出的预测值$\\hat{y_{i}}$,损失函数输出一个非负的实值。这个实值通常用来反映模型误差的大小。\n",
"\n",
"对于线性回归模型来讲,最常见的损失函数就是均方误差(Mean Squared Error, [MSE](https://en.wikipedia.org/wiki/Mean_squared_error))了,它的形式是:\n",
"\n",
"$$MSE=\\frac{1}{n}\\sum_{i=1}^{n}{(\\hat{Y_i}-Y_i)}^2$$\n",
"\n",
"即对于一个大小为$n$的测试集,$MSE$是$n$个数据预测结果误差平方的均值。\n",
"\n",
"### 训练过程\n",
"\n",
"定义好模型结构之后,我们要通过以下几个步骤进行模型训练\n",
" 1. 初始化参数,其中包括权重$\\omega_i$和偏置$b$,对其进行初始化(如0均值,1方差)。\n",
" 2. 网络正向传播计算网络输出和损失函数。\n",
" 3. 根据损失函数进行反向误差传播 ([backpropagation](https://en.wikipedia.org/wiki/Backpropagation)),将网络误差从输出层依次向前传递, 并更新网络中的参数。\n",
" 4. 重复2~3步骤,直至网络训练误差达到规定的程度或训练轮次达到设定值。\n",
"\n",
"## 数据集\n",
"\n",
"### 数据集接口的封装\n",
"首先加载需要的包\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"editable": true
},
"source": [
"import paddle.v2 as paddle\n",
"import paddle.v2.dataset.uci_housing as uci_housing\n"
],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n"
]
}
],
"execution_count": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"我们通过uci_housing模块引入了数据集合[UCI Housing Data Set](https://archive.ics.uci.edu/ml/datasets/Housing)\n",
"\n",
"其中,在uci_housing模块中封装了:\n",
"\n",
"1. 数据下载的过程。下载数据保存在~/.cache/paddle/dataset/uci_housing/housing.data。\n",
"2. [数据预处理](#数据预处理)的过程。\n",
"\n",
"\n",
"### 数据集介绍\n",
"这份数据集共506行,每行包含了波士顿郊区的一类房屋的相关信息及该类房屋价格的中位数。其各维属性的意义如下:\n",
"\n",
"| 属性名 | 解释 | 类型 |\n",
"| ------| ------ | ------ |\n",
"| CRIM | 该镇的人均犯罪率 | 连续值 |\n",
"| ZN | 占地面积超过25,000平方呎的住宅用地比例 | 连续值 |\n",
"| INDUS | 非零售商业用地比例 | 连续值 |\n",
"| CHAS | 是否邻近 Charles River | 离散值,1=邻近;0=不邻近 |\n",
"| NOX | 一氧化氮浓度 | 连续值 |\n",
"| RM | 每栋房屋的平均客房数 | 连续值 |\n",
"| AGE | 1940年之前建成的自用单位比例 | 连续值 |\n",
"| DIS | 到波士顿5个就业中心的加权距离 | 连续值 |\n",
"| RAD | 到径向公路的可达性指数 | 连续值 |\n",
"| TAX | 全值财产税率 | 连续值 |\n",
"| PTRATIO | 学生与教师的比例 | 连续值 |\n",
"| B | 1000(BK - 0.63)^2,其中BK为黑人占比 | 连续值 |\n",
"| LSTAT | 低收入人群占比 | 连续值 |\n",
"| MEDV | 同类房屋价格的中位数 | 连续值 |\n",
"\n",
"### 数据预处理\n",
"#### 连续值与离散值\n",
"观察一下数据,我们的第一个发现是:所有的13维属性中,有12维的连续值和1维的离散值(CHAS)。离散值虽然也常使用类似0、1、2这样的数字表示,但是其含义与连续值是不同的,因为这里的差值没有实际意义。例如,我们用0、1、2来分别表示红色、绿色和蓝色的话,我们并不能因此说“蓝色和红色”比“绿色和红色”的距离更远。所以通常对一个有$d$个可能取值的离散属性,我们会将它们转为$d$个取值为0或1的二值属性或者将每个可能取值映射为一个多维向量。不过就这里而言,因为CHAS本身就是一个二值属性,就省去了这个麻烦。\n",
"\n",
"#### 属性的归一化\n",
"另外一个稍加观察即可发现的事实是,各维属性的取值范围差别很大(如图2所示)。例如,属性B的取值范围是[0.32, 396.90],而属性NOX的取值范围是[0.3850, 0.8170]。这里就要用到一个常见的操作-归一化(normalization)了。归一化的目标是把各位属性的取值范围放缩到差不多的区间,例如[-0.5,0.5]。这里我们使用一种很常见的操作方法:减掉均值,然后除以原取值范围。\n",
"\n",
"做归一化(或 [Feature scaling](https://en.wikipedia.org/wiki/Feature_scaling))至少有以下3个理由:\n",
"- 过大或过小的数值范围会导致计算时的浮点上溢或下溢。\n",
"- 不同的数值范围会导致不同属性对模型的重要性不同(至少在训练的初始阶段如此),而这个隐含的假设常常是不合理的。这会对优化的过程造成困难,使训练时间大大的加长。\n",
"- 很多的机器学习技巧/模型(例如L1,L2正则项,向量空间模型-Vector Space Model)都基于这样的假设:所有的属性取值都差不多是以0为均值且取值范围相近的。\n",
"\n",
"\u003cp align=\"center\"\u003e\n",
" \u003cimg src = \"image/ranges.png\" width=550\u003e\u003cbr/\u003e\n",
" 图2. 各维属性的取值范围\n",
"\u003c/p\u003e\n",
"\n",
"#### 整理训练集与测试集\n",
"我们将数据集分割为两份:一份用于调整模型的参数,即进行模型的训练,模型在这份数据集上的误差被称为**训练误差**;另外一份被用来测试,模型在这份数据集上的误差被称为**测试误差**。我们训练模型的目的是为了通过从训练数据中找到规律来预测未知的新数据,所以测试误差是更能反映模型表现的指标。分割数据的比例要考虑到两个因素:更多的训练数据会降低参数估计的方差,从而得到更可信的模型;而更多的测试数据会降低测试误差的方差,从而得到更可信的测试误差。我们这个例子中设置的分割比例为$8:2$\n",
"\n",
"\n",
"在更复杂的模型训练过程中,我们往往还会多使用一种数据集:验证集。因为复杂的模型中常常还有一些超参数([Hyperparameter](https://en.wikipedia.org/wiki/Hyperparameter_optimization))需要调节,所以我们会尝试多种超参数的组合来分别训练多个模型,然后对比它们在验证集上的表现选择相对最好的一组超参数,最后才使用这组参数下训练的模型在测试集上评估测试误差。由于本章训练的模型比较简单,我们暂且忽略掉这个过程。\n",
"\n",
"## 训练\n",
"\n",
"`fit_a_line/trainer.py`演示了训练的整体过程。\n",
"\n",
"### 初始化PaddlePaddle\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"editable": true
},
"source": [
"paddle.init(use_gpu=False, trainer_count=1)\n"
],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n"
]
}
],
"execution_count": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"### 模型配置\n",
"\n",
"线性回归的模型其实就是一个采用线性激活函数(linear activation,`LinearActivation`)的全连接层(fully-connected layer,`fc_layer`):\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"editable": true
},
"source": [
"x = paddle.layer.data(name='x', type=paddle.data_type.dense_vector(13))\n",
"y_predict = paddle.layer.fc(input=x,\n",
" size=1,\n",
" act=paddle.activation.Linear())\n",
"y = paddle.layer.data(name='y', type=paddle.data_type.dense_vector(1))\n",
"cost = paddle.layer.mse_cost(input=y_predict, label=y)\n"
],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n"
]
}
],
"execution_count": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 创建参数\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"editable": true
},
"source": [
"parameters = paddle.parameters.create(cost)\n"
],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n"
]
}
],
"execution_count": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"### 创建Trainer\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"editable": true
},
"source": [
"optimizer = paddle.optimizer.Momentum(momentum=0)\n",
"\n",
"trainer = paddle.trainer.SGD(cost=cost,\n",
" parameters=parameters,\n",
" update_equation=optimizer)\n"
],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n"
]
}
],
"execution_count": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"### 读取数据且打印训练的中间信息\n",
"\n",
"PaddlePaddle提供一个\n",
"[reader机制](https://github.com/PaddlePaddle/Paddle/tree/develop/doc/design/reader)\n",
"来读取数据。 Reader返回的数据可以包括多列,我们需要一个Python dict把列\n",
"序号映射到网络里的数据层。\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"editable": true
},
"source": [
"feeding={'x': 0, 'y': 1}\n"
],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n"
]
}
],
"execution_count": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"此外,我们还可以提供一个 event handler,来打印训练的进度:\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"editable": true
},
"source": [
"# event_handler to print training and testing info\n",
"import matplotlib.pyplot as plt\n",
"from IPython import display\n",
"import cPickle\n",
"\n",
"step=0\n",
"\n",
"train_costs=[],[]\n",
"test_costs=[],[]\n",
"\n",
"def event_handler(event):\n",
" global step\n",
" global train_costs\n",
" global test_costs\n",
" if isinstance(event, paddle.event.EndIteration):\n",
" need_plot = False\n",
" if step % 10 == 0: # every 10 batches, record a train cost\n",
" train_costs[0].append(step)\n",
" train_costs[1].append(event.cost)\n",
"\n",
" if step % 1000 == 0: # every 1000 batches, record a test cost\n",
" result = trainer.test(\n",
" reader=paddle.batch(\n",
" uci_housing.test(), batch_size=2),\n",
" feeding=feeding)\n",
" test_costs[0].append(step)\n",
" test_costs[1].append(result.cost)\n",
"\n",
" if step % 100 == 0: # every 100 batches, update cost plot\n",
" plt.plot(*train_costs)\n",
" plt.plot(*test_costs)\n",
" plt.legend(['Train Cost', 'Test Cost'], loc='upper left')\n",
" display.clear_output(wait=True)\n",
" display.display(plt.gcf())\n",
" plt.gcf().clear()\n",
" step += 1\n"
],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n"
]
}
],
"execution_count": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"### 开始训练\n",
"\n"
]
},
{
"cell_type": "code",
"metadata": {
"editable": true
},
"source": [
"trainer.train(\n",
" reader=paddle.batch(\n",
" paddle.reader.shuffle(\n",
" uci_housing.train(), buf_size=500),\n",
" batch_size=2),\n",
" feeding=feeding,\n",
" event_handler=event_handler,\n",
" num_passes=30)\n"
],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n"
]
}
],
"execution_count": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"![png](./image/train-and-test.png)\n",
"\n",
"## 总结\n",
"在这章里,我们借助波士顿房价这一数据集,介绍了线性回归模型的基本概念,以及如何使用PaddlePaddle实现训练和测试的过程。很多的模型和技巧都是从简单的线性回归模型演化而来,因此弄清楚线性模型的原理和局限非常重要。\n",
"\n",
"\n",
"## 参考文献\n",
"1. https://en.wikipedia.org/wiki/Linear_regression\n",
"2. Friedman J, Hastie T, Tibshirani R. The elements of statistical learning[M]. Springer, Berlin: Springer series in statistics, 2001.\n",
"3. Murphy K P. Machine learning: a probabilistic perspective[M]. MIT press, 2012.\n",
"4. Bishop C M. Pattern recognition[J]. Machine Learning, 2006, 128.\n",
"\n",
"\u003cbr/\u003e\n",
"\u003ca rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"\u003e\u003cimg alt=\"知识共享许可协议\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png\" /\u003e\u003c/a\u003e\u003cbr /\u003e\u003cspan xmlns:dct=\"http://purl.org/dc/terms/\" href=\"http://purl.org/dc/dcmitype/Text\" property=\"dct:title\" rel=\"dct:type\"\u003e本教程\u003c/span\u003e 由 \u003ca xmlns:cc=\"http://creativecommons.org/ns#\" href=\"http://book.paddlepaddle.org\" property=\"cc:attributionName\" rel=\"cc:attributionURL\"\u003ePaddlePaddle\u003c/a\u003e 创作,采用 \u003ca rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"\u003e知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议\u003c/a\u003e进行许可。\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.0"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
......@@ -159,40 +159,30 @@ feeding={'x': 0, 'y': 1}
```python
# event_handler to print training and testing info
import matplotlib.pyplot as plt
from IPython import display
import cPickle
from paddle.v2.plot import Ploter
step=0
train_title = "Train cost"
test_title = "Test cost"
cost_ploter = Ploter(train_title, test_title)
train_costs=[],[]
test_costs=[],[]
step = 0
def event_handler(event):
global step
global train_costs
global test_costs
if isinstance(event, paddle.event.EndIteration):
need_plot = False
if step % 10 == 0: # every 10 batches, record a train cost
train_costs[0].append(step)
train_costs[1].append(event.cost)
cost_ploter.append(train_title, step, event.cost)
if step % 1000 == 0: # every 1000 batches, record a test cost
if step % 100 == 0: # every 100 batches, record a test cost
result = trainer.test(
reader=paddle.batch(
uci_housing.test(), batch_size=2),
feeding=feeding)
test_costs[0].append(step)
test_costs[1].append(result.cost)
cost_ploter.append(test_title, step, result.cost)
if step % 100 == 0: # every 100 batches, update cost plot
plt.plot(*train_costs)
plt.plot(*test_costs)
plt.legend(['Train Cost', 'Test Cost'], loc='upper left')
display.clear_output(wait=True)
display.display(plt.gcf())
plt.gcf().clear()
cost_ploter.plot()
step += 1
```
......@@ -209,7 +199,7 @@ trainer.train(
num_passes=30)
```
![png](./image/train-and-test.png)
![png](./image/train_and_test.png)
## 总结
在这章里,我们借助波士顿房价这一数据集,介绍了线性回归模型的基本概念,以及如何使用PaddlePaddle实现训练和测试的过程。很多的模型和技巧都是从简单的线性回归模型演化而来,因此弄清楚线性模型的原理和局限非常重要。
......
......@@ -205,40 +205,31 @@ feeding={'x': 0, 'y': 1}
Moreover, an event handler is provided to print the training progress:
```python
import matplotlib.pyplot as plt
from IPython import display
import cPickle
# event_handler to print training and testing info
from paddle.v2.plot import Ploter
step=0
train_title = "Train cost"
test_title = "Test cost"
plot_cost = Ploter(train_title, test_title)
train_costs=[],[]
test_costs=[],[]
step = 0
def event_handler(event):
global step
global train_costs
global test_costs
if isinstance(event, paddle.event.EndIteration):
need_plot = False
if step % 10 == 0: # every 10 batches, record a train cost
train_costs[0].append(step)
train_costs[1].append(event.cost)
plot_cost.append(train_title, step, event.cost)
if step % 1000 == 0: # every 1000 batches, record a test cost
if step % 100 == 0: # every 100 batches, record a test cost
result = trainer.test(
reader=paddle.batch(
uci_housing.test(), batch_size=2),
feeding=feeding)
test_costs[0].append(step)
test_costs[1].append(result.cost)
plot_cost.append(test_title, step, result.cost)
if step % 100 == 0: # every 100 batches, update cost plot
plt.plot(*train_costs)
plt.plot(*test_costs)
plt.legend(['Train Cost', 'Test Cost'], loc='upper left')
display.clear_output(wait=True)
display.display(plt.gcf())
plt.gcf().clear()
plot_cost.plot()
step += 1
```
......@@ -255,7 +246,7 @@ trainer.train(
num_passes=30)
```
![png](./image/train-and-test.png)
![png](./image/train_and_test.png)
## Summary
This chapter introduces *Linear Regression* and how to train and test this model with PaddlePaddle, using the UCI Housing Data Set. Because a large number of more complex models and techniques are derived from linear regression, it is important to understand its underlying theory and limitation.
......
......@@ -201,40 +201,30 @@ feeding={'x': 0, 'y': 1}
```python
# event_handler to print training and testing info
import matplotlib.pyplot as plt
from IPython import display
import cPickle
from paddle.v2.plot import Ploter
step=0
train_title = "Train cost"
test_title = "Test cost"
cost_ploter = Ploter(train_title, test_title)
train_costs=[],[]
test_costs=[],[]
step = 0
def event_handler(event):
global step
global train_costs
global test_costs
if isinstance(event, paddle.event.EndIteration):
need_plot = False
if step % 10 == 0: # every 10 batches, record a train cost
train_costs[0].append(step)
train_costs[1].append(event.cost)
cost_ploter.append(train_title, step, event.cost)
if step % 1000 == 0: # every 1000 batches, record a test cost
if step % 100 == 0: # every 100 batches, record a test cost
result = trainer.test(
reader=paddle.batch(
uci_housing.test(), batch_size=2),
feeding=feeding)
test_costs[0].append(step)
test_costs[1].append(result.cost)
cost_ploter.append(test_title, step, result.cost)
if step % 100 == 0: # every 100 batches, update cost plot
plt.plot(*train_costs)
plt.plot(*test_costs)
plt.legend(['Train Cost', 'Test Cost'], loc='upper left')
display.clear_output(wait=True)
display.display(plt.gcf())
plt.gcf().clear()
cost_ploter.plot()
step += 1
```
......@@ -251,7 +241,7 @@ trainer.train(
num_passes=30)
```
![png](./image/train-and-test.png)
![png](./image/train_and_test.png)
## 总结
在这章里,我们借助波士顿房价这一数据集,介绍了线性回归模型的基本概念,以及如何使用PaddlePaddle实现训练和测试的过程。很多的模型和技巧都是从简单的线性回归模型演化而来,因此弄清楚线性模型的原理和局限非常重要。
......
......@@ -231,6 +231,35 @@ Here `shuffle` is a reader decorator, which takes a reader A as its parameter, a
`batch` is a special decorator, whose input is a reader and output is a *batch reader*, which doesn't yield an instance at a time, but a minibatch.
`event_handler_plot` is used to plot a figure like below:
![png](./image/train_and_test.png)
```python
from paddle.v2.plot import Ploter
train_title = "Train cost"
test_title = "Test cost"
cost_ploter = Ploter(train_title, test_title)
step = 0
# event_handler to plot a figure
def event_handler_plot(event):
global step
if isinstance(event, paddle.event.EndIteration):
if step % 100 == 0:
cost_ploter.append(train_title, step, event.cost)
cost_ploter.plot()
step += 1
if isinstance(event, paddle.event.EndPass):
result = trainer.test(reader=paddle.batch(
paddle.dataset.mnist.test(), batch_size=128))
cost_ploter.append(test_title, step, result.cost)
```
`event_handler` is used to plot some text data when training.
```python
lists = []
......@@ -246,13 +275,15 @@ def event_handler(event):
event.pass_id, result.cost, result.metrics)
lists.append((event.pass_id, result.cost,
result.metrics['classification_error_evaluator']))
```
```python
trainer.train(
reader=paddle.batch(
paddle.reader.shuffle(
paddle.dataset.mnist.train(), buf_size=8192),
batch_size=128),
event_handler=event_handler,
event_handler=event_handler_plot,
num_passes=100)
```
......
......@@ -236,6 +236,34 @@ trainer = paddle.trainer.SGD(cost=cost,
`batch`是一个特殊的decorator,它的输入是一个reader,输出是一个batched reader —— 在PaddlePaddle里,一个reader每次yield一条训练数据,而一个batched reader每次yield一个minbatch。
`event_handler_plot`可以用来在训练过程中画图如下:
![png](./image/train_and_test.png)
```python
from paddle.v2.plot import Ploter
train_title = "Train cost"
test_title = "Test cost"
cost_ploter = Ploter(train_title, test_title)
step = 0
# event_handler to plot a figure
def event_handler_plot(event):
global step
if isinstance(event, paddle.event.EndIteration):
if step % 100 == 0:
cost_ploter.append(train_title, step, event.cost)
cost_ploter.plot()
step += 1
if isinstance(event, paddle.event.EndPass):
result = trainer.test(reader=paddle.batch(
paddle.dataset.mnist.test(), batch_size=128))
cost_ploter.append(test_title, step, result.cost)
```
`event_handler` 用来在训练过程中输出训练结果
```python
lists = []
......@@ -251,13 +279,15 @@ def event_handler(event):
event.pass_id, result.cost, result.metrics)
lists.append((event.pass_id, result.cost,
result.metrics['classification_error_evaluator']))
```
```python
trainer.train(
reader=paddle.batch(
paddle.reader.shuffle(
paddle.dataset.mnist.train(), buf_size=8192),
batch_size=128),
event_handler=event_handler,
event_handler=event_handler_plot,
num_passes=100)
```
......
......@@ -273,6 +273,35 @@ Here `shuffle` is a reader decorator, which takes a reader A as its parameter, a
`batch` is a special decorator, whose input is a reader and output is a *batch reader*, which doesn't yield an instance at a time, but a minibatch.
`event_handler_plot` is used to plot a figure like below:
![png](./image/train_and_test.png)
```python
from paddle.v2.plot import Ploter
train_title = "Train cost"
test_title = "Test cost"
cost_ploter = Ploter(train_title, test_title)
step = 0
# event_handler to plot a figure
def event_handler_plot(event):
global step
if isinstance(event, paddle.event.EndIteration):
if step % 100 == 0:
cost_ploter.append(train_title, step, event.cost)
cost_ploter.plot()
step += 1
if isinstance(event, paddle.event.EndPass):
result = trainer.test(reader=paddle.batch(
paddle.dataset.mnist.test(), batch_size=128))
cost_ploter.append(test_title, step, result.cost)
```
`event_handler` is used to plot some text data when training.
```python
lists = []
......@@ -288,13 +317,15 @@ def event_handler(event):
event.pass_id, result.cost, result.metrics)
lists.append((event.pass_id, result.cost,
result.metrics['classification_error_evaluator']))
```
```python
trainer.train(
reader=paddle.batch(
paddle.reader.shuffle(
paddle.dataset.mnist.train(), buf_size=8192),
batch_size=128),
event_handler=event_handler,
event_handler=event_handler_plot,
num_passes=100)
```
......
......@@ -278,6 +278,34 @@ trainer = paddle.trainer.SGD(cost=cost,
`batch`是一个特殊的decorator,它的输入是一个reader,输出是一个batched reader —— 在PaddlePaddle里,一个reader每次yield一条训练数据,而一个batched reader每次yield一个minbatch。
`event_handler_plot`可以用来在训练过程中画图如下:
![png](./image/train_and_test.png)
```python
from paddle.v2.plot import Ploter
train_title = "Train cost"
test_title = "Test cost"
cost_ploter = Ploter(train_title, test_title)
step = 0
# event_handler to plot a figure
def event_handler_plot(event):
global step
if isinstance(event, paddle.event.EndIteration):
if step % 100 == 0:
cost_ploter.append(train_title, step, event.cost)
cost_ploter.plot()
step += 1
if isinstance(event, paddle.event.EndPass):
result = trainer.test(reader=paddle.batch(
paddle.dataset.mnist.test(), batch_size=128))
cost_ploter.append(test_title, step, result.cost)
```
`event_handler` 用来在训练过程中输出训练结果
```python
lists = []
......@@ -293,13 +321,15 @@ def event_handler(event):
event.pass_id, result.cost, result.metrics)
lists.append((event.pass_id, result.cost,
result.metrics['classification_error_evaluator']))
```
```python
trainer.train(
reader=paddle.batch(
paddle.reader.shuffle(
paddle.dataset.mnist.train(), buf_size=8192),
batch_size=128),
event_handler=event_handler,
event_handler=event_handler_plot,
num_passes=100)
```
......
......@@ -397,6 +397,34 @@ feeding={'image': 0,
Callback function `event_handler` will be called during training when a pre-defined event happens.
`event_handler_plot`is used to plot a figure like below:
![png](./image/train_and_test.png)
```python
from paddle.v2.plot import Ploter
train_title = "Train cost"
test_title = "Test cost"
cost_ploter = Ploter(train_title, test_title)
step = 0
def event_handler_plot(event):
global step
if isinstance(event, paddle.event.EndIteration):
if step % 1 == 0:
cost_ploter.append(train_title, step, event.cost)
cost_ploter.plot()
step += 1
if isinstance(event, paddle.event.EndPass):
result = trainer.test(
reader=paddle.batch(
paddle.dataset.cifar.test10(), batch_size=128),
feeding=feeding)
cost_ploter.append(test_title, step, result.cost)
```
`event_handler` is used to plot some text data when training.
```python
# event handler to track training and testing process
......@@ -422,7 +450,7 @@ Finally, we can invoke `trainer.train` to start training:
trainer.train(
reader=reader,
num_passes=200,
event_handler=event_handler,
event_handler=event_handler_plot,
feeding=feeding)
```
......
......@@ -389,6 +389,35 @@ feeding={'image': 0,
可以使用`event_handler`回调函数来观察训练过程,或进行测试等, 该回调函数是`trainer.train`函数里设定。
`event_handler_plot`可以用来利用回调数据来打点画图:
![png](./image/train_and_test.png)
```python
from paddle.v2.plot import Ploter
train_title = "Train cost"
test_title = "Test cost"
cost_ploter = Ploter(train_title, test_title)
step = 0
def event_handler_plot(event):
global step
if isinstance(event, paddle.event.EndIteration):
if step % 1 == 0:
cost_ploter.append(train_title, step, event.cost)
cost_ploter.plot()
step += 1
if isinstance(event, paddle.event.EndPass):
result = trainer.test(
reader=paddle.batch(
paddle.dataset.cifar.test10(), batch_size=128),
feeding=feeding)
cost_ploter.append(test_title, step, result.cost)
```
`event_handler` 用来在训练过程中输出文本日志
```python
# End batch and end pass event handler
def event_handler(event):
......@@ -413,7 +442,7 @@ def event_handler(event):
trainer.train(
reader=reader,
num_passes=200,
event_handler=event_handler,
event_handler=event_handler_plot,
feeding=feeding)
```
......
......@@ -439,6 +439,34 @@ feeding={'image': 0,
Callback function `event_handler` will be called during training when a pre-defined event happens.
`event_handler_plot`is used to plot a figure like below:
![png](./image/train_and_test.png)
```python
from paddle.v2.plot import Ploter
train_title = "Train cost"
test_title = "Test cost"
cost_ploter = Ploter(train_title, test_title)
step = 0
def event_handler_plot(event):
global step
if isinstance(event, paddle.event.EndIteration):
if step % 1 == 0:
cost_ploter.append(train_title, step, event.cost)
cost_ploter.plot()
step += 1
if isinstance(event, paddle.event.EndPass):
result = trainer.test(
reader=paddle.batch(
paddle.dataset.cifar.test10(), batch_size=128),
feeding=feeding)
cost_ploter.append(test_title, step, result.cost)
```
`event_handler` is used to plot some text data when training.
```python
# event handler to track training and testing process
......@@ -464,7 +492,7 @@ Finally, we can invoke `trainer.train` to start training:
trainer.train(
reader=reader,
num_passes=200,
event_handler=event_handler,
event_handler=event_handler_plot,
feeding=feeding)
```
......
......@@ -431,6 +431,35 @@ feeding={'image': 0,
可以使用`event_handler`回调函数来观察训练过程,或进行测试等, 该回调函数是`trainer.train`函数里设定。
`event_handler_plot`可以用来利用回调数据来打点画图:
![png](./image/train_and_test.png)
```python
from paddle.v2.plot import Ploter
train_title = "Train cost"
test_title = "Test cost"
cost_ploter = Ploter(train_title, test_title)
step = 0
def event_handler_plot(event):
global step
if isinstance(event, paddle.event.EndIteration):
if step % 1 == 0:
cost_ploter.append(train_title, step, event.cost)
cost_ploter.plot()
step += 1
if isinstance(event, paddle.event.EndPass):
result = trainer.test(
reader=paddle.batch(
paddle.dataset.cifar.test10(), batch_size=128),
feeding=feeding)
cost_ploter.append(test_title, step, result.cost)
```
`event_handler` 用来在训练过程中输出文本日志
```python
# End batch and end pass event handler
def event_handler(event):
......@@ -455,7 +484,7 @@ def event_handler(event):
trainer.train(
reader=reader,
num_passes=200,
event_handler=event_handler,
event_handler=event_handler_plot,
feeding=feeding)
```
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册