![]() | ![]() |
Swift For TensorFlow unterstützt die Python-Interoperabilität.
Sie können Python-Module aus Swift importieren, Python-Funktionen aufrufen und Werte zwischen Swift und Python konvertieren.
import PythonKit
print(Python.version)
3.6.9 (default, Oct 8 2020, 12:12:24) [GCC 8.4.0]
Einstellen der Python-Version
Standardmäßig durchsucht Swift beim import Python
Systembibliothekspfade nach der neuesten installierten Version von Python. Um eine bestimmte Python Installation zu verwenden, stellte die PYTHON_LIBRARY
Umgebungsvariable auf die libpython
gemeinsam genutzten Bibliothek durch die Installation zur Verfügung gestellt. Beispielsweise:
export PYTHON_LIBRARY="~/anaconda3/lib/libpython3.7m.so"
Der genaue Dateiname unterscheidet sich in Python-Umgebungen und -Plattformen.
Alternativ können Sie die Umgebungsvariable PYTHON_VERSION
, die Swift anweist, Systembibliothekspfade nach einer passenden Python-Version zu durchsuchen. Beachten Sie, dass PYTHON_LIBRARY
Vorrang vor PYTHON_VERSION
.
Im Code können Sie auch die Funktion PythonLibrary.useVersion
, die dem Festlegen von PYTHON_VERSION
.
// PythonLibrary.useVersion(2)
// PythonLibrary.useVersion(3, 7)
Hinweis: Sie sollten PythonLibrary.useVersion
direkt nach dem import Python
PythonLibrary.useVersion
, bevor Sie Python-Code aufrufen. Es kann nicht zum dynamischen Wechseln von Python-Versionen verwendet werden.
Setzen Sie PYTHON_LOADER_LOGGING=1
, um die Debug-Ausgabe für das Laden der Python-Bibliothek PYTHON_LOADER_LOGGING=1
.
Grundlagen
In Swift repräsentiert PythonObject
ein Objekt aus Python. Alle Python-APIs verwenden PythonObject
Instanzen und geben sie PythonObject
.
Grundtypen in Swift (wie Zahlen und Arrays) können in PythonObject
konvertiert PythonObject
. In einigen Fällen (für Literale und Funktionen, die PythonConvertible
Argumente verwenden) erfolgt die Konvertierung implizit. Verwenden Sie den PythonObject
Initialisierer, um einen Swift-Wert explizit in PythonObject
PythonObject
.
PythonObject
definiert viele Standardoperationen, einschließlich numerischer Operationen, Indizierung und Iteration.
// 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
definiert Konformitäten mit vielen Standard-Swift-Protokollen:
-
Equatable
-
Comparable
-
Hashable
-
SignedNumeric
-
Strideable
-
MutableCollection
- Alle
ExpressibleBy_Literal
Protokolle
Beachten Sie, dass diese Konformitäten nicht typsicher sind: Abstürze treten auf, wenn Sie versuchen, die Protokollfunktionalität einer inkompatiblen PythonObject
Instanz zu verwenden.
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
Um Tupel von Python in Swift zu konvertieren, müssen Sie die Arität des Tupels statisch kennen.
Rufen Sie eine der folgenden Instanzmethoden auf:
-
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 eingebaut
Greifen Sie über die globale Python
Oberfläche auf Python-Buildins zu.
// `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-Module importieren
Verwenden Sie Python.import
, um ein Python-Modul zu importieren. Es funktioniert wie das Schlüsselwort 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.]]
Verwenden Sie die Python.attemptImport
, um einen sicheren Import durchzuführen.
let maybeModule = try? Python.attemptImport("nonexistent_module")
print(maybeModule)
nil
Konvertierung mit numpy.ndarray
Die folgenden Swift-Typen können in und aus numpy.ndarray
:
-
Array<Element>
-
ShapedArray<Scalar>
-
Tensor<Scalar>
Die Konvertierung ist nur erfolgreich, wenn der dtype
von numpy.ndarray
mit dem generischen Parametertyp Element
oder Scalar
kompatibel ist.
Bei Array
ist die Konvertierung von numpy
nur erfolgreich, wenn numpy.ndarray
1-D ist.
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.]
Bilder anzeigen
Sie können Bilder mit matplotlib
wie in Python-Notizbüchern matplotlib
anzeigen.
// 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()
Use `print()` to show values.