「机器学习」写给 Python 开发者的 10 条机器学习建议( 三 )


不要在云上烧钱
没有人喜欢浪费云资源的工程师 。
我们的一些实验可能会持续数小时 。 跟踪它并在完成后关闭云实例是很困难的 。 我自己也犯过错误 , 也看到过有些人会有连续几天不关机的情况 。
这种情况经常会发生在我们周五上班 , 留下一些东西运行 , 直到周一回来才意识到 。
只要在执行结束时调用这个函数 , 你的屁股就再也不会着火了!
使用 `try` 和 `except` 来包裹 main 函数 , 一旦发生异常 , 服务器就不会再运行 。 我就处理过类似的案例
让我们多一点责任感 , 低碳环保从我做起 。
1import os23def run_command(cmd):4 return os.system(cmd)56def 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)
「机器学习」写给 Python 开发者的 10 条机器学习建议
本文插图
创建和保存报告 在建模的某个特定点之后 , 所有的深刻见解都来自于对误差和度量的分析 。 确保为自己和上司创建并保存格式正确的报告 。
不管怎样 , 管理层都喜欢报告 , 不是吗?
1import json2import os34from sklearn.metrics import (accuracy_score, classification_report,5 confusion_matrix, f1_score, fbeta_score)67def 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 }181920def 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)
写出一手好 API结果不好 , 一切都不好 。
你可以做很好的数据清理和建模 , 但是你仍然可以在最后制造巨大的混乱 。 通过我与人打交道的经验告诉我 , 许多人不清楚如何编写好的 api、文档和服务器设置 。 我将很快写另一篇关于这方面的文章 , 但是先让我简要分享一部分 。
下面的方法适用于经典的机器学习 和 深度学习部署 , 在不太高的负载下(比如1000 / min) 。
见识下这个组合: Fastapi + uvicorn + gunicorn

  • 最快的ー用 fastapi 编写 API , 因为这 是最快的 , 原因参见这篇文章 。
  • 文档ー在 fastapi 中编写 API 为我们提供了 http: url/docs 上的免费文档和测试端点 , 当我们更改代码时 , fastapi 会自动生成和更新这些文档 。
  • workerー使用 gunicorn 服务器部署 API , 因为 gunicorn 具有启动多于1个 worker , 而且你应该保留至少 2 个worker 。
运行这些命令来使用 4 个 worker 部署 。 可以通过负载测试优化 worker 数量 。
1pip install fastapi uvicorn gunicorn2gunicorn -w 4 -k uvicorn.workers.UvicornH11Worker main:app


推荐阅读