偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

Python開發(fā)者寶典:10個(gè)有用的機(jī)器學(xué)習(xí)實(shí)踐!

譯文
開發(fā) 后端 機(jī)器學(xué)習(xí)
您可能是名數(shù)據(jù)科學(xué)家,但本質(zhì)上仍是開發(fā)者。這意味著您的編程技巧應(yīng)該很熟練。請(qǐng)遵循以下10條提示,確??焖俳桓稕]有錯(cuò)誤的機(jī)器學(xué)習(xí)解決方案。

[[327915]]

【51CTO.com快譯】

有時(shí)作為數(shù)據(jù)科學(xué)家,我們忘了自己是干什么的。我們主要是開發(fā)者,然后是研究者,最后可能是數(shù)學(xué)家。我們的首要責(zé)任是快速開發(fā)沒有錯(cuò)誤的解決方案。

就因?yàn)槲覀兡軜?gòu)建模型并不意味著我們就是神,這沒有給我們編寫垃圾代碼的自由。

自一開始,我犯過很多錯(cuò)誤,想透露一下我認(rèn)為是機(jī)器學(xué)習(xí)工程最常見的技能。我認(rèn)為,這也是眼下業(yè)界最缺乏的技能。

我稱他們?yōu)椴欢浖臄?shù)據(jù)科學(xué)家,因?yàn)樗麄冎泻芏嗳硕际遣皇怯?jì)算機(jī)專業(yè)科班出身的工程師。而我本人就是那樣。

如果要聘一位優(yōu)秀的數(shù)據(jù)科學(xué)家和一位優(yōu)秀的機(jī)器學(xué)習(xí)工程師,我會(huì)聘后者。

1. 學(xué)習(xí)編寫抽象類。

一旦你開始編寫抽象類,就知道可以如何讓你的代碼庫(kù)清晰許多。它們強(qiáng)制執(zhí)行同樣的方法和方法名稱。如果很多人從事同一個(gè)項(xiàng)目,每個(gè)人會(huì)開始采用不同的方法。這會(huì)造成嚴(yán)重的混亂。 

  1. import os  
  2. from abc import ABCMeta, abstractmethod  
  3. class DataProcessor(metaclass=ABCMeta):  
  4. """Base processor to be used for all preparation."""  
  5. def __init__(self, input_directory, output_directory):  
  6. self.input_directory = input_directory  
  7. self.output_directory = output_directory  
  8. @abstractmethod  
  9. def read(self):  
  10. """Read raw data."""  
  11. @abstractmethod  
  12. def process(self):  
  13. """Processes raw data. This step should create the raw dataframe with all the required features. Shouldn't implement statistical or text cleaning."""  
  14. @abstractmethod  
  15. def save(self):  
  16. """Saves processed data."""  
  17. class Trainer(metaclass=ABCMeta):  
  18. """Base trainer to be used for all models."""  
  19. def __init__(self, directory):  
  20. self.directory = directory  
  21. self.model_directory = os.path.join(directory, 'models' 
  22. @abstractmethod  
  23. def preprocess(self):  
  24. """This takes the preprocessed data and returns clean data. This is more about statistical or text cleaning."""  
  25. @abstractmethod  
  26. def set_model(self):  
  27. """Define model here."""  
  28. @abstractmethod  
  29. def fit_model(self):  
  30. """This takes the vectorised data and returns a trained model."""  
  31. @abstractmethod  
  32. def generate_metrics(self):  
  33. """Generates metric with trained model and test data.""" 
  34. @abstractmethod  
  35. def save_model(self, model_name):  
  36. """This method saves the model in our required format."""  
  37. class Predict(metaclass=ABCMeta):  
  38. """Base predictor to be used for all models.""" 
  39. def __init__(self, directory):  
  40. self.directory = directory  
  41. self.model_directory = os.path.join(directory, 'models' 
  42. @abstractmethod  
  43. def load_model(self):  
  44. """Load model here."""  
  45. @abstractmethod  
  46. def preprocess(self):  
  47. """This takes the raw data and returns clean data for prediction.""" 
  48. @abstractmethod  
  49. def predict(self):  
  50. """This is used for prediction."""  
  51. class BaseDB(metaclass=ABCMeta): 
  52. """ Base database class to be used for all DB connectors."""  
  53. @abstractmethod  
  54. def get_connection(self):  
  55. """This creates a new DB connection."""  
  56. @abstractmethod  
  57. def close_connection(self):  
  58. """This closes the DB connection."""  

2. 搞定最上面的seed。

試驗(yàn)的可重現(xiàn)性很重要,而seed是大敵。處理好seed。不然,它會(huì)導(dǎo)致神經(jīng)網(wǎng)絡(luò)中訓(xùn)練/測(cè)試數(shù)據(jù)的不同分隔和權(quán)重的不同初始化。這會(huì)導(dǎo)致結(jié)果不一致。 

  1. def 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)  

3. 從幾行入手。

如果你的數(shù)據(jù)太龐大,又處在編程的后期階段(比如清理數(shù)據(jù)或建模),就使用nrows避免每次加載龐大數(shù)據(jù)。如果你只想測(cè)試代碼、不想實(shí)際運(yùn)行全部代碼,就使用這招。

如果你的本地PC配置不足以處理數(shù)據(jù)大小,這一招很有用,但你喜歡在Jupyter/VS code/Atom上進(jìn)行本地開發(fā)。 

  1. df_train = pd.read_csv(‘train.csv’, nrows=1000) 

4. 預(yù)料失敗(這是成熟開發(fā)者的標(biāo)志)。

始終檢查數(shù)據(jù)中的NA,因?yàn)檫@些會(huì)在以后給你帶來問題。即便你目前的數(shù)據(jù)沒有任何NA,也并不意味著它不會(huì)出現(xiàn)在將來的再訓(xùn)練循環(huán)中。所以無論如何要檢查。 

  1. print(len(df))  
  2. df.isna().sum()  
  3. df.dropna()  
  4. print(len(df))  

5. 顯示處理的進(jìn)度。

你在處理龐大數(shù)據(jù)時(shí),知道要花多少時(shí)間、處于整個(gè)處理過程中的哪個(gè)環(huán)節(jié),絕對(duì)讓人安心。

方法1 — tqdm 

  1. from tqdm import tqdm  
  2. import time  
  3. tqdm.pandas()  
  4. df['col'] = df['col'].progress_apply(lambda x: x**2)  
  5. text = ""  
  6. for char in tqdm(["a""b""c""d"]):  
  7. time.sleep(0.25)  
  8. text = text + char  

方法2 — fastprogress 

  1. from fastprogress.fastprogress import master_bar, progress_bar  
  2. from time import sleep  
  3. mb = master_bar(range(10))  
  4. for 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}.' 

6. Pandas可能很慢。

如果你接觸過pandas,就知道它有時(shí)會(huì)變得多慢,尤其是執(zhí)行g(shù)roupby操作時(shí)。不必絞盡腦汁為提速尋找“出色的”解決方案,只要更改一行代碼,使用modin就行。 

  1. import modin.pandas as pd 

7. 為函數(shù)計(jì)時(shí)。

不是所有函數(shù)都是一樣的。

即便全部代碼沒問題,也不意味著你編寫的是出色的代碼。一些軟錯(cuò)誤實(shí)際上會(huì)使代碼運(yùn)行起來比較慢,有必要把它們找出來。使用這個(gè)裝飾器來記錄函數(shù)的時(shí)間。 

  1. import time  
  2. def timing(f):  
  3. """Decorator for timing functions  
  4. Usage:  
  5. @timing  
  6. def function(a):  
  7. pass 
  8. "" 
  9. @wraps(f)  
  10. def wrapper(*args, **kwargs):  
  11. start = time.time()  
  12. result = f(*args, **kwargs)  
  13. end = time.time()  
  14. print('function:%r took: %2.2f sec' % (f.__name__, end - start)) 
  15. return result  
  16. return wrapper  

8. 別把錢耗費(fèi)在云上。

沒人喜歡浪費(fèi)云資源的工程師。

一些試驗(yàn)可能持續(xù)數(shù)小時(shí)。很難跟蹤試驗(yàn)、云實(shí)例用完后關(guān)閉。本人就犯過這種錯(cuò)誤,也見過有人任由實(shí)例運(yùn)行數(shù)天。

只是在執(zhí)行結(jié)束時(shí)調(diào)用該函數(shù),永遠(yuǎn)不會(huì)有麻煩!

但用try包主代碼,并用except再采用這種方法,那樣如果出現(xiàn)了錯(cuò)誤,服務(wù)器不會(huì)處于繼續(xù)運(yùn)行的狀態(tài)。是的,我也處理過這種情況。

不妨負(fù)責(zé)任一點(diǎn),別生成二氧化碳了。 

  1. import os  
  2. def run_command(cmd):  
  3. return os.system(cmd)  
  4. def shutdown(seconds=0, os='linux'):  
  5. """Shutdown system after seconds given. Useful for shutting EC2 to save costs."""  
  6. if os == 'linux' 
  7. run_command('sudo shutdown -h -t sec %s' % seconds)  
  8. elif os == 'windows' 
  9. run_command('shutdown -s -t %s' % seconds)  

9. 創(chuàng)建和保存報(bào)告。

建模中某個(gè)點(diǎn)之后,所有寶貴的信息只來自錯(cuò)誤和度量分析。確保為你自己和你的經(jīng)理創(chuàng)建和保存格式完好的報(bào)告。

不管怎樣,管理層愛看報(bào)告,不是嗎? 

  1. import json  
  2. import os  
  3. from sklearn.metrics import (accuracy_score, classification_report,  
  4. confusion_matrix, f1_score, fbeta_score)  
  5. def get_metrics(y, y_pred, beta=2, average_method='macro', y_encoder=None):  
  6. if y_encoder:  
  7. y = y_encoder.inverse_transform(y)  
  8. y_pred = y_encoder.inverse_transform(y_pred)  
  9. return {  
  10. 'accuracy': round(accuracy_score(y, y_pred), 4),  
  11. 'f1_score_macro': round(f1_score(y, y_pred, average=average_method), 4),  
  12. 'fbeta_score_macro': round(fbeta_score(y, y_pred, beta, average=average_method), 4),  
  13. 'report': classification_report(y, y_pred, output_dict=True),  
  14. 'report_csv': classification_report(y, y_pred, output_dict=False).replace('\n','\r\n' 
  15.  
  16. def save_metrics(metrics: dict, model_directory, file_name):  
  17. path = os.path.join(model_directory, file_name + '_report.txt' 
  18. classification_report_to_csv(metrics['report_csv'], path)  
  19. metrics.pop('report_csv' 
  20. path = os.path.join(model_directory, file_name + '_metrics.json' 
  21. json.dump(metrics, open(path, 'w'), indent=4)  

10. 編寫出色的API。

所有結(jié)尾不好的代碼都是不好的。

你的數(shù)據(jù)清理和建??赡茏龅煤芎?,但最后還是會(huì)造成大混亂。經(jīng)驗(yàn)告訴我,許多人不清楚如何編寫優(yōu)秀的API、文檔和服務(wù)器配置。

以下是負(fù)載不太高(比如1000/分鐘)的典型的機(jī)器學(xué)習(xí)和深度學(xué)習(xí)部署的好方法。

不妨見識(shí)這對(duì)組合Fastapi + uvicorn

  • 最快:用fastapi編寫API,因?yàn)榫虸/O型操作而言它是速度最快的(https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7),原因在此(https://fastapi.tiangolo.com/benchmarks/)有解釋。
  • 說明文檔:用fastapi編寫API為我們?cè)趆ttp:url/docs提供了免費(fèi)文檔和測(cè)試端點(diǎn)→我們更改代碼時(shí),由fastapi自動(dòng)生成和更新。
  • Workers:使用uvicorn部署API。

運(yùn)行這些命令使用4個(gè)workers來部署。通過負(fù)載測(cè)試來優(yōu)化workers的數(shù)量。 

  1. pip install fastapi uvicorn  
  2. uvicorn main:app --workers 4 --host 0.0.0.0 --port 8000  

Python開發(fā)者寶典:10個(gè)有用的機(jī)器學(xué)習(xí)實(shí)踐!

原文標(biāo)題:10 Useful Machine Learning Practices For Python Developers,作者:Pratik Bhavsar

【51CTO譯稿,合作站點(diǎn)轉(zhuǎn)載請(qǐng)注明原文譯者和出處為51CTO.com】

 

責(zé)任編輯:龐桂玉 來源: 51CTO
相關(guān)推薦

2011-07-15 10:02:01

JavaScript

2020-06-15 10:29:10

JavaScript開發(fā) 技巧

2019-01-16 18:22:24

機(jī)器學(xué)習(xí)人工智能計(jì)算機(jī)

2015-08-12 11:09:42

開發(fā)者設(shè)計(jì)原則

2018-10-05 23:26:00

機(jī)器學(xué)習(xí)算法數(shù)據(jù)

2015-08-11 11:01:22

設(shè)計(jì)原則開發(fā)者

2011-10-11 10:07:37

2015-03-10 09:23:21

前端開發(fā)Sublime插件Sublime

2013-11-26 09:43:36

開發(fā)日志博客

2015-04-21 12:54:21

2014-10-09 09:29:25

AngularJS

2011-03-17 15:25:31

2012-04-17 09:44:08

JavaScript

2014-07-21 10:00:37

框架HTML5框架模板

2017-04-17 13:59:37

機(jī)器學(xué)習(xí)代碼TensorFlow

2011-05-10 08:47:55

開發(fā)者HTML 5W3C

2020-07-10 10:39:04

Python開發(fā)工具

2018-07-25 15:43:27

機(jī)器學(xué)習(xí)框架開發(fā)

2015-03-17 14:31:53

Web開發(fā)web開發(fā)者云開發(fā)環(huán)境

2012-10-11 10:43:26

開發(fā)SQL
點(diǎn)贊
收藏

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