大数据工程师要学的编程

现实世界中的DS(DS IN THE REAL WORLD)

这篇文章是下面提到的继续。 (This post is in continuation with the one mentioned below.)

In the above post, I have presented some important programming takeaways to know and keep in mind while performing Machine Learning practices to make your implementation faster and effective. Following which we are going to see more of these hacks. Let us begin.

在上面的文章中,我介绍了一些重要的编程要点,它们在执行机器学习实践时要了解并牢记,以使您的实现更快,更有效。 接下来,我们将看到更多这些技巧。 让我们开始吧。

11.操纵宽和长数据帧: (11. Manipulating Wide & Long DataFrames:)

The most effective method for converting wide to long data and long to wide data is pandas.melt() and pandas.pivot_table() function respectively. You will not need anything else to manipulate long and wide data into one another other than these functions.

转换宽数据到长数据和长数据到宽数据的最有效方法分别是pandas.melt()和pandas.pivot_table()函数。 除了这些功能之外,您不需要其他任何东西就可以将长而宽的数据相互转换。

一种。 宽到长(融化) (a. Wide to Long (Melt))

>>> import pandas as pd# create wide dataframe>>> df_wide = pd.DataFrame(...    {"student": ["Andy", "Bernie", "Cindy", "Deb"],...     "school":  ["Z", "Y", "Z", "Y"],...     "english": [66, 98, 61, 67],  # eng grades...     "math":    [87, 48, 88, 47],  # math grades...     "physics": [50, 30, 59, 54]   # physics grades...    }...  )>>> df_wide  student school  english  math  physics0    Andy      Z       66    87       501  Bernie      Y       98    48       302   Cindy      Z       61    88       593     Deb      Y       67    47       54>>> df_wide.melt(id_vars=["student", "school"],...               var_name="subject",  # rename...               value_name="score")  # rename   student school  subject  score0     Andy      Z  english     661   Bernie      Y  english     982    Cindy      Z  english     613      Deb      Y  english     674     Andy      Z     math     875   Bernie      Y     math     486    Cindy      Z     math     887      Deb      Y     math     478     Andy      Z  physics     509   Bernie      Y  physics     3010   Cindy      Z  physics     5911     Deb      Y  physics     54

b。 长到宽(数据透视表) (b. Long to Wide (Pivot Table))

>>> import pandas as pd# create long dataframe>>> df_long = pd.DataFrame({...         "student":...             ["Andy", "Bernie", "Cindy", "Deb",...              "Andy", "Bernie", "Cindy", "Deb",...              "Andy", "Bernie", "Cindy", "Deb"],...         "school":...             ["Z", "Y", "Z", "Y",...              "Z", "Y", "Z", "Y",...              "Z", "Y", "Z", "Y"],...         "class":...             ["english", "english", "english", "english",...              "math", "math", "math", "math",...              "physics", "physics", "physics", "physics"],...         "grade":...             [66, 98, 61, 67,...              87, 48, 88, 47,...              50, 30, 59, 54]... })>>> df_long   student school    class  grade0     Andy      Z  english     661   Bernie      Y  english     982    Cindy      Z  english     613      Deb      Y  english     674     Andy      Z     math     875   Bernie      Y     math     486    Cindy      Z     math     887      Deb      Y     math     478     Andy      Z  physics     509   Bernie      Y  physics     3010   Cindy      Z  physics     5911     Deb      Y  physics     54>>> df_long.pivot_table(index=["student", "school"], ...                     columns='class', ...                     values='grade')class           english  math  physicsstudent school                        Andy    Z            66    87       50Bernie  Y            98    48       30Cindy   Z            61    88       59Deb     Y            67    47       54

12.交叉表: (12. Cross Tabulation:)

When you need to summarise the data, cross tabulation plays a great role to aggregate two or more factors and compute the frequency table for the values. It can be implemented with pandas.crosstab() function which also allows to find the normalized values while printing the output using ‘normalize’ parameter.

当您需要汇总数据时,交叉表在汇总两个或更多因素并计算这些值的频率表方面发挥着重要作用。 可以使用pandas.crosstab()函数实现该函数,该函数还允许在使用'normalize'参数打印输出时查找归一化的值。

>>> import numpy as np>>> import pandas as pd>>> p = np.array(["s1", "s1", "s1", "s1", "b1", "b1",...               "b1", "b1", "s1", "s1", "s1"], dtype=object)>>> q = np.array(["one", "one", "one", "two", "one", "one",...               "one", "two", "two", "two", "one"], dtype=object)>>> r = np.array(["x", "x", "y", "x", "x", "y",...               "y", "x", "y", "y", "y"], dtype=object)>>> pd.crosstab(p, [q, r], rownames=['p'], colnames=['q', 'r'])q  one    two   r    x  y   x  yp               b1   1  2   1  0s1   2  2   1  2# get normalized output values>>> pd.crosstab(p, [q, r], rownames=['p'], colnames=['q', 'r'], normalize=True)q        one                 two          r          x         y         x         yp                                         b1  0.090909  0.181818  0.090909  0.000000s1  0.181818  0.181818  0.090909  0.181818

13. Jupyter主题: (13. Jupyter Themes:)

The one of the best libraries in Python is jupyterthemes that allows you to change and control the style of the notebook view that most of the ML practitioners work upon. As different themes like having dark mode, light mode, etc. or custom styling is preferred by most of the programmers and it can be achieved in Jupyter notebooks using jupyterthemes library.

Python中最好的库之一是jupyterthemes,它使您可以更改和控制大多数ML从业人员从事的笔记本视图的样式。 由于大多数程序员都喜欢不同的主题,例如具有暗模式,亮模式等或自定义样式,因此可以使用jupyterthemes库在Jupyter笔记本中实现。

# pip install$ pip install jupyterthemes# conda install$ conda install -c conda-forge jupyterthemes# list available themes$ jt -lAvailable Themes:   chesterish   grade3   gruvboxd   gruvboxl   monokai   oceans16   onedork   solarizedd   solarizedl# apply the themejt -t chesterish# reverse the theme!jt -r

You can find more about it here on Github https://github.com/dunovank/jupyter-themes.

您可以在Github上找到更多有关它的信息https://github.com/dunovank/jupyter-themes 。

14.将分类转换为虚拟变量: (14. Convert Categorical to Dummy Variable:)

Using pandas.get_dummies() function, you can directly convert the categorical features in the DataFrame to Dummy variables along with drop_first=True to remove the first redundant column.

使用pandas.get_dummies()函数,可以将DataFrame中的分类功能与drop_first = True一起直接转换为Dummy变量,以删除第一个冗余列。

>>> import pandas as pd>>> df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'],...                     'C': [1, 2, 3]})>>> df   A  B  C0  a  b  11  b  a  22  a  c  3>>> pd.get_dummies(df[['A','B']])   A_a  A_b  B_a  B_b  B_c0    1    0    0    1    01    0    1    1    0    02    1    0    0    0    1>>> dummy = pd.get_dummies(df[['A','B']], drop_first=True)>>> dummy   A_b  B_b  B_c0    0    1    01    1    0    02    0    0    1# concat dummy features to existing df>>> df = pd.concat([df, dummy], axis=1)>>> df   A  B  C  A_b  B_b  B_c0  a  b  1    0    1    01  b  a  2    1    0    02  a  c  3    0    0    1

15.转换为数字: (15. Convert into Numeric:)

While loading dataset into pandas, sometimes the numeric column is taken object type and numeric operations cannot be performed on the same. In order to convert them to numeric, we can use pandas.to_numeric() function and update existing Series, or column in DataFrame.

在将数据集加载到熊猫中时,有时会将数字列作为对象类型,并且不能在同一列上执行数字操作。 为了将它们转换为数字,我们可以使用pandas.to_numeric()函数并更新现有的Series或DataFrame中的列。

>>> import pandas as pd>>> s = pd.Series(['1.0', '2', -3, '12', 5])>>> s0    1.01      22     -33     124      5dtype: object>>> pd.to_numeric(s)0     1.01     2.02    -3.03    12.04     5.0dtype: float64>>> pd.to_numeric(s, downcast='signed')0     11     22    -33    124     5dtype: int8

16.分层采样/拆分: (16. Stratified Sampling/Splitting:)

When splitting the dataset, we need to obtain sample population in data splits at times. It is more effective when the classes are not balanced enough in the dataset. In sklearn.model_selection.train_test_split() function, a parameter named “stratify” can be set with target class feature to correctly split the data with same ratio as present in unsplitted dataset for different classes.

拆分数据集时,我们有时需要获取数据拆分中的样本总体。 当类在数据集中不够平衡时,它会更有效。 在sklearn.model_selection .train_test_split()函数中,可以使用目标类别功能设置名为“ stratify ”的参数,以与未分割数据集中不同类别的比率正确分割数据。

from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y,                                                    stratify=y,                                                     test_size=0.25)

17.按类型选择特征: (17. Selecting Features By Type:)

In most of the datasets, we have both types of columns, i.e. Numerical, and Non-Numerical. We often have the need to extract only the numerical columns or categorical columns in the dataset and perform some visualization functions or custom manipulations on the same. In pandas library, we have DataFrame.select_dtypes() function which selects the specific columns from the given dataset that matches the specified datatype.

在大多数数据集中,我们有两种类型的列,即数值列和非数值列。 我们经常需要仅提取数据集中的数字列或分类列,并对它们执行一些可视化功能或自定义操作。 在熊猫库中,我们具有DataFrame.select_dtypes()函数,该函数从给定的数据集中选择与指定数据类型匹配的特定列。

>>> import pandas as pd>>> df = pd.DataFrame({'a': [1, 2] * 3,...                     'b': [True, False] * 3,...                     'c': [1.0, 2.0] * 3})>>> df   a      b    c0  1   True  1.01  2  False  2.02  1   True  1.03  2  False  2.04  1   True  1.05  2  False  2.0>>> df.select_dtypes(include='bool')       b0   True1  False2   True3  False4   True5  False>>> df.select_dtypes(include=['float64'])     c0  1.01  2.02  1.03  2.04  1.05  2.0>>> df.select_dtypes(exclude=['int64'])       b    c0   True  1.01  False  2.02   True  1.03  False  2.04   True  1.05  False  2.0

18. RandomizedSearchCV: (18. RandomizedSearchCV:)

RandomizedSearchCV is a function from sklearn.model_selectionclass that is used to determine random set of hyperparameters for the mentioned learning algorithm, it randomly selects different values for each hyperparameter provided to tune and applied cross-validations on each selected value and determine the best one of them using different scoring mechanism provided while searching.

RandomizedSearchCV是sklearn.model_selection类的一个函数,用于为所提到的学习算法确定随机的超参数集,它为提供的每个超参数随机选择不同的值,以调整和应用对每个选定值的交叉验证,并确定最佳选择之一。他们使用搜索时提供的不同评分机制。

>>> from sklearn.datasets import load_iris>>> from sklearn.linear_model import LogisticRegression>>> from sklearn.model_selection import RandomizedSearchCV>>> from scipy.stats import uniform>>> iris = load_iris()>>> logistic = LogisticRegression(solver='saga', tol=1e-2, ...                               max_iter=300,random_state=12)>>> distributions = dict(C=uniform(loc=0, scale=4),...                      penalty=['l2', 'l1'])>>> clf = RandomizedSearchCV(logistic, distributions, random_state=0)>>> search = clf.fit(iris.data, iris.target)>>> search.best_params_{'C': 2..., 'penalty': 'l1'}

19.魔术功能-历史记录: (19. Magic function — %history:)

A batch of previously ran commands in the notebook can be accessed using ‘%history’ magic function. This will provide all previously executed commands and can be provided custom options to select the specific history commands which you can check using ‘%history?’ in jupyter notebook.

可以使用'%history'魔术功能访问笔记本中一批以前运行的命令。 这将提供所有以前执行的命令,并可以提供自定义选项以选择特定的历史命令,您可以使用'%history?'进行检查。 在jupyter笔记本中。

In [1]: import math

In [2]: math.sin(2)Out[2]: 0.9092974268256817

In [3]: math.cos(2)Out[3]: -0.4161468365471424In [16]: %history -n 1-3   1: import math   2: math.sin(2)   3: math.cos(2)

20.下划线快捷方式(_): (20. Underscore Shortcuts (_):)

In python, you can directly print the last output sent by the interpreter using print(_) function with underscore. This might not be that helpful, but in IPython (jupyter notebook), this feature has been extended and you can print any nth last output using n underscores within print() function. E.g. print(__) with two underscores will give you second-to-last output which skips all command that has no output.

在python中,您可以使用带下划线的print(_)函数直接打印解释器发送的最后输出。 这可能没有帮助,但是在IPython(jupyter笔记本)中,此功能已得到扩展,您可以在print()函数中使用n下划线打印任何n个最后输出。 例如带有两个下划线的print(__)将为您提供倒数第二个输出,该输出将跳过所有没有输出的命令。

Also, another is underscore followed by line number prints the associated output.

