Advertisement
Guest User

Untitled

a guest
Jan 11th, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.96 KB | None | 0 0
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "markdown",
  5. "metadata": {},
  6. "source": [
  7. "# scikit-learn\n",
  8. "\n",
  9. "### Instalacja\n",
  10. "\n",
  11. "W laboratoriach pakiet `sklearn` powinien być zainstalowany pod Windowsem i Linuxem.\n",
  12. "\n",
  13. "* Pod Linuxem można zainstalować lokalnie:\n",
  14. " pip install --user sklearn\n",
  15. "* lub na własnym komputerze:\n",
  16. " sudo pip install sklearn\n",
  17. "\n",
  18. "Konieczne może być ponowne uruchomienie IPython, jeśli był uruchomiony podczas instalacji.\n",
  19. "\n",
  20. "### Dokumentacja\n",
  21. "\n",
  22. "Pełna dokumentacja: http://scikit-learn.org/0.16. Należy zmienić numer wersji zgodnie z zainstalowaną wersją, aby przejść do właściwej dokumentacji.\n",
  23. "\n",
  24. "## 1. Zapoznanie z pakietem\n",
  25. "\n",
  26. "* Zapoznaj się z [dokumentacją](http://scikit-learn.org/0.16) _scikit-learn_. \n",
  27. "* Na podstawie [API](http://scikit-learn.org/0.16/modules/classes.html), podaj listę dostępnych rodzajów klasyfikatorów i regresorów. Które z metod poznaliśmy na wykładach, a które są nowe?\n",
  28. "* Jakie inne zagadnienia (inne niż modele klasyifikacji/regresji) omawiane na wykładach są uwzględniane w pakiecie `sklearn`? Krótko je opisz."
  29. ]
  30. },
  31. {
  32. "cell_type": "markdown",
  33. "metadata": {},
  34. "source": [
  35. "### Lista Regresorów\n",
  36. "\n",
  37. "An AdaBoost regressor ---\n",
  38. "ensemble.AdaBoostRegressor([base_estimator, ...])\t\n",
  39. "\n",
  40. "A Bagging regressor ---\n",
  41. "ensemble.BaggingRegressor([base_estimator, ...])\n",
  42. "\n",
  43. "An extra-trees regressor. (nowe) ---\n",
  44. "ensemble.ExtraTreesRegressor([n_estimators, ...])\n",
  45. "\n",
  46. "Gradient Boosting for regression. ---\n",
  47. "ensemble.GradientBoostingRegressor([loss, ...])\n",
  48. "\n",
  49. "A random forest regressor. (nowe) ---\n",
  50. "ensemble.RandomForestRegressor([...])\n",
  51. "\n",
  52. "Regression based on k-nearest neighbors. ---\n",
  53. "neighbors.KNeighborsRegressor([n_neighbors, ...])\n",
  54. "\n",
  55. "Regression based on neighbors within a fixed radius. ---\n",
  56. "neighbors.RadiusNeighborsRegressor([radius, ...])\n",
  57. "\n",
  58. "Passive Aggressive Regressor (nowe) ---\n",
  59. "linear_model.PassiveAggressiveRegressor([C, ...])\n",
  60. "\n",
  61. "RANSAC (RANdom SAmple Consensus) algorithm. (nowe) ---\n",
  62. "linear_model.RANSACRegressor([...])\n",
  63. "\n",
  64. "Linear model fitted by minimizing a regularized empirical loss with SGD ---\n",
  65. "linear_model.SGDRegressor([loss, penalty, ...])\n",
  66. "\n",
  67. "Theil-Sen Estimator: robust multivariate regression model. (nowe) ---\n",
  68. "linear_model.TheilSenRegressor([...])\n",
  69. "\n",
  70. "\n",
  71. "### Lista klasyfikatorów\n",
  72. "\n",
  73. "An AdaBoost classifier. ---\n",
  74. "ensemble.AdaBoostClassifier([...])\n",
  75. "\n",
  76. "A Bagging classifier. ---\n",
  77. "ensemble.BaggingClassifier([base_estimator, ...])\n",
  78. "\n",
  79. "An extra-trees classifier. (nowe) ---\n",
  80. "ensemble.ExtraTreesClassifier([...])\n",
  81. "\n",
  82. "Gradient Boosting for classification. ---\n",
  83. "ensemble.GradientBoostingClassifier([loss, ...])\n",
  84. "\n",
  85. "A random forest classifier. (nowe) ---\n",
  86. "ensemble.RandomForestClassifier([...])\n",
  87. "\n",
  88. "Linear classifiers (SVM, logistic regression, a.o.) with SGD training. ---\n",
  89. "linear_model.SGDClassifier([loss, penalty, ...])\n",
  90. "\n",
  91. "Classifier implementing the k-nearest neighbors vote. ---\n",
  92. "neighbors.KNeighborsClassifier([...])\n",
  93. "\n",
  94. "Classifier implementing a vote among neighbors within a given radius ---\n",
  95. "neighbors.RadiusNeighborsClassifier([...])\n",
  96. "\n",
  97. "\n",
  98. "### Znajome zagadnienia\n",
  99. "\n",
  100. "Mini-Batch K-Means clustering ---\n",
  101. "cluster.MiniBatchKMeans([n_clusters, init, ...])\n",
  102. "\n",
  103. "Perceptron ---\n",
  104. "linear_model.Perceptron([penalty, alpha, ...])\n",
  105. "\n",
  106. "Normalize samples individually to unit norm. ----\n",
  107. "preprocessing.Normalizer([norm, copy])\n",
  108. " \n",
  109. "Binding of the cross-validation routine (low-level routine) ---\n",
  110. "svm.libsvm.cross_validation"
  111. ]
  112. },
  113. {
  114. "cell_type": "markdown",
  115. "metadata": {},
  116. "source": [
  117. "## 2. Tutorial\n",
  118. "\n",
  119. "* Zapoznaj się z [wprowadzeniem](http://scikit-learn.org/0.15/tutorial/basic/tutorial.html) do `sklearn`.\n",
  120. "* Opracuj [tutorial \"text analytics\"](http://scikit-learn.org/0.16/tutorial/text_analytics/working_with_text_data.html) w formie notatnika IPython w języku polskim. Opracowanie nie może być wyłącznie tłumaczeniem."
  121. ]
  122. },
  123. {
  124. "cell_type": "markdown",
  125. "metadata": {},
  126. "source": [
  127. "sckikit-learn jest jedną z najlepszyhc bibliotek służocych do implementacji algorytmów uczenia maszynowego. Poniżej, na przykładzie pracy z tekstem zaprezentuję, jak działa ta biblioteka."
  128. ]
  129. },
  130. {
  131. "cell_type": "markdown",
  132. "metadata": {},
  133. "source": [
  134. "### Wczytanie i podstawowe operacje na danych tekstowych\n",
  135. "\n",
  136. "Będziemy korzystach z gotowych danych, które oferuje nam bilbioteka sklearn. Jest to zestaw 20000 dokumentów pogrupowanych w 20 różnych kategoriach.\n",
  137. "\n",
  138. "Na potrzeby szybszych czasów odpalania wybiorę 4 grupy i na ich podstawie wczytam listę artykułów"
  139. ]
  140. },
  141. {
  142. "cell_type": "code",
  143. "execution_count": 1,
  144. "metadata": {
  145. "collapsed": false
  146. },
  147. "outputs": [],
  148. "source": [
  149. "categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med']\n",
  150. "from sklearn.datasets import fetch_20newsgroups\n",
  151. "twenty_train = fetch_20newsgroups(subset='train', categories=categories, shuffle=True, random_state=42)"
  152. ]
  153. },
  154. {
  155. "cell_type": "markdown",
  156. "metadata": {},
  157. "source": [
  158. "Sprawdzimy teraz, czy pliki zostały prawidłowo wczytana, na postawie ilości załadowanych plików i przykładowego fragmentu tekstu"
  159. ]
  160. },
  161. {
  162. "cell_type": "code",
  163. "execution_count": 2,
  164. "metadata": {
  165. "collapsed": false
  166. },
  167. "outputs": [
  168. {
  169. "name": "stdout",
  170. "output_type": "stream",
  171. "text": [
  172. "Liczba plików:\n",
  173. "2257\n",
  174. "Przykładowy dokument:\n",
  175. "From: geb@cs.pitt.edu (Gordon Banks)\n",
  176. "Subject: Re: Blindsight\n",
  177. "Reply-To: geb@cs.pitt.edu (Gordon Banks)\n",
  178. "Organization: Univ. of Pittsburgh Computer Science\n",
  179. "Lines: 18\n",
  180. "\n",
  181. "In article <werner-240393161954@tol7mac15.soe.berkeley.edu> werner@soe.berkeley.edu (John Werner) writes:\n",
  182. ">In article <19213@pitt.UUCP>, geb@cs.pitt.edu (Gordon Banks) wrote:\n",
  183. ">> \n",
  184. ">> Explain. I thought there were 3 types of cones, equivalent to RGB.\n",
  185. ">\n",
  186. ">You're basically right, but I think there are just 2 types. One is\n",
  187. ">sensitive to red and green, and the other is sensitive to blue and yellow. \n",
  188. ">This is why the two most common kinds of color-blindness are red-green and\n",
  189. ">blue-yellow.\n",
  190. ">\n",
  191. "\n",
  192. "Yes, I remember that now. Well, in that case, the cones are indeed\n",
  193. "color sensitive, contrary to what the original respondent had claimed.\n",
  194. "-- \n",
  195. "----------------------------------------------------------------------------\n",
  196. "Gordon Banks N3JXP | \"Skepticism is the chastity of the intellect, and\n",
  197. "geb@cadre.dsl.pitt.edu | it is shameful to surrender it too soon.\" \n",
  198. "----------------------------------------------------------------------------\n",
  199. "\n"
  200. ]
  201. }
  202. ],
  203. "source": [
  204. "print \"Liczba plików:\"\n",
  205. "print len(twenty_train.data)\n",
  206. "print \"Przykładowy dokument:\"\n",
  207. "print(\"\\n\".join(twenty_train.data[8].split(\"\\n\")))"
  208. ]
  209. },
  210. {
  211. "cell_type": "markdown",
  212. "metadata": {},
  213. "source": [
  214. "Aby móc pracować algorytmami uczenia maszynowego potrzebujemy poznać kategorię dokumentów. Możemy to zrobić w następujący sposób:"
  215. ]
  216. },
  217. {
  218. "cell_type": "code",
  219. "execution_count": 3,
  220. "metadata": {
  221. "collapsed": false
  222. },
  223. "outputs": [
  224. {
  225. "name": "stdout",
  226. "output_type": "stream",
  227. "text": [
  228. "[1 1 3 3 3]\n",
  229. "comp.graphics\n",
  230. "comp.graphics\n",
  231. "soc.religion.christian\n",
  232. "soc.religion.christian\n",
  233. "soc.religion.christian\n"
  234. ]
  235. }
  236. ],
  237. "source": [
  238. "print twenty_train.target[:5]\n",
  239. "for t in twenty_train.target[:5]:\n",
  240. " print(twenty_train.target_names[t])"
  241. ]
  242. },
  243. {
  244. "cell_type": "markdown",
  245. "metadata": {},
  246. "source": [
  247. "### Wydobywanie cech z tekstu\n",
  248. "\n",
  249. "Aby zacząć pracować nad tekstami, należy wydobyć z nich cechy.\n",
  250. "Skorzystamy z gotowych funkcji i zbudujemy na podstawie naszych tekstów słownik."
  251. ]
  252. },
  253. {
  254. "cell_type": "code",
  255. "execution_count": 4,
  256. "metadata": {
  257. "collapsed": false
  258. },
  259. "outputs": [],
  260. "source": [
  261. "from sklearn.feature_extraction.text import CountVectorizer\n",
  262. "count_vect = CountVectorizer()\n",
  263. "X_train_counts = count_vect.fit_transform(twenty_train.data)"
  264. ]
  265. },
  266. {
  267. "cell_type": "markdown",
  268. "metadata": {},
  269. "source": [
  270. "Możemy teraz sprawdzić ile razy występuje dany wyraz w naszym słowniku (wyraz ten jest naszą cechą)"
  271. ]
  272. },
  273. {
  274. "cell_type": "code",
  275. "execution_count": 5,
  276. "metadata": {
  277. "collapsed": false
  278. },
  279. "outputs": [
  280. {
  281. "name": "stdout",
  282. "output_type": "stream",
  283. "text": [
  284. "Wyraz 'computer' występuje 9338 razy\n"
  285. ]
  286. }
  287. ],
  288. "source": [
  289. "print \"Wyraz 'computer' występuje {} razy\".format(count_vect.vocabulary_.get(u'computer'))"
  290. ]
  291. },
  292. {
  293. "cell_type": "markdown",
  294. "metadata": {},
  295. "source": [
  296. "Kiedy potrafimy utworzyć już słownik z gotowych tekstów jesteśmy na dobrej drodze, aby zacząć analizować częstotliwość wystąpienia danych słów. Pamiętajmy również, że dłuże teksty mogą mieć więcej wystąpień danego słowa, a krótsze mniej, lecz nadal mogą dotyczyć tego samego tematu. Częstotliwość wystąpień danego wyrazu w obrębie tekstu będziemy nazywać tf (od ang. \"Term Frequencies\"). Z kolei tf-idf będziemy nazywać mało istotne słowa które często się pojawiają i nie mają dużego wpływu na grupę dokumentu. tf i tf-idf możemy obliczyć w następujący sposób:"
  297. ]
  298. },
  299. {
  300. "cell_type": "code",
  301. "execution_count": 6,
  302. "metadata": {
  303. "collapsed": true
  304. },
  305. "outputs": [],
  306. "source": [
  307. "from sklearn.feature_extraction.text import TfidfTransformer\n",
  308. "tfidf_transformer = TfidfTransformer()\n",
  309. "X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)"
  310. ]
  311. },
  312. {
  313. "cell_type": "markdown",
  314. "metadata": {},
  315. "source": [
  316. "### Trenowanie klasyfikatora\n",
  317. "\n",
  318. "Kiedy mamy już nasze cechy (słowa) możemy przystąpić do trenowania klasyfikatora, który postara się przewidzieć kategorię dokumentu\n",
  319. "Zacznijmy od naiwnego klasyfikatora bayesowskiego."
  320. ]
  321. },
  322. {
  323. "cell_type": "code",
  324. "execution_count": 7,
  325. "metadata": {
  326. "collapsed": true
  327. },
  328. "outputs": [],
  329. "source": [
  330. "from sklearn.naive_bayes import MultinomialNB\n",
  331. "clf = MultinomialNB().fit(X_train_tfidf, twenty_train.target)"
  332. ]
  333. },
  334. {
  335. "cell_type": "markdown",
  336. "metadata": {},
  337. "source": [
  338. "Spróbujmy teraz podać krótki przykład tekstu i zobaczyć do jakiej kategorii zostanie przypisany"
  339. ]
  340. },
  341. {
  342. "cell_type": "code",
  343. "execution_count": 8,
  344. "metadata": {
  345. "collapsed": false
  346. },
  347. "outputs": [
  348. {
  349. "name": "stdout",
  350. "output_type": "stream",
  351. "text": [
  352. "In monotheism, God is conceived of as the Supreme Being and principal object of faith. The concept of God as described by most theologians includes the attributes of omniscience (infinite knowledge), omnipotence (unlimited power), omnipresence (present everywhere), divine simplicity, and as having an eternal and necessary existence.\n",
  353. "Powyższy tekst należy do kategorii: soc.religion.christian\n",
  354. "\n",
  355. "A video card (also called a display card, graphics card, display adapter or graphics adapter) is an expansion card which generates a feed of output images to a display (such as a computer monitor). Frequently, these are advertised as discrete or dedicated graphics cards, emphasizing the distinction between these and integrated graphics.\n",
  356. "Powyższy tekst należy do kategorii: comp.graphics\n",
  357. "\n",
  358. "Penicillin (PCN or pen) is a group of antibiotics which include penicillin G (intravenous use), penicillin V (use by mouth), and procaine penicillin, and benzathine penicillin (intramuscular use). Penicillin antibiotics were among the first medications to be effective against many bacterial infections caused by staphylococci and streptococci.\n",
  359. "Powyższy tekst należy do kategorii: sci.med\n",
  360. "\n",
  361. "Atheism is, in the broadest sense, the absence of belief in the existence of deities. Less broadly, atheism is the rejection of belief that any deities exist. In an even narrower sense, atheism is specifically the position that there are no deities. Atheism is contrasted with theism, which, in its most general form, is the belief that at least one deity exists.\n",
  362. "Powyższy tekst należy do kategorii: alt.atheism\n",
  363. "\n"
  364. ]
  365. }
  366. ],
  367. "source": [
  368. "docs_new = ['In monotheism, God is conceived of as the Supreme Being and principal object of faith. The concept of God as described by most theologians includes the attributes of omniscience (infinite knowledge), omnipotence (unlimited power), omnipresence (present everywhere), divine simplicity, and as having an eternal and necessary existence.', \n",
  369. " 'A video card (also called a display card, graphics card, display adapter or graphics adapter) is an expansion card which generates a feed of output images to a display (such as a computer monitor). Frequently, these are advertised as discrete or dedicated graphics cards, emphasizing the distinction between these and integrated graphics.',\n",
  370. " 'Penicillin (PCN or pen) is a group of antibiotics which include penicillin G (intravenous use), penicillin V (use by mouth), and procaine penicillin, and benzathine penicillin (intramuscular use). Penicillin antibiotics were among the first medications to be effective against many bacterial infections caused by staphylococci and streptococci.',\n",
  371. " 'Atheism is, in the broadest sense, the absence of belief in the existence of deities. Less broadly, atheism is the rejection of belief that any deities exist. In an even narrower sense, atheism is specifically the position that there are no deities. Atheism is contrasted with theism, which, in its most general form, is the belief that at least one deity exists.']\n",
  372. "X_new_counts = count_vect.transform(docs_new)\n",
  373. "X_new_tfidf = tfidf_transformer.transform(X_new_counts)\n",
  374. "\n",
  375. "predicted = clf.predict(X_new_tfidf)\n",
  376. "\n",
  377. "for doc, category in zip(docs_new, predicted):\n",
  378. " print(doc)\n",
  379. " print \"Powyższy tekst należy do kategorii: \"+twenty_train.target_names[category]\n",
  380. " print"
  381. ]
  382. },
  383. {
  384. "cell_type": "markdown",
  385. "metadata": {},
  386. "source": [
  387. "### Budowanie przepływu\n",
  388. "Używając przepływu, można zapisać to co analizowaliśmy wsześniej w jednej linijce w następujący sposób:"
  389. ]
  390. },
  391. {
  392. "cell_type": "code",
  393. "execution_count": 9,
  394. "metadata": {
  395. "collapsed": false
  396. },
  397. "outputs": [],
  398. "source": [
  399. "from sklearn.pipeline import Pipeline\n",
  400. "text_clf = Pipeline([('vect', CountVectorizer()),\n",
  401. " ('tfidf', TfidfTransformer()),\n",
  402. " ('clf', MultinomialNB()),\n",
  403. "])\n",
  404. "text_clf = text_clf.fit(twenty_train.data, twenty_train.target)"
  405. ]
  406. },
  407. {
  408. "cell_type": "markdown",
  409. "metadata": {},
  410. "source": [
  411. "### Sprawdzanie poprawności na zbiorze testowym\n",
  412. "Sprawdzanie poprawności na zbiorze jest bardzo proste i możemy to uzyskać wykonując następujące operacje:"
  413. ]
  414. },
  415. {
  416. "cell_type": "code",
  417. "execution_count": 10,
  418. "metadata": {
  419. "collapsed": false
  420. },
  421. "outputs": [
  422. {
  423. "name": "stdout",
  424. "output_type": "stream",
  425. "text": [
  426. "Nasz klasyfikator uzyskał skuteczność na poziomie 83.4886817577%\n"
  427. ]
  428. }
  429. ],
  430. "source": [
  431. "import numpy as np\n",
  432. "twenty_test = fetch_20newsgroups(subset='test', categories=categories, shuffle=True, random_state=42)\n",
  433. "docs_test = twenty_test.data\n",
  434. "predicted = text_clf.predict(docs_test)\n",
  435. "print \"Nasz klasyfikator uzyskał skuteczność na poziomie {}%\".format(np.mean(predicted == twenty_test.target)*100) "
  436. ]
  437. },
  438. {
  439. "cell_type": "markdown",
  440. "metadata": {},
  441. "source": [
  442. "Spróbujmy uzyskać lepszą skuteczność posługując się innym klasyfikatorem. Wykorzystajmy do tego maszynę wektorów nośnych, która dla danych tekstowych może przynieść lepszą skuteczność, lecz niestety z dłuższym czasem przetwarzania."
  443. ]
  444. },
  445. {
  446. "cell_type": "code",
  447. "execution_count": 11,
  448. "metadata": {
  449. "collapsed": false
  450. },
  451. "outputs": [
  452. {
  453. "name": "stdout",
  454. "output_type": "stream",
  455. "text": [
  456. "Nasz klasyfikator uzyskał skuteczność na poziomie 91.2782956059%\n"
  457. ]
  458. }
  459. ],
  460. "source": [
  461. "from sklearn.linear_model import SGDClassifier\n",
  462. "text_clf = Pipeline([('vect', CountVectorizer()),\n",
  463. " ('tfidf', TfidfTransformer()),\n",
  464. " ('clf', SGDClassifier(loss='hinge', penalty='l2',\n",
  465. " alpha=1e-3, n_iter=5, random_state=42)),\n",
  466. "])\n",
  467. "_ = text_clf.fit(twenty_train.data, twenty_train.target)\n",
  468. "predicted = text_clf.predict(docs_test)\n",
  469. "print \"Nasz klasyfikator uzyskał skuteczność na poziomie {}%\".format(np.mean(predicted == twenty_test.target)*100) "
  470. ]
  471. },
  472. {
  473. "cell_type": "markdown",
  474. "metadata": {},
  475. "source": [
  476. "Jeżeli zwykły procentowy wynik to dla nas za mało, może równie łatwo zdobyć bardziej szczegółowe statystyki w następujący sposób:"
  477. ]
  478. },
  479. {
  480. "cell_type": "code",
  481. "execution_count": 12,
  482. "metadata": {
  483. "collapsed": false
  484. },
  485. "outputs": [
  486. {
  487. "name": "stdout",
  488. "output_type": "stream",
  489. "text": [
  490. " precision recall f1-score support\n",
  491. "\n",
  492. " alt.atheism 0.95 0.81 0.87 319\n",
  493. " comp.graphics 0.88 0.97 0.92 389\n",
  494. " sci.med 0.94 0.90 0.92 396\n",
  495. "soc.religion.christian 0.90 0.95 0.93 398\n",
  496. "\n",
  497. " avg / total 0.92 0.91 0.91 1502\n",
  498. "\n"
  499. ]
  500. }
  501. ],
  502. "source": [
  503. "from sklearn import metrics\n",
  504. "print(metrics.classification_report(twenty_test.target, predicted,\n",
  505. " target_names=twenty_test.target_names))"
  506. ]
  507. }
  508. ],
  509. "metadata": {
  510. "anaconda-cloud": {},
  511. "hide_input": false,
  512. "kernelspec": {
  513. "display_name": "Python [conda root]",
  514. "language": "python",
  515. "name": "conda-root-py"
  516. },
  517. "language_info": {
  518. "codemirror_mode": {
  519. "name": "ipython",
  520. "version": 2
  521. },
  522. "file_extension": ".py",
  523. "mimetype": "text/x-python",
  524. "name": "python",
  525. "nbconvert_exporter": "python",
  526. "pygments_lexer": "ipython2",
  527. "version": "2.7.12"
  528. }
  529. },
  530. "nbformat": 4,
  531. "nbformat_minor": 0
  532. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement