自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

一切盡在掌控之中:這個(gè)Python腳本,讓工作自動(dòng)向你匯報(bào)進(jìn)度

開發(fā) 后端
隨著數(shù)據(jù)量和數(shù)據(jù)復(fù)雜性的增加,運(yùn)行腳本可能需要一些時(shí)間。在等待數(shù)據(jù)處理完成時(shí)可以同時(shí)做一些其他工作。

本文轉(zhuǎn)載自公眾號(hào)“讀芯術(shù)”(ID:AI_Discovery)

筆者經(jīng)常編寫Python腳本來進(jìn)行數(shù)據(jù)處理、數(shù)據(jù)傳輸和模型訓(xùn)練。隨著數(shù)據(jù)量和數(shù)據(jù)復(fù)雜性的增加,運(yùn)行腳本可能需要一些時(shí)間。在等待數(shù)據(jù)處理完成時(shí)可以同時(shí)做一些其他工作。

為了達(dá)到這個(gè)目的,筆者編寫了一組用于解決這個(gè)問題的Python腳本。使用這些腳本向手機(jī)發(fā)送流程更新、可視化和完成通知。當(dāng)偶爾擁有這些自由的時(shí)刻,你可以享受而不是擔(dān)心模型的進(jìn)度。

需要什么

第一個(gè)問題是,需要知道什么?這取決于你正在做的工作。對(duì)于筆者來說主要有有三個(gè)可能會(huì)占用時(shí)間的處理任務(wù):

  • 模型訓(xùn)練
  • 數(shù)據(jù)處理和/或傳輸
  • 金融模型

我們需要對(duì)于每一種情況具體分析。

模型訓(xùn)練

更新每n個(gè)epoch,必須包括關(guān)鍵指標(biāo)。例如,訓(xùn)練和驗(yàn)證集的損失和準(zhǔn)確性。接著完成通知,包括:

  • 訓(xùn)練期間關(guān)鍵指標(biāo)的可視化(同樣,訓(xùn)練和驗(yàn)證集的損失和準(zhǔn)確性)
  • 其他不太重要但仍然有用的信息,如本地模型目錄、訓(xùn)練時(shí)間、模型架構(gòu)等
  • 預(yù)測(cè)輸出,對(duì)于文本生成來說輸出生成的文本(或它的一個(gè)樣本);對(duì)于圖像生成來說,輸出結(jié)果是一個(gè)(希望)很酷的可視化

以訓(xùn)練一個(gè)神經(jīng)網(wǎng)絡(luò)來重現(xiàn)給定的藝術(shù)風(fēng)格為例。我們需要重點(diǎn)從模型中生成的圖像,損失和精度圖,當(dāng)前的訓(xùn)練時(shí)間,和一個(gè)模型的名稱。

  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個(gè)epoch,就會(huì)發(fā)送一封包含上述所有內(nèi)容的電子郵件。以下是其中一封郵件:

一切盡在掌控之中:這個(gè)Python腳本,讓工作自動(dòng)向你匯報(bào)進(jìn)度

數(shù)據(jù)處理和傳輸

這點(diǎn)不是很有趣,但在時(shí)間消耗方面,它排第一名。

以使用Python將批量數(shù)據(jù)上傳到SQLServer為例(對(duì)于沒有BULK INSERT的人)。在上傳腳本的最后,會(huì)有一個(gè)簡(jiǎn)單的消息通知上傳完成。

  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) 

如果偶爾拋出錯(cuò)誤,還可以添加一個(gè)try-except語句來捕獲錯(cuò)誤,并將其添加到一個(gè)列表中,以包含在更新和/或完成電子郵件中。

金融模型

金融建模中運(yùn)行的所有東西實(shí)際上都非??欤源颂幹荒芴峁┮粋€(gè)示例。

以現(xiàn)金流動(dòng)模型工具為例?,F(xiàn)實(shí)中,這個(gè)過程只需要10-20秒,但現(xiàn)在假設(shè)你是華爾街炙手可熱的定量分析師,正在處理幾百萬筆貸款。在這封電子郵件中,可能想要包含一個(gè)高級(jí)概要分析的投資組合??梢噪S機(jī)選擇一些貸款,并在給定的時(shí)間段內(nèi)可視化關(guān)鍵值——給定一個(gè)小樣本來交叉檢驗(yàn)?zāi)P偷男阅堋?/p>

  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 

代碼

上面的所有功能節(jié)選自一個(gè)名為notify.py的腳本。在示例代碼中將使用Outlook。這里需要兩個(gè)Python庫(kù),email和smtplib:

  • email:用于管理電子郵件消息。有了這個(gè)庫(kù)就可以設(shè)置電子郵件消息本身,包括主題、正文和附件。
  • smtplib:處理SMTP連接。簡(jiǎn)單郵件傳輸協(xié)議(SMTP)是大多數(shù)電子郵件系統(tǒng)使用的協(xié)議,允許郵件通過互聯(lián)網(wǎng)發(fā)送。

[[329972]]

圖源:unsplash

MIME

消息本身是使用來自email模塊的MIMEMultipart對(duì)象構(gòu)建的。還需要使用三個(gè)MIME子類,并將它們附加到MIMEMultipart對(duì)象上:

  • mimetext:這將包含電子郵件“有效負(fù)載”,即電子郵件正文中的文本。
  • mimeimage :這是用于在電子郵件中包含圖像。
  • mimeapplication:用于MIME消息應(yīng)用程序?qū)ο?。也就是文件附件?/li>

除了這些子類之外,還有其他參數(shù),比如MimeMultipart中的Subject值。所有這些加在一起就形成了下面的結(jié)構(gòu)。

把它們都放在一起會(huì)發(fā)生什么:

一切盡在掌控之中:這個(gè)Python腳本,讓工作自動(dòng)向你匯報(bào)進(jìn)度
  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 

這個(gè)腳本相當(dāng)簡(jiǎn)單。在頂部,有導(dǎo)入(這是以前介紹過的MIME部分)以及Python的os庫(kù)。

接下來定義一個(gè)名為message的函數(shù)。這允許使用不同的參數(shù)調(diào)用函數(shù)并輕松地構(gòu)建一個(gè)電子郵件消息對(duì)象。例如,可以這樣寫一封帶有多張圖片和附件的郵件:

  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對(duì)象,并將其分配給msg;然后,使用“subject”鍵設(shè)置電子郵件主題。attach方法向MIMEMultipart對(duì)象添加不同的MIME子類。你可以使用MIMEText子類添加電子郵件正文。

對(duì)于圖像img和attachment附件,可以什么都不傳遞,只傳遞一個(gè)文件路徑,或者傳遞一組文件路徑。我們通過首先檢查參數(shù)是否為None來處理它,如果參數(shù)為None,則傳遞;否則,檢查給定的數(shù)據(jù)類型,不是一個(gè)list,就創(chuàng)建一個(gè),這就使得可以用下面的for循環(huán)來遍歷項(xiàng)。

接著,使用MIMEImage和MIMEApplication子類分別附加圖像和文件。使用os.basename從給定的文件路徑中獲取文件名,附件名包括該文件名。

[[329973]]

圖源:unsplash

SMTP

現(xiàn)在已經(jīng)構(gòu)建好電子郵件消息對(duì)象,下一步就是發(fā)送它。這就是smtplib模塊發(fā)揮作用的地方。代碼同樣非常簡(jiǎn)單,只有一處例外。

由于直接處理不同的電子郵件供應(yīng)商和他們各自的服務(wù)器,需要不同的SMTP地址。在谷歌中輸入“outlook smtp”。不需要單擊頁面,你就可以得到服務(wù)器地址smtp-mail.outlook.com和端口號(hào)587。

當(dāng)使用smtplib.SMTP初始化SMTP對(duì)象時(shí),這兩種方法都需要用。SMTP -接近開始的send函數(shù):

  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(擴(kuò)展Hello)本質(zhì)上是向服務(wù)器打招呼。starttls通知服務(wù)器,將使用加密傳輸級(jí)別安全(TLS)連接進(jìn)行通信。

在此之后,只需從文件中讀取電子郵件和密碼,分別存儲(chǔ)在email和pwd中。然后,使用smtp.login登錄到SMTP服務(wù)器。登錄并使用smtp.sendmail發(fā)送電子郵件。

筆者總是給自己發(fā)送通知,但在自動(dòng)報(bào)告的情況下,可能希望將電子郵件發(fā)送到其他地方。為此,我會(huì)更改destination_address: smtp.sendmail(email、destination_address、 msg.as_string)。

最后,終止會(huì)話并關(guān)閉與smtp.quit的連接。

將所有這些都放在try-except語句中。在瞬間網(wǎng)絡(luò)連接丟失的情況下,將無法連接到服務(wù)器。導(dǎo)致socket.gaierror。使用try-except語句可以防止程序在網(wǎng)絡(luò)連接失敗的情況下崩潰。

筆者將其用于ML模型培訓(xùn)更新和數(shù)據(jù)傳輸完成。如果郵件沒有被發(fā)送,那也沒有關(guān)系。這種簡(jiǎn)單、被動(dòng)地處理連接丟失是合適的。

放在一起

[[329974]]

圖源:unsplash

現(xiàn)在已經(jīng)寫了代碼的兩部分,我們就可以發(fā)送電子郵件了:

  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的自動(dòng)化的全過程。感謝email和smptlib庫(kù),設(shè)置過程變得非常容易。

一切盡在掌控之中:這個(gè)Python腳本,讓工作自動(dòng)向你匯報(bào)進(jìn)度

還有一點(diǎn)請(qǐng)注意,公共電子郵件提供程序服務(wù)器地址和TLS端口。

對(duì)于任何耗費(fèi)大量時(shí)間的處理或訓(xùn)練任務(wù),進(jìn)度更新和完成通知通常才是真正的解放。Python,讓工作更美好!

 

責(zé)任編輯:趙寧寧 來源: 讀芯術(shù)
相關(guān)推薦

2016-08-31 17:24:05

大數(shù)據(jù)分析

2015-07-16 16:35:26

2009-12-01 11:20:56

業(yè)務(wù)服務(wù)管理

2022-07-22 14:05:46

超級(jí)云自動(dòng)化

2013-02-19 10:35:13

摩托羅拉移動(dòng)數(shù)據(jù)終端

2012-10-30 14:41:56

2014-04-25 22:04:16

敏捷網(wǎng)絡(luò)企業(yè)信息化華為

2014-04-24 16:40:36

敏捷網(wǎng)絡(luò)華為

2018-01-12 14:11:35

2021-03-09 09:54:07

數(shù)字化轉(zhuǎn)型5G網(wǎng)絡(luò)

2021-05-28 07:12:59

Python閉包函數(shù)

2013-12-11 16:55:23

3DDCIM解決方案

2019-04-11 14:51:12

數(shù)據(jù)

2011-10-10 09:24:39

Android后PC時(shí)代兼容

2022-04-01 15:24:39

物聯(lián)網(wǎng)

2022-09-13 08:39:22

Bash腳本

2012-12-31 11:22:58

開源開放

2020-09-11 10:55:10

useState組件前端

2016-12-05 17:39:20

投資 大佬

2021-02-28 09:47:54

軟件架構(gòu)軟件開發(fā)軟件設(shè)計(jì)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)