一切尽在掌控之中:这个Python脚本,让工作自动向你汇报进度

开发 后端
随着数据量和数据复杂性的增加,运行脚本可能需要一些时间。在等待数据处理完成时可以同时做一些其他工作。

本文转载自公众号“读芯术”(ID:AI_Discovery)

笔者经常编写Python脚本来进行数据处理、数据传输和模型训练。随着数据量和数据复杂性的增加,运行脚本可能需要一些时间。在等待数据处理完成时可以同时做一些其他工作。

为了达到这个目的,笔者编写了一组用于解决这个问题的Python脚本。使用这些脚本向手机发送流程更新、可视化和完成通知。当偶尔拥有这些自由的时刻,你可以享受而不是担心模型的进度。

需要什么

第一个问题是,需要知道什么?这取决于你正在做的工作。对于笔者来说主要有有三个可能会占用时间的处理任务:

  • 模型训练
  • 数据处理和/或传输
  • 金融模型

我们需要对于每一种情况具体分析。

模型训练

更新每n个epoch,必须包括关键指标。例如,训练和验证集的损失和准确性。接着完成通知,包括:

  • 训练期间关键指标的可视化(同样,训练和验证集的损失和准确性)
  • 其他不太重要但仍然有用的信息,如本地模型目录、训练时间、模型架构等
  • 预测输出,对于文本生成来说输出生成的文本(或它的一个样本);对于图像生成来说,输出结果是一个(希望)很酷的可视化

以训练一个神经网络来重现给定的艺术风格为例。我们需要重点从模型中生成的图像,损失和精度图,当前的训练时间,和一个模型的名称。

  1. import notify 
  2.              STARTdatetime.now()  # this line would be placed before modeltraining begins 
  3.       MODELNAME="SynthwaveGAN"  # giving us ourmodel name 
  4.       NOTIFY=100  # so we send an update notification every100 epochs 
  5.              # for each epoch e,we would include the following code 
  6.       if e % notify_epoch ==0and e !=0: 
  7.           # here we createthe email body message 
  8.          txt = (f"{MODELNAME} update as of " 
  9.                 f"{datetime.now().strftime('%H:%M:%S')}.") 
  10.                  # we build theMIME message object with notify.message 
  11.          msg = notify.message( 
  12.              subject='Synthwave GAN'
  13.              text=txt
  14.              img=[ 
  15.                  f'../visuals/{MODELNAME}/epoch_{e}_loss.png', 
  16.                  f'../visuals/{MODELNAME}/epoch_{e}_iter_{i}.png' 
  17.              ] 
  18.          )  # note that weattach two images here, the loss plot and 
  19.           #    ...a generated image output from our model 
  20.                     notify.send(msg)  # we then send the message 

每隔100个epoch,就会发送一封包含上述所有内容的电子邮件。以下是其中一封邮件:

一切尽在掌控之中:这个Python脚本,让工作自动向你汇报进度

数据处理和传输

这点不是很有趣,但在时间消耗方面,它排第一名。

以使用Python将批量数据上传到SQLServer为例(对于没有BULK INSERT的人)。在上传脚本的最后,会有一个简单的消息通知上传完成。

  1. import os 
  2.       import notify 
  3.       from data importSql  # seehttps://jamescalam.github.io/pysqlplus/lib/data/sql.html 
  4.              dt =Sql('database123', 'server001')  # setup theconnection to SQL Server 
  5.              for i, file inenumerate(os.listdir('../data/new')): 
  6.           dt.push_raw(f'../data/new/{file}')  # push a file to SQL Server 
  7.              # once the upload is complete, send a notification 
  8.       # first we create the message 
  9.       msg = notify.message( 
  10.           subject='SQL Data Upload'
  11.           text=f'Data upload complete, {i} filesuploaded.'
  12.       ) 
  13.              # send the message 
  14.       notify.send(msg) 

如果偶尔抛出错误,还可以添加一个try-except语句来捕获错误,并将其添加到一个列表中,以包含在更新和/或完成电子邮件中。

金融模型

金融建模中运行的所有东西实际上都非常快,所以此处只能提供一个示例。

以现金流动模型工具为例。现实中,这个过程只需要10-20秒,但现在假设你是华尔街炙手可热的定量分析师,正在处理几百万笔贷款。在这封电子邮件中,可能想要包含一个高级概要分析的投资组合。可以随机选择一些贷款,并在给定的时间段内可视化关键值——给定一个小样本来交叉检验模型的性能。

  1. end = datetime.datetime.now()  # get the ending datetime 
  2.              # get the total runtime in hours:minutes:seconds 
  3.                       hours,rem =divmod((end - start).seconds, 3600) 
  4.                       mins,secs =divmod(rem, 60) 
  5.                       runtime='{:02d}:{:02d}:{:02d}'.format(hours, mins,secs) 
  6.              # now built our message 
  7.                       notify.msg( 
  8.                           subject="Cashflow Model Completion"
  9.                           text=(f'{len(model.output)} loansprocessed.\n' 
  10.                                 f'Total runtime:{runtime}'), 
  11.                           img=[ 
  12.                               '../vis/loan01_amortisation.png', 
  13.                               '../vis/loan07_amortisation.png', 
  14.                               '../vis/loan01_profit_and_loss.png', 
  15.                               '../vis/loan07_profit_and_loss.png' 
  16.                           ] 
  17.                       ) 
  18.              notify.send(msg)  # and send it 

代码

上面的所有功能节选自一个名为notify.py的脚本。在示例代码中将使用Outlook。这里需要两个Python库,email和smtplib:

  • email:用于管理电子邮件消息。有了这个库就可以设置电子邮件消息本身,包括主题、正文和附件。
  • smtplib:处理SMTP连接。简单邮件传输协议(SMTP)是大多数电子邮件系统使用的协议,允许邮件通过互联网发送。

[[329972]]

图源:unsplash

MIME

消息本身是使用来自email模块的MIMEMultipart对象构建的。还需要使用三个MIME子类,并将它们附加到MIMEMultipart对象上:

  • mimetext:这将包含电子邮件“有效负载”,即电子邮件正文中的文本。
  • mimeimage :这是用于在电子邮件中包含图像。
  • mimeapplication:用于MIME消息应用程序对象。也就是文件附件。

除了这些子类之外,还有其他参数,比如MimeMultipart中的Subject值。所有这些加在一起就形成了下面的结构。

把它们都放在一起会发生什么:

一切尽在掌控之中:这个Python脚本,让工作自动向你汇报进度
  1. import os 
  2.       from email.mime.text importMIMEText 
  3.       from email.mime.image importMIMEImage 
  4.       from email.mime.application importMIMEApplication 
  5.       from email.mime.multipart importMIMEMultipart 
  6.              defmessage(subject="PythonNotification"text=""img=Noneattachment=None): 
  7.           # build messagecontents 
  8.           msg =MIMEMultipart() 
  9.           msg['Subject'] = subject  # add in thesubject 
  10.           msg.attach(MIMEText(text))  # add text contents 
  11.                  # check if wehave anything given in the img parameter 
  12.           if img isnotNone: 
  13.               # if we do, wewant to iterate through the images, so let's check that 
  14.               # what we haveis actually a list 
  15.               iftype(img) isnot list: 
  16.                   img = [img]  # if it isn't alist, make it one 
  17.               # now iteratethrough our list 
  18.               for one_img in img: 
  19.                   img_data =open(one_img, 'rb').read()  # read the imagebinary data 
  20.                   # attach theimage data to MIMEMultipart using MIMEImage, we add 
  21.                   # the givenfilename use os.basename 
  22.                   msg.attach(MIMEImage(img_data, name=os.path.basename(one_img))) 
  23.                  # we do the samefor attachments as we did for images 
  24.           if attachment isnotNone: 
  25.               iftype(attachment) isnot list: 
  26.                   attachment = [attachment]  # if it isn't a list, make it one 
  27.                           for one_attachment in attachment: 
  28.                   withopen(one_attachment,'rb') as f: 
  29.                       # read in theattachment using MIMEApplication 
  30.                       file =MIMEApplication
  31.                           f.read(), 
  32.                           name=os.path.basename(one_attachment) 
  33.                       ) 
  34.                   # here we editthe attached file metadata 
  35.                   file['Content-Disposition'] =f'attachment; filename="{os.path.basename(one_attachment)}"
  36.                   msg.attach(file)  # finally, addthe attachment to our message object 
  37.           return msg 

这个脚本相当简单。在顶部,有导入(这是以前介绍过的MIME部分)以及Python的os库。

接下来定义一个名为message的函数。这允许使用不同的参数调用函数并轻松地构建一个电子邮件消息对象。例如,可以这样写一封带有多张图片和附件的邮件:

  1. email_msgmessage
  2.     text="Model processing complete,please see attached data."
  3.     img=['accuracy.png', 'loss.png'], 
  4.     attachments=['data_in.csv', 'data_out.csv'] 

首先,初始化MIMEMultipart对象,并将其分配给msg;然后,使用“subject”键设置电子邮件主题。attach方法向MIMEMultipart对象添加不同的MIME子类。你可以使用MIMEText子类添加电子邮件正文。

对于图像img和attachment附件,可以什么都不传递,只传递一个文件路径,或者传递一组文件路径。我们通过首先检查参数是否为None来处理它,如果参数为None,则传递;否则,检查给定的数据类型,不是一个list,就创建一个,这就使得可以用下面的for循环来遍历项。

接着,使用MIMEImage和MIMEApplication子类分别附加图像和文件。使用os.basename从给定的文件路径中获取文件名,附件名包括该文件名。

[[329973]]

图源:unsplash

SMTP

现在已经构建好电子邮件消息对象,下一步就是发送它。这就是smtplib模块发挥作用的地方。代码同样非常简单,只有一处例外。

由于直接处理不同的电子邮件供应商和他们各自的服务器,需要不同的SMTP地址。在谷歌中输入“outlook smtp”。不需要单击页面,你就可以得到服务器地址smtp-mail.outlook.com和端口号587。

当使用smtplib.SMTP初始化SMTP对象时,这两种方法都需要用。SMTP -接近开始的send函数:

  1. import smtplib 
  2.        import socket 
  3.              defsend(server='smtp-mail.outlook.com'port='587', msg): 
  4.            # contain followingin try-except in case of momentary network errors 
  5.            try: 
  6.                # initialiseconnection to email server, the default is Outlook 
  7.                smtp = smtplib.SMTP(server, port) 
  8.                # this is the'Extended Hello' command, essentially greeting our SMTP or ESMTP server 
  9.                smtp.ehlo() 
  10.                # this is the'Start Transport Layer Security' command, tells the server we will 
  11.                # becommunicating with TLS encryption 
  12.                smtp.starttls() 
  13.                           # read email andpassword from file 
  14.                withopen('../data/email.txt', 'r') as fp: 
  15.                    email = fp.read() 
  16.                withopen('../data/password.txt', 'r') as fp: 
  17.                    pwd = fp.read() 
  18.                         # login tooutlook server 
  19.                smtp.login(email, pwd) 
  20.                # sendnotification to self 
  21.                smtp.sendmail(email, email, msg.as_string()) 
  22.                # disconnectfrom the server 
  23.                smtp.quit() 
  24.            except socket.gaierror: 
  25.                print("Network connection error, email notsent.") 

smtp.ehlo()和smtp.starttls()都是SMTP命令。ehlo(扩展Hello)本质上是向服务器打招呼。starttls通知服务器,将使用加密传输级别安全(TLS)连接进行通信。

在此之后,只需从文件中读取电子邮件和密码,分别存储在email和pwd中。然后,使用smtp.login登录到SMTP服务器。登录并使用smtp.sendmail发送电子邮件。

笔者总是给自己发送通知,但在自动报告的情况下,可能希望将电子邮件发送到其他地方。为此,我会更改destination_address: smtp.sendmail(email、destination_address、 msg.as_string)。

最后,终止会话并关闭与smtp.quit的连接。

将所有这些都放在try-except语句中。在瞬间网络连接丢失的情况下,将无法连接到服务器。导致socket.gaierror。使用try-except语句可以防止程序在网络连接失败的情况下崩溃。

笔者将其用于ML模型培训更新和数据传输完成。如果邮件没有被发送,那也没有关系。这种简单、被动地处理连接丢失是合适的。

放在一起

[[329974]]

图源:unsplash

现在已经写了代码的两部分,我们就可以发送电子邮件了:

  1. # builda message object 
  2. msg = message(text="See attached!"img='important.png'
  3.              attachment='data.csv')send(msg)  #send the email (defaults to Outlook) 

这是所有的电子邮件通知和/或使用Python的自动化的全过程。感谢email和smptlib库,设置过程变得非常容易。

一切尽在掌控之中:这个Python脚本,让工作自动向你汇报进度

还有一点请注意,公共电子邮件提供程序服务器地址和TLS端口。

对于任何耗费大量时间的处理或训练任务,进度更新和完成通知通常才是真正的解放。Python,让工作更美好!

 

责任编辑:赵宁宁 来源: 读芯术
相关推荐

2016-08-31 17:24:05

大数据分析

2015-07-16 16:35:26

2009-12-01 11:20:56

业务服务管理

2022-07-22 14:05:46

超级云自动化

2013-02-19 10:35:13

摩托罗拉移动数据终端

2012-10-30 14:41:56

2014-04-25 22:04:16

敏捷网络企业信息化华为

2014-04-24 16:40:36

敏捷网络华为

2018-01-12 14:11:35

2021-03-09 09:54:07

数字化转型5G网络

2013-12-11 16:55:23

3DDCIM解决方案

2021-05-28 07:12:59

Python闭包函数

2019-04-11 14:51:12

数据

2022-09-13 08:39:22

Bash脚本

2011-10-10 09:24:39

Android后PC时代兼容

2022-04-01 15:24:39

物联网

2020-09-11 10:55:10

useState组件前端

2012-12-31 11:22:58

开源开放

2020-10-22 15:35:35

自动驾驶美团人工智能

2024-01-01 16:01:22

Python函数
点赞
收藏

51CTO技术栈公众号