You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

fastnlp_tutorial_1.ipynb 52 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "markdown",
  5. "id": "cdc25fcd",
  6. "metadata": {},
  7. "source": [
  8. "# T1. dataset 和 vocabulary 的基本使用\n",
  9. "\n",
  10. "  1   dataset 的使用与结构\n",
  11. " \n",
  12. "    1.1   dataset 的结构与创建\n",
  13. "\n",
  14. "    1.2   dataset 的数据预处理\n",
  15. "\n",
  16. "    1.3   延伸:instance 和 field\n",
  17. "\n",
  18. "  2   vocabulary 的结构与使用\n",
  19. "\n",
  20. "    2.1   vocabulary 的创建与修改\n",
  21. "\n",
  22. "    2.2   vocabulary 与 OOV 问题\n",
  23. "\n",
  24. "  3   dataset 和 vocabulary 的组合使用\n",
  25. " \n",
  26. "    3.1   从 dataframe 中加载 dataset\n",
  27. "\n",
  28. "    3.2   从 dataset 中获取 vocabulary"
  29. ]
  30. },
  31. {
  32. "cell_type": "markdown",
  33. "id": "0eb18a22",
  34. "metadata": {},
  35. "source": [
  36. "## 1. dataset 的基本使用\n",
  37. "\n",
  38. "### 1.1 dataset 的结构与创建\n",
  39. "\n",
  40. "在`fastNLP 0.8`中,使用`DataSet`模块表示数据集,**`dataset`类似于关系型数据库中的数据表**(下文统一为小写`dataset`)\n",
  41. "\n",
  42. "  **主要包含`field`字段和`instance`实例两个元素**,对应`table`中的`field`字段和`record`记录\n",
  43. "\n",
  44. "在`fastNLP 0.8`中,`DataSet`模块被定义在`fastNLP.core.dataset`路径下,导入该模块后,最简单的\n",
  45. "\n",
  46. "  初始化方法,即将字典形式的表格 **`{'field1': column1, 'field2': column2, ...}`** 传入构造函数"
  47. ]
  48. },
  49. {
  50. "cell_type": "code",
  51. "execution_count": 1,
  52. "id": "a1d69ad2",
  53. "metadata": {},
  54. "outputs": [
  55. {
  56. "data": {
  57. "text/html": [
  58. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
  59. "</pre>\n"
  60. ],
  61. "text/plain": [
  62. "\n"
  63. ]
  64. },
  65. "metadata": {},
  66. "output_type": "display_data"
  67. },
  68. {
  69. "name": "stdout",
  70. "output_type": "stream",
  71. "text": [
  72. "+-----+------------------------+------------------------+-----+\n",
  73. "| idx | sentence | words | num |\n",
  74. "+-----+------------------------+------------------------+-----+\n",
  75. "| 0 | This is an apple . | ['This', 'is', 'an'... | 5 |\n",
  76. "| 1 | I like apples . | ['I', 'like', 'appl... | 4 |\n",
  77. "| 2 | Apples are good for... | ['Apples', 'are', '... | 7 |\n",
  78. "+-----+------------------------+------------------------+-----+\n"
  79. ]
  80. }
  81. ],
  82. "source": [
  83. "from fastNLP.core.dataset import DataSet\n",
  84. "\n",
  85. "data = {'idx': [0, 1, 2], \n",
  86. " 'sentence':[\"This is an apple .\", \"I like apples .\", \"Apples are good for our health .\"],\n",
  87. " 'words': [['This', 'is', 'an', 'apple', '.'], \n",
  88. " ['I', 'like', 'apples', '.'], \n",
  89. " ['Apples', 'are', 'good', 'for', 'our', 'health', '.']],\n",
  90. " 'num': [5, 4, 7]}\n",
  91. "\n",
  92. "dataset = DataSet(data)\n",
  93. "print(dataset)"
  94. ]
  95. },
  96. {
  97. "cell_type": "markdown",
  98. "id": "9260fdc6",
  99. "metadata": {},
  100. "source": [
  101. "&emsp; 在`dataset`的实例中,字段`field`的名称和实例`instance`中的字符串也可以中文"
  102. ]
  103. },
  104. {
  105. "cell_type": "code",
  106. "execution_count": 2,
  107. "id": "3d72ef00",
  108. "metadata": {},
  109. "outputs": [
  110. {
  111. "name": "stdout",
  112. "output_type": "stream",
  113. "text": [
  114. "+------+--------------------+------------------------+------+\n",
  115. "| 序号 | 句子 | 字符 | 长度 |\n",
  116. "+------+--------------------+------------------------+------+\n",
  117. "| 0 | 生活就像海洋, | ['生', '活', '就', ... | 7 |\n",
  118. "| 1 | 只有意志坚强的人, | ['只', '有', '意', ... | 9 |\n",
  119. "| 2 | 才能到达彼岸。 | ['才', '能', '到', ... | 7 |\n",
  120. "+------+--------------------+------------------------+------+\n"
  121. ]
  122. }
  123. ],
  124. "source": [
  125. "temp = {'序号': [0, 1, 2], \n",
  126. " '句子':[\"生活就像海洋,\", \"只有意志坚强的人,\", \"才能到达彼岸。\"],\n",
  127. " '字符': [['生', '活', '就', '像', '海', '洋', ','], \n",
  128. " ['只', '有', '意', '志', '坚', '强', '的', '人', ','], \n",
  129. " ['才', '能', '到', '达', '彼', '岸', '。']],\n",
  130. " '长度': [7, 9, 7]}\n",
  131. "\n",
  132. "chinese = DataSet(temp)\n",
  133. "print(chinese)"
  134. ]
  135. },
  136. {
  137. "cell_type": "markdown",
  138. "id": "202e5490",
  139. "metadata": {},
  140. "source": [
  141. "在`dataset`中,使用`drop`方法可以删除满足条件的实例,这里使用了python中的`lambda`表达式\n",
  142. "\n",
  143. "&emsp; 注一:在`drop`方法中,通过设置`inplace`参数将删除对应实例后的`dataset`作为一个新的实例生成"
  144. ]
  145. },
  146. {
  147. "cell_type": "code",
  148. "execution_count": 3,
  149. "id": "09b478f8",
  150. "metadata": {},
  151. "outputs": [
  152. {
  153. "name": "stdout",
  154. "output_type": "stream",
  155. "text": [
  156. "2438703969992 2438374526920\n",
  157. "+-----+------------------------+------------------------+-----+\n",
  158. "| idx | sentence | words | num |\n",
  159. "+-----+------------------------+------------------------+-----+\n",
  160. "| 0 | This is an apple . | ['This', 'is', 'an'... | 5 |\n",
  161. "| 2 | Apples are good for... | ['Apples', 'are', '... | 7 |\n",
  162. "+-----+------------------------+------------------------+-----+\n",
  163. "+-----+------------------------+------------------------+-----+\n",
  164. "| idx | sentence | words | num |\n",
  165. "+-----+------------------------+------------------------+-----+\n",
  166. "| 0 | This is an apple . | ['This', 'is', 'an'... | 5 |\n",
  167. "| 1 | I like apples . | ['I', 'like', 'appl... | 4 |\n",
  168. "| 2 | Apples are good for... | ['Apples', 'are', '... | 7 |\n",
  169. "+-----+------------------------+------------------------+-----+\n"
  170. ]
  171. }
  172. ],
  173. "source": [
  174. "dropped = dataset\n",
  175. "dropped = dropped.drop(lambda ins:ins['num'] < 5, inplace=False)\n",
  176. "print(id(dropped), id(dataset))\n",
  177. "print(dropped)\n",
  178. "print(dataset)"
  179. ]
  180. },
  181. {
  182. "cell_type": "markdown",
  183. "id": "aa277674",
  184. "metadata": {},
  185. "source": [
  186. "&emsp; 注二:在`fastNLP 0.8`中,**对`dataset`使用等号**,**其效果是传引用**,**而不是赋值**(???)\n",
  187. "\n",
  188. "&emsp; &emsp; 如下所示,**`dropped`和`dataset`具有相同`id`**,**对`dropped`执行删除操作`dataset`同时会被修改**"
  189. ]
  190. },
  191. {
  192. "cell_type": "code",
  193. "execution_count": 4,
  194. "id": "77c8583a",
  195. "metadata": {},
  196. "outputs": [
  197. {
  198. "name": "stdout",
  199. "output_type": "stream",
  200. "text": [
  201. "2438374526920 2438374526920\n",
  202. "+-----+------------------------+------------------------+-----+\n",
  203. "| idx | sentence | words | num |\n",
  204. "+-----+------------------------+------------------------+-----+\n",
  205. "| 0 | This is an apple . | ['This', 'is', 'an'... | 5 |\n",
  206. "| 2 | Apples are good for... | ['Apples', 'are', '... | 7 |\n",
  207. "+-----+------------------------+------------------------+-----+\n",
  208. "+-----+------------------------+------------------------+-----+\n",
  209. "| idx | sentence | words | num |\n",
  210. "+-----+------------------------+------------------------+-----+\n",
  211. "| 0 | This is an apple . | ['This', 'is', 'an'... | 5 |\n",
  212. "| 2 | Apples are good for... | ['Apples', 'are', '... | 7 |\n",
  213. "+-----+------------------------+------------------------+-----+\n"
  214. ]
  215. }
  216. ],
  217. "source": [
  218. "dropped = dataset\n",
  219. "dropped.drop(lambda ins:ins['num'] < 5)\n",
  220. "print(id(dropped), id(dataset))\n",
  221. "print(dropped)\n",
  222. "print(dataset)"
  223. ]
  224. },
  225. {
  226. "cell_type": "markdown",
  227. "id": "a76199dc",
  228. "metadata": {},
  229. "source": [
  230. "在`dataset`中,使用`delet_instance`方法可以删除对应序号的`instance`实例,序号从0开始"
  231. ]
  232. },
  233. {
  234. "cell_type": "code",
  235. "execution_count": 5,
  236. "id": "d8824b40",
  237. "metadata": {},
  238. "outputs": [
  239. {
  240. "name": "stdout",
  241. "output_type": "stream",
  242. "text": [
  243. "+-----+--------------------+------------------------+-----+\n",
  244. "| idx | sentence | words | num |\n",
  245. "+-----+--------------------+------------------------+-----+\n",
  246. "| 0 | This is an apple . | ['This', 'is', 'an'... | 5 |\n",
  247. "| 1 | I like apples . | ['I', 'like', 'appl... | 4 |\n",
  248. "+-----+--------------------+------------------------+-----+\n"
  249. ]
  250. }
  251. ],
  252. "source": [
  253. "dataset = DataSet(data)\n",
  254. "dataset.delete_instance(2)\n",
  255. "print(dataset)"
  256. ]
  257. },
  258. {
  259. "cell_type": "markdown",
  260. "id": "f4fa9f33",
  261. "metadata": {},
  262. "source": [
  263. "在`dataset`中,使用`delet_field`方法可以删除对应名称的`field`字段"
  264. ]
  265. },
  266. {
  267. "cell_type": "code",
  268. "execution_count": 6,
  269. "id": "f68ddb40",
  270. "metadata": {},
  271. "outputs": [
  272. {
  273. "name": "stdout",
  274. "output_type": "stream",
  275. "text": [
  276. "+-----+--------------------+------------------------------+\n",
  277. "| idx | sentence | words |\n",
  278. "+-----+--------------------+------------------------------+\n",
  279. "| 0 | This is an apple . | ['This', 'is', 'an', 'app... |\n",
  280. "| 1 | I like apples . | ['I', 'like', 'apples', '... |\n",
  281. "+-----+--------------------+------------------------------+\n"
  282. ]
  283. }
  284. ],
  285. "source": [
  286. "dataset.delete_field('num')\n",
  287. "print(dataset)"
  288. ]
  289. },
  290. {
  291. "cell_type": "markdown",
  292. "id": "b1e9d42c",
  293. "metadata": {},
  294. "source": [
  295. "### 1.2 dataset 的数据预处理\n",
  296. "\n",
  297. "在`dataset`模块中,`apply`、`apply_field`、`apply_more`和`apply_field_more`函数可以进行简单的数据预处理\n",
  298. "\n",
  299. "&emsp; **`apply`和`apply_more`针对整条实例**,**`apply_field`和`apply_field_more`仅针对实例的部分字段**\n",
  300. "\n",
  301. "&emsp; **`apply`和`apply_field`仅针对单个字段**,**`apply_more`和`apply_field_more`则可以针对多个字段**\n",
  302. "\n",
  303. "&emsp; **`apply`和`apply_field`返回的是个列表**,**`apply_more`和`apply_field_more`返回的是个字典**\n",
  304. "\n",
  305. "***\n",
  306. "\n",
  307. "`apply`的参数包括一个函数`func`和一个新字段名`new_field_name`,函数`func`的处理对象是`dataset`模块中\n",
  308. "\n",
  309. "&emsp; 的每个`instance`实例,函数`func`的处理结果存放在`new_field_name`对应的新建字段内"
  310. ]
  311. },
  312. {
  313. "cell_type": "code",
  314. "execution_count": 7,
  315. "id": "72a0b5f9",
  316. "metadata": {},
  317. "outputs": [
  318. {
  319. "data": {
  320. "application/vnd.jupyter.widget-view+json": {
  321. "model_id": "",
  322. "version_major": 2,
  323. "version_minor": 0
  324. },
  325. "text/plain": [
  326. "Output()"
  327. ]
  328. },
  329. "metadata": {},
  330. "output_type": "display_data"
  331. },
  332. {
  333. "data": {
  334. "text/html": [
  335. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  336. ],
  337. "text/plain": []
  338. },
  339. "metadata": {},
  340. "output_type": "display_data"
  341. },
  342. {
  343. "data": {
  344. "text/html": [
  345. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
  346. "</pre>\n"
  347. ],
  348. "text/plain": [
  349. "\n"
  350. ]
  351. },
  352. "metadata": {},
  353. "output_type": "display_data"
  354. },
  355. {
  356. "name": "stdout",
  357. "output_type": "stream",
  358. "text": [
  359. "+-----+------------------------------+------------------------------+\n",
  360. "| idx | sentence | words |\n",
  361. "+-----+------------------------------+------------------------------+\n",
  362. "| 0 | This is an apple . | ['This', 'is', 'an', 'app... |\n",
  363. "| 1 | I like apples . | ['I', 'like', 'apples', '... |\n",
  364. "| 2 | Apples are good for our h... | ['Apples', 'are', 'good',... |\n",
  365. "+-----+------------------------------+------------------------------+\n"
  366. ]
  367. }
  368. ],
  369. "source": [
  370. "data = {'idx': [0, 1, 2], \n",
  371. " 'sentence':[\"This is an apple .\", \"I like apples .\", \"Apples are good for our health .\"], }\n",
  372. "dataset = DataSet(data)\n",
  373. "dataset.apply(lambda ins: ins['sentence'].split(), new_field_name='words')\n",
  374. "print(dataset)"
  375. ]
  376. },
  377. {
  378. "cell_type": "markdown",
  379. "id": "c10275ee",
  380. "metadata": {},
  381. "source": [
  382. "&emsp; **`apply`使用的函数可以是一个基于`lambda`表达式的匿名函数**,**也可以是一个自定义的函数**"
  383. ]
  384. },
  385. {
  386. "cell_type": "code",
  387. "execution_count": 8,
  388. "id": "b1a8631f",
  389. "metadata": {},
  390. "outputs": [
  391. {
  392. "data": {
  393. "text/html": [
  394. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  395. ],
  396. "text/plain": []
  397. },
  398. "metadata": {},
  399. "output_type": "display_data"
  400. },
  401. {
  402. "data": {
  403. "text/html": [
  404. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  405. ],
  406. "text/plain": []
  407. },
  408. "metadata": {},
  409. "output_type": "display_data"
  410. },
  411. {
  412. "data": {
  413. "text/html": [
  414. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
  415. "</pre>\n"
  416. ],
  417. "text/plain": [
  418. "\n"
  419. ]
  420. },
  421. "metadata": {},
  422. "output_type": "display_data"
  423. },
  424. {
  425. "name": "stdout",
  426. "output_type": "stream",
  427. "text": [
  428. "+-----+------------------------------+------------------------------+\n",
  429. "| idx | sentence | words |\n",
  430. "+-----+------------------------------+------------------------------+\n",
  431. "| 0 | This is an apple . | ['This', 'is', 'an', 'app... |\n",
  432. "| 1 | I like apples . | ['I', 'like', 'apples', '... |\n",
  433. "| 2 | Apples are good for our h... | ['Apples', 'are', 'good',... |\n",
  434. "+-----+------------------------------+------------------------------+\n"
  435. ]
  436. }
  437. ],
  438. "source": [
  439. "dataset = DataSet(data)\n",
  440. "\n",
  441. "def get_words(instance):\n",
  442. " sentence = instance['sentence']\n",
  443. " words = sentence.split()\n",
  444. " return words\n",
  445. "\n",
  446. "dataset.apply(get_words, new_field_name='words')\n",
  447. "print(dataset)"
  448. ]
  449. },
  450. {
  451. "cell_type": "markdown",
  452. "id": "64abf745",
  453. "metadata": {},
  454. "source": [
  455. "`apply_field`的参数,除了函数`func`外还有`field_name`和`new_field_name`,该函数`func`的处理对象仅\n",
  456. "\n",
  457. "&emsp; 是`dataset`模块中的每个`field_name`对应的字段内容,处理结果存放在`new_field_name`对应的新建字段内"
  458. ]
  459. },
  460. {
  461. "cell_type": "code",
  462. "execution_count": 9,
  463. "id": "057c1d2c",
  464. "metadata": {},
  465. "outputs": [
  466. {
  467. "data": {
  468. "text/html": [
  469. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  470. ],
  471. "text/plain": []
  472. },
  473. "metadata": {},
  474. "output_type": "display_data"
  475. },
  476. {
  477. "data": {
  478. "text/html": [
  479. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  480. ],
  481. "text/plain": []
  482. },
  483. "metadata": {},
  484. "output_type": "display_data"
  485. },
  486. {
  487. "data": {
  488. "text/html": [
  489. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
  490. "</pre>\n"
  491. ],
  492. "text/plain": [
  493. "\n"
  494. ]
  495. },
  496. "metadata": {},
  497. "output_type": "display_data"
  498. },
  499. {
  500. "name": "stdout",
  501. "output_type": "stream",
  502. "text": [
  503. "+-----+------------------------------+------------------------------+\n",
  504. "| idx | sentence | words |\n",
  505. "+-----+------------------------------+------------------------------+\n",
  506. "| 0 | This is an apple . | ['This', 'is', 'an', 'app... |\n",
  507. "| 1 | I like apples . | ['I', 'like', 'apples', '... |\n",
  508. "| 2 | Apples are good for our h... | ['Apples', 'are', 'good',... |\n",
  509. "+-----+------------------------------+------------------------------+\n"
  510. ]
  511. }
  512. ],
  513. "source": [
  514. "dataset = DataSet(data)\n",
  515. "dataset.apply_field(lambda sent:sent.split(), field_name='sentence', new_field_name='words')\n",
  516. "print(dataset)"
  517. ]
  518. },
  519. {
  520. "cell_type": "markdown",
  521. "id": "5a9cc8b2",
  522. "metadata": {},
  523. "source": [
  524. "`apply_more`的参数只有函数`func`,函数`func`的处理对象是`dataset`模块中的每个`instance`实例\n",
  525. "\n",
  526. "&emsp; 要求函数`func`返回一个字典,根据字典的`key-value`确定存储在`dataset`中的字段名称与内容"
  527. ]
  528. },
  529. {
  530. "cell_type": "code",
  531. "execution_count": 10,
  532. "id": "51e2f02c",
  533. "metadata": {},
  534. "outputs": [
  535. {
  536. "data": {
  537. "text/html": [
  538. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  539. ],
  540. "text/plain": []
  541. },
  542. "metadata": {},
  543. "output_type": "display_data"
  544. },
  545. {
  546. "data": {
  547. "text/html": [
  548. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  549. ],
  550. "text/plain": []
  551. },
  552. "metadata": {},
  553. "output_type": "display_data"
  554. },
  555. {
  556. "data": {
  557. "text/html": [
  558. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
  559. "</pre>\n"
  560. ],
  561. "text/plain": [
  562. "\n"
  563. ]
  564. },
  565. "metadata": {},
  566. "output_type": "display_data"
  567. },
  568. {
  569. "name": "stdout",
  570. "output_type": "stream",
  571. "text": [
  572. "+-----+------------------------+------------------------+-----+\n",
  573. "| idx | sentence | words | num |\n",
  574. "+-----+------------------------+------------------------+-----+\n",
  575. "| 0 | This is an apple . | ['This', 'is', 'an'... | 5 |\n",
  576. "| 1 | I like apples . | ['I', 'like', 'appl... | 4 |\n",
  577. "| 2 | Apples are good for... | ['Apples', 'are', '... | 7 |\n",
  578. "+-----+------------------------+------------------------+-----+\n"
  579. ]
  580. }
  581. ],
  582. "source": [
  583. "dataset = DataSet(data)\n",
  584. "dataset.apply_more(lambda ins:{'words': ins['sentence'].split(), 'num': len(ins['sentence'].split())})\n",
  585. "print(dataset)"
  586. ]
  587. },
  588. {
  589. "cell_type": "markdown",
  590. "id": "02d2b7ef",
  591. "metadata": {},
  592. "source": [
  593. "`apply_more`的参数只有函数`func`,函数`func`的处理对象是`dataset`模块中的每个`instance`实例\n",
  594. "\n",
  595. "&emsp; 要求函数`func`返回一个字典,根据字典的`key-value`确定存储在`dataset`中的字段名称与内容"
  596. ]
  597. },
  598. {
  599. "cell_type": "code",
  600. "execution_count": 11,
  601. "id": "db4295d5",
  602. "metadata": {},
  603. "outputs": [
  604. {
  605. "data": {
  606. "text/html": [
  607. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  608. ],
  609. "text/plain": []
  610. },
  611. "metadata": {},
  612. "output_type": "display_data"
  613. },
  614. {
  615. "data": {
  616. "text/html": [
  617. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  618. ],
  619. "text/plain": []
  620. },
  621. "metadata": {},
  622. "output_type": "display_data"
  623. },
  624. {
  625. "data": {
  626. "text/html": [
  627. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
  628. "</pre>\n"
  629. ],
  630. "text/plain": [
  631. "\n"
  632. ]
  633. },
  634. "metadata": {},
  635. "output_type": "display_data"
  636. },
  637. {
  638. "name": "stdout",
  639. "output_type": "stream",
  640. "text": [
  641. "+-----+------------------------+------------------------+-----+\n",
  642. "| idx | sentence | words | num |\n",
  643. "+-----+------------------------+------------------------+-----+\n",
  644. "| 0 | This is an apple . | ['This', 'is', 'an'... | 5 |\n",
  645. "| 1 | I like apples . | ['I', 'like', 'appl... | 4 |\n",
  646. "| 2 | Apples are good for... | ['Apples', 'are', '... | 7 |\n",
  647. "+-----+------------------------+------------------------+-----+\n"
  648. ]
  649. }
  650. ],
  651. "source": [
  652. "dataset = DataSet(data)\n",
  653. "dataset.apply_field_more(lambda sent:{'words': sent.split(), 'num': len(sent.split())}, \n",
  654. " field_name='sentence')\n",
  655. "print(dataset)"
  656. ]
  657. },
  658. {
  659. "cell_type": "markdown",
  660. "id": "9c09e592",
  661. "metadata": {},
  662. "source": [
  663. "### 1.3 延伸:instance 和 field\n",
  664. "\n",
  665. "在`fastNLP 0.8`中,使用`Instance`模块表示数据集`dataset`中的每条数据,被称为实例\n",
  666. "\n",
  667. "&emsp; 构造方式类似于构造一个字典,通过键值相同的`Instance`列表,也可以初始化一个`dataset`,代码如下"
  668. ]
  669. },
  670. {
  671. "cell_type": "code",
  672. "execution_count": 12,
  673. "id": "012f537c",
  674. "metadata": {},
  675. "outputs": [],
  676. "source": [
  677. "from fastNLP.core.dataset import DataSet\n",
  678. "from fastNLP.core.dataset import Instance\n",
  679. "\n",
  680. "dataset = DataSet([\n",
  681. " Instance(sentence=\"This is an apple .\",\n",
  682. " words=['This', 'is', 'an', 'apple', '.'],\n",
  683. " num=5),\n",
  684. " Instance(sentence=\"I like apples .\",\n",
  685. " words=['I', 'like', 'apples', '.'],\n",
  686. " num=4),\n",
  687. " Instance(sentence=\"Apples are good for our health .\",\n",
  688. " words=['Apples', 'are', 'good', 'for', 'our', 'health', '.'],\n",
  689. " num=7),\n",
  690. " ])"
  691. ]
  692. },
  693. {
  694. "cell_type": "markdown",
  695. "id": "2fafb1ef",
  696. "metadata": {},
  697. "source": [
  698. "&emsp; 通过`items`、`keys`和`values`方法,可以分别获得`dataset`的`item`列表、`key`列表、`value`列表"
  699. ]
  700. },
  701. {
  702. "cell_type": "code",
  703. "execution_count": 13,
  704. "id": "a4c1c10d",
  705. "metadata": {},
  706. "outputs": [
  707. {
  708. "name": "stdout",
  709. "output_type": "stream",
  710. "text": [
  711. "dict_items([('sentence', 'This is an apple .'), ('words', ['This', 'is', 'an', 'apple', '.']), ('num', 5)])\n",
  712. "dict_keys(['sentence', 'words', 'num'])\n",
  713. "dict_values(['This is an apple .', ['This', 'is', 'an', 'apple', '.'], 5])\n"
  714. ]
  715. }
  716. ],
  717. "source": [
  718. "ins = Instance(sentence=\"This is an apple .\", words=['This', 'is', 'an', 'apple', '.'], num=5)\n",
  719. "\n",
  720. "print(ins.items())\n",
  721. "print(ins.keys())\n",
  722. "print(ins.values())"
  723. ]
  724. },
  725. {
  726. "cell_type": "markdown",
  727. "id": "b5459a2d",
  728. "metadata": {},
  729. "source": [
  730. "&emsp; 通过`add_field`方法,可以在`Instance`实例中,通过参数`field_name`添加字段,通过参数`field`赋值"
  731. ]
  732. },
  733. {
  734. "cell_type": "code",
  735. "execution_count": 14,
  736. "id": "55376402",
  737. "metadata": {},
  738. "outputs": [
  739. {
  740. "name": "stdout",
  741. "output_type": "stream",
  742. "text": [
  743. "+--------------------+------------------------+-----+-----+\n",
  744. "| sentence | words | num | idx |\n",
  745. "+--------------------+------------------------+-----+-----+\n",
  746. "| This is an apple . | ['This', 'is', 'an'... | 5 | 0 |\n",
  747. "+--------------------+------------------------+-----+-----+\n"
  748. ]
  749. }
  750. ],
  751. "source": [
  752. "ins.add_field(field_name='idx', field=0)\n",
  753. "print(ins)"
  754. ]
  755. },
  756. {
  757. "cell_type": "markdown",
  758. "id": "49caaa9c",
  759. "metadata": {},
  760. "source": [
  761. "在`fastNLP 0.8`中,使用`FieldArray`模块表示数据集`dataset`中的每条字段名(注:没有`field`类)\n",
  762. "\n",
  763. "&emsp; 通过`get_all_fields`方法可以获取`dataset`的字段列表\n",
  764. "\n",
  765. "&emsp; 通过`get_field_names`方法可以获取`dataset`的字段名称列表,代码如下"
  766. ]
  767. },
  768. {
  769. "cell_type": "code",
  770. "execution_count": 15,
  771. "id": "fe15f4c1",
  772. "metadata": {},
  773. "outputs": [
  774. {
  775. "data": {
  776. "text/plain": [
  777. "{'sentence': <fastNLP.core.dataset.field.FieldArray at 0x237ce26d388>,\n",
  778. " 'words': <fastNLP.core.dataset.field.FieldArray at 0x237ce26d408>,\n",
  779. " 'num': <fastNLP.core.dataset.field.FieldArray at 0x237ce26d488>}"
  780. ]
  781. },
  782. "execution_count": 15,
  783. "metadata": {},
  784. "output_type": "execute_result"
  785. }
  786. ],
  787. "source": [
  788. "dataset.get_all_fields()"
  789. ]
  790. },
  791. {
  792. "cell_type": "code",
  793. "execution_count": 16,
  794. "id": "5433815c",
  795. "metadata": {},
  796. "outputs": [
  797. {
  798. "data": {
  799. "text/plain": [
  800. "['num', 'sentence', 'words']"
  801. ]
  802. },
  803. "execution_count": 16,
  804. "metadata": {},
  805. "output_type": "execute_result"
  806. }
  807. ],
  808. "source": [
  809. "dataset.get_field_names()"
  810. ]
  811. },
  812. {
  813. "cell_type": "markdown",
  814. "id": "4964eeed",
  815. "metadata": {},
  816. "source": [
  817. "其他`dataset`的基本使用:通过`in`或者`has_field`方法可以判断`dataset`的是否包含某种字段\n",
  818. "\n",
  819. "&emsp; 通过`rename_field`方法可以更改`dataset`中的字段名称;通过`concat`方法可以实现两个`dataset`中的拼接\n",
  820. "\n",
  821. "&emsp; 通过`len`可以统计`dataset`中的实例数目;`dataset`的全部变量与函数可以通过`dir(dataset)`查询"
  822. ]
  823. },
  824. {
  825. "cell_type": "code",
  826. "execution_count": 17,
  827. "id": "25ce5488",
  828. "metadata": {},
  829. "outputs": [
  830. {
  831. "name": "stdout",
  832. "output_type": "stream",
  833. "text": [
  834. "3 False\n",
  835. "6 True\n",
  836. "+------------------------------+------------------------------+--------+\n",
  837. "| sentence | words | length |\n",
  838. "+------------------------------+------------------------------+--------+\n",
  839. "| This is an apple . | ['This', 'is', 'an', 'app... | 5 |\n",
  840. "| I like apples . | ['I', 'like', 'apples', '... | 4 |\n",
  841. "| Apples are good for our h... | ['Apples', 'are', 'good',... | 7 |\n",
  842. "| This is an apple . | ['This', 'is', 'an', 'app... | 5 |\n",
  843. "| I like apples . | ['I', 'like', 'apples', '... | 4 |\n",
  844. "| Apples are good for our h... | ['Apples', 'are', 'good',... | 7 |\n",
  845. "+------------------------------+------------------------------+--------+\n"
  846. ]
  847. }
  848. ],
  849. "source": [
  850. "print(len(dataset), dataset.has_field('length')) \n",
  851. "if 'num' in dataset:\n",
  852. " dataset.rename_field('num', 'length')\n",
  853. "elif 'length' in dataset:\n",
  854. " dataset.rename_field('length', 'num')\n",
  855. "dataset.concat(dataset)\n",
  856. "print(len(dataset), dataset.has_field('length')) \n",
  857. "print(dataset) "
  858. ]
  859. },
  860. {
  861. "cell_type": "markdown",
  862. "id": "e30a6cd7",
  863. "metadata": {},
  864. "source": [
  865. "## 2. vocabulary 的结构与使用\n",
  866. "\n",
  867. "### 2.1 vocabulary 的创建与修改\n",
  868. "\n",
  869. "在`fastNLP 0.8`中,使用`Vocabulary`模块表示词汇表,**`vocabulary`的核心是从单词到序号的映射**\n",
  870. "\n",
  871. "&emsp; 可以直接通过构造函数实例化,通过查找`word2idx`属性,可以找到`vocabulary`映射对应的字典实现\n",
  872. "\n",
  873. "&emsp; **默认补零`padding`用`<pad>`表示**,**对应序号为0**;**未知单词`unknown`用`<unk>`表示**,**对应序号1**\n",
  874. "\n",
  875. "&emsp; 通过打印`vocabulary`可以看到词汇表中的单词列表,其中,`padding`和`unknown`不会显示"
  876. ]
  877. },
  878. {
  879. "cell_type": "code",
  880. "execution_count": 18,
  881. "id": "3515e096",
  882. "metadata": {},
  883. "outputs": [
  884. {
  885. "name": "stdout",
  886. "output_type": "stream",
  887. "text": [
  888. "Vocabulary([]...)\n",
  889. "{'<pad>': 0, '<unk>': 1}\n",
  890. "<pad> 0\n",
  891. "<unk> 1\n"
  892. ]
  893. }
  894. ],
  895. "source": [
  896. "from fastNLP.core.vocabulary import Vocabulary\n",
  897. "\n",
  898. "vocab = Vocabulary()\n",
  899. "print(vocab)\n",
  900. "print(vocab.word2idx)\n",
  901. "print(vocab.padding, vocab.padding_idx)\n",
  902. "print(vocab.unknown, vocab.unknown_idx)"
  903. ]
  904. },
  905. {
  906. "cell_type": "markdown",
  907. "id": "640be126",
  908. "metadata": {},
  909. "source": [
  910. "在`vocabulary`中,通过`add_word`方法或`add_word_lst`方法,可以单独或批量添加单词\n",
  911. "\n",
  912. "&emsp; 通过`len`或`word_count`属性,可以显示`vocabulary`的单词量和每个单词添加的次数"
  913. ]
  914. },
  915. {
  916. "cell_type": "code",
  917. "execution_count": 19,
  918. "id": "88c7472a",
  919. "metadata": {},
  920. "outputs": [
  921. {
  922. "name": "stdout",
  923. "output_type": "stream",
  924. "text": [
  925. "5 Counter({'生活': 1, '就像': 1, '海洋': 1})\n",
  926. "6 Counter({'生活': 1, '就像': 1, '海洋': 1, '只有': 1})\n",
  927. "6 {'<pad>': 0, '<unk>': 1, '生活': 2, '就像': 3, '海洋': 4, '只有': 5}\n"
  928. ]
  929. }
  930. ],
  931. "source": [
  932. "vocab.add_word_lst(['生活', '就像', '海洋'])\n",
  933. "print(len(vocab), vocab.word_count)\n",
  934. "vocab.add_word('只有')\n",
  935. "print(len(vocab), vocab.word_count)\n",
  936. "print(len(vocab), vocab.word2idx)"
  937. ]
  938. },
  939. {
  940. "cell_type": "markdown",
  941. "id": "f9ec8b28",
  942. "metadata": {},
  943. "source": [
  944. "&emsp; **通过`to_word`方法可以找到单词对应的序号**,**通过`to_index`方法可以找到序号对应的单词**\n",
  945. "\n",
  946. "&emsp; &emsp; 由于序号0和序号1已经被占用,所以**新加入的词的序号从2开始计数**,如`'生活'`对应2\n",
  947. "\n",
  948. "&emsp; &emsp; 通过`has_word`方法可以判断单词是否在词汇表中,没有的单词被判做`<unk>`"
  949. ]
  950. },
  951. {
  952. "cell_type": "code",
  953. "execution_count": 20,
  954. "id": "3447acde",
  955. "metadata": {},
  956. "outputs": [
  957. {
  958. "name": "stdout",
  959. "output_type": "stream",
  960. "text": [
  961. "<pad> 0\n",
  962. "<unk> 1\n",
  963. "生活 2\n",
  964. "彼岸 1 False\n"
  965. ]
  966. }
  967. ],
  968. "source": [
  969. "print(vocab.to_word(0), vocab.to_index('<pad>'))\n",
  970. "print(vocab.to_word(1), vocab.to_index('<unk>'))\n",
  971. "print(vocab.to_word(2), vocab.to_index('生活'))\n",
  972. "print('彼岸', vocab.to_index('彼岸'), vocab.has_word('彼岸'))"
  973. ]
  974. },
  975. {
  976. "cell_type": "markdown",
  977. "id": "b4e36850",
  978. "metadata": {},
  979. "source": [
  980. "**`vocabulary`允许反复添加相同单词**,**可以通过`word_count`方法看到相应单词被添加的次数**\n",
  981. "\n",
  982. "&emsp; 但其中没有`<unk>`和`<pad>`,`vocabulary`的全部变量与函数可以通过`dir(vocabulary)`查询\n",
  983. "\n",
  984. "&emsp; 注:**使用`add_word_lst`添加单词**,**单词对应序号不会动态调整**,**使用`dataset`添加单词的情况不同**"
  985. ]
  986. },
  987. {
  988. "cell_type": "code",
  989. "execution_count": 21,
  990. "id": "490b101c",
  991. "metadata": {},
  992. "outputs": [
  993. {
  994. "name": "stdout",
  995. "output_type": "stream",
  996. "text": [
  997. "生活 2\n",
  998. "彼岸 12 True\n",
  999. "13 Counter({'人': 4, '生活': 2, '就像': 2, '海洋': 2, '只有': 2, '意志': 1, '坚强的': 1, '才': 1, '能': 1, '到达': 1, '彼岸': 1})\n",
  1000. "13 {'<pad>': 0, '<unk>': 1, '生活': 2, '就像': 3, '海洋': 4, '只有': 5, '人': 6, '意志': 7, '坚强的': 8, '才': 9, '能': 10, '到达': 11, '彼岸': 12}\n"
  1001. ]
  1002. }
  1003. ],
  1004. "source": [
  1005. "vocab.add_word_lst(['生活', '就像', '海洋', '只有', '意志', '坚强的', '人', '人', '人', '人', '才', '能', '到达', '彼岸'])\n",
  1006. "print(vocab.to_word(2), vocab.to_index('生活'))\n",
  1007. "print('彼岸', vocab.to_index('彼岸'), vocab.has_word('彼岸'))\n",
  1008. "print(len(vocab), vocab.word_count)\n",
  1009. "print(len(vocab), vocab.word2idx)"
  1010. ]
  1011. },
  1012. {
  1013. "cell_type": "markdown",
  1014. "id": "23e32a63",
  1015. "metadata": {},
  1016. "source": [
  1017. "### 2.2 vocabulary 与 OOV 问题\n",
  1018. "\n",
  1019. "在`vocabulary`模块初始化的时候,可以通过指定`unknown`和`padding`为`None`,限制其存在\n",
  1020. "\n",
  1021. "&emsp; 此时添加单词直接从0开始标号,如果遇到未知单词会直接报错,即 out of vocabulary"
  1022. ]
  1023. },
  1024. {
  1025. "cell_type": "code",
  1026. "execution_count": 22,
  1027. "id": "a99ff909",
  1028. "metadata": {},
  1029. "outputs": [
  1030. {
  1031. "name": "stdout",
  1032. "output_type": "stream",
  1033. "text": [
  1034. "{'positive': 0, 'negative': 1}\n",
  1035. "ValueError: word `neutral` not in vocabulary\n"
  1036. ]
  1037. }
  1038. ],
  1039. "source": [
  1040. "vocab = Vocabulary(unknown=None, padding=None)\n",
  1041. "\n",
  1042. "vocab.add_word_lst(['positive', 'negative'])\n",
  1043. "print(vocab.word2idx)\n",
  1044. "\n",
  1045. "try:\n",
  1046. " print(vocab.to_index('neutral'))\n",
  1047. "except ValueError:\n",
  1048. " print(\"ValueError: word `neutral` not in vocabulary\")"
  1049. ]
  1050. },
  1051. {
  1052. "cell_type": "markdown",
  1053. "id": "618da6bd",
  1054. "metadata": {},
  1055. "source": [
  1056. "&emsp; 相应的,如果只指定其中的`unknown`,则编号会后移一个,同时遇到未知单词全部当做`<unk>`"
  1057. ]
  1058. },
  1059. {
  1060. "cell_type": "code",
  1061. "execution_count": 23,
  1062. "id": "432f74c1",
  1063. "metadata": {},
  1064. "outputs": [
  1065. {
  1066. "name": "stdout",
  1067. "output_type": "stream",
  1068. "text": [
  1069. "{'<unk>': 0, 'positive': 1, 'negative': 2}\n",
  1070. "0 <unk>\n"
  1071. ]
  1072. }
  1073. ],
  1074. "source": [
  1075. "vocab = Vocabulary(unknown='<unk>', padding=None)\n",
  1076. "\n",
  1077. "vocab.add_word_lst(['positive', 'negative'])\n",
  1078. "print(vocab.word2idx)\n",
  1079. "\n",
  1080. "print(vocab.to_index('neutral'), vocab.to_word(vocab.to_index('neutral')))"
  1081. ]
  1082. },
  1083. {
  1084. "cell_type": "markdown",
  1085. "id": "b6263f73",
  1086. "metadata": {},
  1087. "source": [
  1088. "## 3 dataset 和 vocabulary 的组合使用\n",
  1089. " \n",
  1090. "### 3.1 从 dataframe 中加载 dataset\n",
  1091. "\n",
  1092. "以下通过 [NLP-beginner](https://github.com/FudanNLP/nlp-beginner) 实践一中 [Rotten Tomatoes 影评数据集](https://www.kaggle.com/c/sentiment-analysis-on-movie-reviews) 的部分训练数据组成`test4dataset.tsv`文件\n",
  1093. "\n",
  1094. "&emsp; 介绍如何使用`dataset`、`vocabulary`简单加载并处理数据集,首先使用`pandas`模块,读取原始数据的`dataframe`"
  1095. ]
  1096. },
  1097. {
  1098. "cell_type": "code",
  1099. "execution_count": 24,
  1100. "id": "3dbd985d",
  1101. "metadata": {},
  1102. "outputs": [
  1103. {
  1104. "data": {
  1105. "text/html": [
  1106. "<div>\n",
  1107. "<style scoped>\n",
  1108. " .dataframe tbody tr th:only-of-type {\n",
  1109. " vertical-align: middle;\n",
  1110. " }\n",
  1111. "\n",
  1112. " .dataframe tbody tr th {\n",
  1113. " vertical-align: top;\n",
  1114. " }\n",
  1115. "\n",
  1116. " .dataframe thead th {\n",
  1117. " text-align: right;\n",
  1118. " }\n",
  1119. "</style>\n",
  1120. "<table border=\"1\" class=\"dataframe\">\n",
  1121. " <thead>\n",
  1122. " <tr style=\"text-align: right;\">\n",
  1123. " <th></th>\n",
  1124. " <th>SentenceId</th>\n",
  1125. " <th>Sentence</th>\n",
  1126. " <th>Sentiment</th>\n",
  1127. " </tr>\n",
  1128. " </thead>\n",
  1129. " <tbody>\n",
  1130. " <tr>\n",
  1131. " <th>0</th>\n",
  1132. " <td>1</td>\n",
  1133. " <td>A series of escapades demonstrating the adage ...</td>\n",
  1134. " <td>negative</td>\n",
  1135. " </tr>\n",
  1136. " <tr>\n",
  1137. " <th>1</th>\n",
  1138. " <td>2</td>\n",
  1139. " <td>This quiet , introspective and entertaining in...</td>\n",
  1140. " <td>positive</td>\n",
  1141. " </tr>\n",
  1142. " <tr>\n",
  1143. " <th>2</th>\n",
  1144. " <td>3</td>\n",
  1145. " <td>Even fans of Ismail Merchant 's work , I suspe...</td>\n",
  1146. " <td>negative</td>\n",
  1147. " </tr>\n",
  1148. " <tr>\n",
  1149. " <th>3</th>\n",
  1150. " <td>4</td>\n",
  1151. " <td>A positively thrilling combination of ethnogra...</td>\n",
  1152. " <td>neutral</td>\n",
  1153. " </tr>\n",
  1154. " <tr>\n",
  1155. " <th>4</th>\n",
  1156. " <td>5</td>\n",
  1157. " <td>A comedy-drama of nearly epic proportions root...</td>\n",
  1158. " <td>positive</td>\n",
  1159. " </tr>\n",
  1160. " <tr>\n",
  1161. " <th>5</th>\n",
  1162. " <td>6</td>\n",
  1163. " <td>The Importance of Being Earnest , so thick wit...</td>\n",
  1164. " <td>neutral</td>\n",
  1165. " </tr>\n",
  1166. " </tbody>\n",
  1167. "</table>\n",
  1168. "</div>"
  1169. ],
  1170. "text/plain": [
  1171. " SentenceId Sentence Sentiment\n",
  1172. "0 1 A series of escapades demonstrating the adage ... negative\n",
  1173. "1 2 This quiet , introspective and entertaining in... positive\n",
  1174. "2 3 Even fans of Ismail Merchant 's work , I suspe... negative\n",
  1175. "3 4 A positively thrilling combination of ethnogra... neutral\n",
  1176. "4 5 A comedy-drama of nearly epic proportions root... positive\n",
  1177. "5 6 The Importance of Being Earnest , so thick wit... neutral"
  1178. ]
  1179. },
  1180. "execution_count": 24,
  1181. "metadata": {},
  1182. "output_type": "execute_result"
  1183. }
  1184. ],
  1185. "source": [
  1186. "import pandas as pd\n",
  1187. "\n",
  1188. "df = pd.read_csv('./data/test4dataset.tsv', sep='\\t')\n",
  1189. "df"
  1190. ]
  1191. },
  1192. {
  1193. "cell_type": "markdown",
  1194. "id": "919ab350",
  1195. "metadata": {},
  1196. "source": [
  1197. "接着,通过`dataset`中的`from_pandas`方法填充数据集,并使用`apply_more`方法对文本进行分词操作"
  1198. ]
  1199. },
  1200. {
  1201. "cell_type": "code",
  1202. "execution_count": 25,
  1203. "id": "4f634586",
  1204. "metadata": {},
  1205. "outputs": [
  1206. {
  1207. "data": {
  1208. "text/html": [
  1209. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  1210. ],
  1211. "text/plain": []
  1212. },
  1213. "metadata": {},
  1214. "output_type": "display_data"
  1215. },
  1216. {
  1217. "data": {
  1218. "text/html": [
  1219. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  1220. ],
  1221. "text/plain": []
  1222. },
  1223. "metadata": {},
  1224. "output_type": "display_data"
  1225. },
  1226. {
  1227. "data": {
  1228. "text/html": [
  1229. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
  1230. "</pre>\n"
  1231. ],
  1232. "text/plain": [
  1233. "\n"
  1234. ]
  1235. },
  1236. "metadata": {},
  1237. "output_type": "display_data"
  1238. },
  1239. {
  1240. "name": "stdout",
  1241. "output_type": "stream",
  1242. "text": [
  1243. "+------------+------------------------------+-----------+\n",
  1244. "| SentenceId | Sentence | Sentiment |\n",
  1245. "+------------+------------------------------+-----------+\n",
  1246. "| 1 | ['a', 'series', 'of', 'es... | negative |\n",
  1247. "| 2 | ['this', 'quiet', ',', 'i... | positive |\n",
  1248. "| 3 | ['even', 'fans', 'of', 'i... | negative |\n",
  1249. "| 4 | ['a', 'positively', 'thri... | neutral |\n",
  1250. "| 5 | ['a', 'comedy-drama', 'of... | positive |\n",
  1251. "| 6 | ['the', 'importance', 'of... | neutral |\n",
  1252. "+------------+------------------------------+-----------+\n"
  1253. ]
  1254. }
  1255. ],
  1256. "source": [
  1257. "from fastNLP.core.dataset import DataSet\n",
  1258. "\n",
  1259. "dataset = DataSet()\n",
  1260. "dataset = dataset.from_pandas(df)\n",
  1261. "dataset.apply_more(lambda ins:{'SentenceId': ins['SentenceId'], \n",
  1262. " 'Sentence': ins['Sentence'].lower().split(), 'Sentiment': ins['Sentiment']})\n",
  1263. "print(dataset)"
  1264. ]
  1265. },
  1266. {
  1267. "cell_type": "markdown",
  1268. "id": "5c1ae192",
  1269. "metadata": {},
  1270. "source": [
  1271. "&emsp; 如果需要保存中间结果,也可以使用`dataset`的`to_csv`方法,生成`.csv`或`.tsv`文件"
  1272. ]
  1273. },
  1274. {
  1275. "cell_type": "code",
  1276. "execution_count": 26,
  1277. "id": "46722efc",
  1278. "metadata": {},
  1279. "outputs": [],
  1280. "source": [
  1281. "dataset.to_csv('./data/test4dataset.csv')"
  1282. ]
  1283. },
  1284. {
  1285. "cell_type": "markdown",
  1286. "id": "5ba13989",
  1287. "metadata": {},
  1288. "source": [
  1289. "### 3.2 从 dataset 中获取 vocabulary\n",
  1290. "\n",
  1291. "然后,初始化`vocabulary`,使用`vocabulary`中的`from_dataset`方法,从`dataset`的指定字段中\n",
  1292. "\n",
  1293. "&emsp; 获取字段中的所有元素,然后编号;如果指定字段是个列表,则针对字段中所有列表包含的元素编号\n",
  1294. "\n",
  1295. "&emsp; 注:**使用`dataset`添加单词**,**不同于`add_word_list`**,**单词被添加次数越多**,**序号越靠前**,例如案例中的`a`"
  1296. ]
  1297. },
  1298. {
  1299. "cell_type": "code",
  1300. "execution_count": 27,
  1301. "id": "a2de615b",
  1302. "metadata": {},
  1303. "outputs": [
  1304. {
  1305. "data": {
  1306. "text/html": [
  1307. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  1308. ],
  1309. "text/plain": []
  1310. },
  1311. "metadata": {},
  1312. "output_type": "display_data"
  1313. },
  1314. {
  1315. "data": {
  1316. "text/html": [
  1317. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  1318. ],
  1319. "text/plain": []
  1320. },
  1321. "metadata": {},
  1322. "output_type": "display_data"
  1323. },
  1324. {
  1325. "data": {
  1326. "text/html": [
  1327. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
  1328. "</pre>\n"
  1329. ],
  1330. "text/plain": [
  1331. "\n"
  1332. ]
  1333. },
  1334. "metadata": {},
  1335. "output_type": "display_data"
  1336. },
  1337. {
  1338. "name": "stdout",
  1339. "output_type": "stream",
  1340. "text": [
  1341. "Counter({'a': 9, 'of': 9, ',': 7, 'the': 6, '.': 5, 'is': 3, 'and': 3, 'good': 2, 'for': 2, 'which': 2, 'this': 2, \"'s\": 2, 'series': 1, 'escapades': 1, 'demonstrating': 1, 'adage': 1, 'that': 1, 'what': 1, 'goose': 1, 'also': 1, 'gander': 1, 'some': 1, 'occasionally': 1, 'amuses': 1, 'but': 1, 'none': 1, 'amounts': 1, 'to': 1, 'much': 1, 'story': 1, 'quiet': 1, 'introspective': 1, 'entertaining': 1, 'independent': 1, 'worth': 1, 'seeking': 1, 'even': 1, 'fans': 1, 'ismail': 1, 'merchant': 1, 'work': 1, 'i': 1, 'suspect': 1, 'would': 1, 'have': 1, 'hard': 1, 'time': 1, 'sitting': 1, 'through': 1, 'one': 1, 'positively': 1, 'thrilling': 1, 'combination': 1, 'ethnography': 1, 'all': 1, 'intrigue': 1, 'betrayal': 1, 'deceit': 1, 'murder': 1, 'shakespearean': 1, 'tragedy': 1, 'or': 1, 'juicy': 1, 'soap': 1, 'opera': 1, 'comedy-drama': 1, 'nearly': 1, 'epic': 1, 'proportions': 1, 'rooted': 1, 'in': 1, 'sincere': 1, 'performance': 1, 'by': 1, 'title': 1, 'character': 1, 'undergoing': 1, 'midlife': 1, 'crisis': 1, 'importance': 1, 'being': 1, 'earnest': 1, 'so': 1, 'thick': 1, 'with': 1, 'wit': 1, 'it': 1, 'plays': 1, 'like': 1, 'reading': 1, 'from': 1, 'bartlett': 1, 'familiar': 1, 'quotations': 1}) \n",
  1342. "\n",
  1343. "{'<pad>': 0, '<unk>': 1, 'a': 2, 'of': 3, ',': 4, 'the': 5, '.': 6, 'is': 7, 'and': 8, 'good': 9, 'for': 10, 'which': 11, 'this': 12, \"'s\": 13, 'series': 14, 'escapades': 15, 'demonstrating': 16, 'adage': 17, 'that': 18, 'what': 19, 'goose': 20, 'also': 21, 'gander': 22, 'some': 23, 'occasionally': 24, 'amuses': 25, 'but': 26, 'none': 27, 'amounts': 28, 'to': 29, 'much': 30, 'story': 31, 'quiet': 32, 'introspective': 33, 'entertaining': 34, 'independent': 35, 'worth': 36, 'seeking': 37, 'even': 38, 'fans': 39, 'ismail': 40, 'merchant': 41, 'work': 42, 'i': 43, 'suspect': 44, 'would': 45, 'have': 46, 'hard': 47, 'time': 48, 'sitting': 49, 'through': 50, 'one': 51, 'positively': 52, 'thrilling': 53, 'combination': 54, 'ethnography': 55, 'all': 56, 'intrigue': 57, 'betrayal': 58, 'deceit': 59, 'murder': 60, 'shakespearean': 61, 'tragedy': 62, 'or': 63, 'juicy': 64, 'soap': 65, 'opera': 66, 'comedy-drama': 67, 'nearly': 68, 'epic': 69, 'proportions': 70, 'rooted': 71, 'in': 72, 'sincere': 73, 'performance': 74, 'by': 75, 'title': 76, 'character': 77, 'undergoing': 78, 'midlife': 79, 'crisis': 80, 'importance': 81, 'being': 82, 'earnest': 83, 'so': 84, 'thick': 85, 'with': 86, 'wit': 87, 'it': 88, 'plays': 89, 'like': 90, 'reading': 91, 'from': 92, 'bartlett': 93, 'familiar': 94, 'quotations': 95} \n",
  1344. "\n",
  1345. "Vocabulary(['a', 'series', 'of', 'escapades', 'demonstrating']...)\n"
  1346. ]
  1347. }
  1348. ],
  1349. "source": [
  1350. "from fastNLP.core.vocabulary import Vocabulary\n",
  1351. "\n",
  1352. "vocab = Vocabulary()\n",
  1353. "vocab = vocab.from_dataset(dataset, field_name='Sentence')\n",
  1354. "print(vocab.word_count, '\\n')\n",
  1355. "print(vocab.word2idx, '\\n')\n",
  1356. "print(vocab)"
  1357. ]
  1358. },
  1359. {
  1360. "cell_type": "markdown",
  1361. "id": "f0857ccb",
  1362. "metadata": {},
  1363. "source": [
  1364. "之后,**通过`vocabulary`的`index_dataset`方法**,**调整`dataset`中指定字段的元素**,**使用编号将之代替**\n",
  1365. "\n",
  1366. "&emsp; 使用上述方法,可以将影评数据集中的单词序列转化为词编号序列,为接下来转化为词嵌入序列做准备"
  1367. ]
  1368. },
  1369. {
  1370. "cell_type": "code",
  1371. "execution_count": 28,
  1372. "id": "2f9a04b2",
  1373. "metadata": {},
  1374. "outputs": [
  1375. {
  1376. "data": {
  1377. "text/html": [
  1378. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  1379. ],
  1380. "text/plain": []
  1381. },
  1382. "metadata": {},
  1383. "output_type": "display_data"
  1384. },
  1385. {
  1386. "data": {
  1387. "text/html": [
  1388. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  1389. ],
  1390. "text/plain": []
  1391. },
  1392. "metadata": {},
  1393. "output_type": "display_data"
  1394. },
  1395. {
  1396. "data": {
  1397. "text/html": [
  1398. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
  1399. "</pre>\n"
  1400. ],
  1401. "text/plain": [
  1402. "\n"
  1403. ]
  1404. },
  1405. "metadata": {},
  1406. "output_type": "display_data"
  1407. },
  1408. {
  1409. "name": "stdout",
  1410. "output_type": "stream",
  1411. "text": [
  1412. "+------------+------------------------------+-----------+\n",
  1413. "| SentenceId | Sentence | Sentiment |\n",
  1414. "+------------+------------------------------+-----------+\n",
  1415. "| 1 | [2, 14, 3, 15, 16, 5, 17,... | negative |\n",
  1416. "| 2 | [12, 32, 4, 33, 8, 34, 35... | positive |\n",
  1417. "| 3 | [38, 39, 3, 40, 41, 13, 4... | negative |\n",
  1418. "| 4 | [2, 52, 53, 54, 3, 55, 8,... | neutral |\n",
  1419. "| 5 | [2, 67, 3, 68, 69, 70, 71... | positive |\n",
  1420. "| 6 | [5, 81, 3, 82, 83, 4, 84,... | neutral |\n",
  1421. "+------------+------------------------------+-----------+\n"
  1422. ]
  1423. }
  1424. ],
  1425. "source": [
  1426. "vocab.index_dataset(dataset, field_name='Sentence')\n",
  1427. "print(dataset)"
  1428. ]
  1429. },
  1430. {
  1431. "cell_type": "markdown",
  1432. "id": "6b26b707",
  1433. "metadata": {},
  1434. "source": [
  1435. "最后,使用相同方法,再将`dataset`中`Sentiment`字段中的`negative`、`neutral`、`positive`转化为数字编号"
  1436. ]
  1437. },
  1438. {
  1439. "cell_type": "code",
  1440. "execution_count": 29,
  1441. "id": "5f5eed18",
  1442. "metadata": {},
  1443. "outputs": [
  1444. {
  1445. "data": {
  1446. "text/html": [
  1447. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  1448. ],
  1449. "text/plain": []
  1450. },
  1451. "metadata": {},
  1452. "output_type": "display_data"
  1453. },
  1454. {
  1455. "name": "stdout",
  1456. "output_type": "stream",
  1457. "text": [
  1458. "{'negative': 0, 'positive': 1, 'neutral': 2}\n"
  1459. ]
  1460. },
  1461. {
  1462. "data": {
  1463. "text/html": [
  1464. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  1465. ],
  1466. "text/plain": []
  1467. },
  1468. "metadata": {},
  1469. "output_type": "display_data"
  1470. },
  1471. {
  1472. "data": {
  1473. "text/html": [
  1474. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
  1475. "</pre>\n"
  1476. ],
  1477. "text/plain": [
  1478. "\n"
  1479. ]
  1480. },
  1481. "metadata": {},
  1482. "output_type": "display_data"
  1483. },
  1484. {
  1485. "name": "stdout",
  1486. "output_type": "stream",
  1487. "text": [
  1488. "+------------+------------------------------+-----------+\n",
  1489. "| SentenceId | Sentence | Sentiment |\n",
  1490. "+------------+------------------------------+-----------+\n",
  1491. "| 1 | [2, 14, 3, 15, 16, 5, 17,... | 0 |\n",
  1492. "| 2 | [12, 32, 4, 33, 8, 34, 35... | 1 |\n",
  1493. "| 3 | [38, 39, 3, 40, 41, 13, 4... | 0 |\n",
  1494. "| 4 | [2, 52, 53, 54, 3, 55, 8,... | 2 |\n",
  1495. "| 5 | [2, 67, 3, 68, 69, 70, 71... | 1 |\n",
  1496. "| 6 | [5, 81, 3, 82, 83, 4, 84,... | 2 |\n",
  1497. "+------------+------------------------------+-----------+\n"
  1498. ]
  1499. }
  1500. ],
  1501. "source": [
  1502. "target_vocab = Vocabulary(padding=None, unknown=None)\n",
  1503. "\n",
  1504. "target_vocab.from_dataset(dataset, field_name='Sentiment')\n",
  1505. "print(target_vocab.word2idx)\n",
  1506. "target_vocab.index_dataset(dataset, field_name='Sentiment')\n",
  1507. "print(dataset)"
  1508. ]
  1509. },
  1510. {
  1511. "cell_type": "markdown",
  1512. "id": "eed7ea64",
  1513. "metadata": {},
  1514. "source": [
  1515. "在最后的最后,通过以下的一张图,来总结本章关于`dataset`和`vocabulary`主要知识点的讲解,以及两者的联系\n",
  1516. "\n",
  1517. "<img src=\"./figures/T1-fig-dataset-and-vocabulary.png\" width=\"80%\" height=\"80%\" align=\"center\"></img>"
  1518. ]
  1519. },
  1520. {
  1521. "cell_type": "code",
  1522. "execution_count": null,
  1523. "id": "35b4f0f7",
  1524. "metadata": {},
  1525. "outputs": [],
  1526. "source": []
  1527. }
  1528. ],
  1529. "metadata": {
  1530. "kernelspec": {
  1531. "display_name": "Python 3 (ipykernel)",
  1532. "language": "python",
  1533. "name": "python3"
  1534. },
  1535. "language_info": {
  1536. "codemirror_mode": {
  1537. "name": "ipython",
  1538. "version": 3
  1539. },
  1540. "file_extension": ".py",
  1541. "mimetype": "text/x-python",
  1542. "name": "python",
  1543. "nbconvert_exporter": "python",
  1544. "pygments_lexer": "ipython3",
  1545. "version": "3.7.4"
  1546. }
  1547. },
  1548. "nbformat": 4,
  1549. "nbformat_minor": 5
  1550. }