python2迁移python3的问题

使用 pathlib 模块来更好地处理路径php

pathlib 是 Python 3默认的用于处理数据路径的模块,它可以帮助咱们避免使用大量的 os.path.joins语句:css

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

向左滑动查看完整代码html

在Python2中,咱们须要经过级联字符串的造成来实现路径的拼接。而如今有了pathlib模块后,数据路径处理将变得更加安全、准确,可读性更强。python

此外,pathlib.Path含有大量的方法,这样Python的初学者将再也不须要搜索每一个方法:git

p.exists() p.is_dir() p.parts() p.with_name('sibling.png') # only change the name, but keep the folder p.with_suffix('.jpg') # only change the extension, but keep the folder and the name p.chmod(mode) p.rmdir()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

使用pathlib还将大大节约你的时间。更多功能请查看:github

官方文档 - https://docs.python.org/3/library/pathlib.html 
参考信息 - https://pymotw.com/3/pathlib/算法

类型提示(Type hinting)成为Python3中的新成员sql

下面是在编译器PyCharm 中,类型提示功能的一个示例: 
 
这里写图片描述express

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

Python3中引入了类型提示工具包来处理复杂的大型项目,使机器能够更好地对代码进行验证。而在这以前,不一样的模块须要使用自定义的方式,对文档中的字符串指定类型 (注意:PyCharm能够将旧的文档字符串转换成新的类型提示)。

下面是一个简单的代码示例,利用类型提示功能来处理不一样类型的数据:

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]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

上述代码对多维的 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
  • 1

这仅仅是一段两行的代码。因此,复杂系统的行为是很是难预测的,有时一个函数就可能致使整个系统的错误。所以,明确地了解哪些类型方法,并在这些类型方法未获得相应参数的时候发出错误提示,这对于大型系统的运做是颇有帮助的。

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

若是你有一个很棒的代码库,诸如 MyPy这样的类型提示工具将可能成为一个大型项目的集成流程中的一部分。不幸的是,类型提示功能还没办法强大到为 ndarrays/tensors 这种细粒度类型发出提示。或许,不久的未来咱们就能够拥有这样全面的的类型提示工具,这将成为数据科学领域须要的强大功能。

从类型提示(运行前)到类型检查(运行时)

默认状况下,函数的注释对于代码的运行是没有影响的,它只是帮你指出每段代码所要作的工做。

在代码运行阶段,不少时候类型提示工具是不起做用的。这种状况你可使用 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, False]) # True any (['False']) # True any2(['False']) # fails any ([False, None, "", 0]) # False any2([False, None, "", 0]) # fails
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

函数注释的其余用途

正如上面咱们提到的,函数的注释部分不只不会影响代码的执行,还会提供能够随时使用的一些元信息(meta-information)。

例如,计量单位是科学界的一个广泛难题,Python3中的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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

若是你须要用Python处理表格类型的科学数据,你能够尝试astropy包,体验一下计量单位随意转换的方便性。你还能够针对某个应用专门定义一个装饰器,用一样的方式来控制或转换输入和输出的计量单位。

经过 @ 实现矩阵乘法

下面,咱们实现一个最简单的机器学习模型,即带 L2 正则化的线性回归 (如岭回归模型),来对比 Python2 和 Python3 之间的差异:

# 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

在 Python3 中,以@做为矩阵乘法符号使得代码总体的可读性更强,且更容易在不一样的深度学习框架间进行转译:由于一些代码如 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Python3 中更好的选择是使用 pathlib:(缺乏个import)

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

Python3中的print函数

诚然,print 在 Python3 中是一个函数,使用 print 须要加上圆括弧(),虽然这是个麻烦的操做,但它仍是具备一些优势:

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

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

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

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

修改与从新定义 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
  • 1
  • 2
  • 3
  • 4

在 Jupyter notebook 中,这种形式可以记录每个独立的文档输出,并在出现错误的时候追踪到报错的文档。这能方便咱们快速定位并解决错误信息。所以咱们能够重写 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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

可是,重写print函数的行为,咱们并不推荐,由于它会引发系统的不稳定。

print函数能够结合列表生成器或其它语言结构一块儿使用。

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

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, epoch, total_epochs, numpy.mean(accuracies), numpy.std(accuracies), time / len(data_batch) ))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

样本输出为:

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

Python 3.6 中引入了格式化字符串 (f-strings):

# Python 3.6+ print(f'{batch:3} {epoch:3} / {total_epochs:3} accuracy: {numpy.mean(accuracies):0.4f}±{numpy.std(accuracies):0.4f} time: {time / len(data_batch):3.2f}')
  • 1
  • 2

另外,这对于查询语句的书写也是很是方便的:

query = f"INSERT INTO STATION VALUES (13, '{city}', '{state}', {latitude}, {longitude})"
  • 1

「true division」和「integer division」之间的明显区别

虽说对于系统编程来讲,Python3所提供的改进还远远不够,但这些便利对于数据科学来讲已经足够。

data = pandas.read_csv('timing.csv') velocity = data['distance'] / data['time']
  • 1
  • 2

Python 2 中的结果依赖于『时间』和『距离』(例如,以米和秒为单位),关注其是否被保存为整数。

而在 Python 3 中,结果的表示都是精确的,由于除法运算获得的都是精确的浮点数。

另外一个例子是整数除法,如今已经做为明确的运算:

n_gifts = money // gift_price  # correct for int and float arguments
  • 1

值得注意的是,整除运算能够应用到Python的内建类型和由numpy、pandas等数据包提供的自定义类型。

严格排序

下面是一个严格排序的例子:

# All these comparisons are illegal in Python 3 3 < '3' 2 < None (3, 4) < (3, None) (4, 5) < [4, 5] # False in both Python 2 and Python 3 (4, 5) == [4, 5]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

严格排序的主要功能有:

防止不一样类型实例之间的偶然性排序。 
“` 
sorted([2, ‘1’, 3]) # invalid for Python 3, in Python 2 returns [2, 3, ‘1’]

在处理原始数据时帮助咱们发现存在的问题。此外,严格排序对None值的合适性检查是(这对于两个版本的 Python 都适用): ``` if a is not None: pass if a: # WRONG check for None pass
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

天然语言处理中的Unicode编码

下面来看一个天然语言处理任务:

s = '您好' print(len(s)) print(s[:2])
  • 1
  • 2
  • 3

比较两个版本Python的输出:

Python2: 6\n�� 
Python3: 2\n 您好

再来看个例子:

x = u'со' x += 'co' # ok x += 'со' # fail
  • 1
  • 2
  • 3

在这里,Python 2 会报错,而 Python 3 可以正常工做。由于我在字符串中使用了俄文字母,对于Python2 是没法识别或编码这样的字符。

Python 3 中的 strs 是 Unicode 字符串,这对非英语文本的天然语言处理任务来讲将更加地方便。还有些其它有趣的应用,例如:

'a' < type < u'a' # Python 2: True 'a' < u'a' # Python 2: False
  • 1
  • 2

from collections import Counter Counter('Möbelstück')
  • 1
  • 2

Python 2: Counter({‘\xc3’: 2, ‘b’: 1, ‘e’: 1, ‘c’: 1, ‘k’: 1, ‘M’: 1, ‘l’: 1, ‘s’: 1, ‘t’: 1, ‘\xb6’: 1, ‘\xbc’: 1}) 
Python 3: Counter({‘M’: 1, ‘ö’: 1, ‘b’: 1, ‘e’: 1, ‘l’: 1, ‘s’: 1, ‘t’: 1, ‘ü’: 1, ‘c’: 1, ‘k’: 1})

对于这些,Python 2 也能正常地工做,但 Python 3 的支持更为友好。

▌保留词典和**kwargs 的顺序

CPython 3.6+ 的版本中字典的默认行为是一种相似 OrderedDict 的类,但最新的 Python3.7 版本,此类已经获得了全面的支持。这就要求在字典理解、json 序列化/反序列化等操做中保持字典原先的顺序。

下面来看个例子:

import json x = {str(i):i for i in range(5)} json.loads(json.dumps(x)) # Python 2 {u'1': 1, u'0': 0, u'3': 3, u'2': 2, u'4': 4} # Python 3 {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

这种保顺性一样适用于 Python3.6 版本中的 **kwargs:它们的顺序就像参数中显示的那样。当设计数据流程时,参数的顺序相当重要。

之前,咱们必须以这样繁琐的方式来编写:

from torch import nn # Python 2 model = nn.Sequential(OrderedDict([ ('conv1', nn.Conv2d(1,20,5)), ('relu1', nn.ReLU()), ('conv2', nn.Conv2d(20,64,5)), ('relu2', nn.ReLU()) ])) # Python 3.6+, how it *can* be done, not supported right now in pytorch model = nn.Sequential( conv1=nn.Conv2d(1,20,5), relu1=nn.ReLU(), conv2=nn.Conv2d(20,64,5), relu2=nn.ReLU()) ) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

