寫給開發(fā)者的 10 條機(jī)器學(xué)習(xí)建議
點(diǎn)擊上方“小白學(xué)視覺(jué)”,選擇加"星標(biāo)"或“置頂”
重磅干貨,第一時(shí)間送達(dá)
本文轉(zhuǎn)自:視學(xué)算法
有時(shí)候,作為一個(gè)數(shù)據(jù)科學(xué)家,我們常常忘記了初心。我們首先是一個(gè)開發(fā)者,然后才是研究人員,最后才可能是數(shù)學(xué)家。我們的首要職責(zé)是快速找到無(wú) bug 的解決方案。
我們能做模型并不意味著我們就是神。這并不是編寫垃圾代碼的理由。
自從我開始學(xué)習(xí)機(jī)器學(xué)習(xí)以來(lái),我犯了很多錯(cuò)誤。因此我想把我認(rèn) 機(jī)器學(xué)習(xí)工程中最常用的技能分享出來(lái)。在我看來(lái),這也是目前這個(gè)行業(yè)最缺乏的技能。
我稱他們?yōu)椴欢浖臄?shù)據(jù)科學(xué)家,因?yàn)樗麄冎泻艽笠徊糠秩硕紱](méi)有系統(tǒng)地學(xué)習(xí)過(guò)計(jì)算機(jī)科學(xué)課程。而我自己也是如此。??
如果要選擇雇傭一個(gè)偉大的數(shù)據(jù)科學(xué)家和一個(gè)偉大的機(jī)器學(xué)習(xí)工程師,我會(huì)選擇雇傭后者。
下面開始我的分享。
一旦開始編寫抽象類,你就能體會(huì)到它給帶來(lái)的好處。抽象類強(qiáng)制子類使用相同的方法和方法名稱。許多人在同一個(gè)項(xiàng)目上工作, 如果每個(gè)人去定義不同的方法,這樣做沒(méi)有必要也很容易造成混亂。
1import os
2from abc import ABCMeta, abstractmethod
3
4
5class DataProcessor(metaclass=ABCMeta):
6 """Base processor to be used for all preparation."""
7 def __init__(self, input_directory, output_directory):
8 self.input_directory = input_directory
9 self.output_directory = output_directory
10
11 @abstractmethod
12 def read(self):
13 """Read raw data."""
14
15 @abstractmethod
16 def process(self):
17 """Processes raw data. This step should create the raw dataframe with all the required features. Shouldn't implement statistical or text cleaning."""
18
19 @abstractmethod
20 def save(self):
21 """Saves processed data."""
22
23
24class Trainer(metaclass=ABCMeta):
25 """Base trainer to be used for all models."""
26
27 def __init__(self, directory):
28 self.directory = directory
29 self.model_directory = os.path.join(directory, 'models')
30
31 @abstractmethod
32 def preprocess(self):
33 """This takes the preprocessed data and returns clean data. This is more about statistical or text cleaning."""
34
35 @abstractmethod
36 def set_model(self):
37 """Define model here."""
38
39 @abstractmethod
40 def fit_model(self):
41 """This takes the vectorised data and returns a trained model."""
42
43 @abstractmethod
44 def generate_metrics(self):
45 """Generates metric with trained model and test data."""
46
47 @abstractmethod
48 def save_model(self, model_name):
49 """This method saves the model in our required format."""
50
51
52class Predict(metaclass=ABCMeta):
53 """Base predictor to be used for all models."""
54
55 def __init__(self, directory):
56 self.directory = directory
57 self.model_directory = os.path.join(directory, 'models')
58
59 @abstractmethod
60 def load_model(self):
61 """Load model here."""
62
63 @abstractmethod
64 def preprocess(self):
65 """This takes the raw data and returns clean data for prediction."""
66
67 @abstractmethod
68 def predict(self):
69 """This is used for prediction."""
70
71
72class BaseDB(metaclass=ABCMeta):
73 """ Base database class to be used for all DB connectors."""
74 @abstractmethod
75 def get_connection(self):
76 """This creates a new DB connection."""
77 @abstractmethod
78 def close_connection(self):
79 """This closes the DB connection."""
實(shí)驗(yàn)的可重復(fù)性是非常重要的,隨機(jī)數(shù)種子是我們的敵人。要特別注重隨機(jī)數(shù)種子的設(shè)置,否則會(huì)導(dǎo)致不同的訓(xùn)練 / 測(cè)試數(shù)據(jù)的分裂和神經(jīng)網(wǎng)絡(luò)中不同權(quán)重的初始化。這些最終會(huì)導(dǎo)致結(jié)果的不一致。
1def set_seed(args):
2 random.seed(args.seed)
3 np.random.seed(args.seed)
4 torch.manual_seed(args.seed)
5 if args.n_gpu > 0:
6 torch.cuda.manual_seed_all(args.seed)
如果你的數(shù)據(jù)量太大,并且你正在處理比如清理數(shù)據(jù)或建模等后續(xù)編碼時(shí),請(qǐng)使用 `nrows `來(lái)避免每次都加載大量數(shù)據(jù)。當(dāng)你只想測(cè)試代碼而不是想實(shí)際運(yùn)行整個(gè)程序時(shí),可以使用此方法。
非常適合在你本地電腦配置不足以處理那么大的數(shù)據(jù)量, 但你喜歡用 Jupyter/VS code/Atom 開發(fā)的場(chǎng)景。
1f_train = pd.read_csv(‘train.csv’, nrows=1000)
總是檢查數(shù)據(jù)中的 NA(缺失值),因?yàn)檫@些數(shù)據(jù)可能會(huì)造成一些問(wèn)題。即使你當(dāng)前的數(shù)據(jù)沒(méi)有,并不意味著它不會(huì)在未來(lái)的訓(xùn)練循環(huán)中出現(xiàn)。所以無(wú)論如何都要留意這個(gè)問(wèn)題。
1print(len(df))
2df.isna().sum()
3df.dropna()
4print(len(df))
在處理大數(shù)據(jù)時(shí),如果能知道還需要多少時(shí)間可以處理完,能夠了解當(dāng)前的進(jìn)度非常重要。
方案1:tqdm
1from tqdm import tqdm
2import time
3
4tqdm.pandas()
5
6df['col'] = df['col'].progress_apply(lambda x: x**2)
7
8text = ""
9for char in tqdm(["a", "b", "c", "d"]):
10 time.sleep(0.25)
11 text = text + char
方案2:fastprogress
1from fastprogress.fastprogress import master_bar, progress_bar
2from time import sleep
3mb = master_bar(range(10))
4for i in mb:
5 for j in progress_bar(range(100), parent=mb):
6 sleep(0.01)
7 mb.child.comment = f'second bar stat'
8 mb.first_bar.comment = f'first bar stat'
9 mb.write(f'Finished loop {i}.')
如果你用過(guò) pandas,你就會(huì)知道有時(shí)候它的速度有多慢ーー尤其在團(tuán)隊(duì)合作時(shí)。與其絞盡腦汁去尋找加速解決方案,不如通過(guò)改變一行代碼來(lái)使用 modin。
1import modin.pandas as pd
記錄函數(shù)的執(zhí)行時(shí)間
并不是所有的函數(shù)都生來(lái)平等。
即使全部代碼都運(yùn)行正常,也并不能意味著你寫出了一手好代碼。一些軟錯(cuò)誤實(shí)際上會(huì)使你的代碼變慢,因此有必要找到它們。使用此裝飾器記錄函數(shù)的時(shí)間。
1import time
2
3def timing(f):
4 """Decorator for timing functions
5 Usage:
6 @timing
7 def function(a):
8 pass
9 """
10
11
12 @wraps(f)
13 def wrapper(*args, **kwargs):
14 start = time.time()
15 result = f(*args, **kwargs)
16 end = time.time()
17 print('function:%r took: %2.2f sec' % (f.__name__, end - start))
18 return result
19 return wrapp
不要在云上燒錢
沒(méi)有人喜歡浪費(fèi)云資源的工程師。
我們的一些實(shí)驗(yàn)可能會(huì)持續(xù)數(shù)小時(shí)。跟蹤它并在完成后關(guān)閉云實(shí)例是很困難的。我自己也犯過(guò)錯(cuò)誤,也看到過(guò)有些人會(huì)有連續(xù)幾天不關(guān)機(jī)的情況。
這種情況經(jīng)常會(huì)發(fā)生在我們周五上班,留下一些東西運(yùn)行,直到周一回來(lái)才意識(shí)到??。
只要在執(zhí)行結(jié)束時(shí)調(diào)用這個(gè)函數(shù),你的屁股就再也不會(huì)著火了!
使用 `try` 和 `except` 來(lái)包裹 main 函數(shù),一旦發(fā)生異常,服務(wù)器就不會(huì)再運(yùn)行。我就處理過(guò)類似的案例??
讓我們多一點(diǎn)責(zé)任感,低碳環(huán)保從我做起。??
1import os
2
3def run_command(cmd):
4 return os.system(cmd)
5
6def shutdown(seconds=0, os='linux'):
7 """Shutdown system after seconds given. Useful for shutting EC2 to save costs."""
8 if os == 'linux':
9 run_command('sudo shutdown -h -t sec %s' % seconds)
10 elif os == 'windows':
11 run_command('shutdown -s -t %s' % seconds)
在建模的某個(gè)特定點(diǎn)之后,所有的深刻見(jiàn)解都來(lái)自于對(duì)誤差和度量的分析。確保為自己和上司創(chuàng)建并保存格式正確的報(bào)告。
不管怎樣,管理層都喜歡報(bào)告,不是嗎???
1import json
2import os
3
4from sklearn.metrics import (accuracy_score, classification_report,
5 confusion_matrix, f1_score, fbeta_score)
6
7def get_metrics(y, y_pred, beta=2, average_method='macro', y_encoder=None):
8 if y_encoder:
9 y = y_encoder.inverse_transform(y)
10 y_pred = y_encoder.inverse_transform(y_pred)
11 return {
12 'accuracy': round(accuracy_score(y, y_pred), 4),
13 'f1_score_macro': round(f1_score(y, y_pred, average=average_method), 4),
14 'fbeta_score_macro': round(fbeta_score(y, y_pred, beta, average=average_method), 4),
15 'report': classification_report(y, y_pred, output_dict=True),
16 'report_csv': classification_report(y, y_pred, output_dict=False).replace('\n','\r\n')
17 }
18
19
20def save_metrics(metrics: dict, model_directory, file_name):
21 path = os.path.join(model_directory, file_name + '_report.txt')
22 classification_report_to_csv(metrics['report_csv'], path)
23 metrics.pop('report_csv')
24 path = os.path.join(model_directory, file_name + '_metrics.json')
25 json.dump(metrics, open(path, 'w'), indent=4)
結(jié)果不好,一切都不好。
你可以做很好的數(shù)據(jù)清理和建模,但是你仍然可以在最后制造巨大的混亂。通過(guò)我與人打交道的經(jīng)驗(yàn)告訴我,許多人不清楚如何編寫好的 api、文檔和服務(wù)器設(shè)置。我將很快寫另一篇關(guān)于這方面的文章,但是先讓我簡(jiǎn)要分享一部分。
下面的方法適用于經(jīng)典的機(jī)器學(xué)習(xí) 和 深度學(xué)習(xí)部署,在不太高的負(fù)載下(比如1000 / min)。
見(jiàn)識(shí)下這個(gè)組合: Fastapi + uvicorn + gunicorn
-
最快的ー用 fastapi 編寫 API,因?yàn)?/span>這 是最快的,原因參見(jiàn)這篇文章。 -
文檔ー在 fastapi 中編寫 API 為我們提供了 http: url/docs 上的免費(fèi)文檔和測(cè)試端點(diǎn),當(dāng)我們更改代碼時(shí),fastapi 會(huì)自動(dòng)生成和更新這些文檔。 -
workerー使用 gunicorn 服務(wù)器部署 API,因?yàn)?gunicorn 具有啟動(dòng)多于1個(gè) worker,而且你應(yīng)該保留至少 2 個(gè)worker。
1pip install fastapi uvicorn gunicorn
2gunicorn -w 4 -k uvicorn.workers.UvicornH11Worker main:app
交流群
歡迎加入公眾號(hào)讀者群一起和同行交流,目前有SLAM、三維視覺(jué)、傳感器、自動(dòng)駕駛、計(jì)算攝影、檢測(cè)、分割、識(shí)別、醫(yī)學(xué)影像、GAN、算法競(jìng)賽等微信群(以后會(huì)逐漸細(xì)分),請(qǐng)掃描下面微信號(hào)加群,備注:”昵稱+學(xué)校/公司+研究方向“,例如:”張三 + 上海交大 + 視覺(jué)SLAM“。請(qǐng)按照格式備注,否則不予通過(guò)。添加成功后會(huì)根據(jù)研究方向邀請(qǐng)進(jìn)入相關(guān)微信群。請(qǐng)勿在群內(nèi)發(fā)送廣告,否則會(huì)請(qǐng)出群,謝謝理解~

