济南 制作网站 公司,网页设计师证书含金量高吗,注册公司如何提供注册地址,推广平台有哪些渠道目录 一、Azure环境准备二、计算目标设置三、试验设置四、直观呈现输入数据五、上传数据并创建 MLTable六、配置物体检测试验适用于图像任务的自动超参数扫描 (AutoMode)适用于图像任务的手动超参数扫描作业限制 七、注册和部署模型获取最佳试用版注册模型配置联机终结点创建终… 目录 一、Azure环境准备二、计算目标设置三、试验设置四、直观呈现输入数据五、上传数据并创建 MLTable六、配置物体检测试验适用于图像任务的自动超参数扫描 (AutoMode)适用于图像任务的手动超参数扫描作业限制 七、注册和部署模型获取最佳试用版注册模型配置联机终结点创建终结点配置联机部署创建部署更新流量 八、测试部署九、直观呈现检测结果十、清理资源 本教程介绍如何通过 Azure 机器学习 Python SDK v2 使用 Azure 机器学习自动化 ML 训练物体检测模型。 此物体检测模型可识别图像是否包含对象如罐、纸箱、奶瓶或水瓶。 关注TechLead分享AI全维度知识。作者拥有10年互联网服务架构、AI产品研发经验、团队管理经验同济本复旦硕复旦机器人智能实验室成员阿里云认证的资深架构师项目管理专业人士上亿营收AI产品研发负责人。 一、Azure环境准备 若要使用 Azure 机器学习你首先需要一个工作区。 如果没有工作区请完成创建开始使用所需的资源以创建工作区并详细了解如何使用它。 此功能支持 Python 3.6 或 3.7 下载并解压缩 odFridgeObjects.zip 数据文件*。 数据集以 Pascal VOC 格式进行注释其中每个图像对应一个 xml 文件。 每个 xml 文件都包含有关其对应图像文件所在位置的信息还包含有关边界框和对象标签的信息。 若要使用此数据首先需要将其转换为所需的 JSONL 格式如笔记本的将下载的数据转换为 JSONL 部分中所示。 使用计算实例来学习本教程无需安装其他软件。 请参阅如何创建计算实例。或者安装 CLI/SDK 以使用你自己的本地环境。 适用于Python SDK azure-ai-ml v2当前版本 使用以下命令安装 Azure 机器学习 Python SDK v2
卸载以前的预览版
pip uninstall azure-ai-ml安装 Azure 机器学习 Python SDK v2
pip install azure-ai-ml azure-identity二、计算目标设置
首先需要设置用于自动化 ML 模型训练的计算目标。 用于图像任务的自动化 ML 模型需要 GPU SKU。
本教程将使用 NCsv3 系列具有 V100 GPU因为此类计算目标会使用多个 GPU 来加速训练。 此外还可以设置多个节点以在优化模型的超参数时利用并行度。
以下代码创建一个大小为 Standard_NC24s_v3 的 GPU 计算其中包含四个节点。
from azure.ai.ml.entities import AmlCompute
compute_name gpu-cluster
cluster_basic AmlCompute(namecompute_name,typeamlcompute,sizeStandard_NC24s_v3,min_instances0,max_instances4,idle_time_before_scale_down120,
)
ml_client.begin_create_or_update(cluster_basic)稍后在创建特定于任务的 automl 作业时会用到此计算。 三、试验设置
可以使用试验来跟踪模型训练作业。
稍后在创建特定于任务的 automl 作业时会用到此试验名称。
exp_name dpv2-image-object-detection-experiment四、直观呈现输入数据
以 JSONLJSON 行格式准备好输入图像数据后就可以直观呈现图像的地面实况边界框。 若要执行此操作请确保你已安装 matplotlib。
%pip install --upgrade matplotlib%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.patches as patches
from PIL import Image as pil_image
import numpy as np
import json
import osdef plot_ground_truth_boxes(image_file, ground_truth_boxes):# Display the imageplt.figure()img_np mpimg.imread(image_file)img pil_image.fromarray(img_np.astype(uint8), RGB)img_w, img_h img.sizefig,ax plt.subplots(figsize(12, 16))ax.imshow(img_np)ax.axis(off)label_to_color_mapping {}for gt in ground_truth_boxes:label gt[label]xmin, ymin, xmax, ymax gt[topX], gt[topY], gt[bottomX], gt[bottomY]topleft_x, topleft_y img_w * xmin, img_h * yminwidth, height img_w * (xmax - xmin), img_h * (ymax - ymin)if label in label_to_color_mapping:color label_to_color_mapping[label]else:# Generate a random color. If you want to use a specific color, you can use something like red.color np.random.rand(3)label_to_color_mapping[label] color# Display bounding boxrect patches.Rectangle((topleft_x, topleft_y), width, height,linewidth2, edgecolorcolor, facecolornone)ax.add_patch(rect)# Display labelax.text(topleft_x, topleft_y - 10, label, colorcolor, fontsize20)plt.show()def plot_ground_truth_boxes_jsonl(image_file, jsonl_file):image_base_name os.path.basename(image_file)ground_truth_data_found Falsewith open(jsonl_file) as fp:for line in fp.readlines():line_json json.loads(line)filename line_json[image_url]if image_base_name in filename:ground_truth_data_found Trueplot_ground_truth_boxes(image_file, line_json[label])breakif not ground_truth_data_found:print(Unable to find ground truth information for image: {}.format(image_file))对于任何给定的图像利用上述帮助程序函数可以运行以下代码来显示边界框。
image_file ./odFridgeObjects/images/31.jpg
jsonl_file ./odFridgeObjects/train_annotations.jsonlplot_ground_truth_boxes_jsonl(image_file, jsonl_file)五、上传数据并创建 MLTable
为了将数据用于训练请将数据上传到 Azure 机器学习工作区的默认 Blob 存储并将其注册为资产。 注册数据的好处包括
便于与团队其他成员共享对元数据位置、描述等进行版本控制世系跟踪
# Uploading image files by creating a data asset URI FOLDER:from azure.ai.ml.entities import Data
from azure.ai.ml.constants import AssetTypes, InputOutputModes
from azure.ai.ml import Inputmy_data Data(pathdataset_dir,typeAssetTypes.URI_FOLDER,descriptionFridge-items images Object detection,namefridge-items-images-object-detection,
)uri_folder_data_asset ml_client.data.create_or_update(my_data)print(uri_folder_data_asset)
print()
print(Path to folder in Blob Storage:)
print(uri_folder_data_asset.path)下一步是使用 jsonl 格式的数据创建 MLTable如下所示。 MLtable 会将数据打包为一个可供训练使用的对象。
paths:- file: ./train_annotations.jsonl
transformations:- read_json_lines:encoding: utf8invalid_lines: errorinclude_path_column: false- convert_column_types:- columns: image_urlcolumn_type: stream_info可以使用以下代码从训练和验证 MLTable 创建数据输入
# Training MLTable defined locally, with local data to be uploaded
my_training_data_input Input(typeAssetTypes.MLTABLE, pathtraining_mltable_path)# Validation MLTable defined locally, with local data to be uploaded
my_validation_data_input Input(typeAssetTypes.MLTABLE, pathvalidation_mltable_path)# WITH REMOTE PATH: If available already in the cloud/workspace-blob-store
# my_training_data_input Input(typeAssetTypes.MLTABLE, pathazureml://datastores/workspaceblobstore/paths/vision-classification/train)
# my_validation_data_input Input(typeAssetTypes.MLTABLE, pathazureml://datastores/workspaceblobstore/paths/vision-classification/valid)六、配置物体检测试验
若要为图像相关任务配置自动化 ML 作业请创建特定于任务的 AutoML 作业。
# Create the AutoML job with the related factory-function.image_object_detection_job automl.image_object_detection(computecompute_name,experiment_nameexp_name,training_datamy_training_data_input,validation_datamy_validation_data_input,target_column_namelabel,primary_metricObjectDetectionPrimaryMetrics.MEAN_AVERAGE_PRECISION,tags{my_custom_tag: My custom value},
)适用于图像任务的自动超参数扫描 (AutoMode)
在 AutoML 作业中可以执行自动超参数扫描以查找最佳模型我们将此功能称为 AutoMode。 你将仅指定试用次数不需要超参数搜索空间、采样方法和提前终止策略。 系统会自动根据试用次数确定要扫描的超参数空间的区域。 介于 10 到 20 之间的值可能适用于许多数据集。
然后你可以提交作业来训练图像模型。
将 AutoML 作业配置为所需的设置后就可以提交作业了。
# Submit the AutoML job
returned_job ml_client.jobs.create_or_update(image_object_detection_job
) # submit the job to the backendprint(fCreated job: {returned_job})适用于图像任务的手动超参数扫描
在 AutoML 作业中可以使用 model_name 参数指定模型体系结构并配置设置以对定义的搜索空间执行超参数扫描以查找最佳模型。
在本示例中我们将使用 yolov5 和 fasterrcnn_resnet50_fpn 训练一个物体检测模型这两者都在 COCO 上预先进行了训练COCO 是一个大规模物体检测、分段和字幕数据集其中包含 80 多个标签类别的数千个带标签的图像。
可以对已定义的搜索空间执行超参数扫描以查找最佳模型。
作业限制
可以通过在限制设置中为作业指定 timeout_minutesmax_trials 和 max_concurrent_trials 来控制 AutoML 映像训练作业上花费的资源。 请参阅有关作业限制参数的详细说明。
# Set limits
image_object_detection_job.set_limits(timeout_minutes60,max_trials10,max_concurrent_trials2,
)以下代码定义了搜索空间准备对每个已定义的体系结构 yolov5 和 fasterrcnn_resnet50_fpn 进行超参数扫描。 在搜索空间中指定 learning_rate、optimizer、lr_scheduler 等的值范围以便 AutoML 在尝试生成具有最佳主要指标的模型时从中进行选择。 如果未指定超参数值则对每个体系结构使用默认值。
对于优化设置通过使用 random sampling_algorithm借助随机抽样从此参数空间中选取样本。 上面配置的作业限制可以让自动化 ML 尝试使用这些不同样本总共进行 10 次试验在使用四个节点进行设置的计算目标上一次运行两次试验。 搜索空间的参数越多查找最佳模型所需的试验次数就越多。
还使用了“Bandit 提前终止”策略。 此策略将终止性能不佳的试用也就是那些与最佳性能试用版相差不在 20% 容许范围内的试用版这样可显著节省计算资源。
# Configure sweep settings
image_object_detection_job.set_sweep(sampling_algorithmrandom,early_terminationBanditPolicy(evaluation_interval2, slack_factor0.2, delay_evaluation6),
)# Define search space
image_object_detection_job.extend_search_space([SearchSpace(model_nameChoice([yolov5]),learning_rateUniform(0.0001, 0.01),model_sizeChoice([small, medium]), # model-specific# image_sizeChoice(640, 704, 768), # model-specific; might need GPU with large memory),SearchSpace(model_nameChoice([fasterrcnn_resnet50_fpn]),learning_rateUniform(0.0001, 0.001),optimizerChoice([sgd, adam, adamw]),min_sizeChoice([600, 800]), # model-specific# warmup_cosine_lr_warmup_epochsChoice([0, 3]),),]
)定义搜索空间和扫描设置后便可以提交作业以使用训练数据集训练图像模型。
将 AutoML 作业配置为所需的设置后就可以提交作业了。
# Submit the AutoML job
returned_job ml_client.jobs.create_or_update(image_object_detection_job
) # submit the job to the backendprint(fCreated job: {returned_job})执行超参数扫描时使用 HyperDrive UI 直观呈现所尝试的不同试用版会很有用。 可以导航到此 UI方法是从上级即 HyperDrive 父作业转到主 automl_image_job 的 UI 中的“子作业”选项卡。 然后可以转到此项的“子作业”选项卡。
也可在下面直接查看 HyperDrive 父作业然后导航到其“子作业”选项卡 七、注册和部署模型
作业完成后可以注册从最佳试用产生了最佳主要指标的配置创建的模型。 可在下载后注册模型也可通过指定具有相应 jobid 的 azureml 路径进行注册。
获取最佳试用版
# Get the best models child runbest_child_run_id mlflow_parent_run.data.tags[automl_best_child_run_id]
print(fFound best child run id: {best_child_run_id})best_run mlflow_client.get_run(best_child_run_id)print(Best child run: )
print(best_run)# Create local folder
local_dir ./artifact_downloads
if not os.path.exists(local_dir):os.mkdir(local_dir)# Download runs artifacts/outputs
local_path mlflow_client.download_artifacts(best_run.info.run_id, outputs, local_dir
)
print(fArtifacts downloaded in: {local_path})
print(fArtifacts: {os.listdir(local_path)})注册模型
使用 azureml 路径或本地下载的路径注册模型。
model_name od-fridge-items-mlflow-model
model Model(pathfazureml://jobs/{best_run.info.run_id}/outputs/artifacts/outputs/mlflow-model/,namemodel_name,descriptionmy sample object detection model,typeAssetTypes.MLFLOW_MODEL,
)# for downloaded file
# model Model(
# pathmlflow_model_dir,
# namemodel_name,
# descriptionmy sample object detection model,
# typeAssetTypes.MLFLOW_MODEL,
# )registered_model ml_client.models.create_or_update(model)注册要使用的模型后可以使用托管联机终结点 deploy-managed-online-endpoint 进行部署
配置联机终结点
# Creating a unique endpoint name with current datetime to avoid conflicts
import datetimeonline_endpoint_name od-fridge-items- datetime.datetime.now().strftime(%m%d%H%M%f
)# create an online endpoint
endpoint ManagedOnlineEndpoint(nameonline_endpoint_name,descriptionthis is a sample online endpoint for deploying model,auth_modekey,tags{foo: bar},
)
print(online_endpoint_name)创建终结点
使用之前创建的 MLClient我们现在将在工作区中创建终结点。 此命令会启动终结点创建操作并在终结点创建操作继续时返回确认响应。
ml_client.begin_create_or_update(endpoint).result()还可以创建一个批处理终结点用于针对一段时间内的大量数据执行批量推理。 签出用于使用批处理终结点执行批量推理的物体检测批处理评分笔记本。
配置联机部署
部署是一组资源用于承载执行实际推理的模型。 我们将使用 ManagedOnlineDeployment 类为终结点创建一个部署。 可为部署群集使用 GPU 或 CPU VM SKU。
deployment ManagedOnlineDeployment(nameod-fridge-items-mlflow-deploy,endpoint_nameonline_endpoint_name,modelregistered_model.id,instance_typeStandard_DS4_V2,instance_count1,request_settingsreq_timeout,liveness_probeProbeSettings(failure_threshold30,success_threshold1,timeout2,period10,initial_delay2000,),readiness_probeProbeSettings(failure_threshold10,success_threshold1,timeout10,period10,initial_delay2000,),
)创建部署
使用前面创建的 MLClient我们将在工作区中创建部署。 此命令将启动部署创建操作并在部署创建操作继续时返回确认响应。
ml_client.online_deployments.begin_create_or_update(deployment).result()更新流量
默认情况下当前部署设置为接收 0% 的流量。 可以设置当前部署应接收的流量百分比。 使用一个终结点的所有部署接收的流量百分比总和不应超过 100%。
# od fridge items deployment to take 100% traffic
endpoint.traffic {od-fridge-items-mlflow-deploy: 100}
ml_client.begin_create_or_update(endpoint).result()八、测试部署
# Create request json
import base64sample_image os.path.join(dataset_dir, images, 1.jpg)def read_image(image_path):with open(image_path, rb) as f:return f.read()request_json {input_data: {columns: [image],data: [base64.encodebytes(read_image(sample_image)).decode(utf-8)],}
}import jsonrequest_file_name sample_request_data.jsonwith open(request_file_name, w) as request_file:json.dump(request_json, request_file)resp ml_client.online_endpoints.invoke(endpoint_nameonline_endpoint_name,deployment_namedeployment.name,request_filerequest_file_name,
)九、直观呈现检测结果
为测试图像评分后可以直观呈现此图像的边界框。 若要执行此操作请确保已安装 matplotlib。
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.patches as patches
from PIL import Image
import numpy as np
import jsonIMAGE_SIZE (18, 12)
plt.figure(figsizeIMAGE_SIZE)
img_np mpimg.imread(sample_image)
img Image.fromarray(img_np.astype(uint8), RGB)
x, y img.sizefig, ax plt.subplots(1, figsize(15, 15))
# Display the image
ax.imshow(img_np)# draw box and label for each detection
detections json.loads(resp)
for detect in detections[0][boxes]:label detect[label]box detect[box]conf_score detect[score]if conf_score 0.6:ymin, xmin, ymax, xmax (box[topY],box[topX],box[bottomY],box[bottomX],)topleft_x, topleft_y x * xmin, y * yminwidth, height x * (xmax - xmin), y * (ymax - ymin)print(f{detect[label]}: [{round(topleft_x, 3)}, {round(topleft_y, 3)}, f{round(width, 3)}, {round(height, 3)}], {round(conf_score, 3)})color np.random.rand(3) #redrect patches.Rectangle((topleft_x, topleft_y),width,height,linewidth3,edgecolorcolor,facecolornone,)ax.add_patch(rect)plt.text(topleft_x, topleft_y - 10, label, colorcolor, fontsize20)
plt.show()十、清理资源
如果打算运行其他 Azure 机器学习教程请不要完成本部分。
如果不打算使用已创建的资源请删除它们以免产生任何费用。
在 Azure 门户中选择最左侧的“资源组”。从列表中选择已创建的资源组。选择“删除资源组”。输入资源组名称。 然后选择“删除”。
还可保留资源组但请删除单个工作区。 显示工作区属性然后选择“删除”。 关注TechLead分享AI全维度知识。作者拥有10年互联网服务架构、AI产品研发经验、团队管理经验同济本复旦硕复旦机器人智能实验室成员阿里云认证的资深架构师项目管理专业人士上亿营收AI产品研发负责人。
文章转载自: http://www.morning.wqrk.cn.gov.cn.wqrk.cn http://www.morning.ruyuaixuexi.com.gov.cn.ruyuaixuexi.com http://www.morning.rbzht.cn.gov.cn.rbzht.cn http://www.morning.tdmgs.cn.gov.cn.tdmgs.cn http://www.morning.mhmdx.cn.gov.cn.mhmdx.cn http://www.morning.kzdgz.cn.gov.cn.kzdgz.cn http://www.morning.rnxs.cn.gov.cn.rnxs.cn http://www.morning.jxwhr.cn.gov.cn.jxwhr.cn http://www.morning.lzqdl.cn.gov.cn.lzqdl.cn http://www.morning.yfmxn.cn.gov.cn.yfmxn.cn http://www.morning.bqhlp.cn.gov.cn.bqhlp.cn http://www.morning.kfcz.cn.gov.cn.kfcz.cn http://www.morning.spghj.cn.gov.cn.spghj.cn http://www.morning.zzqgc.cn.gov.cn.zzqgc.cn http://www.morning.hrzhg.cn.gov.cn.hrzhg.cn http://www.morning.tmrjb.cn.gov.cn.tmrjb.cn http://www.morning.spftz.cn.gov.cn.spftz.cn http://www.morning.ddtdy.cn.gov.cn.ddtdy.cn http://www.morning.yhpl.cn.gov.cn.yhpl.cn http://www.morning.5-73.com.gov.cn.5-73.com http://www.morning.sbqrm.cn.gov.cn.sbqrm.cn http://www.morning.kgnrh.cn.gov.cn.kgnrh.cn http://www.morning.nwczt.cn.gov.cn.nwczt.cn http://www.morning.nmtyx.cn.gov.cn.nmtyx.cn http://www.morning.tqbqb.cn.gov.cn.tqbqb.cn http://www.morning.cpfx.cn.gov.cn.cpfx.cn http://www.morning.rnnq.cn.gov.cn.rnnq.cn http://www.morning.mjqms.cn.gov.cn.mjqms.cn http://www.morning.cgbgc.cn.gov.cn.cgbgc.cn http://www.morning.sqgsx.cn.gov.cn.sqgsx.cn http://www.morning.tfpbm.cn.gov.cn.tfpbm.cn http://www.morning.uycvv.cn.gov.cn.uycvv.cn http://www.morning.rwzqn.cn.gov.cn.rwzqn.cn http://www.morning.bswnf.cn.gov.cn.bswnf.cn http://www.morning.xnkh.cn.gov.cn.xnkh.cn http://www.morning.qhrdx.cn.gov.cn.qhrdx.cn http://www.morning.ymhzd.cn.gov.cn.ymhzd.cn http://www.morning.hsklc.cn.gov.cn.hsklc.cn http://www.morning.snrhg.cn.gov.cn.snrhg.cn http://www.morning.fxqjz.cn.gov.cn.fxqjz.cn http://www.morning.rdzgm.cn.gov.cn.rdzgm.cn http://www.morning.gccdr.cn.gov.cn.gccdr.cn http://www.morning.hxxzp.cn.gov.cn.hxxzp.cn http://www.morning.yrkdq.cn.gov.cn.yrkdq.cn http://www.morning.rpwm.cn.gov.cn.rpwm.cn http://www.morning.dhrbj.cn.gov.cn.dhrbj.cn http://www.morning.fbjnr.cn.gov.cn.fbjnr.cn http://www.morning.pprxs.cn.gov.cn.pprxs.cn http://www.morning.kjrp.cn.gov.cn.kjrp.cn http://www.morning.xjnjb.cn.gov.cn.xjnjb.cn http://www.morning.lydtr.cn.gov.cn.lydtr.cn http://www.morning.srbl.cn.gov.cn.srbl.cn http://www.morning.tmnyj.cn.gov.cn.tmnyj.cn http://www.morning.ylkkh.cn.gov.cn.ylkkh.cn http://www.morning.xrrjb.cn.gov.cn.xrrjb.cn http://www.morning.tyjp.cn.gov.cn.tyjp.cn http://www.morning.pndw.cn.gov.cn.pndw.cn http://www.morning.wzknt.cn.gov.cn.wzknt.cn http://www.morning.pshpx.cn.gov.cn.pshpx.cn http://www.morning.qfcnp.cn.gov.cn.qfcnp.cn http://www.morning.mgkcz.cn.gov.cn.mgkcz.cn http://www.morning.sgnxl.cn.gov.cn.sgnxl.cn http://www.morning.wdprz.cn.gov.cn.wdprz.cn http://www.morning.kdbbm.cn.gov.cn.kdbbm.cn http://www.morning.qyjqj.cn.gov.cn.qyjqj.cn http://www.morning.rwcw.cn.gov.cn.rwcw.cn http://www.morning.rgnp.cn.gov.cn.rgnp.cn http://www.morning.thmlt.cn.gov.cn.thmlt.cn http://www.morning.wcrcy.cn.gov.cn.wcrcy.cn http://www.morning.lhyhx.cn.gov.cn.lhyhx.cn http://www.morning.yltnl.cn.gov.cn.yltnl.cn http://www.morning.nwcgj.cn.gov.cn.nwcgj.cn http://www.morning.c7624.cn.gov.cn.c7624.cn http://www.morning.yldgw.cn.gov.cn.yldgw.cn http://www.morning.mnbcj.cn.gov.cn.mnbcj.cn http://www.morning.ghgck.cn.gov.cn.ghgck.cn http://www.morning.yrjym.cn.gov.cn.yrjym.cn http://www.morning.sjwws.cn.gov.cn.sjwws.cn http://www.morning.qmsbr.cn.gov.cn.qmsbr.cn http://www.morning.pyxwn.cn.gov.cn.pyxwn.cn