加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python2.7到3.x迁移指南

发布时间:2020-05-24 18:42:24 所属栏目:Python 来源:互联网
导读:目前,Python科学栈中的所有主要项目都同时支持Python3.x和Python2.7,不过,这种情况很快即将结束。去年11月,Numpy团队的一份声明引发了数据科学社区的关注:这一科学计算库即将放弃对于Python2.7的支持,全面转向

目前,Python 科学栈中的所有主要项目都同时支持 Python 3.x 和 Python 2.7,不过,这种情况很快即将结束。去年 11 月,Numpy 团队的一份声明引发了数据科学社区的关注:这一科学计算库即将放弃对于 Python 2.7 的支持,全面转向 Python 3。Numpy 并不是唯一宣称即将放弃 Python 旧版本支持的工具,pandas 与 Jupyter notebook 等很多产品也在即将放弃支持的名单之中。对于数据科学开发者而言,如何将已有项目从 Python 2 转向 Python 3 成为了正在面临的重大问题。来自莫斯科大学的 Alex Rogozhnikov 博士为我们整理了一份代码迁移指南。

Python 3 功能简介

Python 是机器学习和其他科学领域中的主流语言,我们通常需要使用它处理大量的数据。Python 兼容多种深度学习框架,且具备很多优秀的工具来执行数据预处理和可视化。

但是,Python 2 和 Python 3 长期共存于 Python 生态系统中,很多数据科学家仍然使用 Python 2。2019 年底,Numpy 等很多科学计算工具都将停止支持 Python 2,而 2018 年后 Numpy 的所有新功能版本将只支持 Python 3。

为了使 Python 2 向 Python 3 的转换更加轻松,我收集了一些 Python 3 的功能,希望对大家有用。

使用 pathlib 更好地处理路径

pathlib 是 Python 3 的默认模块,帮助避免使用大量的 os.path.joins:

from pathlib import Path
dataset = 'wiki_images'
datasets_root = Path('/path/to/datasets/') 
train_path = datasets_root / dataset / 'train'
test_path = datasets_root / dataset / 'test'
for image_path in train_path.iterdir(): 
with image_path.open() as f: # note,open is a method of Path object
# do something with an image

Python 2 总是试图使用字符串级联(准确,但不好),现在有了 pathlib,代码安全、准确、可读性强。

此外,pathlib.Path 具备大量方法,这样 Python 新用户就不用每个方法都去搜索了:

p.exists()
p.is_dir()
p.parts()
p.with_name('sibling.png') # only change the name,but keep the folderp.with_suffix('.jpg') # only change the extension,but keep the folder and the name
p.chmod(mode)
p.rmdir()

pathlib 会节约大量时间,详见:

文档:https://docs.python.org/3/library/pathlib.html;

参考信息:https://pymotw.com/3/pathlib/。

类型提示(Type hinting)成为语言的一部分

Python 不只是适合脚本的语言,现在的数据流程还包括大量步骤,每一步都包括不同的框架(有时也包括不同的逻辑)。

类型提示被引入 Python,以帮助处理越来越复杂的项目,使机器可以更好地进行代码验证。而之前需要不同的模块使用自定义方式在文档字符串中指定类型(注意:PyCharm 可以将旧的文档字符串转换成新的类型提示)。

下列代码是一个简单示例,可以处理不同类型的数据(这就是我们喜欢 Python 数据栈之处)。

def repeat_each_entry(data):
""" Each entry in the data is doubled
<blah blah nobody reads the documentation till the end>
"""
index = numpy.repeat(numpy.arange(len(data)),2) 
return data[index]

上述代码适用于 numpy.array(包括多维)、astropy.Table 和 astropy.Column、bcolz、cupy、mxnet.ndarray 等。

该代码同样可用于 pandas.Series,但是方式是错误的:

repeat_each_entry(pandas.Series(data=[0,1,2],index=[3,4,5])) # returns Series with Nones inside

这是一个两行代码。想象一下复杂系统的行为多么难预测,有时一个函数就可能导致错误的行为。明确了解哪些类型方法适合大型系统很有帮助,它会在函数未得到此类参数时给出提醒。

def repeat_each_entry(data: Union[numpy.ndarray,bcolz.carray]):

如果你有一个很棒的代码库,类型提示工具如 MyPy 可能成为集成流程中的一部分。不幸的是,提示没有强大到足以为 ndarrays/tensors 提供细粒度类型,但是或许我们很快就可以拥有这样的提示工具了,这将是 DS 的伟大功能。

类型提示 → 运行时的类型检查

默认情况下,函数注释不会影响代码的运行,不过它也只能帮你指出代码的意图。

但是,你可以在运行时中使用 enforce 等工具强制进行类型检查,这可以帮助你调试代码(很多情况下类型提示不起作用)。

@enforce.runtime_validation
def foo(text: str) -> None: 
print(text)
foo('Hi') # ok
foo(5) # fails
@enforce.runtime_validation
def any2(x: List[bool]) -> bool: 
return any(x)
any ([False,False,True,False]) # True
any2([False,False]) # True
any (['False']) # True
any2(['False']) # fails
any ([False,None,"",0]) # False
any2([False,0]) # fails

