Skip to content

Instantly share code, notes, and snippets.

@mani3
Created December 10, 2019 07:05
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/667e2e5cd57679d2cc55f8568420b139 to your computer and use it in GitHub Desktop.
Save mani3/667e2e5cd57679d2cc55f8568420b139 to your computer and use it in GitHub Desktop.
Differentiable 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": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"▿ 2 elements\n",
" - value : 0.62245935\n",
" - gradient : 0.23500371\n"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"@differentiable\n",
"func sigmoid(_ x: Float) -> Float {\n",
" return 1 / (1 + TensorFlow.exp(-x))\n",
"}\n",
"let a: Float = 0.5\n",
"valueWithGradient(at: a) { a in sigmoid(a) }"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"value: 0.62245935\r\n",
"gradient: 0.23500371\r\n"
]
}
],
"source": [
"// 合っているか確認\n",
"// f(x) = 1 / (1 + e^−x), f'(x) = f(x)(1 − f(x))\n",
"print(\"value:\", sigmoid(a))\n",
"print(\"gradient:\", sigmoid(a) * (1 - sigmoid(a)))"
]
}
],
"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