歡迎光臨
每天分享高質量文章

Python 2.7 即將停止支援,請收下這份 3.x 遷移指南

本文經機器之心(微信公眾號:almosthuman2014)授權轉載,禁止二次轉載

文地址:https://github.com/arogozhnikov/python3_with_pleasure

選自GitHub,作者:Alex Rogozhnikov,機器之心編譯


目前,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:


  1. from pathlib import Path

  2. dataset = 'wiki_images'

  3. datasets_root = Path('/path/to/datasets/')

  4. train_path = datasets_root / dataset / 'train'

  5. test_path = datasets_root / dataset / 'test'

  6. for image_path in train_path.iterdir():

  7.    with image_path.open() as f: # note, open is a method of Path object

  8.        # do something with an image


Python 2 總是試圖使用字串級聯(準確,但不好),現在有了 pathlib,程式碼安全、準確、可讀性強。


此外,pathlib.Path 具備大量方法,這樣 Python 新使用者就不用每個方法都去搜索了:


  1. p.exists()

  2. p.is_dir()

  3. p.parts()

  4. p.with_name('sibling.png') # only change the name, but keep the folder

  5. p.with_suffix('.jpg') # only change the extension, but keep the folder and the name

  6. p.chmod(mode)

  7. p.rmdir()


pathlib 會節約大量時間,詳見:


  • 檔案:https://docs.python.org/3/library/pathlib.html;

  • 參考資訊:https://pymotw.com/3/pathlib/。


型別提示(Type hinting)成為語言的一部分


PyCharm 中的型別提示示例:


Python 不只是適合指令碼的語言,現在的資料流程還包括大量步驟,每一步都包括不同的框架(有時也包括不同的邏輯)。


型別提示被引入 Python,以幫助處理越來越複雜的專案,使機器可以更好地進行程式碼驗證。而之前需要不同的模組使用自定義方式在檔案字串中指定型別(註意:PyCharm 可以將舊的檔案字串轉換成新的型別提示)。


下列程式碼是一個簡單示例,可以處理不同型別的資料(這就是我們喜歡 Python 資料棧之處)。


  1. def repeat_each_entry(data):

  2.    """ Each entry in the data is doubled

  3.    

  4.    """

  5.    index = numpy.repeat(numpy.arange(len(data)), 2)

  6.    return data[index]

上述程式碼適用於 numpy.array(包括多維)、astropy.Table 和 astropy.Column、bcolz、cupy、mxnet.ndarray 等。


該程式碼同樣可用於 pandas.Series,但是方式是錯誤的:


  1. 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]):

如果你有一個很棒的程式碼庫,型別提示工具如 MyPy 可能成為整合流程中的一部分。不幸的是,提示沒有強大到足以為 ndarrays/tensors 提供細粒度型別,但是或許我們很快就可以擁有這樣的提示工具了,這將是 DS 的偉大功能。


型別提示 → 執行時的型別檢查


預設情況下,函式註釋不會影響程式碼的執行,不過它也只能幫你指出程式碼的意圖。


但是,你可以在執行時中使用 enforce 等工具強制進行型別檢查,這可以幫助你除錯程式碼(很多情況下型別提示不起作用)。


  1. @enforce.runtime_validation

  2. def foo(text: str) -> None:

  3.    print(text)

  4. foo('Hi') # ok

  5. foo(5)    # fails

  6. @enforce.runtime_validation

  7. def any2(x: List[bool]) -> bool:

  8.    return any(x)

  9. any ([False, False, True, False]) # True

  10. any2([False, False, True, False]) # True

  11. any (['False']) # True

  12. any2(['False']) # fails

  13. any ([False, None, "", 0]) # False

  14. any2([False, None, "", 0]) # fails

函式註釋的其他用處


如前所述,註釋不會影響程式碼執行,而且會提供一些元資訊,你可以隨意使用。


例如,計量單位是科學界的一個普遍難題,astropy 包提供一個簡單的裝飾器(Decorator)來控制輸入量的計量單位,並將輸出轉換成所需單位。


  1. # Python 3

  2. from astropy import units as u

  3. @u.quantity_input()

  4. def frequency(speed: u.meter / u.s, wavelength: u.m) -> u.terahertz:

  5.    return speed / wavelength

  6. frequency(speed=300_000 * u.km / u.s, wavelength=555 * u.nm)

  7. # output: 540.5405405405404 THz, frequency of green visible light

如果你擁有 Python 表格式科學資料(不必要太多),你應該嘗試一下 astropy。你還可以定義針對某個應用的裝飾器,用同樣的方式來控制/轉換輸入和輸出。


