Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

temporary comparison via review nb #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 41 additions & 21 deletions L03-perceptron/code/perceptron-numpy.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,22 @@
"Sebastian Raschka \n",
"\n",
"CPython 3.7.1\n",
"IPython 7.10.1\n",
"IPython 7.11.1\n",
"\n",
"numpy 1.17.4\n"
"torch 1.4.0\n"
]
}
],
"source": [
"%load_ext watermark\n",
"%watermark -a 'Sebastian Raschka' -v -p numpy"
"%watermark -a 'Sebastian Raschka' -v -p torch"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- Runs on CPU or GPU (if available)"
]
},
{
Expand All @@ -45,7 +52,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Implementation of the classic Perceptron by Frank Rosenblatt for binary classification (here: 0/1 class labels) in NumPy"
"Implementation of the classic Perceptron by Frank Rosenblatt for binary classification (here: 0/1 class labels) in PyTorch"
]
},
{
Expand All @@ -63,6 +70,7 @@
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import torch\n",
"%matplotlib inline"
]
},
Expand Down Expand Up @@ -189,15 +197,24 @@
"metadata": {},
"outputs": [],
"source": [
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
"\n",
"\n",
"class Perceptron():\n",
" def __init__(self, num_features):\n",
" self.num_features = num_features\n",
" self.weights = np.zeros((num_features, 1), dtype=np.float)\n",
" self.bias = np.zeros(1, dtype=np.float)\n",
" self.weights = torch.zeros(num_features, 1, \n",
" dtype=torch.float32, device=device)\n",
" self.bias = torch.zeros(1, dtype=torch.float32, device=device)\n",
" \n",
" # placeholder vectors so they don't\n",
" # need to be recreated each time\n",
" self.ones = torch.ones(1)\n",
" self.zeros = torch.zeros(1)\n",
"\n",
" def forward(self, x):\n",
" linear = np.dot(x, self.weights) + self.bias\n",
" predictions = np.where(linear > 0., 1, 0)\n",
" linear = torch.add(torch.mm(x, self.weights), self.bias)\n",
" predictions = torch.where(linear > 0., self.ones, self.zeros)\n",
" return predictions\n",
" \n",
" def backward(self, x, y): \n",
Expand All @@ -209,13 +226,14 @@
" for e in range(epochs):\n",
" \n",
" for i in range(y.shape[0]):\n",
" # use view because backward expects a matrix (i.e., 2D tensor)\n",
" errors = self.backward(x[i].reshape(1, self.num_features), y[i]).reshape(-1)\n",
" self.weights += (errors * x[i]).reshape(self.num_features, 1)\n",
" self.bias += errors\n",
" \n",
" def evaluate(self, x, y):\n",
" predictions = self.forward(x).reshape(-1)\n",
" accuracy = np.sum(predictions == y) / y.shape[0]\n",
" accuracy = torch.sum(predictions == y).float() / y.shape[0]\n",
" return accuracy"
]
},
Expand All @@ -236,24 +254,23 @@
"output_type": "stream",
"text": [
"Model parameters:\n",
"\n",
"\n",
" Weights: [[1.27340847]\n",
" [1.34642288]]\n",
"\n",
" Bias: [-1.]\n",
"\n"
" Weights: tensor([[1.2734],\n",
" [1.3464]])\n",
" Bias: tensor([-1.])\n"
]
}
],
"source": [
"ppn = Perceptron(num_features=2)\n",
"\n",
"ppn.train(X_train, y_train, epochs=5)\n",
"X_train_tensor = torch.tensor(X_train, dtype=torch.float32, device=device)\n",
"y_train_tensor = torch.tensor(y_train, dtype=torch.float32, device=device)\n",
"\n",
"ppn.train(X_train_tensor, y_train_tensor, epochs=5)\n",
"\n",
"print('Model parameters:\\n\\n')\n",
"print(' Weights: %s\\n' % ppn.weights)\n",
"print(' Bias: %s\\n' % ppn.bias)"
"print('Model parameters:')\n",
"print(' Weights: %s' % ppn.weights)\n",
"print(' Bias: %s' % ppn.bias)"
]
},
{
Expand All @@ -277,7 +294,10 @@
}
],
"source": [
"test_acc = ppn.evaluate(X_test, y_test)\n",
"X_test_tensor = torch.tensor(X_test, dtype=torch.float32, device=device)\n",
"y_test_tensor = torch.tensor(y_test, dtype=torch.float32, device=device)\n",
"\n",
"test_acc = ppn.evaluate(X_test_tensor, y_test_tensor)\n",
"print('Test set accuracy: %.2f%%' % (test_acc*100))"
]
},
Expand Down
Loading