<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by No Risk on Medium]]></title>
        <description><![CDATA[Stories by No Risk on Medium]]></description>
        <link>https://medium.com/@norisk?source=rss-c55e83e4003------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a0XbXDYgzFt7swl7kllx8w.png</url>
            <title>Stories by No Risk on Medium</title>
            <link>https://medium.com/@norisk?source=rss-c55e83e4003------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:21:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@norisk/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Visualizing Monte Carlo Simulations with R and gganimate]]></title>
            <link>https://medium.com/@norisk/visualizing-monte-carlo-simulations-with-r-and-gganimate-97b4237925f7?source=rss-c55e83e4003------2</link>
            <guid isPermaLink="false">https://medium.com/p/97b4237925f7</guid>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[No Risk]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 06:14:31 GMT</pubDate>
            <atom:updated>2023-11-28T05:50:39.849Z</atom:updated>
            <content:encoded><![CDATA[<p>Monte Carlo simulations are a class of computational algorithms that rely on repeated random sampling to obtain numerical results. They are particularly useful for understanding the behavior of systems too complex for analytical solutions. In this blog post, we’ll explore how to visualize Monte Carlo simulations using `R`, with the help of the `gganimate`, `tidyverse`, `gridExtra`, and `magick` packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GqlEBUtEusImZZk-4R7WBA.gif" /></figure><h4>Setting the Scene</h4><p>To ensure reproducibility, we set a seed for R’s random number generator. We also define the precision of our output for clarity and consistency.</p><pre>options(digit = 6)<br>old &lt;- options(pillar.sigfig = 7)<br>set.seed(42)</pre><h4>The Monte Carlo Case</h4><p>We consider a voltage divider, where voltage ratio $G = \frac{R1}{R1 + R2}$, where R1 and R2 are independent variables following normal distributions. Our goal is to simulate this process a million times and visualize the distribution of G.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*m1y4GuO2ffJIG8GekHlUCA.png" /></figure><pre>N_SIM &lt;- 1e6<br>mcHist &lt;- tibble(R1 = rnorm(N_SIM, 1, 0.04/12),<br> R2 = rnorm(N_SIM, 1, 0.04/12)) %&gt;%<br> mutate(G = R1 /(R1+R2)) %&gt;% <br> mutate(index = row_number()) %&gt;% <br> pivot_longer(cols = c(&quot;R1&quot;, &quot;R2&quot;, &quot;G&quot;),<br> names_to = &quot;Variable&quot;, <br> values_to = &quot;value&quot;) %&gt;% <br> mutate(round = if_else(Variable == &quot;G&quot;, <br> plyr::round_any(value, 5e-4), # create round value or bins <br> plyr::round_any(value, 1e-3)))</pre><h4>Creating a Frequency Table</h4><p>We group the simulation results to create a frequency table, which will be the basis for our histogram.</p><pre>count_by_round &lt;-mcHist %&gt;%<br>  select(Variable, round) %&gt;%<br>  group_by(Variable, round) %&gt;%<br>  summarise(n = n(), .groups = &quot;drop&quot;) %&gt;%<br>  ungroup()</pre><h4>Visualizing the Histograms</h4><p>We use `ggplot` to create histograms for \( G \), \( R1 \), and \( R2 \), showing the frequency of each rounded value.</p><pre>gplot &lt;- count_by_round %&gt;%<br>  filter(Variable == &quot;G&quot;) %&gt;% <br>  ggplot(aes(round, n)) +<br>  facet_grid(~Variable) +<br>  geom_bar(stat = &quot;identity&quot;, color=&quot;black&quot;) + <br>  geom_vline(xintercept = 0.49, color=&quot;blue&quot;) + <br>  geom_vline(xintercept = 0.51, color=&quot;blue&quot;) +<br>  theme_bw() + <br>  theme(strip.text = element_text(size = 16, hjust = 0.1),<br>        axis.text.y = element_blank(),<br>        axis.text.x = element_text(angle=90, vjust=.5, hjust=1))<br><br>rplot &lt;- count_by_round %&gt;%<br>  filter(Variable != &quot;G&quot;) %&gt;% <br>  ggplot(aes(round, n)) +<br>  facet_grid(~Variable) +<br>  geom_bar(stat = &quot;identity&quot;, color=&quot;black&quot;) + <br>  geom_vline(xintercept = 0.98, color=&quot;blue&quot;) + <br>  geom_vline(xintercept = 1.02, color=&quot;blue&quot;) +<br>  theme_bw() + <br>  theme(strip.text = element_text(size = 16, hjust = 0.1),<br>        axis.text.y = element_blank(),<br>        axis.text.x = element_text(angle=90, vjust=.5, hjust=1))<br><br># Combine plots<br>plot = grid.arrange(rplot, gplot, nrow = 2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*DlyIv4Ahsg46qcLX7DvY8g.png" /></figure><h4>Animating the Simulation</h4><p>Animations can provide a dynamic view of the simulation process. Here, we’ll create several animations to illustrate different aspects of the Monte Carlo simulation.</p><p>Preparation</p><p>Slice the simulated data into (N_Frames — 1) slices, where the first frame has zero simulations.</p><pre>count_by_index &lt;- function(mcHist, nframes=120) {<br>  # Initialization of variables<br>  data &lt;- tibble(idx = integer(),<br>                 n_sample = integer(),<br>                 Variable = character(),<br>                 round = numeric(),<br>                 n = integer())<br>  N_SIM = max(mcHist$index)<br>  step &lt;- floor(N_SIM / (nframes-1))<br>  data &lt;- data %&gt;% <br>    add_row(tibble(idx = 1,<br>                 n_sample = 0,<br>                 Variable = c(&quot;G&quot;,&quot;R1&quot;, &quot;R2&quot;),<br>                 round = c(0.5, 1.0, 1.0),<br>                 n = 0))<br><br>  for (i in 1:nframes-1) {<br>    # Data manipulation and summarization steps<br>    row &lt;- mcHist %&gt;%<br>           select(index, Variable, round) %&gt;%<br>           filter(index &lt;= step * i) %&gt;%<br>           group_by(Variable, round) %&gt;%<br>           summarise(n = n(), .groups = &#39;drop&#39;) %&gt;%<br>           mutate(idx = i + 1,<br>                  n_sample = floor(step * i))<br>    # Append the summary data to the main data frame<br>    data &lt;- data %&gt;%<br>            add_row(row)<br>  }<br>  return(data)<br>}<br><br>hist_anim_data &lt;- count_by_index(mcHist, N_FRAME) %&gt;% <br>  arrange(idx)</pre><p>1. Dot Histogram Animation</p><p>Each dot represents one data point in the simulation, and we animate the appearance of these dots over time.</p><pre>textplot_data &lt;- mcHist %&gt;% <br>  filter(index&lt;=5) %&gt;% <br>  arrange(index, Variable)<br># dot plot for first 5 samples <br>tgplot &lt;- textplot_data %&gt;%<br>  filter(Variable == &quot;G&quot;) %&gt;%<br>  ggplot(aes(group = index, x = round)) + # group by index is important<br>  facet_grid(~Variable) +<br>  geom_point(aes(y=0), size = 5, color=&quot;black&quot;) + <br>  geom_text(aes(x=0.5, y=0.1, label = round), <br>                position = position_dodge(width=0.9), color=&quot;blue&quot;, size = 10) +<br>  labs(x = &quot;&quot;, y = &quot;Frequency&quot;) +<br>  xlim(0.49, 0.51) +<br>  theme_bw() +<br>  theme(panel.grid = element_blank(),<br>    strip.text = element_text(size = 16, hjust = 0.1),<br>    axis.text.y = element_blank()) <br><br>trplot &lt;- textplot_data %&gt;%<br>  filter(Variable != &quot;G&quot;) %&gt;%<br>  ggplot(aes(group = index, x = round)) + # group by index is important<br>  facet_grid(~Variable) +<br>  geom_point(aes(y=0), size = 5, color=&quot;black&quot;) + <br>  geom_text(aes(x=1, y=0.1, label = round), <br>                position = position_dodge(width=0.9), color=&quot;blue&quot;, size = 10) +<br>  labs(x = &quot;&quot;, y = &quot;Frequency&quot;) +<br>    xlim(0.98, 1.02) +<br>    theme_bw() +<br>    theme(<br>      panel.grid = element_blank(),<br>      strip.text = element_text(size = 16, hjust = 0.1),<br>      axis.text.y = element_blank()<br>    )<br><br># Create GIF<br>r_anim &lt;- trplot + transition_manual(frames = index) <br>rgif &lt;- animate(r_anim,<br>                width = 800, height = 300,<br>                nframes = 5, <br>                fps = 2.5,<br>                #renderer = magick_renderer()<br>                renderer = gifski_renderer(&quot;./anim/tr.gif&quot;)<br>                # renderer = file_renderer(&quot;./frames&quot;, prefix = &quot;tr&quot;)<br>                )<br><br>a_mgif &lt;- image_read(rgif)<br>b_mgif &lt;- image_read(ggif)<br>new_gif &lt;- image_append(c(a_mgif[1], b_mgif[1]), stack = TRUE)<br>for(i in 2:5) {<br>  combined &lt;- image_append(c(a_mgif[i], b_mgif[i]), stack = TRUE)<br>  new_gif &lt;- c(new_gif, combined)<br>}<br>anim_save(&quot;./anim/5dots.gif&quot;, new_gif)<br><br>stack2gif &lt;- function(gif1, gif2, n_frames){<br>  # read gif as imageck format <br>  a_mgif &lt;- image_read(gif1) <br>  b_mgif &lt;- image_read(gif2)<br>  new_gif &lt;- image_append(c(a_mgif[1], b_mgif[1]), stack = TRUE)<br>  for(i in 2:n_frames) {<br>    combined &lt;- image_append(c(a_mgif[i], b_mgif[i]), stack = TRUE)<br>    new_gif &lt;- c(new_gif, combined)<br>    }<br>return(new_gif)  <br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ncB7d0BEpGj5ivaHBDlJyA.gif" /></figure><p>### 2. 1. Dot Histogram Animation</p><p>We animate the transfer function to show how each pair of \( R1 \) and \( R2 \) values produce a corresponding \( G \) value.</p><pre>first_n &lt;- 100<br><br>count_data_n &lt;- mcHist %&gt;% <br>  filter(index &lt;= first_n) %&gt;% <br>  arrange(index, Variable) %&gt;% <br>  group_by(Variable, round) %&gt;% <br>  mutate(y = seq_along(round))<br><br>fg_plot &lt;- count_data_n %&gt;%<br>  filter(Variable == &quot;G&quot;) %&gt;%<br>  ggplot(aes(group = index, round, y)) + # group by index is important<br>  facet_grid(~Variable) +<br>  geom_point(size = 2) +<br>  labs(x = &quot;&quot;, y = &quot;Frequency&quot;) +<br>  theme_bw() +<br>  theme(<br>    panel.grid = element_blank(),<br>    strip.text = element_text(size = 32, hjust = 0.1),<br>    axis.text.y = element_blank()<br>  )<br><br>plot2frames &lt;- function(plot, <br>                     prefix, <br>                     w = 800, h = 300,<br>                     path_frames = &quot;./frames&quot;<br>                     ){<br>  anim &lt;- plot + transition_manual(index, cumulative = TRUE)<br>  gif &lt;- animate(<br>    anim,<br>    width = w,<br>    height = h,<br>    renderer = file_renderer(path_frames, prefix = prefix)<br>  )<br>  return(gif)<br>} <br><br><br>fg_anim &lt;- plot2frames(fg_plot, prefix = &quot;gdot&quot;)<br><br>fr_plot &lt;- count_data_n %&gt;%<br>  filter(Variable != &quot;G&quot;) %&gt;%<br>  ggplot(aes(group = index, round, y)) + # group by index is important<br>  facet_grid(~Variable) +<br>  geom_point(size = 2) +<br>  labs(x = &quot;&quot;, y = &quot;Frequency&quot;) +<br>  theme_bw() +<br>  theme(<br>    panel.grid = element_blank(),<br>    strip.text = element_text(size = 32, hjust = 0.1),<br>    axis.text.y = element_blank()<br>  )<br><br><br>fg_anim &lt;- plot2frames(fg_plot, prefix = &quot;gdot&quot;)<br>fr_anim &lt;- plot2frames(fr_plot, prefix = &quot;rdot&quot;)<br><br>fn_gif &lt;- stack2gif(fr_anim, fg_anim, first_n) %&gt;% <br>  image_animate(<br>    fps = FPS,<br>    loop = 0,<br>  )<br><br>anim_save(&quot;./anim/fn.gif&quot;, fn_gif)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*M_PCO6v85-DpMInfQzOIvQ.gif" /></figure><p>### 3. Bar Histogram Animation</p><p>We also create a bar histogram gif where the bars grow over time to represent the increasing number of samples.</p><p>```r<br># Define the bar histogram plot<br>gbar_anim &lt;- gplot + <br> transition_manual(frames = idx)</p><p># Animate the histogram<br>gbar_gif &lt;- animate(gbar_anim, …)<br>```</p><p>### Combining GIFs</p><p>We combine the different gifs into one using the `magick` package for a comprehensive view of the simulation.</p><p>```r<br># Combine the gifs<br>stack2gif &lt;- function(gif1, gif2, n_frames) { … }</p><p># Save the combined gif<br>anim_save(“./anim/combined.gif”, combined_gif)<br>```</p><h4>Conclusion</h4><p>Through these visualizations, we’ve provided a window into the behavior of a system modeled by a Monte Carlo simulation. These techniques can be applied to various domains where Monte Carlo methods are used, from finance to physics, to gain insights into complex phenomena.</p><h4>References</h4><p>- Roh’s Engineering Blog: <a href="https://roh.engineering/posts/2018/05/animating-a-monte-carlo-simulation/">Animating a Monte Carlo Simulation without gganimate</a><br>- Stack Overflow: <a href="https://stackoverflow.com/questions/61446108/animated-dot-histogram-built-observation-by-observation-using-gganimate-in-r">Animated Dot Histogram Built Observation by Observation using gganimate</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97b4237925f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mac Mini M2 8G for Deep Learning?]]></title>
            <link>https://medium.com/@norisk/mac-mini-m2-8g-4e618a4b3483?source=rss-c55e83e4003------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e618a4b3483</guid>
            <dc:creator><![CDATA[No Risk]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 04:47:15 GMT</pubDate>
            <atom:updated>2023-08-28T04:48:37.724Z</atom:updated>
            <content:encoded><![CDATA[<p>A quick follow up on <a href="https://medium.com/@norisk/first-week-with-mac-mini-m2-dc876508a7aa">my new base configuration Mac Mini M2</a>. The <a href="https://developer.apple.com/metal/tensorflow-plugin/">Metal Accelerated Tensorflow</a> is able to handle the basic deep learning tasks. Testing with the code from the <a href="https://github.com/ageron/handson-ml3/blob/main/10_neural_nets_with_keras.ipynb">Hands-on </a><a href="https://homl.info/er3">Hands-on Machine Learning with Scikit-Learn, Keras and TensorFlow (3rd edition)</a>, the speed on the Mac is similar to the free-tier of Google Colab, T4 GPU or TPU runtime. Quick prototyping or beginners’ learning should be fine on the most basic Mac setup.</p><p>The basic configuration with only 8GB memory will be a challenge for larger models. I fail to load the LLama model using the Huggingface pipeline (codes modified from the <a href="https://huggingface.co/blog/codellama">official webpage.</a>)</p><pre>from transformers import AutoTokenizer<br>import transformers<br>import torch<br><br>tokenizer = AutoTokenizer.from_pretrained(&quot;codellama/CodeLlama-7b-hf&quot;)<br><br>pipeline = transformers.pipeline(<br>    &quot;text-generation&quot;,<br>    model=&quot;codellama/CodeLlama-7b-hf&quot;,<br>    torch_dtype=torch.float16,<br>    device = torch.device(&#39;mps&#39;),<br>)</pre><p>The error message indicates the memory might be culprit.</p><pre>MPS backend out of memory (MPS allocated: 8.92 GB, other allocations: 86.60 MB, max allowed: 9.07 GB). Tried to allocate 86.00 MB on private pool. Use PYTORCH_MPS_HIGH_WATERMARK_RATIO=0.0 to disable upper limit for memory allocations (may cause system failure).</pre><p>Someone may find a way to fix this later, e.g. `Accelerate 4.33`, but I don’t think running LLM’s on Mac Mini 8G makes much sense to begin with :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e618a4b3483" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First Week with Mac mini M2]]></title>
            <link>https://medium.com/@norisk/first-week-with-mac-mini-m2-dc876508a7aa?source=rss-c55e83e4003------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc876508a7aa</guid>
            <dc:creator><![CDATA[No Risk]]></dc:creator>
            <pubDate>Mon, 21 Aug 2023 04:37:06 GMT</pubDate>
            <atom:updated>2023-08-21T05:27:35.083Z</atom:updated>
            <content:encoded><![CDATA[<p>Just got the Mac mini M2. It is everything the reviews have said about it, small , quiet, fast on daily jobs. My loud and hot 2017 Macbook Pro is ready to enjoy the retirement.</p><p>Installed all the apps and then follow the instructions from [<a href="https://medium.com/@jeantimex/how-to-configure-iterm2-and-vim-like-a-pro-on-macos-e303d25d5b5c">Yong Su</a>] to config iterms2 and vim. No surprise.</p><p>One benefit of buying the Mac with M2 today is that many of the deep learning packages have been optimized for the Apple Silicon. It is still pretty slow, but prototyping locally is possible.</p><p>Googling the instructions of installing ML packages will return many that already outdated. A much safer bet is to follow the official instructions.</p><ol><li><a href="https://developer.apple.com/metal/tensorflow-plugin/">Apple tensorflow-metal</a></li><li><a href="https://pytorch.org/get-started/locally/">Pytorch.org</a></li><li><a href="https://huggingface.co/docs/transformers/installation">HuggingFace</a></li></ol><p>Yes, there are several uninstalls and reinstalls, but my Python and R are up and running. Cheers.</p><p>One suggestion, if you are using `conda`, please don&#39;t force the strict channel priority. That gave me a lot of headache.</p><p>Another hint, use a extension cord for your wireless keyboard/mouse dongle, if they are on 2.4GHz. The i<a href="https://www.usb.org/sites/default/files/327216.pdf">nterference with USB 3.0</a> is annoying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*WCn0Fxo16EC0UdRPKJWvVw.png" /></figure><p>Next step, do the work.</p><figure><img alt="Do the work" src="https://cdn-images-1.medium.com/max/500/1*nlMuJj4dW6DBW7vu7fsR3Q.jpeg" /></figure><blockquote>A child has no trouble believing the unbelievable, nor does the genius or the madman. <br>It’s only you and I, with our big brains and our tiny hearts who doubt and overthink and hesitate.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc876508a7aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Daily Stoic]]></title>
            <link>https://medium.com/@norisk/daily-stoic-fc095425d17f?source=rss-c55e83e4003------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc095425d17f</guid>
            <category><![CDATA[stoic]]></category>
            <dc:creator><![CDATA[No Risk]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 02:50:23 GMT</pubDate>
            <atom:updated>2023-03-04T00:38:34.038Z</atom:updated>
            <content:encoded><![CDATA[<p>Just received my Stoic Bullion from <a href="https://www.etsy.com/listing/1052685101/stoic-coin-bullion-bar-memento-mori-amor">Etsy</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0GiJ8zosZwC6k4iC.jpg" /><figcaption>Stoic Bullion from Etsy</figcaption></figure><p>It is creadit card size, and fits in my wallet. The fonts on the back is too small to read, but overall the build quality is good.</p><h3>The Cardinal Virtues</h3><ul><li>Wisdom</li><li>Justice</li><li>Courage</li><li>Temperance</li></ul><blockquote><strong><em>Summum bonum</em></strong></blockquote><blockquote><em>Memento Praecepta</em></blockquote><blockquote><em>Acta Non Verba</em></blockquote><h3>TO LIVE IN ACCORDANCE WITH NATURE</h3><h3>MEMENTO MORI</h3><blockquote><em>Do not act as if you had thousands of years to live. The unavoidable hangs above your head. While you have life in you, while you sill can, make yourself good. — Marcus Aurelius</em></blockquote><blockquote><em>Remember death: To say this to tell a person to remember their freedom. — Sensca</em></blockquote><blockquote><em>Act as if you have already died and what is left is now a gift. Now go live the rest properly. — Marcus Aurelius</em></blockquote><h3>PREMEDITATIO MALORUM</h3><blockquote><em>Everyone faces up more bravely to a thing for which he has long prepared himself, suffering can be withstood if they have been trained for in advance. — Seneca</em></blockquote><blockquote><em>If you wart a person to keep his head when a crisis comes you must give them training before it comes. — Seneca</em></blockquote><blockquote><em>All our human lot should be before our eyes. — Seneca</em></blockquote><h3>AMOR FATI</h3><blockquote><em>The spirit must be trainad to a realisation and an acceptance of its lot. — Seneca</em></blockquote><blockquote><em>What fortune has made is not your own. — Seneca</em></blockquote><blockquote><em>Remember that you are an actor in a play. For that is your business, to act the role that is assigned to you as well as you can. — Epicletus</em></blockquote><h3>TEMET NOSCE</h3><blockquote><em>To know thyself is the beginning of wisdom. — Aristotle</em></blockquote><blockquote><em>The unexamined life is not worth living. — Socrates</em></blockquote><blockquote><em>To find yourself, think for yeurself. — Socrates</em></blockquote><blockquote><em>Dig within. Therein lies the fountain of good. — Marcus Aurelius</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc095425d17f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>