7.Working with External Libraries

在本课中,我将讨论Python中的imports,提供一些使用不熟悉的库(以及它们返回的对象)的技巧,并深入研究Python的内容,以及谈谈运算符重载。

Imports

到目前为止,我们已经讨论了内置于该语言的类型和函数。
但是关于Python的最好的事情之一(特别的如果你是一名数据科学家)是为它编写的大量高质量自定义库。
其中一些库位于“标准库”中,这意味着您可以在运行Python的任何位置找到它们。 其他库可以轻松添加,即使它们并不总是随Python一起提供。
无论哪种方式,我们都会使用导入访问此代码。
我们将从标准库中导入math开始我们的示例。

【1】

import mathprint("It's math! It has type {}".format(type(math)))
It's math! It has type <class 'module'>

math是一个模块,模块只是其他人定义的变量集合。 我们可以使用内置函数dir()查看数学中的所有名称。

【2】

print(dir(math))
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

我们可以使用点语法访问这些变量。 其中一些是指简单的值,比如math.pi:

【3】

print("pi to 4 significant digits = {:.4}".format(math.pi))
pi to 4 significant digits = 3.142

但是我们在模块中找到最多的是函数:像math.log:

[4]

math.log(32, 2)
5.0

当然,如果我们不了解math.log做什么,我们调用help()函数:

【5】

help(math.log)
Help on built-in function log in module math:log(...)log(x[, base])Return the logarithm of x to the given base.If the base not specified, returns the natural logarithm (base e) of x.

我们也可以在模块本身上调用help()。 这将为我们提供模块中所有函数和值的组合文档(以及模块的高级描述)。 

【6】

help(math)

Other import syntax

如果我们知道我们将经常使用math中的函数,我们可以在较短的别名下导入它以节省一些输入(尽管在这种情况下“math”已经相当短)。

【7】

import math as mt
mt.pi
3.141592653589793

您可能已经看到了使用某些流行的库(如Pandas,Numpy,Tensorflow或Matplotlib)执行此操作的代码。 例如,import numpy as np 和 import pandas as pd是一种常见的约定。

as相当于重命名导入模块,等价于如下操作:

[8]

import math
mt = math

如果我们可以自己引用数学模块中的所有变量,那不是很好吗? 即如果我们可以只引用pi而不是math.pi或mt.pi? 好消息:我们可以做到这一点。

[9]

from math import *
print(pi, log(32, 2))
3.141592653589793 5.0

import *使您可以直接访问所有模块的变量。
坏消息:一些纯粹主义者可能会抱怨你这样做。
[10]

from math import *
from numpy import *
print(pi, log(32, 2))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-9b512bc684f5> in <module>()1 from math import *2 from numpy import *
----> 3 print(pi, log(32, 2))TypeError: return arrays must be of ArrayType

什么是什么? 但它以前工作过!
这些“star imports”偶尔会导致奇怪的,难以调试的情况。
这种情况下的问题是math和numpy模块都有称为log的函数,但它们具有不同的语义。 因为numpy导入在第二个,覆盖了我们从math导入的变量。
一个很好的折衷方案是只从每个模块导入我们需要的特定内容:

[11]

from math import log, pi
from numpy import asarray

Submodules

我们已经看到模块包含可以引用函数或值的变量。 需要注意的是,它们也可以包含引用其他模块的变量。

[12]

import numpy
print("numpy.random is a", type(numpy.random))
print("it contains names such as...",dir(numpy.random)[-15:])
numpy.random is a <class 'module'>
it contains names such as... ['set_state', 'shuffle', 'standard_cauchy', 'standard_exponential', 'standard_gamma', 'standard_normal', 'standard_t', 'test', 'triangular', 'uniform', 'vonmises', 'wald', 'warnings', 'weibull', 'zipf']

如果我们导入numpy模块,调用randon子模块中的函数需要两个点号。

【13】

# Roll 10 dice
rolls = numpy.random.randint(low=1, high=6, size=10)
rolls
array([2, 1, 5, 2, 4, 5, 4, 5, 5, 5])

Oh the places you'll go, oh the objects you'll see

所以在经过6课之后,你对 整数,浮点数,布尔,列表,字符串和字典很熟悉了(对吧?)。
即使这是真的,也不会就此结束。 当您使用各种库进行专门任务时,您会发现他们定义了您自己必须学习使用的类型。 例如,如果您使用图形库matplotlib,您将接触到它定义的对象,这些对象代表子图,数字,TickMark和注释。 pandas函数将为您提供DataFrames和Series。
在本节中,我想与您分享一个快速生存指南,用于处理奇怪的类型。

Three tools for understanding strange objects

在上面的例子中,我们看到调用一个numpy函数给了我们一个“数组”。 我们以前从未见过这样的事情(不管怎么说都不是这样)。 但不要惊慌:我们有三个熟悉的内置函数来帮助我们。
1:type()(这是什么东西?)

【14】

type(rolls)numpy.ndarray

2.dir()(我可以用它做什么?)

【15】

print(dir(rolls))
['T', '__abs__', '__add__', '__and__', '__array__', '__array_finalize__', '__array_interface__', '__array_prepare__', '__array_priority__', '__array_struct__', '__array_ufunc__', '__array_wrap__', '__bool__', '__class__', '__complex__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__', '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__imul__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__lshift__', '__lt__', '__matmul__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmatmul__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__xor__', 'all', 'any', 'argmax', 'argmin', 'argpartition', 'argsort', 'astype', 'base', 'byteswap', 'choose', 'clip', 'compress', 'conj', 'conjugate', 'copy', 'ctypes', 'cumprod', 'cumsum', 'data', 'diagonal', 'dot', 'dtype', 'dump', 'dumps', 'fill', 'flags', 'flat', 'flatten', 'getfield', 'imag', 'item', 'itemset', 'itemsize', 'max', 'mean', 'min', 'nbytes', 'ndim', 'newbyteorder', 'nonzero', 'partition', 'prod', 'ptp', 'put', 'ravel', 'real', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'setfield', 'setflags', 'shape', 'size', 'sort', 'squeeze', 'std', 'strides', 'sum', 'swapaxes', 'take', 'tobytes', 'tofile', 'tolist', 'tostring', 'trace', 'transpose', 'var', 'view']

【16】

# What am I trying to do with this dice roll data? Maybe I want the average roll, in which case the "mean"
# method looks promising...
rolls.mean()
3.8

【17】

# Or maybe I just want to get back on familiar ground, in which case I might want to check out "tolist"
rolls.tolist()
[2, 1, 5, 2, 4, 5, 4, 5, 5, 5]

3.help()(告诉我更多)

【18】

# That "ravel" attribute sounds interesting. I'm a big classical music fan.
help(rolls.ravel)Help on built-in function ravel:ravel(...) method of numpy.ndarray instancea.ravel([order])Return a flattened array.Refer to `numpy.ravel` for full documentation.See Also--------numpy.ravel : equivalent functionndarray.flat : a flat iterator on the array.

【19】

# Okay, just tell me everything there is to know about numpy.ndarray
# (Click the "output" button to see the novel-length output)
help(rolls)

当然,你可能更喜欢查看在线文档。

Operator overloading

下面表达式的值是多少?

【20】

[3, 4, 1, 2, 2, 1] + 10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-1b8555d93650> in <module>()
----> 1 [3, 4, 1, 2, 2, 1] + 10TypeError: can only concatenate list (not "int") to list

多么愚蠢的问题,当然会报错。

但是。。。

【21】

rolls + 10array([12, 11, 15, 12, 14, 15, 14, 15, 15, 15])

我们可能会认为Python严格控制其核心语法的行为,例如+,<,in,==或方括号用于索引和切片。 但事实上,它需要一种非常不干涉的方法。 定义新类型时,可以选择添加的工作方式,或者该类型的对象与其他对象的含义相同。
列表的设计者决定不允许将它们添加到数字中。 numpy数组的设计者采用了不同的方式(将数字添加到数组的每个元素)。
下面是一些numpy数组如何与Python运算符交互(或者至少与列表不同)的示例。

【22】

# At which indices are the dice less than or equal to 3?
rolls <= 3
array([ True,  True, False,  True, False, False, False, False, False,False])

【23】

xlist = [[1,2,3],[2,4,6],]
# Create a 2-dimensional array
x = numpy.asarray(xlist)
print("xlist = {}\nx =\n{}".format(xlist, x))xlist = [[1, 2, 3], [2, 4, 6]]
x =
[[1 2 3][2 4 6]]

【24】

# Get the last element of the second row of our numpy array
x[1,-1]6

【25】

# Get the last element of the second sublist of our nested list?
xlist[1,-1]---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-f74d164f666a> in <module>()1 # Get the last element of the second sublist of our nested list?
----> 2 xlist[1,-1]TypeError: list indices must be integers or slices, not tuple

numpy的ndarray类型专门用于处理多维数据,因此它定义了自己的索引逻辑,允许我们通过元组来指定每个维度的索引。

1 + 1何时不等于2?

事情可能比这更奇怪。 您可能听说过(甚至使用过)tensorflow,这是一种广泛用于深度学习的Python库。 它广泛使用了运算符重载。

【26】

import tensorflow as tf
# Create two constants, each with value 1
a = tf.constant(1)
b = tf.constant(1)
# Add them together to get...
a + b
<tf.Tensor 'add:0' shape=() dtype=int32>

a + b不是2,它是(引用tensorflow的文档)......
     操作的一个输出的符号句柄。 它不保存该操作的输出值,而是提供在TensorFlow tf.Session中计算这些值的方法。
重要的是要意识到这样的事情是可能的,并且库通常会以非显而易见或神奇的方式使用运算符重载。

理解Python的运算符在应用于整数,字符串和列表时的工作原理并不能保证您在应用与tensorflow Tensor,numpy ndarray或pandas DataFrame时能够立即理解它们的作用。
例如,一旦您对DataFrame有一点兴趣,下面的表达式开始看起来很吸引人:

# Get the rows with population over 1m in South America
df[(df['population'] > 10*6) & (df['continent'] == 'South America')]

但为什么它有效呢? 上面的例子有5个不同的重载运算符。 这些操作中的每一项都在做什么? 当事情开始出错时,它可以帮助你知道答案。

很好奇这些是怎么工作的?

你有没有在一个对象上调用help()或dir(),并想知道所有带有双下划线的名字到底是什么?

【27】