透過 @ 實現矩陣乘法


下麵,我們實現一個最簡單的機器學習模型,即帶 L2 正則化的線性回歸:


  1. # l2-regularized linear regression: || AX - b ||^2 + alpha * ||x||^2 -> min

  2. # Python 2

  3. X = np.linalg.inv(np.dot(A.T, A) + alpha * np.eye(A.shape[1])).dot(A.T.dot(b))

  4. # Python 3

  5. 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 中得到了支援。


  1. import glob

  2. # Python 2

  3. found_images =

  4.    glob.glob('/path/*.jpg')

  5.  + glob.glob('/path/*/*.jpg')

  6.  + glob.glob('/path/*/*/*.jpg')

  7.  + glob.glob('/path/*/*/*/*.jpg')

  8.  + glob.glob('/path/*/*/*/*/*.jpg')

  9. # Python 3

  10. found_images = glob.glob('/path/**/*.jpg', recursive=True)

python3 中更好的選擇是使用 pathlib:


  1. # Python 3

  2. found_images = pathlib.Path('/path/').glob('**/*.jpg')

Print 在 Python3 中是函式


Python 3 中使用 Print 需要加上麻煩的圓括弧,但它還是有一些優點。


使用檔案描述符的簡單句法:


  1. print >>sys.stderr, "critical error"      # Python 2

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

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


  1. # Python 3

  2. print(*array, sep=' ')

  3. print(batch, epoch, loss, accuracy, time, sep=' ')

修改與重新定義 print 函式的輸出:


  1. # Python 3

  2. _print = print # store the original print function

  3. def print(*args, **kargs):

  4.    pass  # do something useful, e.g. store output to some file

在 Jupyter 中,非常好的一點是記錄每一個輸出到獨立的檔案,併在出現錯誤的時候追蹤出現問題的檔案,所以我們現在可以重寫 print 函式了。


在下麵的程式碼中,我們可以使用背景關係管理器暫時重寫 print 函式的行為:


  1. @contextlib.contextmanager

  2. def replace_print():

  3.    import builtins

  4.    _print = print # saving old print function

  5.    # or use some other function here

  6.    builtins.print = lambda *args, **kwargs: _print('new printing', *args, **kwargs)

  7.    yield

  8.    builtins.print = _print

  9. with replace_print():

  10.    <code here will invoke other print function>

上面並不是一個推薦的方法,因為它會引起系統的不穩定。


print 函式可以加入串列解析和其它語言構建結構。


  1. # Python 3

  2. result = process(x) if is_valid(x) else print('invalid item: ', x)

f-strings 可作為簡單和可靠的格式化


預設的格式化系統提供了一些靈活性,且在資料實驗中不是必須的。但這樣的程式碼對於任何修改要麼太冗長,要麼就會變得很零碎。而代表性的資料科學需要以固定的格式迭代地輸出一些日誌資訊,通常需要使用的程式碼如下:


  1. # Python 2

  2. print('{batch:3} {epoch:3} / {total_epochs:3}  accuracy: {acc_mean:0.4f}±{acc_std:0.4f} time: {avg_time:3.2f}'.format(

  3.    batch=batch, epoch=epoch, total_epochs=total_epochs,

  4.    acc_mean=numpy.mean(accuracies), acc_std=numpy.std(accuracies),

  5.    avg_time=time / len(data_batch)

  6. ))

  7. # Python 2 (too error-prone during fast modifications, please avoid):

  8. print('{:3} {:3} / {:3}  accuracy: {:0.4f}±{:0.4f} time: {:3.2f}'.format(

  9.    batch, epoch, total_epochs, numpy.mean(accuracies), numpy.std(accuracies),

  10.    time / len(data_batch)

  11. ))

樣本輸出:


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

f-strings 即格式化字串在 Python 3.6 中被引入:


  1. # Python 3.6+

  2. 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. query = f"INSERT INTO STATION VALUES (13, '{city}', '{state}', {latitude}, {longitude})"

「true division」和「integer division」之間的明顯區別


對於資料科學來說這種改變帶來了便利(但我相信對於系統程式設計來說不是)。


  1. data = pandas.read_csv('timing.csv')

  2. velocity = data['distance'] / data['time']

Python 2 中的結果依賴於『時間』和『距離』(例如,以米和秒為單位)是否被儲存為整數。


在 Python 3 中,結果的表示都是精確的,因為除法的結果是浮點數。


另一個案例是整數除法,現在已經作為明確的運算:


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

註意,該運算可以應用到內建型別和由資料包(例如,numpy 或 pandas)提供的自定義型別。


嚴格排序


  1. # All these comparisons are illegal in Python 3

  2. 3 < '3'

  3. 2 < None

  4. (3, 4) < (3, None)

  5. (4, 5) < [4, 5]

  6. # False in both Python 2 and Python 3

  7. (4, 5) == [4, 5]

防止不同型別實體的偶然性的排序。


  1. sorted([2, '1', 3])  # invalid for Python 3, in Python 2 returns [2, 3, '1']

在處理原始資料時幫助發現存在的問題。


旁註:對 None 的合適檢查是(兩個版本的 Python 都適用):


  1. if a is not None:

  2.  pass

  3. if a: # WRONG check for None

  4.  pass

自然語言處理的 Unicode


  1. s = '您好'

  2. print(len(s))

  3. print(s[:2])

輸出:

  • Python 2: 6
    ��

  • Python 3: 2
    您好.

  1. x = u'со'

  2. x += 'co' # ok

  3. x += 'со' # fail

Python 2 在此失敗了,而 Python 3 可以如期工作(因為我在字串中使用了俄文字母)。

在 Python 3 中 strs 是 Unicode 字串,對非英語文字的 NLP 處理更加方便。


還有其它有趣的方面,例如:


  1. 'a' < type < u'a'  # Python 2: True

  2. 'a' < u'a'         # Python 2: False

  1. from collections import Counter

  2. Counter('Möbelstück')

  • Python 2: Counter({'Ã': 2, 'b': 1, 'e': 1, 'c': 1, 'k': 1, 'M': 1, 'l': 1, 's': 1, 't': 1, '¶': 1, '¼': 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 序列化/反序列化期間)保持順序。


  1. import json

  2. x = {str(i):i for i in range(5)}

  3. json.loads(json.dumps(x))

  4. # Python 2

  5. {u'1': 1, u'0': 0, u'3': 3, u'2': 2, u'4': 4}

  6. # Python 3

  7. {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4}

它同樣適用於**kwargs(在 Python 3.6+版本中):它們的順序就像引數中顯示的那樣。當設計資料流程時,順序至關重要,以前,我們必須以這樣繁瑣的方式來編寫:


  1. from torch import nn

  2. # Python 2

  3. model = nn.Sequential(OrderedDict([

  4.          ('conv1', nn.Conv2d(1,20,5)),

  5.          ('relu1', nn.ReLU()),

  6.          ('conv2', nn.Conv2d(20,64,5)),

  7.          ('relu2', nn.ReLU())

  8.        ]))

  9. # Python 3.6+, how it *can* be done, not supported right now in pytorch

  10. model = nn.Sequential(

  11.    conv1=nn.Conv2d(1,20,5),

  12.    relu1=nn.ReLU(),

  13.    conv2=nn.Conv2d(20,64,5),

  14.    relu2=nn.ReLU())

  15. )        

註意到了嗎?名稱的唯一性也會被自動檢查。


迭代地拆封


  1. # handy when amount of additional stored info may vary between experiments, but the same code can be used in all cases

  2. model_paramteres, optimizer_parameters, *other_params = load(checkpoint_name)

  3. # picking two last values from a sequence

  4. *prev, next_to_last, last = values_history

  5. # This also works with any iterables, so if you have a function that yields e.g. qualities,

  6. # below is a simple way to take only last two values from a list

  7. *prev, next_to_last, last = iter_train(args)

預設的 pickle 引擎為陣列提供更好的壓縮


  1. # Python 2

  2. import cPickle as pickle

  3. import numpy

  4. print len(pickle.dumps(numpy.random.normal(size=[1000, 1000])))

  5. # result: 23691675

  6. # Python 3

  7. import pickle

  8. import numpy

  9. len(pickle.dumps(numpy.random.normal(size=[1000, 1000])))

  10. # result: 8000162

節省 3 倍空間,而且速度更快。實際上,類似的壓縮(不過與速度無關)可以透過 protocol=2 引數來實現,但是使用者通常會忽略這個選項(或者根本不知道)。


更安全的解析


  1. labels = <initial_value>

  2. predictions = [model.predict(data) for data, labels in dataset]

  3. # labels are overwritten in Python 2

  4. # labels are not affected by comprehension in Python 3

關於 super()


Python 2 的 super(...)是程式碼錯誤中的常見原因。


  1. # Python 2

  2. class MySubClass(MySuperClass):

  3.    def __init__(self, name, **options):

  4.        super(MySubClass, self).__init__(name='subclass', **options)

  5. # Python 3

  6. class MySubClass(MySuperClass):

  7.    def __init__(self, name, **options):

  8.        super().__init__(name='subclass', **options)

關於 super 和方法解析順序的更多內容,參見 stackoverflow:https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods


更好的 IDE 會給出變數註釋


在使用 Java、C# 等語言程式設計的過程中最令人享受的事情是 IDE 可以提供非常好的建議,因為在執行程式碼之前,所有識別符號的型別都是已知的。


而在 Python 中這很難實現,但是註釋可以幫助你:

  • 以清晰的形式寫下你的期望

  • 從 IDE 獲取良好的建議

這是一個帶變數註釋的 PyCharm 示例。即使你使用的函式不帶註釋(例如,由於向後相容性),它也能工作。


多種拆封(unpacking)


在 Python3 中融合兩個字典的程式碼示例:


  1. x = dict(a=1, b=2)

  2. y = dict(b=3, d=4)

  3. # Python 3.5+

  4. z = {**x, **y}

  5. # z = {'a': 1, 'b': 3, 'd': 4}, note that value for `b` is taken from the latter dict.


可以在這個連結中檢視 Python2 中的程式碼對比:https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression


aame 方法對於串列(list)、元組(tuple)和集合(set)都是有效的(a、b、c 是任意的可迭代物件):


  1. [*a, *b, *c] # list, concatenating

  2. (*a, *b, *c) # tuple, concatenating

  3. {*a, *b, *c} # set, union



對於*args 和 **kwargs,函式也支援額外的 unpacking:


  1. Python 3.5+

  2. do_something(**{**default_settings, **custom_settings})

  3. # Also possible, this code also checks there is no intersection between keys of dictionaries

  4. do_something(**first_args, **second_args)


只帶關鍵字引數的 API


我們考慮這個程式碼片段:


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


很明顯,程式碼的作者還沒熟悉 Python 的程式碼風格(很可能剛從 cpp 和 rust 跳到 Python)。不幸的是,這不僅僅是個人偏好的問題,因為在 SVC 中改變引數的順序(adding/deleting)會使得程式碼無效。特別是,sklearn 經常會重排序或重新命名大量的演演算法引數以提供一致的 API。每次重構都可能使程式碼失效。


在 Python3,庫的編寫者可能需要使用*以明確地命名引數:


  1. class SVC(BaseSVC):

  2.    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 模組中的常量


  1. # Python 3

  2. math.inf # 'largest' number

  3. math.nan # not a number

  4. max_quality = -math.inf  # no more magic initial values!

  5. for model in trained_models:

  6.    max_quality = max(max_quality, compute_quality(model, data))


小調:單精度整數型別


Python 2 提供了兩個基本的整數型別,即 int(64 位符號整數)和用於長時間計算的 long(在 C++變的相當莫名其妙)。


Python 3 有一個單精度型別的 int,它包含了長時間的運算。


下麵是檢視值是否是整數的方法:


  1. isinstance(x, numbers.Integral) # Python 2, the canonical way

  2. isinstance(x, (long, int))      # Python 2

  3. 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,因此對你來講沒用的功能對於你可能只想使用一次的庫很有用。


資料科學特有的程式碼遷移問題(以及如何解決它們)


停止對巢狀引數的支援:


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


然而,它依然完美適用於不同的理解:


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


通常,理解在 Python 2 和 3 之間可以更好地「翻譯」。


  • map(), .keys(), .values(), .items(), 等等傳回迭代器,而不是串列。迭代器的主要問題有:沒有瑣碎的分割和無法迭代兩次。將結果轉化為串列幾乎可以解決所有問題。

  • 遇到問題請參見 Python 問答:我如何移植到 Python 3?(https://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 才開始行動,提前享受新語言的功能吧。


遷移過後,我敢保證程式會更加順暢:「我們不會再做向後不相容的事情了(https://snarky.ca/why-python-3-exists/)」。


●本文編號342,以後想閱讀這篇文章直接輸入342即可

●輸入m獲取到文章目錄

推薦↓↓↓

Java程式設計

更多推薦18個技術類公眾微信

涵蓋:程式人生、演演算法與資料結構、駭客技術與網路安全、大資料技術、前端開發、Java、Python、Web開發、安卓開發、iOS開發、C/C++、.NET、Linux、資料庫、運維等。

贊(0)

分享創造快樂

© 2024 知識星球   網站地圖