Skip to content

Instantly share code, notes, and snippets.

@mani3
Last active December 10, 2019 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mani3/1ebc2abca22e5ec7fa23fc176875f839 to your computer and use it in GitHub Desktop.
Save mani3/1ebc2abca22e5ec7fa23fc176875f839 to your computer and use it in GitHub Desktop.
Numpy in Swift for TensorFlow
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"('inline', 'module://ipykernel.pylab.backend_inline')\n"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import TensorFlow\n",
"import Python\n",
"\n",
"%include \"EnableIPythonDisplay.swift\"\n",
"IPythonDisplay.shell.enable_matplotlib(\"inline\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"最初に、TensorFlowやPythonのモジュールをインポートします。 もし、 notebook上で外部コード(.swift)を使いたい場合は、%include を呼ぶとインポートすることができます。"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[ 12. 1. -80.]\r\n",
"bins: [-90 -87 -84 -81 -78 -75 -72 -69 -66 -63 -60 -57 -54 -51 -48 -45 -42 -39\r\n",
" -36 -33 -30 -27 -24 -21 -18 -15 -12 -9 -6 -3 0 3 6 9 12 15\r\n",
" 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69\r\n",
" 72 75 78 81 84 87 90] type: PythonObject\r\n",
"indices: [35 31 4] type: PythonObject\r\n"
]
}
],
"source": [
"let np = Python.import(\"numpy\")\n",
"let r = np.array([12, 1, -80], np.float32)\n",
"let bins = np.arange(-90, 93, 3, dtype: np.int32)\n",
"let binLabels = np.digitize(r, bins).astype(np.int32)\n",
"print(r)\n",
"print(\"bins:\", bins, \"type:\", type(of: bins))\n",
"print(\"indices:\", binLabels, \"type:\", type(of: binLabels))"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tensor<Int32> [35, 31, 4]\r\n",
"PythonObject [35 31 4]\r\n"
]
}
],
"source": [
"// numpy -> Tensor\n",
"let tensor = Tensor<Int32>(numpy: binLabels)!\n",
"print(type(of: tensor), tensor)\n",
"\n",
"// Tensor -> numpy\n",
"let array = tensor.makeNumpyArray()\n",
"print(type(of: array), array)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Swift",
"language": "swift",
"name": "swift"
},
"language_info": {
"file_extension": ".swift",
"mimetype": "text/x-swift",
"name": "swift",
"version": ""
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment