图源:unsplash
笔者经常编写Python脚本来进行数据处理、数据传输和模型训练。随着数据量和数据复杂性的增加,运行脚本可能需要一些时间。在等待数据处理完成时可以同时做一些其他工作。
为了达到这个目的,笔者编写了一组用于解决这个问题的Python脚本。使用这些脚本向手机发送流程更新、可视化和完成通知。当偶尔拥有这些自由的时刻,你可以享受而不是担心模型的进度。
需要什么
第一个问题是,需要知道什么?这取决于你正在做的工作。对于笔者来说主要有有三个可能会占用时间的处理任务:
· 模型训练
· 数据处理和/或传输
· 金融模型
我们 需要 对于每一种情况具体分析。
模型训练
更新每n个epoch,必须包括关键指标。例如,训练和验证集的损失和准确性。接着完成通知,包括:
· 训练期间关键指标的可视化(同样,训练和验证集的损失和准确性)
· 其他不太重要但仍然有用的信息,如本地模型目录、训练时间、模型架构等
· 预测输出,对于文本生成来说输出生成的文本(或它的一个样本);对于图像生成来说,输出结果是一个(希望)很酷的可视化
以训练一个神经网络来重现给定的艺术风格为例。我们需要重点从模型中生成的图像,损失和精度图,当前的训练时间,和一个模型的名称。
import notify
START= datetime.now() # this line would be placed before modeltraining begins
MODELNAME="SynthwaveGAN" # giving us ourmodel name
NOTIFY=100 # so we send an update notification every100 epochs
# for each epoch e,we would include the following code
if e % notify_epoch ==0and e !=0:
# here we createthe email body message
txt = (f"{MODELNAME} update as of "
f"{datetime.now().strftime( %H:%M:%S )}.")
# we build theMIME message object with notify.message
msg = notify.message(
subject= Synthwave GAN ,
text=txt,
img=[
f ../visuals/{MODELNAME}/epoch_{e}_loss.png ,
f ../visuals/{MODELNAME}/epoch_{e}_iter_{i}.png
]
) # note that weattach two images here, the loss plot and
# ...a generated image output from our model
notify.send(msg) # we then send the message
每隔100个epoch,就会发送一封包含上述所有内容的电子邮件。以下是其中一封邮件:
数据处理和传输
这点不是很有趣,但在时间消耗方面,它排第一名。
以使用Python将批量数据上传到SQLServer为例(对于没有BULK INSERT的人)。在上传脚本的最后,会有一个简单的消息通知上传完成。
import os
import notify
from data importSql # seehttps://jamescalam.github.io/pysqlplus/lib/data/sql.html
dt =Sql( database123 , server001 ) # setup theconnection to SQL Server
for i, file inenumerate(os.listdir( ../data/new )):
dt.push_raw(f ../data/new/{file} ) # push a file to SQL Server
# once the upload is complete, send a notification
# first we create the message
msg = notify.message(
subject= SQL Data Upload ,
text=f Data upload complete, {i} filesuploaded. ,
)
# send the message
notify.send(msg)
如果偶尔抛出错误,还可以添加一个try-except语句来捕获错误,并将其添加到一个列表中,以包含在更新和/或完成电子邮件中。
金融模型
金融建模中运行的所有东西实际上都非常快,所以此处只能提供一个示例。
以 现金流动模型工具 为例。现实中,这个过程只需要10-20秒,但现在假设你是华尔街炙手可热的定量分析师,正在处理几百万笔贷款。在这封电子邮件中,可能想要包含一个高级概要分析的投资组合。可以随机选择一些贷款,并在给定的时间段内可视化关键值——给定一个小样本来交叉检验模型的性能。
end = datetime.datetime.now() # get the ending datetime
# get the total runtime in hours:minutes:seconds
hours,rem =divmod((end - start).seconds, 3600)
mins,secs =divmod(rem, 60)
runtime= {:02d}:{:02d}:{:02d} .format(hours, mins,secs)
# now built our message
notify.msg(
subject="Cashflow Model Completion",
text=(f {len(model.output)} loansprocessed.
f Total runtime:{runtime} ),
img=[
../vis/loan01_amortisation.png ,
../vis/loan07_amortisation.png ,
../vis/loan01_profit_and_loss.png ,
../vis/loan07_profit_and_loss.png
]
)
notify.send(msg) # and send it
代码
上面的所有功能节选自一个名为notify.py的脚本。在示例代码中将使用Outlook。这里需要两个Python库,email和smtplib:
· email :用于管理电子邮件消息。有了这个库就可以设置电子邮件消息本身,包括主题、正文和附件。
· smtplib :处理SMTP连接。简单邮件传输协议(SMTP)是大多数电子邮件系统使用的协议,允许邮件通过互联网发送。
图源:unsplash
MIME
消息本身是使用来自email模块的MIMEMultipart对象构建的。还需要使用三个MIME子类,并将它们附加到MIMEMultipart对象上:
· mimetext:这将包含电子邮件“有效负载”,即电子邮件正文中的文本。
· mimeimage :这是用于在电子邮件中包含图像。
· mimeapplication:用于MIME消息应用程序对象。也就是文件附件。
除了这些子类之外,还有其他参数,比如MimeMultipart中的Subject值。所有这些加在一起就形成了下面的结构。
把它们都放在一起会发生什么:
import os
from email.mime.text importMIMEText
from email.mime.image importMIMEImage
from email.mime.application importMIMEApplication
from email.mime.multipart importMIMEMultipart
defmessage(subject="PythonNotification", text="", img=None, attachment=None):
# build messagecontents
msg =MIMEMultipart()
msg[ Subject ] = subject # add in thesubject
msg.attach(MIMEText(text)) # add text contents
# check if wehave anything given in the img parameter
if img isnotNone:
# if we do, wewant to iterate through the images, so let s check that
# what we haveis actually a list
iftype(img) isnot list:
img = [img] # if it isn t alist, make it one
# now iteratethrough our list
for one_img in img:
img_data =open(one_img, rb ).read() # read the imagebinary data
# attach theimage data to MIMEMultipart using MIMEImage, we add
# the givenfilename use os.basename
msg.attach(MIMEImage(img_data, name=os.path.basename(one_img)))
# we do the samefor attachments as we did for images
if attachment isnotNone:
iftype(attachment) isnot list:
attachment = [attachment] # if it isn t a list, make it one
for one_attachment in attachment:
withopen(one_attachment, rb ) as f:
# read in theattachment using MIMEApplication
file =MIMEApplication(
f.read(),
name=os.path.basename(one_attachment)
)
# here we editthe attached file metadata
file[ Content-Disposition ] =f attachment; filename="{os.path.basename(one_attachment)}"
msg.attach(file) # finally, addthe attachment to our message object
return msg
这个脚本相当简单。在顶部,有导入(这是以前介绍过的MIME部分)以及Python的os库。
接下来定义一个名为message的函数。这允许使用不同的参数调用函数并轻松地构建一个电子邮件消息对象。例如,可以这样写一封带有多张图片和附件的邮件:
email_msg= message(
text="Model processing complete,please see attached data.",
img=[ accuracy.png , loss.png ],
attachments=[ data_in.csv , data_out.csv ]
)
首先,初始化MIMEMultipart对象,并将其分配给msg;然后,使用“subject”键设置电子邮件主题。attach方法向MIMEMultipart对象添加不同的MIME子类。你可以使用MIMEText子类添加电子邮件正文。
对于图像img和attachment附件,可以什么都不传递,只传递一个文件路径,或者传递一组文件路径。我们通过首先检查参数是否为None来处理它,如果参数为None,则传递;否则,检查给定的数据类型,不是一个list,就创建一个,这就使得可以用下面的for循环来遍历项。
接着,使用MIMEImage和MIMEApplication子类分别附加图像和文件。使用os.basename从给定的文件路径中获取文件名,附件名包括该文件名。
图源:unsplash
SMTP
现在已经构建好电子邮件消息对象,下一步就是发送它。这就是smtplib模块发挥作用的地方。代码同样非常简单,只有一处例外。
由于直接处理不同的电子邮件供应商和他们各自的服务器,需要不同的SMTP地址。在谷歌中输入“outlook smtp”。不需要单击页面,你就可以得到服务器地址smtp-mail.outlook.com和端口号587。