Created
March 7, 2021 03:00
-
-
Save crcrpar/5f084ae9b7a2bf5a4bfb4408207b737b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"id": "spare-light", | |
"metadata": {}, | |
"source": [ | |
"# nn-parameter-changes-input-tensor/" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"id": "manufactured-squad", | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"import numpy as np\n", | |
"import torch\n", | |
"import torch.nn as nn" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 2, | |
"id": "charming-patch", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"w0 tensor([[-0.8809, -0.1315, 0.7930],\n", | |
" [-0.2604, -1.3041, 0.6648]])\n", | |
"model.w Parameter containing:\n", | |
"tensor([[-0.8809, -0.1315, 0.7930],\n", | |
" [-0.2604, -1.3041, 0.6648]], requires_grad=True)\n", | |
"w0 tensor([[-0.8809, -0.1315, 0.7930],\n", | |
" [-0.2604, -1.3041, 0.6648]])\n", | |
"model.w Parameter containing:\n", | |
"tensor([[-0.7809, -0.2315, 0.8930],\n", | |
" [-0.3604, -1.2041, 0.5648]], requires_grad=True)\n" | |
] | |
} | |
], | |
"source": [ | |
"class mymodel(nn.Module):\n", | |
" def __init__(self, w0):\n", | |
" super().__init__() \n", | |
" self.w = nn.Parameter(w0.clone().detach())\n", | |
" def forward(self, x):\n", | |
" diff = self.w * x - 10\n", | |
" self.loss = torch.mean(diff * diff)\n", | |
" return self.loss\n", | |
"\n", | |
"w0 = torch.randn(2, 3)\n", | |
"model = mymodel(w0)\n", | |
"print(\"w0\", w0)\n", | |
"print(\"model.w\", model.w)\n", | |
"\n", | |
"optimizer = torch.optim.Adam(model.parameters(), lr = 0.1)\n", | |
"inputs = torch.randn(2, 3)\n", | |
"loss = model(inputs)\n", | |
"optimizer.zero_grad()\n", | |
"loss.backward()\n", | |
"optimizer.step()\n", | |
"print(\"w0\", w0)\n", | |
"print(\"model.w\", model.w)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"id": "excited-program", | |
"metadata": {}, | |
"outputs": [], | |
"source": [] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Python 3", | |
"language": "python", | |
"name": "python3" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": "3.7.9" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 5 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment