File size: 11,213 Bytes
bcf16ee |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 |
{
"cells": [
{
"cell_type": "markdown",
"id": "dedefa38",
"metadata": {},
"source": [
"## Machine Learning\n",
"### Coordinate Descent for Lasso Regression\n",
"In a post of the repository of Optimization, we talked abour **Coordinate Descent**. here, we want to use it for Lasso regression. Let's remind us of the coordinate descent algorithm when the objective function $f$ is convex but not differentiable:\n",
"<br>$\\boldsymbol{w}\\leftarrow$ some initial vector\n",
"<br>for $k$ in range($iter$):\n",
"<br>for $j$ in range($q$):\n",
"<br>$w_j\\leftarrow w_j-\\eta_k g_j(\\boldsymbol{w})$\n",
"<br>where $g_j$ is the $j$th component of subgradient vector $\\boldsymbol{g}$ such that $\\boldsymbol{g}\\in\\partial f(\\boldsymbol{w})$\n",
"<br> We remind that $\\partial f(\\boldsymbol{w})$ is the **subdifferential** of $f$ at point $\\boldsymbol{w}$. Moreover, $q$ is the number of components of $\\boldsymbol{w}$, and $iter$ is the number of iterations.\n",
"<Br>For Lasso, however, we can analytically solve when $0\\in \\partial f(\\boldsymbol{w})$. it should be reminded that if function $f$ is differentiable, this property is reduced to $\\nabla f(\\boldsymbol{w})=0$ \n",
"<br> The loss of Lasso regression is mentioned here again:\n",
"<br>$L_{Lasso}(\\boldsymbol{w})=\\frac{1}{2}||\\boldsymbol{y}-X\\boldsymbol{w}||^2+\\lambda ||\\boldsymbol{w}||_1$\n",
"<br>We compute $\\partial L_{Lasso}(\\boldsymbol{w})$ and find its minimum for each component $w_j$ of parameter vector $\\boldsymbol{w}$. The detalis are in **Pinterest page** stated below.\n",
"<br>**Reminder:** We have data points $(\\boldsymbol{x}_i,y_i)$ where the first components of $\\boldsymbol{x}_i$ are one. Thus, the rows of matrix $X$ are composed of $\\boldsymbol{x}^T_i$ such that the first column of $X$ is all one. Vectors are denoted here by bold symbols, and they are all column vectors.\n",
"<br><br>In the following, we download the file *diabetes.csv*, which is our dataset, composing of 768 rows and 9 columns. Its last column holds the values of $y_i$, while the rest of columns holds the values of $\\boldsymbol{x}^T_i$. in fact, each row of the dataset is a data point $(\\boldsymbol{x}^T_i,y_i)$ \n",
" - First we load the dataset, and then normalize each column of its input data (excluding the last column).\n",
" - Next, the coordinate descent with subdifferential is used to estimate the parameters.\n",
" - For deeper discussion on subdifferential and/or coordinate descent, see our post in Repository **Optimization**.\n",
" - Finally, we measure the accuracy of the model for *binary classification*.\n",
" \n",
"<hr>\n",
"The Python code at: https://github.com/ostad-ai/Machine-Learning\n",
"<br> Explanation: https://www.pinterest.com/HamedShahHosseini/Machine-Learning/"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "85af9aac",
"metadata": {},
"outputs": [],
"source": [
"# importing required modules\n",
"import numpy as np\n",
"import pandas as pd"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "dddddcd7",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The dataset has 768 rows and 9 columns\n"
]
},
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>Pregnancies</th>\n",
" <th>Glucose</th>\n",
" <th>BloodPressure</th>\n",
" <th>SkinThickness</th>\n",
" <th>Insulin</th>\n",
" <th>BMI</th>\n",
" <th>DiabetesPedigreeFunction</th>\n",
" <th>Age</th>\n",
" <th>Outcome</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>6</td>\n",
" <td>148</td>\n",
" <td>72</td>\n",
" <td>35</td>\n",
" <td>0</td>\n",
" <td>33.6</td>\n",
" <td>0.627</td>\n",
" <td>50</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>1</td>\n",
" <td>85</td>\n",
" <td>66</td>\n",
" <td>29</td>\n",
" <td>0</td>\n",
" <td>26.6</td>\n",
" <td>0.351</td>\n",
" <td>31</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>8</td>\n",
" <td>183</td>\n",
" <td>64</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>23.3</td>\n",
" <td>0.672</td>\n",
" <td>32</td>\n",
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>1</td>\n",
" <td>89</td>\n",
" <td>66</td>\n",
" <td>23</td>\n",
" <td>94</td>\n",
" <td>28.1</td>\n",
" <td>0.167</td>\n",
" <td>21</td>\n",
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>0</td>\n",
" <td>137</td>\n",
" <td>40</td>\n",
" <td>35</td>\n",
" <td>168</td>\n",
" <td>43.1</td>\n",
" <td>2.288</td>\n",
" <td>33</td>\n",
" <td>1</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Pregnancies Glucose BloodPressure SkinThickness Insulin BMI \\\n",
"0 6 148 72 35 0 33.6 \n",
"1 1 85 66 29 0 26.6 \n",
"2 8 183 64 0 0 23.3 \n",
"3 1 89 66 23 94 28.1 \n",
"4 0 137 40 35 168 43.1 \n",
"\n",
" DiabetesPedigreeFunction Age Outcome \n",
"0 0.627 50 1 \n",
"1 0.351 31 0 \n",
"2 0.672 32 1 \n",
"3 0.167 21 0 \n",
"4 2.288 33 1 "
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# loading the csv dataset\n",
"filepath='./diabetes.csv'\n",
"df=pd.read_csv(filepath)\n",
"rows,cols=df.shape\n",
"print(f'The dataset has {rows} rows and {cols} columns')\n",
"df.head() # showing top five rows"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "bf32a4ff",
"metadata": {},
"outputs": [],
"source": [
"# separating pairs X_i and y_i into matrix Xs and vector ys\n",
"# and then normalizing each data column separately, except the last column\n",
"ys=df['Outcome'].values\n",
"df_xs=df.drop(['Outcome'],axis=1)\n",
"df_xs=(df_xs-df_xs.mean())/df_xs.std()\n",
"Xs=df_xs.to_numpy() #converting to a numpy array"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "50709065",
"metadata": {},
"outputs": [],
"source": [
"def soft_threshold(c,landa):\n",
" if c<-landa:\n",
" return c+landa\n",
" elif c>landa:\n",
" return c-landa\n",
" else:\n",
" return 0\n",
"# coordinate descent for Lasso\n",
"# Xs is a matrix with n rows and q-1 columns\n",
"# ys is a column vector of size n holding the dependent values yi\n",
"def CD_Lasso(Xs,ys,iter=50,landa=1):\n",
" X=np.ones((Xs.shape[0],Xs.shape[1]+1))\n",
" X[:,1:]=Xs.copy()\n",
" q=X.shape[1]\n",
" n=X.shape[0]\n",
" w=.1*np.random.rand(q) \n",
" for k in range(iter):\n",
" for j in range(q):\n",
" xj=X[:,j]\n",
" aj=np.sum(xj**2)\n",
" cj=0\n",
" for i in range(n):\n",
" xi=X[i,:]\n",
" cj+=xi[j]*(ys[i]-np.dot(xi,w)+xi[j]*w[j])\n",
" w[j]=soft_threshold(cj,landa)/aj\n",
" return w"
]
},
{
"cell_type": "markdown",
"id": "fb2f43fb",
"metadata": {},
"source": [
"In the following cell, we use the CD for Lasso with its default $\\lambda$.\n",
"However, you can change its value and observe the difference in parameters and/or accuracies."
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "0c3a7617",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The estimated parameters:\n",
"[ 0.34765625 0.06853232 0.18749844 -0.04260573 0. -0.01774993\n",
" 0.10337061 0.04766322 0.02977783]\n"
]
}
],
"source": [
"# example\n",
"# estimated parameters for diabetes \n",
"# because of L1 norm, \n",
"# we see some (usually unneccesary) parameters are zero or near to zero\n",
"w_hat=CD_Lasso(Xs,ys)\n",
"print(f'The estimated parameters:\\n{w_hat}')"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "dca3f94b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The accuracy of the model for classification: 0.7799479166666666\n"
]
}
],
"source": [
"# measuring accuracy of the model for classification\n",
"# we use value of .5 to thereshold output to zero or one\n",
"X=np.ones((Xs.shape[0],Xs.shape[1]+1))\n",
"X[:,1:]=Xs.copy()\n",
"ys_hat=np.int16(X@w_hat.reshape(-1,1)>.5).flatten() # estimated ys\n",
"accuracy=np.sum(ys_hat==ys)/len(ys)\n",
"print(f'The accuracy of the model for classification: {accuracy}')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8b6d8a05",
"metadata": {},
"outputs": [],
"source": []
}
],
"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.11.1"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|