注意到了吗?名称的惟一性也会被自动检查。

迭代拆封

Python3 中引入迭代式拆封功能,下面来看一段代码:

# handy when amount of additional stored info may vary between experiments, but the same code can be used in all cases
model_paramteres, optimizer_parameters, *other_params = load(checkpoint_name) # picking two last values from a sequence *prev, next_to_last, last = values_history # This also works with any iterables, so if you have a function that yields e.g. qualities, # below is a simple way to take only last two values from a list *prev, next_to_last, last = iter_train(args) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

默认的 pickle 引擎为数组提供更好的压缩

Python3 中引入 pickle 引擎,为数组提供更好的压缩,节省参数空间:

# Python 2 import cPickle as pickle import numpy print len(pickle.dumps(numpy.random.normal(size=[1000, 1000]))) # result: 23691675 # Python 3 import pickle import numpy len(pickle.dumps(numpy.random.normal(size=[1000, 1000]))) # result: 8000162 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

这个小的改进节省了3倍的空间,并且运行阶段速度更快。实际上,若是不关心速度的话,相似的压缩性能也能够经过设置参数 protocol=2 来实现,可是用户常常会忽略这个选项或者根本不了解这个功能。

更安全的解析功能

Python3 能为代码提供更安全的解析,提升代码的可读性。具体以下段代码所示:

labels = <initial_value>
predictions = [model.predict(data) for data, labels in dataset] # labels are overwritten in Python 2 # labels are not affected by comprehension in Python 3 
  • 1
  • 2
  • 3
  • 4
  • 5

关于 super(),simply super()

Python2 中的 super() 方法,是常见的错误代码。咱们来看这段代码:

# Python 2 class MySubClass(MySuperClass): def __init__(self, name, **options): super(MySubClass, self).__init__(name='subclass', **options) # Python 3 class MySubClass(MySuperClass): def __init__(self, name, **options): super().__init__(name='subclass', **options)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

有关 super() 方法及方法解析顺序的更多内容,参见 stackoverflow: 
https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods

更好的 IDE 会给出变量注释

编程过程当中使用一个好的IDE,可以给初学者一种更好的编程体验。一个好的IDE可以给不一样的编程语言如Java、C#等,提供友好的编程环境及很是有用的编程建议,由于在执行代码以前,全部标识符的类型都是已知的。

对于 Python,虽然这些 IDE 的功能是很难实现,可是代码的注释可以在编程过程帮助到咱们:

  • 以清晰的形式提示你下一步想要作的
  • 从 IDE 获取良好的建议

这是 PyCharm IDE 的一个示例。虽然例子中所使用的函数不带注释,可是这些带注释的变量,利用代码的后向兼容性,也能保证程序的正常工做。

多种拆封(unpacking)

下面是 Python3 中字典融合的代码示例:

x = dict(a=1, b=2) y = dict(b=3, d=4) # Python 3.5+ z = {**x, **y} # z = {'a': 1, 'b': 3, 'd': 4}, note that value for `b` is taken from the latter dict.
  • 1
  • 2
  • 3
  • 4
  • 5

若是你想对比两个版本之间的差别性,能够参考如下这个连接来了解更多的信息: 
https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression

aame 方法对于 Python 中的列表(list)、元组(tuple)和集合(set)等类型都是有效的,经过下面这段代码咱们可以更清楚地了解它们的工做原理,其中a、b、c是任意的可迭代对象:

[*a, *b, *c] # list, concatenating (*a, *b, *c) # tuple, concatenating {*a, *b, *c} # set, union 
  • 1
  • 2
  • 3

此外,函数一样支持 *args 和 **kwargs 的 unpacking 过程:

Python 3.5+ do_something(**{**default_settings, **custom_settings}) # Also possible, this code also checks there is no intersection between keys of dictionaries do_something(**first_args, **second_args)
  • 1
  • 2
  • 3
  • 4

不会过期的技术—只带关键字参数的 API

咱们来看这段代码:

model = sklearn.svm.SVC(2, 'poly', 2, 4, 0.5)
  • 1

显而易见,这段代码的做者还不熟悉 Python 的代码风格,极可能刚从 C++ 或 rust语言转 Python。代码风格不只是我的偏好的问题,还由于在 SVC 接口中改变参数顺序(adding/deleting)会使代码无效。特别是对于 sklearn,常常要经过从新排序或重命名大量的算法参数以提供一致的 API。而每次的重构均可能使代码失效。

在 Python3中依赖库的编写者一般会须要使用*以明确地命名参数:

class SVC(BaseSVC):
    def __init__(self, *, C=1.0, kernel='rbf', degree=3, gamma='auto', coef0=0.0, ... )
  • 1
  • 2

使用时,用户须要明确规定 sklearn.svm.SVC(C=2, kernel=’poly’, degree=2, gamma=4, coef0=0.5) 中参数的命名。 
这种参数命名机制使得 API 同时兼具可靠性和灵活性。

微调:math模块中的常量

Python3 中 math 模块的改动,能够查看下面这段代码:

# Python 3 math.inf # 'largest' number math.nan # not a number max_quality = -math.inf # no more magic initial values! for model in trained_models: max_quality = max(max_quality, compute_quality(model, data))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

微调:单精度整数类型

Python 2 中提供了两种基本的整数类型,即 int(64 位符号整数)和用于长整型数值计算的 long 类型(长整型)。而在 Python 3 中对单精度的整型数据有个微小的改动,使其包含长整型(long) 的运算。下面这段代码教你如何查看整型值:

isinstance(x, numbers.Integral) # Python 2, the canonical way isinstance(x, (long, int)) # Python 2 isinstance(x, int) # Python 3, easier to remember
  • 1
  • 2
  • 3

其余改动

  • Enums 的改动具备理论价值,是由于字符串输入已普遍应用在 python 数据栈中。Enums - 虽然不与 numpy 库交互,可是在 pandas 中有良好的兼容性。
  • 协同程序将颇有可能用于数据流程的处理,虽然目前尚未大规模应用的出现。
  • Python 3 有稳定的 ABI。
  • Python 3 支持 unicode 编码格式,如 ω = Δφ / Δt 也是能够容许的,但最好使用兼容性更好的旧 ASCII 名称。
  • 一些库好比 jupyterhub(jupyter in cloud)、django 和新版 ipython 都只支持 Python 3,所以这些用处不大的库对你来说,可能只会偶尔使用一次。

数据科学中代码迁移所会碰到的问题及解决方案

放弃对嵌套参数的支持:

map(lambda x, (y, z): x, z, dict.items())
  • 1

然而,它依然可以完美地适用于不一样的理解:

{x:z for x, (y, z) in d.items()}
  • 1

一般,理解在 Python2 和 3 之间差别可以帮助咱们更好地‘转义’代码。

map(), .keys(), .values(), .items() 等等,返回的是迭代器而不是列表。迭代器的主要问题包括:没有琐碎的分割,以及没法进行二次迭代。将返回的结果转化为列表几乎能够解决全部问题。

如遇到其余问题请参见这篇有关 Python 的问答:“如何将 Python3 移植到个人程序中?”( https://eev.ee/blog/2016/07/31/python-faq-how-do-i-port-to-python-3/)

Python 机器学习和 python 数据科学领域所会碰到的主要问题

这些课程的做者首先要花点时间解释 python 中什么是迭代器,为何它不能像字符串那样被分片/级联/相乘/二次迭代(以及如何处理它)。

我相信大多数课程的做者都很但愿可以避开这些繁琐的细节,可是如今看来这几乎是个不可避免的话题。

结论

Python 的两个版本( Python2 与 Python3 )共存了近10年的时间。时至今日,咱们不得不说:是时候该转向 Python 3 了。

科学研究和实际生产中,代码应该更短,可读性更强,而且在迁移到 Python 3 后的代码库将更加得安全。

目前 Python 的大多数库仍同时支持 2.x 和 3.x 两个版本。但咱们不该等到这些依赖库开始中止支持 Python 2 才开始转向 Python3,咱们如今就能够享受新语言的功能。

迁移到 Python3 后,我敢保证你的程序运行会更加顺畅:「咱们不会再作向后不兼容的事情了(https://snarky.ca/why-python-3-exists/)」。

参考内容:

Key differences between Python 2.7 and Python 3.x 
http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html 
Python FAQ: How do I port to Python 3? 
https://eev.ee/blog/2016/07/31/python-faq-how-do-i-port-to-python-3/ 
10 awesome features of Python that you can’t use because you refuse to 
upgrade to Python 3 
http://www.asmeurer.com/python3-presentation/slides.html Trust me, 
python 3.3 is better than 2.7 (video) 
http://pyvideo.org/pycon-us-2013/python-33-trust-me-its-better-than-27.html 
Python 3 for scientists 
http://python-3-for-scientists.readthedocs.io/en/latest/

原文连接: 
https://github.com/arogozhnikov/python3_with_pleasure#future-proof-apis-with-keyword-only-arguments

相关文章
相关标签/搜索