add updated 00 & 01 notebooks

This commit is contained in:
Daniel Bourke committed 2021-10-26 08:12:34 +10:00
1 parent cb0780e7e3
commit 82451ca74e
2 files changed
+327 -33

No files matched your search

+22 -24
View File
@@ -1767,6 +1767,26 @@
"tensor[:, :, 0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## TK - Changing values\n",
"\n",
"Use `scatter()` to change values for things like one-hot encoding.\n",
"\n",
"https://pytorch.org/docs/stable/generated/torch.Tensor.scatter_.html#torch.Tensor.scatter_ \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# TODO - add in example of scatter"
]
},
{
"cell_type": "markdown",
"metadata": {
@@ -2201,30 +2221,8 @@
},
"source": [
"UPTOHERE:\n",
"* get tensors on GPU\n",
"* show how to go back and forth between GPU and non-GPU\n",
"* go back through headings and make sure code is good to go...\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5Ji-FyLNFMgh"
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ulZG668QFVgX"
},
"outputs": [],
"source": [
"import torch\n",
"torch.arange(1, 10, 1)"
"* add in scatter (for changing values)\n",
"* go back through headings and make sure cells are complete \n"
]
}
],
+305 -9
View File
@@ -16,22 +16,318 @@
"\n",
"## TK - What we're going to cover\n",
"\n",
"1. Data\n",
"2. Load data\n",
"3. Build model\n",
"4. Fitting model to data (training)\n",
"5. Making predictions (inference)\n",
"6. Saving and loading model\n",
"7. Putting it all together\n",
"1. Data (prepare and load)\n",
"2. Build model\n",
"3. Fitting model to data (training)\n",
"4. Making predictions and evaluating a model (inference)\n",
" * Improving a model through experimentations (optional)\n",
"5. Saving and loading model\n",
"6. Putting it all together\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": []
"source": [
"import torch\n",
"from torch import nn\n",
"from torch.utils.data import DataLoader\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## TK - Data\n",
"\n",
"Let's create the data as a straight line.\n",
"\n",
"We'll use linear regression to create the data with known parameters and then we'll use PyTorch to see if we can build model to estimate these parameters using gradient descent.\n",
"\n",
"TK - the essence of machine learning (and deep learning) is to create model that's able to estimate some function, a function being a way to navigate patterns in data.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([ 0, 5, 10, 15, 20, 25, 30, 35, 40, 45]),\n",
" tensor([ 3, 38, 73, 108, 143, 178, 213, 248, 283, 318]))"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"weight = 7\n",
"bias = 3\n",
"start = 0\n",
"end = 1000\n",
"step = 5\n",
"\n",
"# Create data\n",
"torch.manual_seed(42)\n",
"X = torch.arange(start, end, step)\n",
"y = weight * X + bias\n",
"\n",
"X[:10], y[:10]"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0. ],\n",
" [0.00502513],\n",
" [0.01005025],\n",
" [0.01507538],\n",
" [0.0201005 ],\n",
" [0.02512563],\n",
" [0.03015075],\n",
" [0.03517588],\n",
" [0.04020101],\n",
" [0.04522613]])"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get data between 0 & 1 (neural networks like data between 0 & 1)\n",
"from sklearn.preprocessing import MinMaxScaler\n",
"min_max = MinMaxScaler()\n",
"X_scaled = min_max.fit_transform(X.numpy().reshape(-1, 1))\n",
"X_scaled[:10]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"TK - explain: \n",
"* torch.squeeze() - remove extra dimension\n",
"* torch.from_numpy() - convert numpy array to torch tensor\n",
"* .type() - convert default Numpy array datatype of float64 to torch.float (float32) "
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"tensor([0.0000, 0.0050, 0.0101, 0.0151, 0.0201, 0.0251, 0.0302, 0.0352, 0.0402,\n",
" 0.0452])"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get scaled data back to PyTorch type\n",
"X_scaled = torch.squeeze(torch.from_numpy(X_scaled)).type(dtype=torch.float)\n",
"\n",
"X_scaled[:10]"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(160, 160, 40, 40)"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Create train/test split\n",
"train_split = int(0.8 * len(X_scaled)) # 80% of data used for training set\n",
"X_train, y_train = X_scaled[:train_split], y[:train_split]\n",
"X_test, y_test = X_scaled[train_split:], y[train_split:]\n",
"\n",
"len(X_train), len(y_train), len(X_test), len(y_test)"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlwAAAGbCAYAAAARGU4hAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8rg+JYAAAACXBIWXMAAAsTAAALEwEAmpwYAAAut0lEQVR4nO3de5id8734/fcnM0gkEtFMInIQJTQRx0To86tTseOUX+rqT6VsjdauPJ3oj6uqiLaEaj2t7pZdNGorLZdDWzbbsbYfD1pEUIcYigoS0xzs/exG2opkvs8fc89Yk8xhTWbW+f26rnWte33Xfa/1XXMP88nn+1mfO1JKSJIkqXAGlHoCkiRJ1c6AS5IkqcAMuCRJkgrMgEuSJKnADLgkSZIKrL7UE+jJiBEj0oQJE0o9DUmSpB4988wzq1NKDRuPl33ANWHCBBYvXlzqaUiSJPUoIt7qbNwlRUmSpAIz4JIkSSowAy5JkqQCM+CSJEkqMAMuSZKkAiv7byn25C9/+QsrV67kww8/LPVUVOa22GILRo4cydChQ0s9FUlSjanogOsv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WHHXZYj8dJkqrTwmcWti8fljrIymWneeDKK2H9+tb7cvT4448zc+ZMTj75ZPbee2923nln/vjHPxZ9HpMmTWL58uW8++5HpXeLFy/uNogbNmwYo0eP5sknP/riakqpvSYL4L333qOpqYn58+dz+OGHM2nSJNasWcP69evb99lyyy0BNim2f/zxx/nqV7/KMcccw+67784222zT4VufkqTa0JbZmjRiEnVRx9ypZZJFyfS2LYRKYNddd+XWW2/l8ccfZ8SIEfzLv/wLb775Jvvss09R53HEEUew2267MWfOHC677DL+9re/8bWvfY36+vpuM19nnHEG3/ve99h1113ZY489uOqqq2hubmb06NEADB8+nBEjRvCzn/2McePGsXz5cs4++2zq6z/69Rw5ciSDBg3igQceYMKECQwcOJBhw4ax6667cuONN7L//vuzdu1avvGNb7QHZ5Kk2tGW2Wpa3cT6b6/v+YAiM8NVAb75zW8yffp0jjrqKA466CAGDx7MSSedVPR5DBgwgDvuuIMPPviA6dOnM2fOHM4//3wigoEDB3Z53FlnncUXv/hF/umf/on999+flpaWDvMfMGAAt956Ky+88AJTpkxh3rx5XHzxxWy11Vbt+9TX13PFFVdw7bXXssMOOzBr1iwArrvuOt5//32mTp3K7Nmz+dKXvsSECRMK9jOQJJWPzuq1yi2z1SZaC+rL17Rp01JX3cWbmpqYNGlSkWekXM8//zx77703ixcvZurUqaWeTl78vZGkyjbvnnksfGYhLamFRKIu6somqxURz6SUpm087pKieuWOO+5g8ODBTJw4kaVLl/K1r32Nvfbai3333bfUU5Mk1Yi25UOgrLNauVxSVK+sWbOG008/ncmTJ3PSSScxadIkHnjggYJ9e1GSJCjfdg/5cklRNcffG0mqPPUX1bMhbSir5cPOdLWkaIZLkiSVpUoqiu+JNVySJKmsbFwUX25NTDeHAZckSSorlVgU3xOXFCVJUslVelF8T8xwSZKkkivXayD2FzNckiSpZMr9Goj9xYCrBkyYMIHLLrusJO997LHHcsopp5TkvSVJ5W/jayBWW2arjQFXkUVEt7e+BCcXXnghU6ZM2WT86aefprGxsQ+zLp5HHnmEiGD16tWlnookqUCqqd1DvqzhKrLm5ub27bvvvpsvf/nLHcYGDRrU7+/Z0NDQ768pSVJvVWO7h3yZ4Sqy7bffvv227bbbbjL26KOPMnXqVAYOHMhOO+3E+eefz7p169qPv/3229lzzz0ZNGgQ2223HQcffDArVqzg+uuvZ8GCBSxZsqQ9W3b99dcDmy4pRgTXXHMNxx9/PIMHD+bjH/84N954Y4d5PvXUU+y7774MHDiQffbZh3vvvZeI4JFHHunys/31r3/llFNOYciQIYwaNYrvfve7m+xz4403st9++7HNNtswcuRIjj/+eJYvXw7A0qVLOfTQQ4HWIDE343f//fdz4IEHMnz4cLbbbjtmzJhBU1NTb3/8kqQSals+bLvgdLVntXIZcJWRBx54gJNOOonTTz+dJUuWcN111/HrX/+a+fPnA/DnP/+Z2bNnM2fOHJqamnj00Uc5+eSTATjhhBM466yz2G233Whubqa5uZkTTjihy/e66KKLmDVrFs8//zwnnHACX/rSl3jrrbcAeP/99zn22GP5xCc+wTPPPMP3v/99zj777B7n//Wvf50HH3yQ3/zmNzz00EM899xzPProox32WbduHQsWLOD555/n7rvvZvXq1Xz+858HYNy4cfzmN78BYMmSJTQ3N3P55ZcDsHbtWs4880wWLVrEI488wrBhw5g5c2aHYFSSVH6qvd1D3lJKZX2bOnVq6srLL7/c5XO90Xh3Y6pbUJca727sl9fL169+9avUegpaHXjggemiiy7qsM8dd9yRBg8enFpaWtIzzzyTgLR06dJOX++CCy5Iu++++ybjO+64Y/rBD37Q/hhI5557bvvjDz/8MA0aNCj98pe/TCml9NOf/jQNHz48/fWvf23f56abbkpAevjhhzt97zVr1qQtt9wy3XjjjR3Ghg0blubMmdPlz6CpqSkB6Z133kkppfTwww8nIK1atarLY1JK6f33308DBgxIjz32WLf7daa/fm8kST2rW1CXuJBUt6Cu1FMpCmBx6iSeMcNFx94Line truncated
"text/plain": [
"<Figure size 720x504 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# Plot train/test data\n",
"plt.figure(figsize=(10, 7))\n",
"\n",
"# Plot training data in blue\n",
"plt.scatter(X_train, y_train, c=\"b\", s=4, label=\"Training data\")\n",
"\n",
"# Plot test data in green\n",
"plt.scatter(X_test, y_test, c=\"g\", s=4, label=\"Testing data\")\n",
"\n",
"# Show legend\n",
"plt.legend(prop={\"size\": 14});"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Build model\n",
"\n",
"Now we've got some data, let's build a model to use the blue dots to predict the green dots.\n",
"\n",
"TK - In PyTorch everything to do with models is considered a Module (from nn.Module)... "
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [],
"source": [
"class LinearRegressionModel(nn.Module):\n",
" def __init__(self):\n",
" super().__init__() \n",
" self.weights = nn.Parameter(torch.randn(1,\n",
" requires_grad=True, \n",
" dtype=torch.float\n",
" ))\n",
"\n",
" self.bias = nn.Parameter(torch.randn(1, \n",
" requires_grad=True,\n",
" dtype=torch.float\n",
" ))\n",
"\n",
" # Forward defines the computation in the model\n",
" def forward(self, x):\n",
" return self.weights * x + self.bias"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Parameter containing:\n",
" tensor([0.3367], requires_grad=True),\n",
" Parameter containing:\n",
" tensor([0.1288], requires_grad=True)]"
]
},
"execution_count": 62,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"torch.manual_seed(42)\n",
"model_0 = LinearRegressionModel()\n",
"list(model_0.parameters())"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"OrderedDict([('weights', tensor([0.3367])), ('bias', tensor([0.1288]))])"
]
},
"execution_count": 65,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# List named parameters \n",
"model_0.state_dict()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We want to start from random parameters and get the model to update them towards parameters that fit our data best (the original `weight` and `bias` values)."
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'cuda'"
]
},
"execution_count": 63,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Setup device agnostic code\n",
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"device"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# UPTOHERE... \n",
"\n",
"* Use model to make predictions\n",
"* Get data/model on device etc...\n",
"* Go through steps above"
]
}
],
"metadata": {