此外,另一个是下划线,其后是行号,以打印相关的输出。

In [1]: import math

In [2]: math.sin(2)Out[2]: 0.9092974268256817

In [3]: math.cos(2)Out[3]: -0.4161468365471424In [4]: print(_)-0.4161468365471424

In [5]: print(__)0.9092974268256817In [6]: _2Out[13]: 0.9092974268256817

That’s all for now. I will present more of these important hacks/functions that every data engineer should know about in more next few parts.

目前为止就这样了。 我将在接下来的几个部分中介绍每个数据工程师都应该了解的这些重要的技巧/功能。

Stay tuned.

敬请关注。

Photo by Howie R on Unsplash
照片由Howie R在Unsplash上拍摄

Thanks for reading. You can find my other Machine Learning related posts here.

谢谢阅读。 您可以在这里找到我其他与机器学习有关的帖子。

I hope this post has been useful. I appreciate feedback and constructive criticism. If you want to talk about this article or other related topics, you can drop me a text here or at LinkedIn.

希望这篇文章对您有所帮助。 我感谢反馈和建设性的批评。 如果您想谈论本文或其他相关主题,可以在此处或在LinkedIn上给我发短信。

翻译自: https://towardsdatascience.com/ml-programming-hacks-that-every-data-engineer-should-know-part-2-61c0df0f215c

大数据工程师要学的编程


http://www.taodudu.cc/news/show-4024059.html

相关文章:

  • ML机器学习基础的编程技巧:
  • ML常用技巧
  • 狂神 Git
  • 狂神jvm
  • JavaWeb 狂神
  • JavaWeb kuangshen汇总
  • 狂神说jvm笔记
  • SpringMVC-狂神笔记
  • 狂神Git笔记
  • 狂神说Springboot
  • Java使用zip4j库 压缩文件工具类(自适应压缩包编码格式)
  • 重庆市总工会送法到中建三局城建档案馆项目
  • linux常见维护命令报错,Linux系统维护命令小结.ppt
  • FusionGAN解读2:跑起来
  • ADC0804工作原理及过程
  • springcloud搭建以及集成tx-lcn分布式事务解决框架
  • 超大文件调用讯飞语音听写解决方案
  • 数据猿·金猿榜丨2017中国智能语音领域最具潜力创业公司
  • 老板不好当
  • java操作数据库步骤_java数据库操作基本流程
  • 中科院信工所雏鹰团队在SemEval上大显神威
  • 华南理工计算机就业棒棒,为梦想、为公益,华南理工大学学子为爱发声
  • 【一】情感对话 Towards Emotional Support Dialog Systems 论文阅读
  • 2014网络红人斌少网络红人彭伟个人资料
  • 学习+彭伟《揭秘深度强化学习》PDF+源代码+资料
  • 【二】情感对话 Control Globally,Understand Locally: A Global-to-Local Hierarchical Graph Network for ESConv
  • 2014网络红人彭伟个人资料及照片
  • video截取视频内容作为封面
  • Vue 截取视频第一帧作为封面图 然后转成base64,base64转成图片
  • python cv2 截取视频指定帧图片

大数据工程师要学的编程_每个数据工程师都应了解的ml编程技巧,第2部分相关推荐

  1. 计算机硬件工程师需要学哪些,想当一个硬件工程师 需要学哪方面的知识

    原标题:想当一个硬件工程师 需要学哪方面的知识 硬件工程师分好多种,笼统的来说需要精通电脑软硬件.周边产品的安装调试及组网.作为一个硬件工程师既需要塌实的硬件知识也需要很好的软件知识,并掌握主板芯片级 ...

  2. delphi windows编程_学习C/C++:伴随我成长的编程书!

    学习C++是一个艰难的过程.如果从我第一次看C++的书算起,现在已经过了11年了.一开始的动机也是很不靠谱的.刚开始我很喜欢用VB6来开发游戏,但是我能找到的资料都是用C++来做例子的,文字部分又不丰 ...

  3. 运维工程师是桥的护栏_运维工程师岗位职责与任职要求

    驻场运维工程师岗位职责及要求 一. 系统维护人员能力 / 素质要求: 1. 具备优秀的计算机软.硬件知识,能够快速判断软.硬件故障,并且能 够指导用户使用主流软.硬件: 2. 熟悉常用的操作系统 (W ...

  4. 优秀工程师应该具备哪些素质_优秀的工程师该具备什么能力?

    平庸的人会一直平庸,但是优秀的人却各有千秋!在这个优秀的框架中,又蕴藏着怎样的相通点?当然了,听说以下这十大能力,是开往优秀工程师的"必经之路"! 一.预备工作的能力 俗话说&qu ...

  5. java中级工程师所需的技能_一个Java工程师的岗位职责及所需的知识技能!

    据调查显示,世界上有大约900万的Java开发人员,作为即将成为这900万大军中的一员,你知道去企业后你的工作职责是什么吗?作为一名Java开发人员需要掌握哪些知识技能呢?这些可都关系到你的成长和利益 ...

  6. 程序员和瑜伽_每个程序员都应尝试的5种瑜伽姿势

    程序员和瑜伽 如果您还不知道, 坐就是新吸烟 . 这也是大多数编码人员一生中非常突出的特征. 编码在大多数情况下是固定的,固定在椅子上的活动(除非您有漂亮的站立式办公桌). 编码工作需要您连续几个小时 ...

  7. 负基础学python编程_【数据科学系统学习】Python # 编程基础[二]

    在上一篇中我们讲到了函数,如果你想在所编写的别的程序中重用一些函数的话,应该怎么办?正如你可能想象到的那样,答案是模块(Modules).我们这一篇就从模块说起. 模块 为了编写可维护的代码,我们把很 ...

  8. 在哪个公众号学python好_怎么通过公众号来快速学习python编程?

    现在各个公司对运维工程师的需求,要求具备Python编程能力已经成了一个不争的事实,所以现在不管你是刚入门还是已经参加工作几年了,如果不具备python编程能力,在过几年竞争可能会越来越弱,如果不突破 ...

  9. 99 网络编程_传统网络工程师如何利用python实现公司内网IP地址信息查询?

      网   工   圈 网络工程师阿龙圈内最早的公益公众号,本号已认证!学网络关注我一个就够了(关注近5w+)关注听说99%的网工都来这里充电吖关注我,一个老HCIE(编号3558)带你轻松玩网络技术 ...

  10. 开元弧焊机器人编程_【数据】2019年中国焊接机器人市场发展现状与趋势分析...

    导 语 READ 焊接机器人市场分析 焊接机器人是从事焊接(包括切割与喷涂)的工业机器人.根据国际标准化组织(ISO)工业机器人属于标准焊接机器人的定义,工业机器人是一种多用途的.可重复编程的自动控制 ...

最新文章

  1. 附录:PyTorch记事本
  2. python内置数据结构之str
  3. weex开发安卓原生应用
  4. operator new/delete,operator-> / *【C++运算符重载】
  5. Retrofit 2使用要点梳理:小白进阶回忆录
  6. taro压缩_Taro 如何开始微信小程序的开发
  7. lodop指定打印机打印_GitHub - xtjatswc/formext: 基于Lodop封装的打印框架,支持表单、报表配置。...
  8. python2.7教程 pdf_PYTHON基础教程至60课(2.7版本)整理
  9. rs232串口驱动_RS232与RS485在性能上有啥区别和联系?老电工总结分析,一目了然...
  10. pdo-mysql_PHP: MySQL (PDO) - Manual
  11. 集群监控之Ganglia的部署
  12. 我们为什么这样选择损失函数
  13. go mysql id为0_go 语言中mysql操作200万数据时应该如何写?
  14. Objective-C 高性能的循环
  15. Spark Mllib里相似度度量(基于余弦相似度计算不同用户之间相似性)(图文详解)...
  16. jeep智能手表软件测评中心的测试,够了,不要太帅:Jeep黑骑士智能手表深度评测...
  17. 微信小程序官方开发文档——框架
  18. mysql常见练习题45题
  19. 大连考研英语培训百家外语考研英语一如何准备?
  20. javascript 获取汉字笔画拼音,使用笔画排序

热门文章

  1. 计算机虚拟化技术试题,虚拟现实技术考试题及答案.doc
  2. stupid代码提交到github
  3. 温度对免疫代谢调节和癌症进展的影响
  4. 在win10系统中安装多个不同版本的python环境
  5. 基于 Win32 的应用程序
  6. android popWindow组件微信式实现(较完整版)
  7. 终于不用早起抢菜了?GitHub 买菜插件出世开源了!
  8. 区块链技术的应用价值了解下
  9. TCP的request_sock与sock
  10. 去掉网页从网页中拷贝到word中段落带有的背景颜色