<?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 Leon Bovett on Medium]]></title>
        <description><![CDATA[Stories by Leon Bovett on Medium]]></description>
        <link>https://medium.com/@leonbovett?source=rss-93268c3ab586------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*j9Wsgq6Rk2FPyVCxrd0TqQ.jpeg</url>
            <title>Stories by Leon Bovett on Medium</title>
            <link>https://medium.com/@leonbovett?source=rss-93268c3ab586------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:44:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leonbovett/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[Executing Python MapReduce Jobs using Hadoop inside Docker Containers on Apple Silicon Mac]]></title>
            <link>https://selectfrom.dev/executing-python-mapreduce-jobs-using-hadoop-in-a-docker-container-on-apple-silicon-mac-b59a5eda892d?source=rss-93268c3ab586------2</link>
            <guid isPermaLink="false">https://medium.com/p/b59a5eda892d</guid>
            <category><![CDATA[mapreduce]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[apple-silicon]]></category>
            <category><![CDATA[hadoop]]></category>
            <dc:creator><![CDATA[Leon Bovett]]></dc:creator>
            <pubDate>Thu, 14 Apr 2022 13:55:29 GMT</pubDate>
            <atom:updated>2024-03-10T14:30:10.610Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*xx248I2GsY0g16C-" /><figcaption><a href="https://unsplash.com/photos/tjX_sniNzgQ">Image</a> by <a href="https://unsplash.com/@frankiefoto">Frank McKenna</a> on Unsplash</figcaption></figure><p>Whilst learning about Hadoop, I wanted to run it locally on my Apple Silicon Mac. Also, as I am familiar with Python, I wanted to run Python-based MapReduce jobs.</p><p>These instructions may work for Intel Macs, but I have not tested it.</p><h3>Steps</h3><p>The steps needed to get started are:</p><ol><li>Install <a href="https://www.docker.com/products/docker-desktop/">docker desktop</a> for Apple Silicon.</li><li>Clone <a href="https://github.com/wxw-matt/docker-hadoop">this repo</a> for Hadoop Docker Container.</li><li>Enable docker-compose build steps for the containers.</li><li>In the Dockerfileinstall python3(and set python3as the default).</li><li>Build the containers and start your Hadoop cluster using docker-compose.</li><li>Create your mapper.pyand reducer.py scripts.</li><li>Create your data input files.</li><li>Launch a terminal inside the namenodeservice.</li><li>Copy your data input files into HDFS using hadoop dfs.</li><li>Execute your job using mapredand view the results in the output folder.</li></ol><h3>Detailed Instructions</h3><h4>Install Docker Desktop</h4><p>Install <a href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a> for Apple Silicon. Consider increasing the amount of memory available.</p><h4>Clone Hadoop on Docker</h4><p>See more details in the article <a href="https://towardsdev.com/how-to-run-hadoop-on-macos-apple-m1-and-intel-cpu-by-one-command-1398d5f3d0df">here</a>, but you can just go ahead and clone the repo:</p><p><em>Note that </em><em>$ is shown here to remind you that you are executing these commands outside the docker container:</em></p><pre>$ git clone <a href="/service/mailto:git@github.com">git@github.com</a>:wxw-matt/docker-hadoop.git ~/docker-hadoop</pre><h4>Enable Build Steps for the Containers</h4><p>Ensure that docker-compose build will trigger a build of the various components, e.g. in docker-compose.yml for the namenode:</p><p><em>Note that </em><em>+ is shown here to indicate the addition of lines to the existing files:</em></p><pre>namenode:<br>    image: wxwmatt/hadoop-namenode:2.1.1-hadoop3.3.1-java8<br>+   build:<br>+       context: namenode<br>+       dockerfile: Dockerfile<br>    container_name: namenode</pre><p>Repeat this step for:</p><ul><li>namenode</li><li>datanode</li><li>resourcemanager</li><li>nodemanager1</li></ul><h4>Install Python3 as the Default</h4><p>In the dockerfile for each component, install python3. You could do it at the beginning as it’s a higher level dependency for the Docker container environment and not specifically related to Hadoop.</p><pre>FROM wxwmatt/hadoop-base:2.1.1-hadoop3.3.1-java8</pre><pre>+RUN apt-get update &amp;&amp; DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends python3.6</pre><pre>+RUN update-alternatives --install /usr/bin/python python /usr/bin/python3 1</pre><pre>HEALTHCHECK CMD curl -f http://localhost:9870/ || exit 1</pre><p>Repeat this step for</p><ul><li>namenode</li><li>datanode</li><li>resourcemanager</li><li>nodemanager1</li></ul><h4>Build the Containers and Start your Hadoop Cluster</h4><p>Once you have built one of the containers, the base image should be cached. You may need to wait for all of the containers to be running so that they can see each other.</p><pre>$ docker-compose up --build -d</pre><h4>Write your Mapper and Reducer Scripts</h4><p>In the /jobs/jars folder, create mapper.py:</p><pre># -*-coding:utf-8 -*</pre><pre>import sys<br>import string<br>import collections</pre><pre>wordCount = collections.Counter()</pre><pre>for line in sys.stdin:<br>    # remove leading and trailing whitespace<br>    line = line.strip()</pre><pre>    # ignore case to avoid duplicates<br>    lower = line.lower()</pre><pre>    # replace punctuation with spaces, except for hyphens<br>    punc = string.punctuation<br>    punc_nohyphens = punc.replace(&#39;-&#39;, &#39;&#39;)<br>    justText = lower.translate(<br>        str.maketrans(&#39; &#39;, &#39; &#39;, punc_nohyphens))</pre><pre>    # allow hyphenated words, but watch out for<br>    # double-hyphens which might be a stand-in for em-dash<br>    emdashRemoved = justText.replace(&#39;--&#39;, &#39; &#39;)</pre><pre>    # split the line into words<br>    words = emdashRemoved.split()</pre><pre>    # now we can remove leading and trailing curly quotes <br>    # and hyphens, but leave apostrophes in the middle <br>    # and allow hyphenated words.<br>    # note that we lose possessive ending in s, e.g Angus&#39;<br>    punc_curly = &#39;”’‘“-&#39;<br>    for word in words:<br>        word = word.strip(punc_curly)<br>        if len(word) &gt; 0:<br>            wordCount[word] += 1</pre><pre># write the results, tab delimited<br># which will be the input for reducer.py<br>for word, count in wordCount.most_common():<br>    print (&#39;%s\t%s&#39; % (word, count))</pre><p>And reducer.py:</p><pre># -*-coding:utf-8 -*</pre><pre>import sys<br>import collections<br>import statistics</pre><pre>wordCount = collections.Counter()<br>wordLengthCount = collections.Counter()<br>wordLengthList = []</pre><pre>for line in sys.stdin:<br>    # remove leading and trailing whitespace<br>    line = line.strip()</pre><pre>    # parse the input we got from mapper.py<br>    word, count = line.split(&#39;\t&#39;, 1)</pre><pre>    # ensure that it&#39;s a string followed by an int<br>    try:<br>        word = str(word)<br>        count = int(count)<br>    except ValueError:<br>        # count was not a number, so silently<br>        # ignore/discard this line<br>        continue</pre><pre>    length = len(word)<br>    wordCount[word] += count<br>    wordLengthCount[length] += count</pre><pre>    # expand the counted words to a full list<br>    # to enable median to be calculated later<br>    lengthRepeated = [length] * count<br>    wordLengthList.extend(lengthRepeated)</pre><pre>for commonWord, commonWordCount in wordCount.most_common(100):<br>    print (&quot;{}\t{}&quot;.format(commonWord, commonWordCount))</pre><pre>print (&quot;\n&quot;)<br>for commonLength, commonLengthCount in wordLengthCount.most_common():<br>    print (&quot;{}\t{}&quot;.format(commonLength, commonLengthCount))</pre><pre>print (&quot;\n&quot;)<br>print(&quot;Number of words: {}&quot;.format(<br>    len(wordLengthList)))</pre><pre>print(&quot;Median word length: {:.0f}&quot;.format(<br>    statistics.median(wordLengthList)))</pre><p>The files will be available in the /app/jars folder inside the Docker container.</p><h4>Create Your Data Input Files</h4><p>Create your text input files in the ./jobs/data/input folder (outside of the Docker container).</p><p>Further on, we copy the files into HDFS from inside the Docker container, where the files are mapped to /app/data/input.</p><h4>Launch a Terminal inside the Name Node</h4><p>You can click on the icon inside the Docker desktop, or you can run it from the command line:</p><pre>$ docker exec -it namenode bash</pre><p>Python should be available inside the container:</p><p><em>Note that </em><em>&gt;is shown here to remind you that you are executing these commands inside the Docker container:</em></p><pre>&gt; which python <br>/usr/bin/python<br><br>&gt; python --version<br>Python 3.7.3</pre><h4>Copy Your Data Input Files into HDFS</h4><pre>&gt; hadoop fs -mkdir -p /test/<br>&gt; hadoop fs -copyFromLocal -f /app/data/input /test/</pre><p>Don’t forget to clean up any past jobs.</p><pre>&gt; hadoop fs -rm -r -f /test/output</pre><h4>Execute Your Job and View the Results</h4><p>The important point is to avoid using the Hadoop streaming jar, but to use mapred instead:</p><pre>&gt; cd /app/jars<br>&gt; mapred streaming \<br>-files mapper.py,reducer.py \<br>-input /test/input \<br>-output /test/output \<br>-mapper “/usr/bin/python mapper.py” \<br>-reducer “/usr/bin/python reducer.py”</pre><p>The output needs quotes for the wildcard:</p><pre>&gt; hadoop fs cat “/test/output/*”</pre><h3>Credit</h3><p>All of the hard work was already done by others who came before me, so standing on the shoulders of giants made this possible:</p><ul><li><a href="https://github.com/wxw-matt">Matt Wang</a> has extended <a href="https://towardsdev.com/how-to-run-hadoop-on-macos-apple-m1-and-intel-cpu-by-one-command-1398d5f3d0df">BigDataEurope</a>’s work on Hadoop for Docker.</li><li><a href="https://stackoverflow.com/questions/52076577/error-java-lang-runtimeexception-pipemapred-waitoutputthreads-subprocess-fa/61624913#61624913">Advice</a> from <a href="https://github.com/jeugregg">Grégory Lang</a> was the big revelation that mapred is the way to go.</li><li>Thanks to <a href="https://github.com/froeba">Bert Froeba</a> for their encouragement and inspirational suggestions!</li></ul><h3>References</h3><ul><li><a href="https://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/">https://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/</a></li><li><a href="https://dev.to/boyu1997/run-python-mapreduce-on-local-docker-hadoop-cluster-1g46">https://dev.to/boyu1997/run-python-mapreduce-on-local-docker-hadoop-cluster-1g46</a></li><li><a href="https://stackoverflow.com/questions/56997793/dockerfile-from-vs-docker-compose-image">https://stackoverflow.com/questions/56997793/dockerfile-from-vs-docker-compose-image</a></li><li><a href="https://dev.to/meetsohail/change-the-python3-default-version-in-ubuntu-1ekb">https://dev.to/meetsohail/change-the-python3-default-version-in-ubuntu-1ekb</a></li><li><a href="https://stackoverflow.com/questions/20938661/hadoop-hdfs-copy-with-wildcards">https://stackoverflow.com/questions/20938661/hadoop-hdfs-copy-with-wildcards</a></li><li><a href="https://datagy.io/python-remove-punctuation-from-string/">https://datagy.io/python-remove-punctuation-from-string/</a></li></ul><h4>The world’s fastest cloud data warehouse:</h4><p>When designing analytics experiences which are consumed by customers in production, even the smallest delays in query response times become critical. Learn how to achieve <strong>sub-second</strong> performance over TBs of data with <a href="https://www.firebolt.io/?v=m"><strong>Firebolt</strong>.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b59a5eda892d" width="1" height="1" alt=""><hr><p><a href="https://selectfrom.dev/executing-python-mapreduce-jobs-using-hadoop-in-a-docker-container-on-apple-silicon-mac-b59a5eda892d">Executing Python MapReduce Jobs using Hadoop inside Docker Containers on Apple Silicon Mac</a> was originally published in <a href="https://selectfrom.dev/">SelectFrom</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with Keras on a Mac with Blackmagic eGPU]]></title>
            <link>https://medium.com/@leonbovett/getting-started-with-keras-on-a-mac-with-blackmagic-egpu-4459bf5128c8?source=rss-93268c3ab586------2</link>
            <guid isPermaLink="false">https://medium.com/p/4459bf5128c8</guid>
            <category><![CDATA[anaconda]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[egpu]]></category>
            <dc:creator><![CDATA[Leon Bovett]]></dc:creator>
            <pubDate>Sun, 17 Mar 2019 19:32:51 GMT</pubDate>
            <atom:updated>2019-03-17T19:32:51.339Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rationale</h3><p>I decided to start learning about Deep Learning (again), and hence learning Python (again). I made the following choices:</p><ul><li>I found this book: <a href="https://www.manning.com/books/deep-learning-with-python">https://www.manning.com/books/deep-learning-with-python</a>, so I decided to start with Keras, as it seems to be good for learning about deep learning.</li><li>Early chapters of the book recommend to use either a cloud account or an eGPU. I decided that I would go with the eGPU approach.</li><li>I’m a Mac user so I decided to stick with the Mac. In order to use AMD eGPUs on the Mac, you need to use PlaidML as the backend for Keras, because Tensorflow requires Nvidia CUDA, but Macs use AMD GPUs. I found a lot of inspiration for this approach <a href="https://medium.com/@danbrice.datascience/deep-learning-on-a-mac-with-amd-gpu-4be1f18944a">here</a> and <a href="https://www.bignerdranch.com/blog/macos-machine-learning-in-2019/">here</a>.</li><li>I have an LG 5k display, so I decided to purchase the Blackmagic eGPU (the cheap one which uses the Radeon Pro 580) as at the time of writing, there are no eGPU enclosures that support the dual Thunderbolt3 connection required.</li></ul><p>I’m using a Macbook Pro:</p><pre>Model Name:    MacBook Pro<br>  Model Identifier:    MacBookPro14,2<br>  Processor Name:    Intel Core i7<br>  Processor Speed:    3.5 GHz<br>  Number of Processors:    1<br>  Total Number of Cores:    2<br>  L2 Cache (per Core):    256 KB<br>  L3 Cache:    4 MB<br>  Memory:    16 GB</pre><p>I plugged in the Blackmagic and it was recognised as an eGPU immediately by Mac OS Mojave. Remember to eject before disconnecting from Thunderbolt3!</p><h3>Installation</h3><p>The first step is to get python set up on your Mac. After a long process, I discovered that using <em>matplotlib</em> (which is useful for showing graphs) requires a “framework” installation of python, so I was advised to go with the Anaconda flavour of Python.</p><h4>Anaconda</h4><p>Start by totally cleaning your existing anaconda environment, see <a href="https://docs.anaconda.com/anaconda/install/uninstall/">here</a>. Optionally you can first run the cleaner:</p><pre>$ conda install anaconda-clean<br>$ anaconda-clean --yes</pre><p>And then just delete the entire folder (assuming this was where it was installed:</p><pre>$ which conda<br>~/anaconda3/bin/conda</pre><pre>$ rm -rf ~/anaconda3</pre><p>Now you’re ready to install anaconda from scratch. See <a href="https://medium.com/@GalarnykMichael/install-python-on-mac-anaconda-ccd9f2014072">here</a>.</p><p>Select the anaconda version you want by copying the path to a .sh file <a href="https://repo.continuum.io/archive/">here</a>, and replacing in the curl command. <strong>BE CAREFUL</strong> to choose the <em>Anaconda3</em> version (<strong>not</strong> <em>Anaconda2</em>):</p><pre>$ cd ~<br>$ curl <a href="https://repo.continuum.io/archive/Anaconda3-2018.12-MacOSX-x86_64.sh">https://repo.continuum.io/archive/Anaconda3-2018.12-MacOSX-x86_64.sh</a> -o anaconda3.sh<br>$ bash anaconda3.sh -b -p ~/anaconda3<br>$ rm anaconda3.sh</pre><p>Ensure that Anaconda is the first and only python environment in your PATH:</p><pre>$ echo ‘export PATH=”~/anaconda3/bin:$PATH”’ &gt;&gt; ~/.bash_profile<br>$ source .bash_profile</pre><p>Remember to update <em>conda</em> in case there were any changes since the archive version:</p><pre>$ conda update conda</pre><h4>Flake8</h4><p>Set up flake8 for python linting in atom (see <a href="https://atom.io/packages/flake8">here</a>)</p><pre>$ conda install flake8<br>$ pip install flake8-docstrings<br>$ apm install linter-flake8</pre><p>Add config to <strong>.flake8</strong> file in the project directory:</p><pre>[flake8]<br>exclude = .git,*migrations*<br>max-line-length = 119<br>ignore =<br> # E402: Module level import not at top of file<br> E402,</pre><h4>PlaidML</h4><p>PlaidML is an alternative backend for Keras. It is needed to use AMD chipset on MacOS using Metal.</p><pre># note that pip should be coming from anaconda3 bin folder<br>$ pip install plaidml-keras<br>$ plaidml-setup</pre><pre>PlaidML Setup (0.5.0</pre><pre>...</pre><pre>Multiple devices detected (You can override by setting PLAIDML_DEVICE_IDS).<br>Please choose a default device:</pre><pre>1 : metal_intel(r)_iris(tm)_plus_graphics_650.0<br>2 : metal_amd_radeon_pro_580.0</pre><pre>Default device? (1,2)[1]:2<br></pre><p>Select <strong>2 : metal_amd_radeon_pro_580.0</strong></p><pre>Selected device:<br> metal_amd_radeon_pro_580.0</pre><pre>Almost done. Multiplying some matrices…<br>Tile code:<br> function (B[X,Z], C[Z,Y]) -&gt; (A) { A[x,y : X,Y] = +(B[x,z] * C[z,y]); }<br>Whew. That worked.</pre><pre>Save settings to ~/.plaidml? (y,n)[y]:y<br>Success!</pre><p>PlaidML should now be installed! You can test your installation by running <strong>vgg16</strong> in plaidbench:</p><pre>$ pip install plaidbench<br>$ plaidbench keras --plaid vgg16<br>Running 1024 examples with vgg16, batch size 1, on backend plaid </pre><p>Note that you should see the correct version of PlaidML which you selected in the PlaidML setup: <strong>metal_amd_radeon_pro_580.0</strong></p><pre>INFO:plaidml:Opening device “metal_amd_radeon_pro_580.0”<br>Model loaded.<br>Compiling network…<br>INFO:plaidml:Analyzing Ops: 88 of 160 operations complete<br> Warming up… Running…<br>Example finished, elapsed: 6.460s (compile), 31.598s (execution)</pre><p>For referece, I also ran it using the built-in GPU:</p><pre>INFO:plaidml:Opening device &quot;metal_intel(r)_iris(tm)_plus_graphics_650.0&quot;<br>Model loaded.<br>Compiling network…<br>INFO:plaidml:Analyzing Ops: 88 of 160 operations complete<br> Warming up… Running…<br>Example finished, elapsed: 6.769s (compile), 132.859s (execution)</pre><p>So that shows a satisfying speed up of 4x.</p><h4>Useful other libraries</h4><p>Here we install matplotlib, and now we get the pay-off from using Anaconda.</p><pre>$ conda install matplotlib<br>$ conda install pydot<br>$ conda install graphviz<br>$ export PATH=$PATH:/usr/local/opt/graphviz/bin/</pre><h3>Getting Started</h3><h4>Argparse</h4><p>It’s a good idea to pass in variables to enable rapid iteration of the model and the training approach.</p><pre>import argparse</pre><pre>parser = argparse.ArgumentParser(description=’Simple Linear Regression.’)<br>parser.add_argument(‘-b’, ‘ — batch_size’, type=int, <br>    help=’The size of each batch’, required=True)<br>parser.add_argument(‘-e’, ‘ — epochs’, type=int, <br>    help=’The number of epochs’, required=True)<br>args = parser.parse_args()</pre><pre>print(“batch size: {}; epochs: {}”.format(args.batch_size, args.epochs))</pre><h4>Keras</h4><p>First, remember to set the environment to use the PlaidML <strong>KERAS_BACKEND</strong>.</p><pre>import os<br>os.environ[“KERAS_BACKEND”] = “plaidml.keras.backend”</pre><h4>Generate sample dataset</h4><pre>import numpy as np<br>from pylab import linspace</pre><pre>random = np.random.randint(-2, 2, 1000).reshape(-1, 1)<br>data = linspace(1, 2, 1000).reshape(-1, 1)<br>squares = np.square(data)<br>y = (squares * 100) + random</pre><h4>Create the model</h4><pre>from keras.models import Sequential<br>from keras.layers import Dense<br>from keras import optimizers</pre><pre>model = Sequential()<br>model.add(Dense(1, activation=’linear’, input_dim=1))<br>model.compile(<br> optimizer=optimizers.SGD(lr=0.2),<br> loss=’mean_squared_error’,<br> metrics=[‘accuracy’])</pre><h4>Train the model</h4><pre>model.fit(<br> data,<br> y,<br> epochs=args.epochs,<br> batch_size=args.batch_size)</pre><h4>Matplotlib</h4><p>When you are ready to plot some predicted results, it is easy to add multiple series to a graph.</p><pre>import matplotlib.pyplot as plt</pre><pre>plt.plot(data, y)<br>plt.plot(data, regr.predict(data))<br>plt.show()</pre><h4>Results</h4><pre>batch size: 10; epochs: 4</pre><pre>Using plaidml.keras.backend backend.</pre><pre>INFO:plaidml:Opening device &quot;metal_amd_radeon_pro_580.0&quot;</pre><pre>Epoch 1/4</pre><pre>1000/1000 [==============================] - 0s 347us/step - loss: 2413.7776 - acc: 0.0000e+00</pre><pre>Epoch 2/4</pre><pre>1000/1000 [==============================] - 0s 320us/step - loss: 280.6935 - acc: 0.0000e+00</pre><pre>Epoch 3/4</pre><pre>1000/1000 [==============================] - 0s 323us/step - loss: 95.6569 - acc: 0.0000e+00</pre><pre>Epoch 4/4</pre><pre>1000/1000 [==============================] - 0s 343us/step - loss: 77.2313 - acc: 0.0000e+00</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7XmNiG1PsbCI5Msu46TjQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4459bf5128c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>