Pythonの相互運用性

TensorFlow.org で見る Google Colab で実行する GitHub でソースを表示

Swift For TensorFlow は Python の相互運用性をサポートします。

Swift から Python モジュールをインポートし、Python 関数を呼び出し、Swift と Python の間で値を変換できます。

import PythonKit
print(Python.version)
3.6.9 (default, Oct  8 2020, 12:12:24) 
[GCC 8.4.0]

Pythonのバージョンの設定

デフォルトでは、 import Pythonと、Swift はインストールされている最新バージョンの Python のシステム ライブラリ パスを検索します。特定の Python インストールを使用するには、 PYTHON_LIBRARY環境変数を、インストールによって提供されるlibpython共有ライブラリに設定します。例えば:

export PYTHON_LIBRARY="~/anaconda3/lib/libpython3.7m.so"

正確なファイル名は、Python 環境およびプラットフォームによって異なります。

あるいは、 PYTHON_VERSION環境変数を設定して、一致する Python バージョンのシステム ライブラリ パスを検索するように Swift に指示することもできます。 PYTHON_LIBRARY PYTHON_VERSIONよりも優先されることに注意してください。

コードでは、 PythonLibrary.useVersion関数を呼び出すこともできます。これはPYTHON_VERSIONを設定するのと同じです。

// PythonLibrary.useVersion(2)
// PythonLibrary.useVersion(3, 7)

注: import Pythonの直後、Python コードを呼び出す前にPythonLibrary.useVersionを実行する必要があります。 Python のバージョンを動的に切り替えるために使用することはできません。

PYTHON_LOADER_LOGGING=1を設定すると、 Python ライブラリの読み込みのデバッグ出力が表示されます。

基本

Swift では、 PythonObject Python からのオブジェクトを表します。すべての Python API は、 PythonObjectインスタンスを使用して返します。

Swift の基本型 (数値や配列など) はPythonObjectに変換できます。場合によっては (リテラルやPythonConvertible引数を取る関数の場合)、変換は暗黙的に行われます。 Swift 値をPythonObjectに明示的にキャストするには、 PythonObjectイニシャライザを使用します。

PythonObject数値演算、インデックス付け、反復などの多くの標準演算を定義します。

// Convert standard Swift types to Python.
let pythonInt: PythonObject = 1
let pythonFloat: PythonObject = 3.0
let pythonString: PythonObject = "Hello Python!"
let pythonRange: PythonObject = PythonObject(5..<10)
let pythonArray: PythonObject = [1, 2, 3, 4]
let pythonDict: PythonObject = ["foo": [0], "bar": [1, 2, 3]]

// Perform standard operations on Python objects.
print(pythonInt + pythonFloat)
print(pythonString[0..<6])
print(pythonRange)
print(pythonArray[2])
print(pythonDict["bar"])
4.0
Hello 
slice(5, 10, None)
3
[1, 2, 3]

// Convert Python objects back to Swift.
let int = Int(pythonInt)!
let float = Float(pythonFloat)!
let string = String(pythonString)!
let range = Range<Int>(pythonRange)!
let array: [Int] = Array(pythonArray)!
let dict: [String: [Int]] = Dictionary(pythonDict)!

// Perform standard operations.
// Outputs are the same as Python!
print(Float(int) + float)
print(string.prefix(6))
print(range)
print(array[2])
print(dict["bar"]!)
4.0
Hello 
5..<10
3
[1, 2, 3]

PythonObject多くの標準 Swift プロトコルへの準拠を定義します。

  • Equatable
  • Comparable
  • Hashable
  • SignedNumeric
  • Strideable
  • MutableCollection
  • すべてのExpressibleBy_Literalプロトコル

これらの適合性はタイプセーフではないことに注意してください。互換性のないPythonObjectインスタンスからプロトコル機能を使用しようとすると、クラッシュが発生します。

let one: PythonObject = 1
print(one == one)
print(one < one)
print(one + one)

let array: PythonObject = [1, 2, 3]
for (i, x) in array.enumerated() {
  print(i, x)
}
True
False
2
0 1
1 2
2 3

タプルを Python から Swift に変換するには、タプルのアリティを静的に知る必要があります。

次のインスタンス メソッドのいずれかを呼び出します。

  • PythonObject.tuple2
  • PythonObject.tuple3
  • PythonObject.tuple4
let pythonTuple = Python.tuple([1, 2, 3])
print(pythonTuple, Python.len(pythonTuple))

// Convert to Swift.
let tuple = pythonTuple.tuple3
print(tuple)
(1, 2, 3) 3
(1, 2, 3)

Python ビルトイン

グローバルPythonインターフェイスを介して Python ビルトインにアクセスします。

// `Python.builtins` is a dictionary of all Python builtins.
_ = Python.builtins

// Try some Python builtins.
print(Python.type(1))
print(Python.len([1, 2, 3]))
print(Python.sum([1, 2, 3]))
<class 'int'>
3
6

Python モジュールのインポート

Python.import使用して Python モジュールをインポートします。これは、 Pythonimportキーワードのように機能します。

let np = Python.import("numpy")
print(np)
let zeros = np.ones([2, 3])
print(zeros)
<module 'numpy' from '/tmpfs/src/tf_docs_env/lib/python3.6/site-packages/numpy/__init__.py'>
[[1. 1. 1.]
 [1. 1. 1.]]

安全なインポートを実行するには、スロー関数Python.attemptImportを使用します。

let maybeModule = try? Python.attemptImport("nonexistent_module")
print(maybeModule)
nil

numpy.ndarrayによる変換

次の Swift 型は、 numpy.ndarrayとの間で変換できます。

  • Array<Element>
  • ShapedArray<Scalar>
  • Tensor<Scalar>

変換は、 numpy.ndarraydtype ElementまたはScalarジェネリック パラメーター タイプと互換性がある場合にのみ成功します。

Arrayの場合、 numpyからの変換は、 numpy.ndarrayが 1 次元の場合にのみ成功します。

import TensorFlow

let numpyArray = np.ones([4], dtype: np.float32)
print("Swift type:", type(of: numpyArray))
print("Python type:", Python.type(numpyArray))
print(numpyArray.shape)
Swift type: PythonObject
Python type: <class 'numpy.ndarray'>
(4,)

// Examples of converting `numpy.ndarray` to Swift types.
let array: [Float] = Array(numpy: numpyArray)!
let shapedArray = ShapedArray<Float>(numpy: numpyArray)!
let tensor = Tensor<Float>(numpy: numpyArray)!

// Examples of converting Swift types to `numpy.ndarray`.
print(array.makeNumpyArray())
print(shapedArray.makeNumpyArray())
print(tensor.makeNumpyArray())

// Examples with different dtypes.
let doubleArray: [Double] = Array(numpy: np.ones([3], dtype: np.float))!
let intTensor = Tensor<Int32>(numpy: np.ones([2, 3], dtype: np.int32))!
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]

画像を表示する

Python ノートブックと同様に、 matplotlibを使用して画像をインラインで表示できます。

// This cell is here to display plots inside a Jupyter Notebook.
// Do not copy it into another environment.
%include "EnableIPythonDisplay.swift"
print(IPythonDisplay.shell.enable_matplotlib("inline"))
('inline', 'module://ipykernel.pylab.backend_inline')

let np = Python.import("numpy")
let plt = Python.import("matplotlib.pyplot")

let time = np.arange(0, 10, 0.01)
let amplitude = np.exp(-0.1 * time)
let position = amplitude * np.sin(3 * time)

plt.figure(figsize: [15, 10])

plt.plot(time, position)
plt.plot(time, amplitude)
plt.plot(time, -amplitude)

plt.xlabel("Time (s)")
plt.ylabel("Position (m)")
plt.title("Oscillations")

plt.show()

png

Use `print()` to show values.