看图片识车型,自己写个这样的程序其实一点也不难:
不认识车标,辨不清车型,有时候还真挺难的。
其实在基于深度学习的图像分类领域,情况也是这样。写一个能认识汽车的程序,这没啥技术难度。可要想从众多汽车的照片中找出具体的品牌型号,这就有点棘手了。
车辆检测及型号识别,这种技术就被广泛应用于物业、交通管理等场景。通过在停车场出入口、路口、高速卡口等位置采集图片数据,对车辆的数量、型号等进行识别,可以以较高效率对车型、数量信息等进行采集。随后通过采集的数据就可以在不同场景中辅助业务开展,如商场停车位的规划、路况规划或者公安系统追踪肇事车辆等。
迁移学习不是一种算法,而是一种机器学习思想,应用到深度学习就是微调(Fine-tune)。通过修改预训练网络模型结构(如修改样本类别输出个数),选择性载入预训练网络模型权重,再用自己的数据集重新训练模型就是微调的基本步骤。微调能够快速训练好一个模型,用相对较小的数据量,还能达到不错的结果。
本解决方案使用AmazonSageMaker,它可以帮助开发人员和数据科学家构建、训练和部署ML模型。AmazonSageMaker是一项完全托管的服务,涵盖了ML的整个工作流,可以标记和准备数据、选择算法、训练模型、调整和优化模型以便部署、预测和执行操作。同时,本方案基于MXNet,ApacheMXNet(孵化)是一个深度学习框架,旨在提高效率和灵活性。它可供我们混合符号和命令式编程,以最大限度地提高效率和生产力。
下文会重点介绍在AmazonSageMaker中如何基于MXNet,使用自己的数据来微调一个预训练的图像分类模型并且达到较高的准确率来构建一个车型号分类器。
在此示例中,我们将使用AmazonSageMaker执行以下操作:
%%timeimportboto3importrefromsagemakerimportget_execution_rolefromsagemaker.amazon.amazon_estimatorimportget_image_urirole=get_execution_role()bucket='app-cars-classfication'#customizetoyourbuckettraining_image=get_image_uri(boto3.Session().region_name,'image-classification')2.数据预处理本文使用了斯坦福大学提供的开源数据集Carsdataset,该数据集包含了196种不同汽车品牌车型的16185张图片。其中我们将使用8144张作为训练集,8041张作为测试集,每个车型号在训练和测试集中分布均衡。您可以访问该数据集主页查看完整的数据说明和进行下载,示例图片如下:
为提高IO效率,不会直接读取图片文件,而是先将图片列表和标签转换为RecordIO格式的二进制文件,训练时就可以顺序读取数据,大大提高了IO速率。MXNet社区提供了一个很好的图片转换工具im2rec.py,可进行快速图像转换。主要利用的是MXNetim2rec.py工具生成List和Record文件,并按照Validation的数据和Training数据的比例进行自动的数据拆分。具体命令如下图,首先生成标签为汽车种类个数的List文件之后,按照多个并发线程的方式进行Record格式转换,并存在定义的目录内。具体转换的Shell脚本内容如下。需要注意的是,这里的data_path为此Shell脚本的入参,需要自己指定为自己存放数据集的本地路径:
importosimportboto3defupload_to_s3(file):s3=boto3.resource('s3')data=open(file,"rb")key=files3.Bucket(bucket).put_object(Key=key,Body=data)#caltech-256s3_train_key="car_data_sample/train"s3_validation_key="car_data_sample/validation"s3_train='s3://{}/{}/'.format(bucket,s3_train_key)s3_validation='s3://{}/{}/'.format(bucket,s3_validation_key)upload_to_s3('car_data_sample/train/data_train.rec')upload_to_s3('car_data_sample/validation/data_val.rec')3.使用迁移学习进行模型训练数据集准备结束之后,就可以开始模型的训练了。但在开始训练任务之前,需要配置模型训练的一系列超参数,具体的超参数含义如下:
#Thealgorithmsupportsmultiplenetworkdepth(numberoflayers).Theyare18,34,50,101,152and200#Forthistraining,wewilluse18layersnum_layers=18#weneedtospecifytheinputimageshapeforthetrainingdataimage_shape="3,224,224"#wealsoneedtospecifythenumberoftrainingsamplesinthetrainingset#forcaltechitis15420num_training_samples=96#specifythenumberofoutputclassesnum_classes=3#batchsizefortrainingmini_batch_size=30#numberofepochsepochs=100#learningratelearning_rate=0.01top_k=2#Sinceweareusingtransferlearning,wesetuse_pretrained_modelto1sothatweightscanbe#initializedwithpre-trainedweightsuse_pretrained_model=1之后,我们进行必要的SageMakerAPI创建,构建对应的训练任务。其中有指定训练的输入与输出,训练的计算实例配置,这里我们使用的是ml.p2.xlargeGPU实例。需要注意的是,这里Sagemakernotebook进行本地的数据处理、模型训练、模型推理是不同环境,可以根据不同的计算任务的需求进行不同的机型选择。
同时,在训练过程中,我们还可以通过监控Cloudwatchlog来查看训练过程中的loss变化:
训练结束后,我们在之前配置的S3存储桶就获得了最新的模型文件。接下来将其进行线上部署,这样就可以通过接受来自客户端的RestfulAPI请求进行预测。
首先创建模型:
%%timeimportboto3fromtimeimportgmtime,strftimesage=boto3.Session().client(service_name='sagemaker')model_name="cars-imageclassification-"+time.strftime('-%Y-%m-%d-%H-%M-%S',time.gmtime())print(model_name)info=sage.describe_training_job(TrainingJobName=job_name)model_data=info['ModelArtifacts']['S3ModelArtifacts']print(model_data)hosting_image=get_image_uri(boto3.Session().region_name,'image-classification')primary_container={'Image':hosting_image,'ModelDataUrl':model_data,}create_model_response=sage.create_model(ModelName=model_name,ExecutionRoleArn=role,PrimaryContainer=primary_container)print(create_model_response['ModelArn'])然后配置接口,可以看到,这里推理使用的实例是ml.m4.xlarge:
%%timeimporttimetimestamp=time.strftime('-%Y-%m-%d-%H-%M-%S',time.gmtime())endpoint_name=job_name_prefix+'-ep-'+timestampprint('Endpointname:{}'.format(endpoint_name))endpoint_params={'EndpointName':endpoint_name,'EndpointConfigName':endpoint_config_name,}endpoint_response=sagemaker.create_endpoint(**endpoint_params)print('EndpointArn={}'.format(endpoint_response['EndpointArn']))在等待端口创建的时候,可以通过查看端口创建状态来获得创建的状态:
#getthestatusoftheendpointresponse=sagemaker.describe_endpoint(EndpointName=endpoint_name)status=response['EndpointStatus']print('EndpointStatus={}'.format(status))#waituntilthestatushaschangedsagemaker.get_waiter('endpoint_in_service').wait(EndpointName=endpoint_name)#printthestatusoftheendpointendpoint_response=sagemaker.describe_endpoint(EndpointName=endpoint_name)status=endpoint_response['EndpointStatus']print('EndpointcreationendedwithEndpointStatus={}'.format(status))如果上述代码运行结果为EndpointcreationendedwithEndpointStatus=InService,那么代表已经成功创建了一个终结点。我们也可以通过SagemakerConsole查看到已经创建好的终结点。
现在我们使用一个随意挑选的汽车图片进行型号分类。本例挑选了一张Acura的AcuraRLSedan2012车型,图片如下:
我们可以直接调用创建的终结点进行推理,可以看到结果与概率,并能看到准确判断出了相对应的分类。这里的概率并不是非常高,但鉴于我们作为范例只训练了不多的epoch,已经是个很不错的结果了。如果想要得到更高的准确率,请使用完整数据集进行更多轮次的训练。
importjsonimportnumpyasnpwithopen(file_name,'rb')asf:payload=f.read()payload=bytearray(payload)response=runtime.invoke_endpoint(EndpointName=endpoint_name,ContentType='application/x-image',Body=payload)result=response['Body'].read()#resultwillbeinjsonformatandconvertittondarrayresult=json.loads(result)#theresultwilloutputtheprobabilitiesforallclasses#findtheclasswithmaximumprobabilityandprinttheclassindexindex=np.argmax(result)object_categories=['AcuraIntegraTypeR2001','AcuraRLSedan2012','AcuraTLSedan2012']print("Result:label-"+object_categories[index]+",probability-"+str(result[index]))
今晚八点,#AmazonLiveCoding#将演示如何利用AmazonServerless和MachineLearning服务来快速构建语音翻译器:你只需要说出中文,亚马逊云科技(AmazonLambda)就会帮你把语音转换成文本(AmazonTranscribe),翻译成选择的语言(比如英文)(AmazonTranslate),然后转换成对应的语音(AmazonPolly)。你就可以造出神奇的宝贝鱼,科技让沟通无障碍~