Swift For TensorFlow תומך בפעולה הדדית של Python.
אתה יכול לייבא מודולים של Python מ-Swift, לקרוא לפונקציות 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 תואמת. שים לב ש- PYTHON_LIBRARY
מקבל עדיפות על פני PYTHON_VERSION
.
בקוד, אתה יכול גם לקרוא לפונקציה PythonLibrary.useVersion
, המקבילה להגדרת PYTHON_VERSION
.
// PythonLibrary.useVersion(2)
// PythonLibrary.useVersion(3, 7)
הערה: עליך להפעיל את PythonLibrary.useVersion
מיד לאחר import Python
, לפני שתקרא קוד Python כלשהו. לא ניתן להשתמש בו כדי להחליף באופן דינמי גרסאות Python.
הגדר את PYTHON_LOADER_LOGGING=1
כדי לראות פלט ניפוי באגים עבור טעינת ספריית Python .
יסודות
ב-Swift, PythonObject
מייצג אובייקט מ-Python. כל ממשקי ה-API של Python משתמשים ומחזירים מופעים 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
כדי להמיר tuples מ-Python לסוויפט, עליך לדעת באופן סטטי את האריטי של tuple.
קרא לאחת משיטות המופע הבאות:
-
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.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. זה עובד כמו מילת המפתח import
ב- 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.]]
השתמש בפונקציית השלכת Python.attemptImport
כדי לבצע ייבוא בטוח.
let maybeModule = try? Python.attemptImport("nonexistent_module")
print(maybeModule)
nil
המרה עם numpy.ndarray
ניתן להמיר את סוגי Swift הבאים אל numpy.ndarray
וממנו:
-
Array<Element>
-
ShapedArray<Scalar>
-
Tensor<Scalar>
ההמרה תצליח רק אם ה- dtype
של ה- numpy.ndarray
תואם לסוג הפרמטר הגנרי Element
או Scalar
.
עבור Array
, המרה מ- numpy
מצליחה רק אם ה- 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.]
מציג תמונות
אתה יכול להציג תמונות בשורה באמצעות matplotlib
, בדיוק כמו במחברות של 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()
Use `print()` to show values.