相关文章
【一】-环境配置+python入门教学
【二】-Parl基础命令
【三】-Notebook、&pdb、ipdb 调试
【四】-强化学习入门简介
【五】-Sarsa&Qlearing详细讲解
【六】-DQN
【七】-Policy Gradient
【八】-DDPG
【九】-四轴飞行器仿真
飞桨PARL_2.0&1.8.5(遇到bug调试修正)
一、AI Studio 项目详解【VisualDL工具】
二、AI Studio 项目详解【环境使用说明、脚本任务】
三、AI Studio 项目详解【分布式训练-单机多机】
四、AI Studio 项目详解【图形化任务】
五、AI Studio 项目详解【在线部署及预测】
在线部署与预测为开发者提供训练模型向应用化API转换的功能. 开发者在AI Studio平台通过NoteBook项目完成模型训练后, 在Notebook详情页通过创建一个在线服务, 应用模型生成在线API, 使用该API可以直接检验模型效果或实际应用到开发者的私有项目中.目前, 该功能暂时仅对Notebook项目开放。
import paddle
import paddle.fluid as fluid
import numpy
import math
import sys
from __future__ import print_function
BATCH_SIZE = 20
train_reader = paddle.batch(
paddle.reader.shuffle(
paddle.dataset.uci_housing.train(), buf_size=500),
batch_size=BATCH_SIZE)
test_reader = paddle.batch(
paddle.reader.shuffle(
paddle.dataset.uci_housing.test(), buf_size=500),
batch_size=BATCH_SIZE)
params_dirname = "model2"
x = fluid.layers.data(name='x', shape=[13], dtype='float32')
y = fluid.layers.data(name='y', shape=[1], dtype='float32')
y_predict = fluid.layers.fc(input=x, size=1, act=None)
main_program = fluid.default_main_program()
startup_program = fluid.default_startup_program()
cost = fluid.layers.square_error_cost(input=y_predict, label=y)
avg_loss = fluid.layers.mean(cost)
sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.001)
sgd_optimizer.minimize(avg_loss)
#clone a test_program
test_program = main_program.clone(for_test=True)
use_cuda = False
place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
exe = fluid.Executor(place)
num_epochs = 100
# For training test cost
def train_test(executor, program, reader, feeder, fetch_list):
accumulated = 1 * [0]
count = 0
for data_test in reader():
outs = executor.run(program=program,
feed=feeder.feed(data_test),
fetch_list=fetch_list)
accumulated = [x_c[0] + x_c[1][0] for x_c in zip(accumulated, outs)]
count += 1
return [x_d / count for x_d in accumulated]
params_dirname = "fit_a_line.inference.model"
feeder = fluid.DataFeeder(place=place, feed_list=[x, y])
naive_exe = fluid.Executor(place)
naive_exe.run(startup_program)
step = 0
exe_test = fluid.Executor(place)
# main train loop.
for pass_id in range(num_epochs):
for data_train in train_reader():
avg_loss_value, = exe.run(main_program,
feed=feeder.feed(data_train),
fetch_list=[avg_loss])
if step % 10 == 0: # record a train cost every 10 batches
print (step, avg_loss_value[0])
if step % 100 == 0: # record a test cost every 100 batches
test_metics = train_test(executor=exe_test,
program=test_program,
reader=test_reader,
fetch_list=[avg_loss.name],
feeder=feeder)
print (step, test_metics[0])
# If the accuracy is good enough, we can stop the training.
if test_metics[0] < 10.0:
break
step += 1
if math.isnan(float(avg_loss_value[0])):
sys.exit("got NaN loss, training failed.")
if params_dirname is not None:
# We can save the trained parameters for the inferences later
fluid.io.save_inference_model(params_dirname, ['x'],
[y_predict], exe)
!wget
在Notebook中传输模型文件到环境目录。以房价预测的线性回归模型为例, 通过!wget https://ai.baidu.com/file/4E1D1FCC670E4A5E8441634201658107 -O fit_a_line.inference.model
传输文件, 解压后直接被在线服务使用.在进行解压unzip
创建一个在线服务
完成模型训练后, 在Notebook项目页面点击【创建预测服务】
第一步 选择模型文件
- 勾选模型文件
- 设置主程序, 主程序为
paddle.fluid.io.save_inference_model
中参数main_program
配置的程序, 在房价预测的示例中,我们使用默认参数调用save_inference_model
, 因此将__model__
文件设置为主程序.第二步 确认输入输出
填写模型的输入输出参数. 以房价预测的线性回归模型为例(参数参考), 添加参数如下图所示.
第三步 制作参数转换器
参数转换器帮助用户转化合法输入并完成数据预处理.
- 方式一:自定义转换器(Python2.7)(推荐).
输入参数转换器方法
def reader_infer(data_args): """ reader_infer 输入参数转换器方法 :param data_args: 接口传入的数据,以k-v形式 :return [[]], feeder """ #构造内容 pass
输出参数转换器方法
def output(results, data_args): """ output 输出参数转换器方法 :param results 模型预测结果 :param data_args: 接口传入的数据,以k-v形式 :return array 需要能被json_encode的数据格式 """ #构造内容 pass
转换器代码示例, 以房价预测为例.
输入参数转换器:
import os import sys sys.path.append("..") from PIL import Image import numpy as np import paddle.fluid as fluid from home.utility import base64_to_image def reader_infer(data_args): """ reader_infer 输入参数转换器方法 :param data_args: 接口传入的数据,以k-v形式 :return [[]], feeder """ def reader(): """ reader :return: """ x = fluid.layers.data(name='x', shape=[13], dtype='float32') # y = fluid.layers.data(name='y', shape=[1], dtype='float32') feeder = fluid.DataFeeder(place=fluid.CPUPlace(), feed_list=[x]) CRIM = float(data_args["CRIM"]) ZN = float(data_args["ZN"]) INDUS = float(data_args["INDUS"]) CHAS = float(data_args["CHAS"]) NOX = float(data_args["NOX"]) RM = float(data_args["RM"]) AGE = float(data_args["AGE"]) DIS = float(data_args["DIS"]) RAD = float(data_args["RAD"]) TAX = float(data_args["TAX"]) PTRATIO = float(data_args["PTRATIO"]) B = float(data_args["B"]) LSTAT = float(data_args["LSTAT"]) return [[[CRIM, ZN, INDUS, CHAS, NOX, RM, AGE, DIS, RAD, TAX, PTRATIO, B, LSTAT]]], feeder return reader
输出参数转换器:
def output(results, data_args): """ output 输出参数转换器方法 :param results 模型预测结果 :param data_args: 接口传入的数据,以k-v形式 :return array 需要能被json_encode的数据格式 """ lines = [] for dt in results: y = dt.tolist() lines.append({"predict": y}) return lines
方式二: 默认参数, 不设置转换器.
用户的API参数直接传递给模型.
用户可以同时部署至多五个沙盒服务, 用来对比模型优化结果.
录入名称点击【生成沙盒】或者点击【暂存】将沙盒保存到草稿箱.
对沙盒列表中的沙盒服务进行测试,验证是否配置正确。
点击【正式部署】部署线上API.
依据API key、服务地址和用户自定义参数, 实现对服务的调用.
以房价预测项目为例.
curl -H "Content-Type: application/json" -X POST -d '{"CRIM":0.01887747, "ZN":-0.11363636, "INDUS":0.25525005, "CHAS":-0.06916996, "NOX":0.29898136, "RM": -0.04476612, "AGE": 0.14340987, "DIS":-0.14797285, "RAD":0.62828665, "TAX":0.49191383, "PTRATIO":0.18558153, "B":0.05473289, "LSTAT":0.16851371}' "https://aistudio.baidu.com/serving/online/xxx?apiKey=xxxxxxxxxx"
import json
import traceback
import urllib
import urllib2
formdata = {
"CRIM":0.01887747,
"ZN":-0.11363636,
"INDUS":0.25525005,
"CHAS":-0.06916996,
"NOX":0.29898136,
"RM": -0.04476612,
"AGE": 0.14340987,
"DIS":-0.14797285,
"RAD":0.62828665,
"TAX":0.49191383,
"PTRATIO":0.18558153,
"B":0.05473289,
"LSTAT":0.16851371
}
header = {"Content-Type": "application/json; charset=utf-8"}
url = "https://aistudio.baidu.com/serving/online/xxx?apiKey=a280cf48-6d0c-4baf-bd39xxxxxxcxxxxx"
data = json.dumps(formdata)
try:
request = urllib2.Request(url, data, header)
response = urllib2.urlopen(request)
response_str = response.read()
response.close()
print(response_str)
except urllib2.HTTPError as e:
print("The server couldn't fulfill the request")
print(e.code)
print(e.read())
except urllib2.URLError as e:
print("Failed to reach the server")
print(e.reason)
except:
traceback.print_exc()