print(dir(list))['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

结果与运算符重载直接相关。
当Python程序员想要定义操作符在其类型上的行为方式时,他们通过实现具有特殊名称的方法来实现,这些特征名称以2个下划线开头和结尾,例如__lt __,__ setattr __或__contains__。 通常,遵循此双下划线格式的名称对Python具有特殊含义。
因此,例如,[1,2,3]中的表达式x实际上是在幕后调用list方法__contains__。 它相当于(更加丑陋)[1,2,3] .__包含__(x)。
如果您想了解更多信息,可以查看Python的官方文档,其中描述了许多这些特殊的“下划线”方法。
我们不会在这些课程中定义我们自己的类型,但我希望你能够体验到后来定义你自己的奇妙,怪异类型的乐趣。

Your turn!

转到最后一个练习笔记本,再进行一轮涉及导入库,处理不熟悉的对象,当然还有更多的赌博的编程问题。

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/440359.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

计算机原理期中考试,计算机组成原理期中考试试题

一、单选题(每小题2分&#xff0c;共34分)1&#xff0e;完整的计算机系统应包括__________。A&#xff0e;运算器、存储器、控制器 B&#xff0e; 主机和实用程序C&#xff0e;配套的硬件设备和软件系统 D&#xff0e; 外部设备和主机2&#xff0e;下列数中真值最小的数是_____…

【HDU - 1839】Delay Constrained Maximum Capacity Path(最短路 + 二分)

题干&#xff1a; 考虑一个包含 N 个顶点的无向图&#xff0c;编号从 1 到 N&#xff0c;并包含 M 条边。编号为 1 的顶点对应了一个矿藏&#xff0c;可从中提取珍稀的矿石。编号为 N 的顶点对应了一个矿石加工厂。每条边有相应的通行时间 (以时间单位计)&#xff0c;以及相应…

0.Overview

本文为Kaggle Learn的Python课程的中文翻译&#xff0c;原文链接为&#xff1a;https://www.kaggle.com/learn/python 欢迎来到Kaggle Learn的Python课程。本课程将介绍在开始使用Python进行数据科学之前需要的基本Python技能。这些课程针对那些具有一些编程经验的人&#xff…

量子计算机的体积有多大,量子计算机也能实现摩尔定律

原标题&#xff1a;量子计算机也能实现摩尔定律量子计算机拥有很强大的计算力&#xff0c;但是这对IBM来说&#xff0c;似乎还不够。据CNET消息&#xff0c;IBM制作了一个路线图&#xff0c;表达出了自己在量子计算领域的野心。IBM在图表的纵轴上列出了一个单位“量子体积(Quan…

1.How Models work

Introduction 我们首先概述机器学习模型如何工作以及如何使用它们。如果您之前已完成统计建模或机器学习&#xff0c;这可能会感觉很基础。别担心&#xff0c;我们很快就会建立强大的模型。 本课程将为您构建以下场景的模型&#xff1a; 你的堂兄已经花了数百万美元预测房地产…

【BZOJ - 1059】矩阵游戏(二分图匹配,建图,最小边覆盖)

题干&#xff1a; 小Q是一个非常聪明的孩子&#xff0c;除了国际象棋&#xff0c;他还很喜欢玩一个电脑益智游戏——矩阵游戏。矩阵游戏在一个N *N黑白方阵进行&#xff08;如同国际象棋一般&#xff0c;只是颜色是随意的&#xff09;。每次可以对该矩阵进行两种操作&#xff…

ji计算机一级题库,全国计算机等级考试一级题库0l0ji.doc

全国计算机等级考试一级题库0l0ji全国计算机等级考试一级题库(1)1&#xff0e;微机中1K字节表示的二进制位数是( )。D?   A、1000   B、8x1000   C、1024   D、8x1024??2&#xff0e;计算机硬件能直接识别和执行的只有( )。D?   A、高级语言   B、符号语言   …

2.Explore Your Data

Using Pandas to Get Familiar With Your Data 任何机器学习项目的第一步都是熟悉数据。 您将使用Pandas库。 Pandas是科学家用于挖掘和处理数据的主要工具。 大多数人在他们的代码中将pandas缩写为pd。 我们使用如下命令执行此操作。 [1] import pandas as pd Pandas库中最…

【POJ - 3026】Borg Maze(bfs预处理 + 最小生成树,建图)

题干&#xff1a; The Borg is an immensely powerful race of enhanced humanoids from the delta quadrant of the galaxy. The Borg collective is the term used to describe the group consciousness of the Borg civilization. Each Borg individual is linked to the c…

计算机统考测试,计算机统考专业测试题.doc

文档介绍&#xff1a;应用所有单选题1、下面是某单位主页地址的,其中符合格式的是。A:B:C:D:答案:C知识点:应用部分\和的使用\浏览器的使用\1网页的几个基本术语2、用浏览器浏览网页,在地址栏中输入网址时,通常可以省略的是。A:B:C:D:答案:A知识点:应用部分\和的使用\浏览器的使…

3.Your First Machine Learning Model

Selecting Data for Modeling 你的数据集有太多的变量包裹住你的头。你怎么能把这些压倒性的数据削减到你能理解的东西&#xff1f; 我们首先使用我们的直觉选择一些变量。 后面的课程将向您展示自动确定变量优先级的统计技巧。 要选择变量/列&#xff0c;我们需要查看数据集中…

【POJ - 3020】Antenna Placement (匈牙利算法,二分图最小边覆盖)

题干&#xff1a; The Global Aerial Research Centre has been allotted the task of building the fifth generation of mobile phone nets in Sweden. The most striking reason why they got the job, is their discovery of a new, highly noise resistant, antenna. It …

计算机教室安全预案 博客,校园安全应急预案

校园安全应急预案为了确保师生的人身安全&#xff0c;严格执行上级安全工作的管理要求&#xff0c;保证一旦发生安全事故能够及时处理&#xff0c;特制定我校安全应急预案。一、领导小组组 长&#xff1a;副组长&#xff1a;成 员&#xff1a;全体教师二、主要职责1、组长任校…

4.Model Validation

你已经建立了一个模型。 但它有多好&#xff1f; 在本课程中&#xff0c;您将学习如何使用模型验证来衡量模型的质量。 测量模型质量是迭代改进模型的关键。 What is Model Validation 你几乎要评估你构建的每个模型。在大多数&#xff08;尽管不是全部&#xff09;应用中&am…

【POJ - 2195】Going Home(二分图最优匹配,费用流 或 KM)

题干&#xff1a; On a grid map there are n little men and n houses. In each unit time, every little man can move one unit step, either horizontally, or vertically, to an adjacent point. For each little man, you need to pay a $1 travel fee for every step h…

微机原理实验8254计算机钢琴,GitHub - SincereXIA/PianoMFC: 西电微机原理课设项目,键盘电子乐器演奏程序设计(电子琴),MFC...

PianoMFC西电微机原理课设项目&#xff0c;键盘电子乐器演奏程序设计(电子琴)&#xff0c;MFC需要连接西电微机原理实验室提供的 QTH9054 微机试验箱&#xff0c;使用其蜂鸣器发声&#xff0c;若不连接&#xff0c;程序会直接播放 mp3 文件模拟钢琴声。请在 release 处下载编译…

5.Underfitting and Overfitting

在这一步结束时&#xff0c;您将了解欠拟合和过拟合的概念&#xff0c;并且您将能够应用这些办法来使您的模型更准确。 Experimenting With Different Models 现在您已经有了一种可靠的方法来测量模型精度&#xff0c;您可以尝试使用其他模型&#xff0c;并查看哪种模型可以提…

福建省计算机初级职称,2019福建助理工程师职称评定条件材料及审核管理制度...

一学历、资历条件要求(破格申报不在此列&#xff0c;详情请咨询了解)申报工程技术系列中级工程师须符合下列条件之一&#xff1a;1.博士研究生毕业&#xff1b;2.硕士研究生毕业后&#xff0c;从事所申报专业工作满3年&#xff1b;3.本科毕业后&#xff0c;从事所申报专业工作满…

【POJ - 2594】Treasure Exploration(floyd传递闭包 + 最小路径覆盖,图论)

题干&#xff1a; Have you ever read any book about treasure exploration? Have you ever see any film about treasure exploration? Have you ever explored treasure? If you never have such experiences, you would never know what fun treasure exploring brings…

6.Random Forests

Introduction 决策树会让您做出艰难的决定。 有很多树叶的深树将会过拟合&#xff0c;因为每个预测都来自其叶子上只有少数房屋的历史数据。 但是叶子很少的浅树会表现不佳&#xff0c;因为它无法捕获原始数据中的许多区别。 即使在今天&#xff0c;最成熟的建模技术也面临着过…