上面并不是一个推荐的方法,因为它会引起系统的不稳定。
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, epoch, total_epochs, numpy.mean(accuracies), numpy.std(accuracies),
time / len(data_batch)
))
样本输出:
120 12 / 300 accuracy: 0.8180±0.4649 time: 56.60
f-strings 即格式化字符串在 Python 3.6 中被引入:
# 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}')
另外,写查询语句时非常方便:
query = f"INSERT INTO STATION VALUES (13, '{city}', '{state}', {latitude}, {longitude})"
「true division」和「integer division」之间的明显区别
对于数据科学来说这种改变带来了便利(但我相信对于系统编程来说不是)。
data = pandas.read_csv('timing.csv')
velocity = data['distance'] / data['time']
Python 2 中的结果依赖于『时间』和『距离』(例如,以米和秒为单位)是否被保存为整数。
在 Python 3 中,结果的表示都是精确的,因为除法的结果是浮点数。
另一个案例是整数除法,现在已经作为明确的运算:
n_gifts = money // gift_price # correct for int and float arguments
注意,该运算可以应用到内建类型和由数据包(例如,numpy 或 pandas)提供的自定义类型。
推荐:Python核心团队计划2020年停止支持Python2,NumPy宣布停止支持计划表
[Python核心团队计划在2020年停止支持Python 2。NumPy项目自2010年以来一直支持Python 2和Python 3,并且发现支持Python 2对我们有限的资源增加了负担;因此,我们最终计划
严格排序
# 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]
防止不同类型实例的偶然性的排序。
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
自然语言处理的 Unicode
s = '您好'
print(len(s))
print(s[:2])
输出:
Python 2: 6\n��
Python 3: 2\n 您好.
x = u'со'
x += 'co' # ok
x += 'со' # fail
Python 2 在此失败了,而 Python 3 可以如期工作(因为我在字符串中使用了俄文字母)。
在 Python 3 中 strs 是 Unicode 字符串,对非英语文本的 NLP 处理更加方便。
还有其它有趣的方面,例如:
'a' < type < u'a' # Python 2: True
'a' < u'a' # Python 2: False
from collections import Counter
Counter('Möbelstück')
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(在 3.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}
它同样适用于**kwargs(在 Python 3.6+版本中):它们的顺序就像参数中显示的那样。当设计数据流程时,顺序至关重要,以前,我们必须以这样繁琐的方式来编写:
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())
)
注意到了吗?名称的唯一性也会被自动检查。
迭代地拆封
# 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)
默认的 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
节省 3 倍空间,而且速度更快。实际上,类似的压缩(不过与速度无关)可以通过 protocol=2 参数来实现,但是用户通常会忽略这个选项(或者根本不知道)。
更安全的解析
labels =
predictions = [model.predict(data) for data, labels in dataset]
# labels are overwritten in Python 2
# labels are not affected by comprehension in Python 3
关于 super()
Python 2 的 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)
关于 super 和方法解析顺序的更多内容,参见 stackoverflow:
http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods
更好的 IDE 会给出变量注释
在使用 Java、C# 等语言编程的过程中最令人享受的事情是 IDE 可以提供非常好的建议,因为在执行代码之前,所有标识符的类型都是已知的。
而在 Python 中这很难实现,但是注释可以帮助你:
以清晰的形式写下你的期望
从 IDE 获取良好的建议
这是一个带变量注释的 PyCharm 示例。即使你使用的函数不带注释(例如,由于向后兼容性),它也能工作。
多种拆封(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.
可以在这个链接中查看 Python2 中的代码对比:http://stackoverflow.com/questions/38987/how-to-merge-two-
dictionaries-in-a-single-expression
aame 方法对于列表(list)、元组(tuple)和集合(set)都是有效的(a、b、c 是任意的可迭代对象):
[*a, *b, *c] # list, concatenating
(*a, *b, *c) # tuple, concatenating
{*a, *b, *c} # set, union
对于*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)
只带关键字参数的 API
我们考虑这个代码片段:
model = sklearn.svm.SVC(2, 'poly', 2, 4, 0.5)
很明显,代码的作者还没熟悉 Python 的代码风格(很可能刚从 cpp 和 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, ... )
现在,用户需要明确规定参数 sklearn.svm.SVC(C=2, kernel='poly', degree=2, gamma=4, coef0=0.5) 的命名。
这种机制使得 API 同时具备了可靠性和灵活性。
小调: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)
小调:单精度整数类型
Python 2 提供了两个基本的整数类型,即 int(64 位符号整数)和用于长时间计算的 long(在 C++变的相当莫名其妙)。
Python 3 有一个单精度类型的 int,它包含了长时间的运算。
下面是查看值是否是整数的方法:
isinstance(x, numbers.Integral) # Python 2, the canonical way
isinstance(x, (long, int)) # Python 2
isinstance(x, int) # Python 3, easier to remember
其他
Enums 有理论价值,但是 字符串输入已广泛应用在 python 数据栈中。 Enums 似乎不与 numpy 交互,并且不一定来自 pandas。
协同程序也非常有希望用于数据流程,但还没有出现大规模应用。
Python 3 有稳定的 ABI
Python 3 支持 unicode(因此ω = Δφ / Δt 也 okay),但你最好使用好的旧的 ASCII 名称
一些库比如 jupyterhub(jupyter in cloud)、django 和新版 ipython 只支持 Python 3,因此对你来讲没用的功能对于你可能只想使用一次的库很有用。
数据科学特有的代码迁移问题(以及如何解决它们)
停止对嵌套参数的支持:
map(lambda x, (y, z): x, z, dict.items())
然而,它依然完美适用于不同的理解:
{x:z for x, (y, z) in d.items()}
通常,理解在 Python 2 和 3 之间可以更好地「翻译」。
map(), .keys(), .values(), .items(), 等等返回迭代器,而不是列表。迭代器的主要问题有: 没有琐碎的分割和 无法迭代两次。 将结果转化为列表几乎可以解决所有问题。
遇到问题请参见 Python 问答:我如何移植到 Python 3?(http://eev.ee/blog/2016/07/31/python-faq-how-do-i-port-to-python-3/)
用 python 教机器学习和数据科学的主要问题
课程作者应该首先花时间解释什么是迭代器,为什么它不能像字符串那样被分片/级联/相乘/迭代两次(以及如何处理它)。
我相信大多数课程作者很高兴避开这些细节,但是现在几乎不可能。
结论
Python 2 与 Python 3 共存了近 10 年,时至今日,我们必须要说:是时候转向 Python 3 了。
研究和生产代码应该更短,更易读取,并且在迁移到 Python 3 代码库之后明显更加的安全。
现在大多数库同时支持 2.x 和 3.x 两个版本。但我们不应等到流行工具包开始停止支持 Python 2 才开始行动,提前享受新语言的功能吧。
QQ客服
公众号
手机版
帮助中心