Skip to content

Instantly share code, notes, and snippets.

@mertbozkir
Last active May 12, 2022 08:21
Show Gist options
  • Save mertbozkir/a708ca5a307c2cd6114097b31e7daed0 to your computer and use it in GitHub Desktop.
Save mertbozkir/a708ca5a307c2cd6114097b31e7daed0 to your computer and use it in GitHub Desktop.
Simple Linear Regression with Gradient Descent from Scratch
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "fa3a47c2",
"metadata": {},
"outputs": [],
"source": [
"def cost_function(Y, b, w, X):\n",
" m = len(Y)\n",
" sse = 0\n",
" for i in range(0, m):\n",
" y_hat = b + w * X[i]\n",
" y = Y[i]\n",
" sse += (y_hat - y) ** 2\n",
" \n",
" mse = sse / m\n",
" return mse"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "1a64d483",
"metadata": {},
"outputs": [],
"source": [
"def update_weights(Y, b, w, X, learning_rate):\n",
" m = len(Y)\n",
" \n",
" b_deriv_sum = 0\n",
" w_deriv_sum = 0\n",
" \n",
" for i in range(0, m):\n",
" y_hat = b + w * X[i] \n",
" y = Y[i]\n",
" b_deriv_sum = (y_hat - y)\n",
" w_deriv_sum = (y_hat - y) * X[i]\n",
" \n",
" new_b = b - (learning_rate * 1 / m * b_deriv_sum)\n",
" new_w = w - (learning_rate * 1 / m * w_deriv_sum)\n",
" return new_b, new_w"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "0e830209",
"metadata": {},
"outputs": [],
"source": [
"def train(Y, initial_b, initial_w, X, learning_rate, num_iters):\n",
" print(\"Starting gradient descent at b = {0}, w = {1}, mse = {2}\".format(Y, initial_b, initial_w, X))\n",
" \n",
" \n",
" b = initial_b\n",
" w = initial_w\n",
" cost_history = []\n",
" for i in range(num_iters):\n",
" b, w = update_weights(Y, b, w, X, learning_rate)\n",
" mse = cost_function(Y, b, w, X)\n",
" cost_history.append(mse)\n",
" \n",
" if i%100 ==0:\n",
" print(\"iter={:d} b={:.2f} w={:.4f} \".format(i, b, w, mse))\n",
" \n",
" print(\"after {0} iterations b = {1}, w = {2}, mse = {3}\".format(num_iters, b, w, cost_function(Y, b, w, X)))\n",
" return cost_history, b, w"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.9.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment