Interoperabilità Python

Visualizza su TensorFlow.org Esegui in Google Colab Visualizza la fonte su GitHub

Swift For TensorFlow supporta l'interoperabilità con Python.

Puoi importare moduli Python da Swift, chiamare funzioni Python e convertire valori tra Swift e Python.

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

Impostazione della versione di Python

Per impostazione predefinita, quando import Python , Swift cerca nei percorsi della libreria di sistema la versione più recente di Python installata. Per utilizzare un'installazione Python specifica, impostare la variabile d'ambiente PYTHON_LIBRARY sulla libreria condivisa libpython fornita dall'installazione. Per esempio:

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

Il nome file esatto varierà a seconda degli ambienti e delle piattaforme Python.

In alternativa, puoi impostare la variabile d'ambiente PYTHON_VERSION , che indica a Swift di cercare nei percorsi della libreria di sistema una versione Python corrispondente. Tieni presente che PYTHON_LIBRARY ha la precedenza su PYTHON_VERSION .

Nel codice, puoi anche chiamare la funzione PythonLibrary.useVersion , che equivale a impostare PYTHON_VERSION .

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

Nota: dovresti eseguire PythonLibrary.useVersion subito dopo import Python , prima di chiamare qualsiasi codice Python. Non può essere utilizzato per cambiare dinamicamente le versioni di Python.

Imposta PYTHON_LOADER_LOGGING=1 per vedere l'output di debug per il caricamento della libreria Python .

Nozioni di base

In Swift, PythonObject rappresenta un oggetto di Python. Tutte le API Python utilizzano e restituiscono istanze PythonObject .

I tipi di base in Swift (come numeri e array) sono convertibili in PythonObject . In alcuni casi (per valori letterali e funzioni che accettano argomenti PythonConvertible ), la conversione avviene in modo implicito. Per trasmettere esplicitamente un valore Swift a PythonObject , utilizzare l'inizializzatore PythonObject .

PythonObject definisce molte operazioni standard, incluse operazioni numeriche, indicizzazione e iterazione.

// 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 definisce la conformità a molti protocolli Swift standard:

  • Equatable
  • Comparable
  • Hashable
  • SignedNumeric
  • Strideable
  • MutableCollection
  • Tutti i protocolli ExpressibleBy_Literal

Tieni presente che queste conformità non sono indipendenti dai tipi: si verificheranno arresti anomali se tenti di utilizzare la funzionalità del protocollo da un'istanza PythonObject incompatibile.

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

Per convertire le tuple da Python a Swift, devi conoscere staticamente l'arietà della tupla.

Chiama uno dei seguenti metodi di istanza:

  • 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)

Componenti incorporati di Python

Accedi ai componenti integrati di Python tramite l'interfaccia globale 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

Importazione di moduli Python

Utilizza Python.import per importare un modulo Python. Funziona come la parola chiave import in Python .

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.]]

Utilizza la funzione di lancio Python.attemptImport per eseguire l'importazione sicura.

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

Conversione con numpy.ndarray

I seguenti tipi Swift possono essere convertiti in e da numpy.ndarray :

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

La conversione ha esito positivo solo se il dtype di numpy.ndarray è compatibile con il tipo di parametro generico Element o Scalar .

Per Array , la conversione da numpy ha esito positivo solo se numpy.ndarray è 1-D.

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.]

Visualizzazione delle immagini

Puoi visualizzare le immagini in linea utilizzando matplotlib , proprio come nei notebook Python.

// 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.