函数注释的其他用处

如前所述,注释不会影响代码执行,而且会提供一些元信息,你可以随意使用。

例如,计量单位是科学界的一个普遍难题,astropy 包提供一个简单的装饰器(Decorator)来控制输入量的计量单位,并将输出转换成所需单位。

# Python 3
from astropy import units as u
@u.quantity_input()
def frequency(speed: u.meter / u.s,wavelength: u.m) -> u.terahertz: 
return speed / wavelength
frequency(speed=300_000 * u.km / u.s,wavelength=555 * u.nm)
# output: 540.5405405405404 THz,frequency of green visible light

如果你拥有 Python 表格式科学数据(不必要太多),你应该尝试一下 astropy。你还可以定义针对某个应用的装饰器,用同样的方式来控制/转换输入和输出。

通过 @ 实现矩阵乘法

下面,我们实现一个最简单的机器学习模型,即带 L2 正则化的线性回归:

# l2-regularized linear regression: || AX - b ||^2 + alpha * ||x||^2 -> min# 
Python 2
X = np.linalg.inv(np.dot(A.T,A) + alpha * np.eye(A.shape[1])).dot(A.T.dot(b))
# Python 3
X = np.linalg.inv(A.T @ A + alpha * np.eye(A.shape[1])) @ (A.T @ b)

下面 Python 3 带有 @ 作为矩阵乘法的符号更具有可读性,且更容易在深度学习框架中转译:因为一些如 X @ W + b[None,:] 的代码在 numpy、cupy、pytorch 和 tensorflow 等不同库下都表示单层感知机。

使用 ** 作为通配符

递归文件夹的通配符在 Python2 中并不是很方便,因此才存在定制的 glob2 模块来克服这个问题。递归 flag 在 Python 3.6 中得到了支持。

import glob
# Python 2
found_images =  
glob.glob('/path/*.jpg')  
+ glob.glob('/path/*/*.jpg')  
+ glob.glob('/path/*/*/*.jpg')  
+ glob.glob('/path/*/*/*/*.jpg')  
+ glob.glob('/path/*/*/*/*/*.jpg') 
# Python 3
found_images = glob.glob('/path/**/*.jpg',recursive=True)

python3 中更好的选择是使用 pathlib:

# Python 3
found_images = pathlib.Path('/path/').glob('**/*.jpg')

Print 在 Python3 中是函数

Python 3 中使用 Print 需要加上麻烦的圆括弧,但它还是有一些优点。

使用文件描述符的简单句法:

print >>sys.stderr,"critical error" # Python 2
print("critical error",file=sys.stderr) # Python 3

在不使用 str.join 下输出 tab-aligned 表格:

# Python 3
print(*array,sep='t')
print(batch,epoch,loss,accuracy,time,sep='t')

修改与重新定义 print 函数的输出:

# Python 3
_print = print # store the original print function
def print(*args,**kargs): 
pass # do something useful,e.g. store output to some file

在 Jupyter 中,非常好的一点是记录每一个输出到独立的文档,并在出现错误的时候追踪出现问题的文档,所以我们现在可以重写 print 函数了。

在下面的代码中,我们可以使用上下文管理器暂时重写 print 函数的行为:

@contextlib.contextmanager
def replace_print(): 
import builtins 
_print = print # saving old print function 
# or use some other function here 
builtins.print = lambda *args,**kwargs: _print('new printing',*args,**kwargs) 
yield 
builtins.print = _print
with replace_print(): 
<code here will invoke other print function>

上面并不是一个推荐的方法,因为它会引起系统的不稳定。

print 函数可以加入列表解析和其它语言构建结构。

# Python 3
result = process(x) if is_valid(x) else print('invalid item: ',x)

f-strings 可作为简单和可靠的格式化

默认的格式化系统提供了一些灵活性,且在数据实验中不是必须的。但这样的代码对于任何修改要么太冗长,要么就会变得很零碎。而代表性的数据科学需要以固定的格式迭代地输出一些日志信息,通常需要使用的代码如下:

# Python 2
print('{batch:3} {epoch:3} / {total_epochs:3} accuracy: {acc_mean:0.4f}±{acc_std:0.4f} time: {avg_time:3.2f}'.format( 
batch=batch,epoch=epoch,total_epochs=total_epochs,acc_mean=numpy.mean(accuracies),acc_std=numpy.std(accuracies),avg_time=time / len(data_batch)))# Python 2 (too error-prone during fast modifications,please avoid):
print('{:3} {:3} / {:3} accuracy: {:0.4f}±{:0.4f} time: {:3.2f}'.format( 
batch,total_epochs,numpy.mean(accuracies),numpy.std(accuracies),time / len(data_batch)))

样本输出:

120 12 / 300 accuracy: 0.8180±0.4649 time: 56.60

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读