Guest User

Untitled

a guest
Jan 21st, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.39 KB | None | 0 0
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "code",
  5. "execution_count": 153,
  6. "metadata": {
  7. "autoscroll": false,
  8. "collapsed": false,
  9. "ein.hycell": false,
  10. "ein.tags": "worksheet-0",
  11. "slideshow": {
  12. "slide_type": "-"
  13. }
  14. },
  15. "outputs": [],
  16. "source": [
  17. "import pandas as pd\n",
  18. "import numpy as np\n",
  19. "from sklearn.linear_model import LinearRegression\n",
  20. "\n",
  21. "import warnings\n",
  22. "warnings.filterwarnings('ignore')"
  23. ]
  24. },
  25. {
  26. "cell_type": "markdown",
  27. "metadata": {
  28. "ein.tags": "worksheet-0",
  29. "slideshow": {
  30. "slide_type": "-"
  31. }
  32. },
  33. "source": [
  34. "### Load data\n",
  35. "\n",
  36. "We know that we will want to include sex. \n",
  37. "\n",
  38. "If we assume a linear model, then we can regress our target variable on sex, and use the residuals to pick among the remaining variables."
  39. ]
  40. },
  41. {
  42. "cell_type": "code",
  43. "execution_count": 201,
  44. "metadata": {
  45. "autoscroll": false,
  46. "collapsed": false,
  47. "ein.hycell": false,
  48. "ein.tags": "worksheet-0",
  49. "slideshow": {
  50. "slide_type": "-"
  51. }
  52. },
  53. "outputs": [],
  54. "source": [
  55. "dat = pd.read_csv('train_data.txt', sep=' ', header=None)\n",
  56. "\n",
  57. "y = dat.values[:, 0]\n",
  58. "X = dat.values[:, 1:]\n",
  59. "\n",
  60. "sex = X[:, 1].reshape(-1,1)\n",
  61. "markers = X[:, 1:]\n",
  62. "\n",
  63. "lin = LinearRegression()\n",
  64. "lin.fit(sex, y)\n",
  65. "err = y - lin.predict(sex)"
  66. ]
  67. },
  68. {
  69. "cell_type": "markdown",
  70. "metadata": {
  71. "ein.tags": "worksheet-0",
  72. "slideshow": {
  73. "slide_type": "-"
  74. }
  75. },
  76. "source": [
  77. "### Lasso\n",
  78. "\n",
  79. "A first attempt might be to run Lasso on our markers and the residuals. This gives us a couple of markers, which is a good start!"
  80. ]
  81. },
  82. {
  83. "cell_type": "code",
  84. "execution_count": 211,
  85. "metadata": {
  86. "autoscroll": false,
  87. "collapsed": false,
  88. "ein.hycell": false,
  89. "ein.tags": "worksheet-0",
  90. "slideshow": {
  91. "slide_type": "-"
  92. }
  93. },
  94. "outputs": [],
  95. "source": [
  96. "from sklearn.linear_model import LassoCV\n",
  97. "\n",
  98. "def lasso_selection(X, y):\n",
  99. " model = LassoCV(cv=3)\n",
  100. " model.fit(X, y)\n",
  101. " selected = np.argwhere(model.coef_ != 0).reshape(-1)\n",
  102. " best_score = np.min(model.mse_path_.mean(1))\n",
  103. " return selected, best_score"
  104. ]
  105. },
  106. {
  107. "cell_type": "code",
  108. "execution_count": 218,
  109. "metadata": {
  110. "autoscroll": false,
  111. "collapsed": false,
  112. "ein.hycell": false,
  113. "ein.tags": "worksheet-0",
  114. "slideshow": {
  115. "slide_type": "-"
  116. }
  117. },
  118. "outputs": [
  119. {
  120. "data": {
  121. "text/plain": [
  122. "(array([4860, 4999]), 9.636899707219222, 8.2643213236732)"
  123. ]
  124. },
  125. "execution_count": 218,
  126. "metadata": {},
  127. "output_type": "execute_result"
  128. }
  129. ],
  130. "source": [
  131. "simple_lasso_markers, best_score = lasso_selection(markers, err)\n",
  132. "simple_lasso_markers, best_score, score_ols(simple_lasso_markers, sex, markers, y)"
  133. ]
  134. },
  135. {
  136. "cell_type": "markdown",
  137. "metadata": {
  138. "ein.tags": "worksheet-0",
  139. "slideshow": {
  140. "slide_type": "-"
  141. }
  142. },
  143. "source": [
  144. "# Prescreen and run OLS\n",
  145. "\n",
  146. "Another option, might be to do a simple prescreening based on partial correlations, and then do an exhaustive search over the space of linear models created by the top _ markers by partial correlation.\n",
  147. "\n",
  148. "This gives us 4 markers, and a much better cross-validated MSE. "
  149. ]
  150. },
  151. {
  152. "cell_type": "code",
  153. "execution_count": 205,
  154. "metadata": {
  155. "autoscroll": false,
  156. "collapsed": false,
  157. "ein.hycell": false,
  158. "ein.tags": "worksheet-0",
  159. "slideshow": {
  160. "slide_type": "-"
  161. }
  162. },
  163. "outputs": [],
  164. "source": [
  165. "from itertools import combinations\n",
  166. "\n",
  167. "def prescreen(X, y, top):\n",
  168. " cors = [pd.Series(y).corr(m) for _,m in pd.DataFrame(X).T.iterrows()]\n",
  169. " sorted_corrs = list(pd.Series(cors).abs().sort_values(ascending=False).index)\n",
  170. " x = [[np.array(l) for l in list(combinations(sorted_corrs[:top], i))] for i in range(1,5)]\n",
  171. " return [i for l in x for i in l], sorted_corrs\n",
  172. "\n",
  173. "def score_ols(i, sex, markers, y):\n",
  174. " final_X = np.concatenate([sex, markers[:, i]], 1)\n",
  175. " l = LinearRegression()\n",
  176. " return -np.mean(cross_val_score(l,final_X, y, cv=3, scoring = 'neg_mean_squared_error'))"
  177. ]
  178. },
  179. {
  180. "cell_type": "code",
  181. "execution_count": 206,
  182. "metadata": {
  183. "autoscroll": false,
  184. "collapsed": false,
  185. "ein.hycell": false,
  186. "ein.tags": "worksheet-0",
  187. "slideshow": {
  188. "slide_type": "-"
  189. }
  190. },
  191. "outputs": [
  192. {
  193. "data": {
  194. "text/plain": [
  195. "(array([4999, 4998, 4860, 3211]), 2.7520014965420962)"
  196. ]
  197. },
  198. "execution_count": 206,
  199. "metadata": {},
  200. "output_type": "execute_result"
  201. }
  202. ],
  203. "source": [
  204. "screened, sorted_corrs = prescreen(markers, err, 6)\n",
  205. "scores = [score_ols(i, sex, markers, y) for i in screened] \n",
  206. "combinitorial_markers = screened[np.argsort(scores)[0]]\n",
  207. "\n",
  208. "combinitorial_markers, np.min(scores)"
  209. ]
  210. },
  211. {
  212. "cell_type": "markdown",
  213. "metadata": {
  214. "ein.tags": "worksheet-0",
  215. "slideshow": {
  216. "slide_type": "-"
  217. }
  218. },
  219. "source": [
  220. "### Use Lasso on the prescreened variables \n",
  221. "\n",
  222. "Another option could be to use Lasso in combination with the prescreened variables, thus running Lasso on the top (50) variables by partial correlation. "
  223. ]
  224. },
  225. {
  226. "cell_type": "code",
  227. "execution_count": 217,
  228. "metadata": {
  229. "autoscroll": false,
  230. "collapsed": false,
  231. "ein.hycell": false,
  232. "ein.tags": "worksheet-0",
  233. "slideshow": {
  234. "slide_type": "-"
  235. }
  236. },
  237. "outputs": [
  238. {
  239. "data": {
  240. "text/plain": [
  241. "(27, 3.548344879465436, 4.006063575106914)"
  242. ]
  243. },
  244. "execution_count": 217,
  245. "metadata": {},
  246. "output_type": "execute_result"
  247. }
  248. ],
  249. "source": [
  250. "idx = sorted_corrs[:50]\n",
  251. "model = LassoCV()\n",
  252. "model.fit(markers[:, idx], err)\n",
  253. "lasso_markers = np.array(sorted_corrs)[np.argwhere(model.coef_ != 0).reshape(-1)]\n",
  254. "best_score = np.min(np.mean(model.mse_path_, axis=1))\n",
  255. "\n",
  256. "len(lasso_markers), best_score, score_ols(lasso_markers, sex, markers, y)"
  257. ]
  258. },
  259. {
  260. "cell_type": "markdown",
  261. "metadata": {
  262. "ein.tags": "worksheet-0",
  263. "slideshow": {
  264. "slide_type": "-"
  265. }
  266. },
  267. "source": [
  268. "### Adding an L2 regularization\n",
  269. "\n",
  270. "Our Lasso didn't do quite as well as our simple prescreening. But it also picked many more markers (27 vs 4). Now that we have our variables selected, we find that adding a regularization parameter improves the cross-validation scores. This is intuitive, as our dataset is very small, and even with a small number of selected markers, the results of the simple OLS can be sensitive to high leverage points. Regularization reduces that sensitivity, and an L2 regularization allows us to keep all our chosen markers. "
  271. ]
  272. },
  273. {
  274. "cell_type": "code",
  275. "execution_count": 219,
  276. "metadata": {
  277. "autoscroll": false,
  278. "collapsed": false,
  279. "ein.hycell": false,
  280. "ein.tags": "worksheet-0",
  281. "slideshow": {
  282. "slide_type": "-"
  283. }
  284. },
  285. "outputs": [],
  286. "source": [
  287. "from sklearn.linear_model import RidgeCV, Ridge\n",
  288. "\n",
  289. "def ridger(ids, sex, markers, y):\n",
  290. " final_X = np.concatenate([sex, markers[:, ids]], 1)\n",
  291. " model = RidgeCV(cv=3)\n",
  292. " model.fit(final_X, y)\n",
  293. "\n",
  294. " model = Ridge(alpha = model.alpha_)\n",
  295. " score = -np.mean(cross_val_score(model, final_X, y, cv=3, scoring = 'neg_mean_squared_error'))\n",
  296. " return model, score"
  297. ]
  298. },
  299. {
  300. "cell_type": "code",
  301. "execution_count": 220,
  302. "metadata": {
  303. "autoscroll": false,
  304. "collapsed": false,
  305. "ein.hycell": false,
  306. "ein.tags": "worksheet-0",
  307. "slideshow": {
  308. "slide_type": "-"
  309. }
  310. },
  311. "outputs": [
  312. {
  313. "data": {
  314. "text/plain": [
  315. "1.6131415123627557"
  316. ]
  317. },
  318. "execution_count": 220,
  319. "metadata": {},
  320. "output_type": "execute_result"
  321. }
  322. ],
  323. "source": [
  324. "model,score = ridger(lasso_markers, sex, markers, y)\n",
  325. "score"
  326. ]
  327. }
  328. ],
  329. "metadata": {
  330. "kernelspec": {
  331. "display_name": "Python 3",
  332. "name": "python3"
  333. },
  334. "name": "Untitled.ipynb"
  335. },
  336. "nbformat": 4,
  337. "nbformat_minor": 2
  338. }
Add Comment
Please, Sign In to add comment