1
0

index.html 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Deep Learning in R</title>
  5. <meta charset="utf-8">
  6. <meta name="author" content="metya" />
  7. <meta name="date" content="2018-12-08" />
  8. <link href="libs/pagedtable/css/pagedtable.css" rel="stylesheet" />
  9. <script src="libs/pagedtable/js/pagedtable.js"></script>
  10. <script src="libs/htmlwidgets/htmlwidgets.js"></script>
  11. <script src="libs/jquery/jquery.min.js"></script>
  12. <link href="libs/leaflet/leaflet.css" rel="stylesheet" />
  13. <script src="libs/leaflet/leaflet.js"></script>
  14. <link href="libs/leafletfix/leafletfix.css" rel="stylesheet" />
  15. <script src="libs/Proj4Leaflet/proj4-compressed.js"></script>
  16. <script src="libs/Proj4Leaflet/proj4leaflet.js"></script>
  17. <link href="libs/rstudio_leaflet/rstudio_leaflet.css" rel="stylesheet" />
  18. <script src="libs/leaflet-binding/leaflet.js"></script>
  19. <link href="libs/datatables-css/datatables-crosstalk.css" rel="stylesheet" />
  20. <script src="libs/datatables-binding/datatables.js"></script>
  21. <link href="libs/dt-core/css/jquery.dataTables.min.css" rel="stylesheet" />
  22. <link href="libs/dt-core/css/jquery.dataTables.extra.css" rel="stylesheet" />
  23. <script src="libs/dt-core/js/jquery.dataTables.min.js"></script>
  24. <link href="libs/crosstalk/css/crosstalk.css" rel="stylesheet" />
  25. <script src="libs/crosstalk/js/crosstalk.min.js"></script>
  26. <link rel="stylesheet" href="xaringan-themer.css" type="text/css" />
  27. </head>
  28. <body>
  29. <textarea id="source">
  30. class: center, middle, inverse, title-slide
  31. # Deep Learning in R
  32. ## ░ <br/>Обзор фреймворков с примерами
  33. ### metya
  34. ### 2018-12-08
  35. ---
  36. class: center, middle
  37. background-color: #8d6e63
  38. #Disclaimer
  39. Цель доклада не дать понимаение что такое глубокое обучение и детально разобрать как работать с ним и обучать современные модели, а скорее показать как просто можно начать тем, кто давно хотел и чесались руки, но все было никак не взяться
  40. ---
  41. # Deep Learning
  42. ## Что это?
  43. --
  44. * Когда у нас есть исскуственная нейронная сеть
  45. --
  46. * Когда скрытых слоев в этой сети больше чем два
  47. --
  48. ![](https://cdn-images-1.medium.com/max/1600/1*dnvGC-PORSoCo7VXT3PV_A.png)
  49. .footnotes[[1] https://machinelearningmastery.com/what-is-deep-learning/]
  50. ---
  51. ## Как это математически
  52. ![](Deep_Learning_in_R_files/perceptron.png)
  53. ???
  54. На самом деле это конечно самый простой юнит, самый базовый.
  55. ---
  56. background-image: url(https://3qeqpr26caki16dnhd19sv6by6v-wpengine.netdna-ssl.com/wp-content/uploads/2016/08/Why-Deep-Learning-1024x742.png)
  57. ???
  58. Image credit: [Andrew Ng](http://www.slideshare.net/ExtractConf)
  59. ---
  60. class: inverse, center, middle, title-slide
  61. # Frameworks
  62. ---
  63. ![](https://cdn-images-1.medium.com/max/1600/1*s_BwkYxpGv34vjOHi8tDzg.png)
  64. .footnotes[
  65. [1] https://towardsdatascience.com/deep-learning-framework-power-scores-2018-23607ddf297a
  66. ]
  67. ---
  68. ## Нас интересуют только те, что есть в R через API
  69. --
  70. * ###TensorFlow
  71. --
  72. * ###theano
  73. --
  74. * ###Keras
  75. --
  76. * ###CNTK
  77. --
  78. * ###MXNet
  79. --
  80. * ###ONNX
  81. ---
  82. ## Есть еше несколько пакетов
  83. * darch (removed from cran)
  84. * deepnet
  85. * deepr
  86. * H2O (interface) ([Tutorial](https://htmlpreview.github.io/?https://github.com/ledell/sldm4-h2o/blob/master/sldm4-deeplearning-h2o.html))
  87. ???
  88. Вода это по большей части МЛ фреймворк, с недавних пор, где появился модуль про глубокое обучение. Есть неплохой туториал для р пакета. Умеет в поиск гиперпараметров, кроссвалидацию и прочие нужные для МЛ штуки для сеток, очевидно это работает только для маленьких сетей)
  89. Но они р специфичны, кроме воды, и соотвественно медленные, да и умеют довольно мало. Новые годные архитектуры сетей туда не имплементированы.
  90. ---
  91. ![](https://cdn-images-1.medium.com/max/1600/1*zmMOdVZ_j9vwMcpdD8Uceg.png)
  92. https://www.tensorflow.org/
  93. https://tensorflow.rstudio.com/
  94. - Делает Google
  95. - Самый популярный, имеет тучу туториалов и книг
  96. - Имеет самый большой спрос у продакшн систем
  97. - Имеет API во множестве языков
  98. - Имеет статический граф вычислений, что бывает неудобно, зато оптимизированно
  99. - Примерно с лета имеет фичу **eager execution**, который почти нивелирует это неудобство. Но почти не считается
  100. - Доступен в R как самостоятельно, так и как бэкэнд Keras
  101. ---
  102. ![](https://cdn-images-1.medium.com/max/1600/1*dT-zhP2bmtxSuOja8gNGxA.png)
  103. http://www.deeplearning.net/software/theano/
  104. - Делался силами университета Монреаль с 2007
  105. - Один из самый старых фреймворков, но почти почил в забытьи
  106. - Придумали идею абстракции вычислительных графов (статических) для оптимизации и вычисления нейронных сетей
  107. - В R доступен как бэкенд через Keras
  108. ---
  109. ![](https://cdn-images-1.medium.com/max/1600/1*tzgWkBhJPl5FFFe4uhn1AA.png)
  110. https://cntk.ai/
  111. - Делается силами Майкрософт
  112. - Имеет половинчатые динамические вычислительные графы (на самом деле динамические тензоры скорее)
  113. - Доступен как бэкенд Keras так и как самостоятельный бэкенд с биндингами в R через reticulate package, что значит нужно иметь python версию фреймворка
  114. ---
  115. ![](https://cdn-images-1.medium.com/max/1600/1*k9LIDsTb1K-Uejn7MCO7nA.png)
  116. https://keras.io/
  117. https://keras.rstudio.com/
  118. https://tensorflow.rstudio.com/keras/
  119. - Высокоуровневый фреймворк над другими такими бэкэндами как Theano, CNTK, Tensorflow, и еще некоторые на подходе
  120. - Делается Франсуа Шолле, который написал книгу Deep Learning in R
  121. - Очень простой код
  122. - Один и тот же код рабоает на разных бэкендах, что теоретически может быть полезно (нет)
  123. - Есть очень много блоков нейросетей из современных SOTA работ
  124. - Нивелирует боль статических вычислительных графов
  125. - Уже давно дефолтом поставляется вместе с TensorFlow как его часть, но можно использовать и отдельно
  126. ---
  127. ![](https://raw.githubusercontent.com/dmlc/web-data/master/mxnet/image/mxnet_logo_2.png)&lt;img src="https://raw.githubusercontent.com/dmlc/dmlc.github.io/master/img/logo-m/mxnetR.png" style=width:30% /&gt;
  128. https://mxnet.apache.org/
  129. https://github.com/apache/incubator-mxnet/tree/master/R-package
  130. - Является проектом Apache
  131. - Сочетает в себе динамические и статические графы
  132. - Тоже имеет зоопарк предобученных моделей
  133. - Как и TensorFlow поддерживается многими языками, что может быть очень полезно
  134. - Довольно разумный и хороший фреймворк, непонятно, почему не пользуется популярностью
  135. ---
  136. ![](https://onnx.ai/onnx-r/articles/imgs/ONNX_logo_main.png)
  137. https://onnx.ai/
  138. https://onnx.ai/onnx-r/
  139. - Предоставляет открытый формат представления вычислительных графов, чтобы можно было обмениваться запускать одни и теже, экспортированные в этот формат, модели с помощью разных фреймворков и своего рантайма
  140. - Можно работать из R
  141. - Изначально делался Microsoft вместе с Facebook
  142. - Поддерживает кучу фреймворков нативно и конвертацию в ML и TF, Keras
  143. ---
  144. class: inverse, middle, center
  145. # Deep Learning with MXNet
  146. ---
  147. ## Установка
  148. В Windows и MacOS в R
  149. ```r
  150. # Windows and MacOs
  151. cran &lt;- getOption("repos")
  152. cran["dmlc"] &lt;- "https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/R/CRAN/GPU/cu92"
  153. options(repos = cran)
  154. install.packages("mxnet")
  155. ```
  156. Linux bash
  157. ```bash
  158. # On linux
  159. git clone --recursive https://github.com/apache/incubator-mxnet.git mxnet
  160. cd mxnet/docs/install
  161. ./install_mxnet_ubuntu_python.sh
  162. ./install_mxnet_ubuntu_r.sh
  163. cd incubator-mxnet
  164. make rpkg
  165. ```
  166. ---
  167. ## Загрузка и обработка данных
  168. ```r
  169. df &lt;- read_csv("data.csv")
  170. set.seed(100)
  171. ```
  172. ```r
  173. #transform and split train on x and y
  174. train_ind &lt;- sample(1:77, 60)
  175. x_train &lt;- as.matrix(df[train_ind, 2:8])
  176. y_train &lt;- unlist(df[train_ind, 9])
  177. x_val &lt;- as.matrix(df[-train_ind, 2:8])
  178. y_val &lt;- unlist(df[-train_ind, 9])
  179. ```
  180. ---
  181. ## Задания архитектуры сети
  182. ```r
  183. require(mxnet)
  184. # define graph
  185. data &lt;- mx.symbol.Variable("data")
  186. fc1 &lt;- mx.symbol.FullyConnected(data, num_hidden = 1)
  187. linreg &lt;- mx.symbol.LinearRegressionOutput(fc1)
  188. # define learing parameters
  189. initializer &lt;- mx.init.normal(sd = 0.1)
  190. optimizer &lt;- mx.opt.create("sgd",
  191. learning.rate = 1e-6,
  192. momentum = 0.9)
  193. # define logger
  194. logger &lt;- mx.metric.logger()
  195. epoch.end.callback &lt;- mx.callback.log.train.metric(
  196. period = 4, # число батчей, после которого оценивается метрика
  197. logger = logger)
  198. # num of epoch
  199. n_epoch &lt;- 20
  200. ```
  201. ---
  202. ## Построим граф модели
  203. ```r
  204. # plot our model
  205. graph.viz(linreg)
  206. ```
  207. &lt;img src="Deep_Learning_in_R_files/graph.png" style="width:50%" &gt;
  208. ---
  209. ## Обучим
  210. ```r
  211. model &lt;- mx.model.FeedForward.create(
  212. symbol = linreg, # our model
  213. X = x_train, # our data
  214. y = y_train, # our label
  215. ctx = mx.cpu(), # engine
  216. num.round = n_epoch,
  217. initializer = initializer, # inizialize weigths
  218. optimizer = optimizer, # sgd optimizer
  219. eval.data = list(data = x_val, label = y_val), # evaluation on evey epoch
  220. eval.metric = mx.metric.rmse, # metric
  221. array.batch.size = 15,
  222. epoch.end.callback = epoch.end.callback) # logger
  223. ```
  224. ```
  225. ## Warning in mx.model.select.layout.train(X, y): Auto detect layout of input matrix, use rowmajor..
  226. ```
  227. ```
  228. ## Start training with 1 devices
  229. ```
  230. ```
  231. ## [1] Train-rmse=7.85010987520218
  232. ```
  233. ```
  234. ## [1] Validation-rmse=7.99821019172668
  235. ```
  236. ```
  237. ## [2] Train-rmse=9.21365368366241
  238. ```
  239. ```
  240. ## [2] Validation-rmse=4.74030923843384
  241. ```
  242. ```
  243. ## [3] Train-rmse=4.16309010982513
  244. ```
  245. ```
  246. ## [3] Validation-rmse=7.18643116950989
  247. ```
  248. ```
  249. ## [4] Train-rmse=5.20915931463242
  250. ```
  251. ```
  252. ## [4] Validation-rmse=3.87698078155518
  253. ```
  254. ```
  255. ## [5] Train-rmse=4.94802039861679
  256. ```
  257. ```
  258. ## [5] Validation-rmse=3.80227029323578
  259. ```
  260. ```
  261. ## [6] Train-rmse=2.69853216409683
  262. ```
  263. ```
  264. ## [6] Validation-rmse=3.90478467941284
  265. ```
  266. ```
  267. ## [7] Train-rmse=3.52689051628113
  268. ```
  269. ```
  270. ## [7] Validation-rmse=2.31562197208405
  271. ```
  272. ```
  273. ## [8] Train-rmse=2.99551945924759
  274. ```
  275. ```
  276. ## [8] Validation-rmse=2.93496096134186
  277. ```
  278. ```
  279. ## [9] Train-rmse=2.22769635915756
  280. ```
  281. ```
  282. ## [9] Validation-rmse=2.37067186832428
  283. ```
  284. ```
  285. ## [10] Train-rmse=2.5699103474617
  286. ```
  287. ```
  288. ## [10] Validation-rmse=1.86853647232056
  289. ```
  290. ```
  291. ## [11] Train-rmse=2.24543181061745
  292. ```
  293. ```
  294. ## [11] Validation-rmse=2.3385466337204
  295. ```
  296. ```
  297. ## [12] Train-rmse=2.03947871923447
  298. ```
  299. ```
  300. ## [12] Validation-rmse=1.82985359430313
  301. ```
  302. ```
  303. ## [13] Train-rmse=2.111790984869
  304. ```
  305. ```
  306. ## [13] Validation-rmse=1.74209445714951
  307. ```
  308. ```
  309. ## [14] Train-rmse=1.98190069198608
  310. ```
  311. ```
  312. ## [14] Validation-rmse=1.98799872398376
  313. ```
  314. ```
  315. ## [15] Train-rmse=1.9320664703846
  316. ```
  317. ```
  318. ## [15] Validation-rmse=1.68956047296524
  319. ```
  320. ```
  321. ## [16] Train-rmse=1.91881200671196
  322. ```
  323. ```
  324. ## [16] Validation-rmse=1.68268179893494
  325. ```
  326. ```
  327. ## [17] Train-rmse=1.87585905194283
  328. ```
  329. ```
  330. ## [17] Validation-rmse=1.79575181007385
  331. ```
  332. ```
  333. ## [18] Train-rmse=1.85955160856247
  334. ```
  335. ```
  336. ## [18] Validation-rmse=1.64644628763199
  337. ```
  338. ```
  339. ## [19] Train-rmse=1.83187100291252
  340. ```
  341. ```
  342. ## [19] Validation-rmse=1.63903748989105
  343. ```
  344. ```
  345. ## [20] Train-rmse=1.81522011756897
  346. ```
  347. ```
  348. ## [20] Validation-rmse=1.68724113702774
  349. ```
  350. ---
  351. ## Построим кривую обучения
  352. ```r
  353. rmse_log &lt;- data.frame(RMSE = c(logger$train, logger$eval),dataset = c(rep("train", length(logger$train)), rep("val", length(logger$eval))),epoch = 1:n_epoch)
  354. library(ggplot2)
  355. ggplot(rmse_log, aes(epoch, RMSE, group = dataset, colour = dataset)) + geom_point() + geom_line()
  356. ```
  357. ![](Deep_Learning_in_R_files/figure-html/unnamed-chunk-7-1.svg)&lt;!-- --&gt;
  358. ---
  359. class: inverse, center, middle
  360. # Deep Learning with Keras
  361. ---
  362. ## Установка
  363. ```r
  364. install.packages("keras")
  365. keras::install_keras(tensorflow = 'gpu')
  366. ```
  367. ### Загрузка нужных нам пакетов
  368. ```r
  369. require(keras) # Neural Networks
  370. require(tidyverse) # Data cleaning / Visualization
  371. require(knitr) # Table printing
  372. require(rmarkdown) # Misc. output utilities
  373. require(ggridges) # Visualization
  374. ```
  375. ---
  376. ## Загрузка данных
  377. ```r
  378. activityLabels &lt;- read.table("Deep_Learning_in_R_files/HAPT Data Set/activity_labels.txt",
  379. col.names = c("number", "label"))
  380. activityLabels %&gt;% kable(align = c("c", "l"))
  381. ```
  382. number label
  383. -------- -------------------
  384. 1 WALKING
  385. 2 WALKING_UPSTAIRS
  386. 3 WALKING_DOWNSTAIRS
  387. 4 SITTING
  388. 5 STANDING
  389. 6 LAYING
  390. 7 STAND_TO_SIT
  391. 8 SIT_TO_STAND
  392. 9 SIT_TO_LIE
  393. 10 LIE_TO_SIT
  394. 11 STAND_TO_LIE
  395. 12 LIE_TO_STAND
  396. ---
  397. ```r
  398. labels &lt;- read.table("Deep_Learning_in_R_files/HAPT Data Set/RawData/labels.txt",
  399. col.names = c("experiment", "userId", "activity", "startPos", "endPos"))
  400. dataFiles &lt;- list.files("Deep_Learning_in_R_files/HAPT Data Set/RawData")
  401. labels %&gt;%
  402. head(50) %&gt;%
  403. paged_table()
  404. ```
  405. &lt;div data-pagedtable="false"&gt;
  406. &lt;script data-pagedtable-source type="application/json"&gt;
  407. {"columns":[{"label":[""],"name":["_rn_"],"type":[""],"align":["left"]},{"label":["experiment"],"name":[1],"type":["int"],"align":["right"]},{"label":["userId"],"name":[2],"type":["int"],"align":["right"]},{"label":["activity"],"name":[3],"type":["int"],"align":["right"]},{"label":["startPos"],"name":[4],"type":["int"],"align":["right"]},{"label":["endPos"],"name":[5],"type":["int"],"align":["right"]}],"data":[{"1":"1","2":"1","3":"5","4":"250","5":"1232","_rn_":"1"},{"1":"1","2":"1","3":"7","4":"1233","5":"1392","_rn_":"2"},{"1":"1","2":"1","3":"4","4":"1393","5":"2194","_rn_":"3"},{"1":"1","2":"1","3":"8","4":"2195","5":"2359","_rn_":"4"},{"1":"1","2":"1","3":"5","4":"2360","5":"3374","_rn_":"5"},{"1":"1","2":"1","3":"11","4":"3375","5":"3662","_rn_":"6"},{"1":"1","2":"1","3":"6","4":"3663","5":"4538","_rn_":"7"},{"1":"1","2":"1","3":"10","4":"4539","5":"4735","_rn_":"8"},{"1":"1","2":"1","3":"4","4":"4736","5":"5667","_rn_":"9"},{"1":"1","2":"1","3":"9","4":"5668","5":"5859","_rn_":"10"},{"1":"1","2":"1","3":"6","4":"5860","5":"6786","_rn_":"11"},{"1":"1","2":"1","3":"12","4":"6787","5":"6977","_rn_":"12"},{"1":"1","2":"1","3":"1","4":"7496","5":"8078","_rn_":"13"},{"1":"1","2":"1","3":"1","4":"8356","5":"9250","_rn_":"14"},{"1":"1","2":"1","3":"1","4":"9657","5":"10567","_rn_":"15"},{"1":"1","2":"1","3":"1","4":"10750","5":"11714","_rn_":"16"},{"1":"1","2":"1","3":"3","4":"13191","5":"13846","_rn_":"17"},{"1":"1","2":"1","3":"2","4":"14069","5":"14699","_rn_":"18"},{"1":"1","2":"1","3":"3","4":"14869","5":"15492","_rn_":"19"},{"1":"1","2":"1","3":"2","4":"15712","5":"16377","_rn_":"20"},{"1":"1","2":"1","3":"3","4":"16530","5":"17153","_rn_":"21"},{"1":"1","2":"1","3":"2","4":"17298","5":"17970","_rn_":"22"},{"1":"2","2":"1","3":"5","4":"251","5":"1226","_rn_":"23"},{"1":"2","2":"1","3":"7","4":"1227","5":"1432","_rn_":"24"},{"1":"2","2":"1","3":"4","4":"1433","5":"2221","_rn_":"25"},{"1":"2","2":"1","3":"8","4":"2222","5":"2377","_rn_":"26"},{"1":"2","2":"1","3":"5","4":"2378","5":"3304","_rn_":"27"},{"1":"2","2":"1","3":"11","4":"3305","5":"3572","_rn_":"28"},{"1":"2","2":"1","3":"6","4":"3573","5":"4435","_rn_":"29"},{"1":"2","2":"1","3":"10","4":"4436","5":"4619","_rn_":"30"},{"1":"2","2":"1","3":"4","4":"4620","5":"5452","_rn_":"31"},{"1":"2","2":"1","3":"9","4":"5453","5":"5689","_rn_":"32"},{"1":"2","2":"1","3":"6","4":"5690","5":"6467","_rn_":"33"},{"1":"2","2":"1","3":"12","4":"6468","5":"6709","_rn_":"34"},{"1":"2","2":"1","3":"1","4":"7624","5":"8252","_rn_":"35"},{"1":"2","2":"1","3":"1","4":"8618","5":"9576","_rn_":"36"},{"1":"2","2":"1","3":"1","4":"9991","5":"10927","_rn_":"37"},{"1":"2","2":"1","3":"1","4":"11311","5":"12282","_rn_":"38"},{"1":"2","2":"1","3":"3","4":"13129","5":"13379","_rn_":"39"},{"1":"2","2":"1","3":"3","4":"13495","5":"13927","_rn_":"40"},{"1":"2","2":"1","3":"2","4":"14128","5":"14783","_rn_":"41"},{"1":"2","2":"1","3":"3","4":"15037","5":"15684","_rn_":"42"},{"1":"2","2":"1","3":"2","4":"15920","5":"16598","_rn_":"43"},{"1":"2","2":"1","3":"3","4":"16847","5":"17471","_rn_":"44"},{"1":"2","2":"1","3":"2","4":"17725","5":"18425","_rn_":"45"},{"1":"3","2":"2","3":"5","4":"298","5":"1398","_rn_":"46"},{"1":"3","2":"2","3":"7","4":"1399","5":"1555","_rn_":"47"},{"1":"3","2":"2","3":"4","4":"1686","5":"2627","_rn_":"48"},{"1":"3","2":"2","3":"8","4":"2628","5":"2769","_rn_":"49"},{"1":"3","2":"2","3":"5","4":"2770","5":"3904","_rn_":"50"}],"options":{"columns":{"min":{},"max":[10]},"rows":{"min":[10],"max":[10]},"pages":{}}}
  408. &lt;/script&gt;
  409. &lt;/div&gt;
  410. ---
  411. ```r
  412. fileInfo &lt;- data_frame(
  413. filePath = dataFiles
  414. ) %&gt;%
  415. filter(filePath != "labels.txt") %&gt;%
  416. separate(filePath, sep = '_',
  417. into = c("type", "experiment", "userId"),
  418. remove = FALSE) %&gt;%
  419. mutate(
  420. experiment = str_remove(experiment, "exp"),
  421. userId = str_remove_all(userId, "user|\\.txt")
  422. ) %&gt;%
  423. spread(type, filePath)
  424. fileInfo %&gt;% head() %&gt;% kable()
  425. ```
  426. experiment userId acc gyro
  427. ----------- ------- --------------------- ----------------------
  428. 01 01 acc_exp01_user01.txt gyro_exp01_user01.txt
  429. 02 01 acc_exp02_user01.txt gyro_exp02_user01.txt
  430. 03 02 acc_exp03_user02.txt gyro_exp03_user02.txt
  431. 04 02 acc_exp04_user02.txt gyro_exp04_user02.txt
  432. 05 03 acc_exp05_user03.txt gyro_exp05_user03.txt
  433. 06 03 acc_exp06_user03.txt gyro_exp06_user03.txt
  434. ---
  435. # remark.js
  436. Some differences between using remark.js (left) and using **xaringan** (right):
  437. .pull-left[
  438. 1. Start with a boilerplate HTML file;
  439. 1. Plain Markdown;
  440. 1. Write JavaScript to autoplay slides;
  441. 1. Manually configure MathJax;
  442. 1. Highlight code with `*`;
  443. 1. Edit Markdown source and refresh browser to see updated slides;
  444. ]
  445. .pull-right[
  446. 1. Start with an R Markdown document;
  447. 1. R Markdown (can embed R/other code chunks);
  448. 1. Provide an option `autoplay`;
  449. 1. MathJax just works;&lt;sup&gt;*&lt;/sup&gt;
  450. 1. Highlight code with `{{}}`;
  451. 1. The RStudio addin "Infinite Moon Reader" automatically refreshes slides on changes;
  452. ]
  453. .footnote[[*] Not really. See next page.]
  454. ---
  455. # Math Expressions
  456. You can write LaTeX math expressions inside a pair of dollar signs, e.g. &amp;#36;\alpha+\beta$ renders `\(\alpha+\beta\)`. You can use the display style with double dollar signs:
  457. ```
  458. $$\bar{X}=\frac{1}{n}\sum_{i=1}^nX_i$$
  459. ```
  460. `$$\bar{X}=\frac{1}{n}\sum_{i=1}^nX_i$$`
  461. Limitations:
  462. 1. The source code of a LaTeX math expression must be in one line, unless it is inside a pair of double dollar signs, in which case the starting `$$` must appear in the very beginning of a line, followed immediately by a non-space character, and the ending `$$` must be at the end of a line, led by a non-space character;
  463. 1. There should not be spaces after the opening `$` or before the closing `$`.
  464. 1. Math does not work on the title slide (see [#61](https://github.com/yihui/xaringan/issues/61) for a workaround).
  465. ---
  466. # R Code
  467. ```r
  468. # a boring regression
  469. fit = lm(dist ~ 1 + speed, data = cars)
  470. coef(summary(fit))
  471. ```
  472. ```
  473. # Estimate Std. Error t value Pr(&gt;|t|)
  474. # (Intercept) -17.579095 6.7584402 -2.601058 1.231882e-02
  475. # speed 3.932409 0.4155128 9.463990 1.489836e-12
  476. ```
  477. ```r
  478. dojutsu = c('地爆天星', '天照', '加具土命', '神威', '須佐能乎', '無限月読')
  479. grep('天', dojutsu, value = TRUE)
  480. ```
  481. ```
  482. # character(0)
  483. ```
  484. ---
  485. # R Plots
  486. ```r
  487. par(mar = c(4, 4, 1, .1))
  488. plot(cars, pch = 19, col = 'darkgray', las = 1)
  489. abline(fit, lwd = 2)
  490. ```
  491. ![](Deep_Learning_in_R_files/figure-html/cars-1.svg)&lt;!-- --&gt;
  492. ---
  493. # Tables
  494. If you want to generate a table, make sure it is in the HTML format (instead of Markdown or other formats), e.g.,
  495. ```r
  496. knitr::kable(head(iris), format = 'html')
  497. ```
  498. &lt;table&gt;
  499. &lt;thead&gt;
  500. &lt;tr&gt;
  501. &lt;th style="text-align:right;"&gt; Sepal.Length &lt;/th&gt;
  502. &lt;th style="text-align:right;"&gt; Sepal.Width &lt;/th&gt;
  503. &lt;th style="text-align:right;"&gt; Petal.Length &lt;/th&gt;
  504. &lt;th style="text-align:right;"&gt; Petal.Width &lt;/th&gt;
  505. &lt;th style="text-align:left;"&gt; Species &lt;/th&gt;
  506. &lt;/tr&gt;
  507. &lt;/thead&gt;
  508. &lt;tbody&gt;
  509. &lt;tr&gt;
  510. &lt;td style="text-align:right;"&gt; 5.1 &lt;/td&gt;
  511. &lt;td style="text-align:right;"&gt; 3.5 &lt;/td&gt;
  512. &lt;td style="text-align:right;"&gt; 1.4 &lt;/td&gt;
  513. &lt;td style="text-align:right;"&gt; 0.2 &lt;/td&gt;
  514. &lt;td style="text-align:left;"&gt; setosa &lt;/td&gt;
  515. &lt;/tr&gt;
  516. &lt;tr&gt;
  517. &lt;td style="text-align:right;"&gt; 4.9 &lt;/td&gt;
  518. &lt;td style="text-align:right;"&gt; 3.0 &lt;/td&gt;
  519. &lt;td style="text-align:right;"&gt; 1.4 &lt;/td&gt;
  520. &lt;td style="text-align:right;"&gt; 0.2 &lt;/td&gt;
  521. &lt;td style="text-align:left;"&gt; setosa &lt;/td&gt;
  522. &lt;/tr&gt;
  523. &lt;tr&gt;
  524. &lt;td style="text-align:right;"&gt; 4.7 &lt;/td&gt;
  525. &lt;td style="text-align:right;"&gt; 3.2 &lt;/td&gt;
  526. &lt;td style="text-align:right;"&gt; 1.3 &lt;/td&gt;
  527. &lt;td style="text-align:right;"&gt; 0.2 &lt;/td&gt;
  528. &lt;td style="text-align:left;"&gt; setosa &lt;/td&gt;
  529. &lt;/tr&gt;
  530. &lt;tr&gt;
  531. &lt;td style="text-align:right;"&gt; 4.6 &lt;/td&gt;
  532. &lt;td style="text-align:right;"&gt; 3.1 &lt;/td&gt;
  533. &lt;td style="text-align:right;"&gt; 1.5 &lt;/td&gt;
  534. &lt;td style="text-align:right;"&gt; 0.2 &lt;/td&gt;
  535. &lt;td style="text-align:left;"&gt; setosa &lt;/td&gt;
  536. &lt;/tr&gt;
  537. &lt;tr&gt;
  538. &lt;td style="text-align:right;"&gt; 5.0 &lt;/td&gt;
  539. &lt;td style="text-align:right;"&gt; 3.6 &lt;/td&gt;
  540. &lt;td style="text-align:right;"&gt; 1.4 &lt;/td&gt;
  541. &lt;td style="text-align:right;"&gt; 0.2 &lt;/td&gt;
  542. &lt;td style="text-align:left;"&gt; setosa &lt;/td&gt;
  543. &lt;/tr&gt;
  544. &lt;tr&gt;
  545. &lt;td style="text-align:right;"&gt; 5.4 &lt;/td&gt;
  546. &lt;td style="text-align:right;"&gt; 3.9 &lt;/td&gt;
  547. &lt;td style="text-align:right;"&gt; 1.7 &lt;/td&gt;
  548. &lt;td style="text-align:right;"&gt; 0.4 &lt;/td&gt;
  549. &lt;td style="text-align:left;"&gt; setosa &lt;/td&gt;
  550. &lt;/tr&gt;
  551. &lt;/tbody&gt;
  552. &lt;/table&gt;
  553. ---
  554. # HTML Widgets
  555. I have not thoroughly tested HTML widgets against **xaringan**. Some may work well, and some may not. It is a little tricky.
  556. Similarly, the Shiny mode (`runtime: shiny`) does not work. I might get these issues fixed in the future, but these are not of high priority to me. I never turn my presentation into a Shiny app. When I need to demonstrate more complicated examples, I just launch them separately. It is convenient to share slides with other people when they are plain HTML/JS applications.
  557. See the next page for two HTML widgets.
  558. ---
  559. ```r
  560. library(leaflet)
  561. leaflet() %&gt;% addTiles() %&gt;% setView(-93.65, 42.0285, zoom = 17)
  562. ```
  563. <div id="htmlwidget-b7ecac2f591f1b4cd6fe" style="width:100%;height:432px;" class="leaflet html-widget"></div>
  564. <script type="application/json" data-for="htmlwidget-b7ecac2f591f1b4cd6fe">{"x":{"options":{"crs":{"crsClass":"L.CRS.EPSG3857","code":null,"proj4def":null,"projectedBounds":null,"options":{}}},"calls":[{"method":"addTiles","args":["//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",null,null,{"minZoom":0,"maxZoom":18,"tileSize":256,"subdomains":"abc","errorTileUrl":"","tms":false,"noWrap":false,"zoomOffset":0,"zoomReverse":false,"opacity":1,"zIndex":1,"detectRetina":false,"attribution":"&copy; <a href=\"http://openstreetmap.org\">OpenStreetMap<\/a> contributors, <a href=\"http://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA<\/a>"}]}],"setView":[[42.0285,-93.65],17,[]]},"evals":[],"jsHooks":[]}</script>
  565. ---
  566. ```r
  567. DT::datatable(
  568. head(iris, 10),
  569. fillContainer = FALSE, options = list(pageLength = 8)
  570. )
  571. ```
  572. <div id="htmlwidget-6f33f6a94c1e991ec95e" style="width:100%;height:auto;" class="datatables html-widget"></div>
  573. <script type="application/json" data-for="htmlwidget-6f33f6a94c1e991ec95e">{"x":{"filter":"none","fillContainer":false,"data":[["1","2","3","4","5","6","7","8","9","10"],[5.1,4.9,4.7,4.6,5,5.4,4.6,5,4.4,4.9],[3.5,3,3.2,3.1,3.6,3.9,3.4,3.4,2.9,3.1],[1.4,1.4,1.3,1.5,1.4,1.7,1.4,1.5,1.4,1.5],[0.2,0.2,0.2,0.2,0.2,0.4,0.3,0.2,0.2,0.1],["setosa","setosa","setosa","setosa","setosa","setosa","setosa","setosa","setosa","setosa"]],"container":"<table class=\"display\">\n <thead>\n <tr>\n <th> <\/th>\n <th>Sepal.Length<\/th>\n <th>Sepal.Width<\/th>\n <th>Petal.Length<\/th>\n <th>Petal.Width<\/th>\n <th>Species<\/th>\n <\/tr>\n <\/thead>\n<\/table>","options":{"pageLength":8,"columnDefs":[{"className":"dt-right","targets":[1,2,3,4]},{"orderable":false,"targets":0}],"order":[],"autoWidth":false,"orderClasses":false,"lengthMenu":[8,10,25,50,100]}},"evals":[],"jsHooks":[]}</script>
  574. ---
  575. # Some Tips
  576. - When you use the "Infinite Moon Reader" addin in RStudio, your R session will be blocked by default. You can click the red button on the right of the console to stop serving the slides, or use the _daemonized_ mode so that it does not block your R session. To do the latter, you can set the option
  577. ```r
  578. options(servr.daemon = TRUE)
  579. ```
  580. in your current R session, or in `~/.Rprofile` so that it is applied to all future R sessions. I do the latter by myself.
  581. To know more about the web server, see the [**servr**](https://github.com/yihui/servr) package.
  582. --
  583. - Do not forget to try the `yolo` option of `xaringan::moon_reader`.
  584. ```yaml
  585. output:
  586. xaringan::moon_reader:
  587. yolo: true
  588. ```
  589. ---
  590. # Some Tips
  591. - Slides can be automatically played if you set the `autoplay` option under `nature`, e.g. go to the next slide every 30 seconds in a lightning talk:
  592. ```yaml
  593. output:
  594. xaringan::moon_reader:
  595. nature:
  596. autoplay: 30000
  597. ```
  598. --
  599. - A countdown timer can be added to every page of the slides using the `countdown` option under `nature`, e.g. if you want to spend one minute on every page when you give the talk, you can set:
  600. ```yaml
  601. output:
  602. xaringan::moon_reader:
  603. nature:
  604. countdown: 60000
  605. ```
  606. Then you will see a timer counting down from `01:00`, to `00:59`, `00:58`, ... When the time is out, the timer will continue but the time turns red.
  607. ---
  608. # Some Tips
  609. - There are several ways to build incremental slides. See [this presentation](https://slides.yihui.name/xaringan/incremental.html) for examples.
  610. - The option `highlightLines: true` of `nature` will highlight code lines that start with `*`, or are wrapped in `{{ }}`, or have trailing comments `#&lt;&lt;`;
  611. ```yaml
  612. output:
  613. xaringan::moon_reader:
  614. nature:
  615. highlightLines: true
  616. ```
  617. See examples on the next page.
  618. ---
  619. # Some Tips
  620. .pull-left[
  621. An example using a leading `*`:
  622. ```r
  623. if (TRUE) {
  624. ** message("Very important!")
  625. }
  626. ```
  627. Output:
  628. ```r
  629. if (TRUE) {
  630. * message("Very important!")
  631. }
  632. ```
  633. This is invalid R code, so it is a plain fenced code block that is not executed.
  634. ]
  635. .pull-right[
  636. An example using `{{}}`:
  637. ```{r tidy=FALSE}
  638. if (TRUE) {
  639. *{{ message("Very important!") }}
  640. }
  641. ```
  642. Output:
  643. ```r
  644. if (TRUE) {
  645. * message("Very important!")
  646. }
  647. ```
  648. ```
  649. ## Very important!
  650. ```
  651. It is valid R code so you can run it. Note that `{{}}` can wrap an R expression of multiple lines.
  652. ]
  653. ---
  654. # Some Tips
  655. An example of using the trailing comment `#&lt;&lt;` to highlight lines:
  656. ````markdown
  657. ```{r tidy=FALSE}
  658. library(ggplot2)
  659. ggplot(mtcars) +
  660. aes(mpg, disp) +
  661. geom_point() + #&lt;&lt;
  662. geom_smooth() #&lt;&lt;
  663. ```
  664. ````
  665. Output:
  666. ```r
  667. library(ggplot2)
  668. ggplot(mtcars) +
  669. aes(mpg, disp) +
  670. * geom_point() +
  671. * geom_smooth()
  672. ```
  673. ---
  674. # Some Tips
  675. - To make slides work offline, you need to download a copy of remark.js in advance, because **xaringan** uses the online version by default (see the help page `?xaringan::moon_reader`).
  676. - You can use `xaringan::summon_remark()` to download the latest or a specified version of remark.js. By default, it is downloaded to `libs/remark-latest.min.js`.
  677. - Then change the `chakra` option in YAML to point to this file, e.g.
  678. ```yaml
  679. output:
  680. xaringan::moon_reader:
  681. chakra: libs/remark-latest.min.js
  682. ```
  683. - If you used Google fonts in slides (the default theme uses _Yanone Kaffeesatz_, _Droid Serif_, and _Source Code Pro_), they won't work offline unless you download or install them locally. The Heroku app [google-webfonts-helper](https://google-webfonts-helper.herokuapp.com/fonts) can help you download fonts and generate the necessary CSS.
  684. ---
  685. # Macros
  686. - remark.js [allows users to define custom macros](https://github.com/yihui/xaringan/issues/80) (JS functions) that can be applied to Markdown text using the syntax `![:macroName arg1, arg2, ...]` or `![:macroName arg1, arg2, ...](this)`. For example, before remark.js initializes the slides, you can define a macro named `scale`:
  687. ```js
  688. remark.macros.scale = function (percentage) {
  689. var url = this;
  690. return '&lt;img src="' + url + '" style="width: ' + percentage + '" /&gt;';
  691. };
  692. ```
  693. Then the Markdown text
  694. ```markdown
  695. ![:scale 50%](image.jpg)
  696. ```
  697. will be translated to
  698. ```html
  699. &lt;img src="image.jpg" style="width: 50%" /&gt;
  700. ```
  701. ---
  702. # Macros (continued)
  703. - To insert macros in **xaringan** slides, you can use the option `beforeInit` under the option `nature`, e.g.,
  704. ```yaml
  705. output:
  706. xaringan::moon_reader:
  707. nature:
  708. beforeInit: "macros.js"
  709. ```
  710. You save your remark.js macros in the file `macros.js`.
  711. - The `beforeInit` option can be used to insert arbitrary JS code before `remark.create()`. Inserting macros is just one of its possible applications.
  712. ---
  713. # CSS
  714. Among all options in `xaringan::moon_reader`, the most challenging but perhaps also the most rewarding one is `css`, because it allows you to customize the appearance of your slides using any CSS rules or hacks you know.
  715. You can see the default CSS file [here](https://github.com/yihui/xaringan/blob/master/inst/rmarkdown/templates/xaringan/resources/default.css). You can completely replace it with your own CSS files, or define new rules to override the default. See the help page `?xaringan::moon_reader` for more information.
  716. ---
  717. # CSS
  718. For example, suppose you want to change the font for code from the default "Source Code Pro" to "Ubuntu Mono". You can create a CSS file named, say, `ubuntu-mono.css`:
  719. ```css
  720. @import url(https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic);
  721. .remark-code, .remark-inline-code { font-family: 'Ubuntu Mono'; }
  722. ```
  723. Then set the `css` option in the YAML metadata:
  724. ```yaml
  725. output:
  726. xaringan::moon_reader:
  727. css: ["default", "ubuntu-mono.css"]
  728. ```
  729. Here I assume `ubuntu-mono.css` is under the same directory as your Rmd.
  730. See [yihui/xaringan#83](https://github.com/yihui/xaringan/issues/83) for an example of using the [Fira Code](https://github.com/tonsky/FiraCode) font, which supports ligatures in program code.
  731. ---
  732. # Themes
  733. Don't want to learn CSS? Okay, you can use some user-contributed themes. A theme typically consists of two CSS files `foo.css` and `foo-fonts.css`, where `foo` is the theme name. Below are some existing themes:
  734. ```r
  735. names(xaringan:::list_css())
  736. ```
  737. ```
  738. ## [1] "chocolate-fonts" "chocolate" "default-fonts"
  739. ## [4] "default" "duke-blue" "hygge-duke"
  740. ## [7] "hygge" "kunoichi" "lucy-fonts"
  741. ## [10] "lucy" "metropolis-fonts" "metropolis"
  742. ## [13] "middlebury-fonts" "middlebury" "ninjutsu"
  743. ## [16] "rladies-fonts" "rladies" "robot-fonts"
  744. ## [19] "robot" "rutgers-fonts" "rutgers"
  745. ## [22] "shinobi" "tamu-fonts" "tamu"
  746. ## [25] "uo-fonts" "uo"
  747. ```
  748. To use a theme, you can specify the `css` option as an array of CSS filenames (without the `.css` extensions), e.g.,
  749. ```yaml
  750. output:
  751. xaringan::moon_reader:
  752. css: [default, metropolis, metropolis-fonts]
  753. ```
  754. If you want to contribute a theme to **xaringan**, please read [this blog post](https://yihui.name/en/2017/10/xaringan-themes).
  755. ---
  756. class: inverse, middle, center
  757. background-image: url(https://upload.wikimedia.org/wikipedia/commons/3/39/Naruto_Shiki_Fujin.svg)
  758. background-size: contain
  759. # Naruto
  760. ---
  761. background-image: url(https://upload.wikimedia.org/wikipedia/commons/b/be/Sharingan_triple.svg)
  762. background-size: 100px
  763. background-position: 90% 8%
  764. # Sharingan
  765. The R package name **xaringan** was derived&lt;sup&gt;1&lt;/sup&gt; from **Sharingan**, a dōjutsu in the Japanese anime _Naruto_ with two abilities:
  766. - the "Eye of Insight"
  767. - the "Eye of Hypnotism"
  768. I think a presentation is basically a way to communicate insights to the audience, and a great presentation may even "hypnotize" the audience.&lt;sup&gt;2,3&lt;/sup&gt;
  769. .footnote[
  770. [1] In Chinese, the pronounciation of _X_ is _Sh_ /ʃ/ (as in _shrimp_). Now you should have a better idea of how to pronounce my last name _Xie_.
  771. [2] By comparison, bad presentations only put the audience to sleep.
  772. [3] Personally I find that setting background images for slides is a killer feature of remark.js. It is an effective way to bring visual impact into your presentations.
  773. ]
  774. ---
  775. # Naruto terminology
  776. The **xaringan** package borrowed a few terms from Naruto, such as
  777. - [Sharingan](http://naruto.wikia.com/wiki/Sharingan) (写輪眼; the package name)
  778. - The [moon reader](http://naruto.wikia.com/wiki/Moon_Reader) (月読; an attractive R Markdown output format)
  779. - [Chakra](http://naruto.wikia.com/wiki/Chakra) (查克拉; the path to the remark.js library, which is the power to drive the presentation)
  780. - [Nature transformation](http://naruto.wikia.com/wiki/Nature_Transformation) (性質変化; transform the chakra by setting different options)
  781. - The [infinite moon reader](http://naruto.wikia.com/wiki/Infinite_Tsukuyomi) (無限月読; start a local web server to continuously serve your slides)
  782. - The [summoning technique](http://naruto.wikia.com/wiki/Summoning_Technique) (download remark.js from the web)
  783. You can click the links to know more about them if you want. The jutsu "Moon Reader" may seem a little evil, but that does not mean your slides are evil.
  784. ---
  785. class: center
  786. # Hand seals (印)
  787. Press `h` or `?` to see the possible ninjutsu you can use in remark.js.
  788. ![](https://upload.wikimedia.org/wikipedia/commons/7/7e/Mudra-Naruto-KageBunshin.svg)
  789. ---
  790. class: center, middle
  791. # Thanks!
  792. Slides created via the R package [**xaringan**](https://github.com/yihui/xaringan).
  793. The chakra comes from [remark.js](https://remarkjs.com), [**knitr**](http://yihui.name/knitr), and [R Markdown](https://rmarkdown.rstudio.com).
  794. </textarea>
  795. <script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
  796. <script>var slideshow = remark.create({
  797. "highlightStyle": "github",
  798. "highlightLines": true,
  799. "countIncrementalSlides": false
  800. });
  801. if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
  802. window.dispatchEvent(new Event('resize'));
  803. });
  804. (function() {
  805. var d = document, s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
  806. if (!r) return;
  807. s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
  808. d.head.appendChild(s);
  809. })();</script>
  810. <script>
  811. (function() {
  812. var i, text, code, codes = document.getElementsByTagName('code');
  813. for (i = 0; i < codes.length;) {
  814. code = codes[i];
  815. if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
  816. text = code.textContent;
  817. if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
  818. /^\$\$(.|\s)+\$\$$/.test(text) ||
  819. /^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
  820. code.outerHTML = code.innerHTML; // remove <code></code>
  821. continue;
  822. }
  823. }
  824. i++;
  825. }
  826. })();
  827. </script>
  828. <!-- dynamically load mathjax for compatibility with self-contained -->
  829. <script>
  830. (function () {
  831. var script = document.createElement('script');
  832. script.type = 'text/javascript';
  833. script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML';
  834. if (location.protocol !== 'file:' && /^https?:/.test(script.src))
  835. script.src = script.src.replace(/^https?:/, '');
  836. document.getElementsByTagName('head')[0].appendChild(script);
  837. })();
  838. </script>
  839. </body>
  840. </html>