<?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 Humphrey Sheil on Medium]]></title>
        <description><![CDATA[Stories by Humphrey Sheil on Medium]]></description>
        <link>https://medium.com/@hsheil?source=rss-3fa04a4eae53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xsCtJAPmVJ1a7CH9kk0vjw.png</url>
            <title>Stories by Humphrey Sheil on Medium</title>
            <link>https://medium.com/@hsheil?source=rss-3fa04a4eae53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:26:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hsheil/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[Personalised XIRR and investing using Python — part 1]]></title>
            <link>https://medium.com/@hsheil/personalised-xirr-and-investing-using-python-part-1-40c06dc6fa75?source=rss-3fa04a4eae53------2</link>
            <guid isPermaLink="false">https://medium.com/p/40c06dc6fa75</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[investing]]></category>
            <dc:creator><![CDATA[Humphrey Sheil]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 16:39:35 GMT</pubDate>
            <atom:updated>2024-11-01T17:33:40.331Z</atom:updated>
            <content:encoded><![CDATA[<h3>Personalised XIRR and investing using Python — part 1</h3><blockquote>Last week I cycled to the <a href="https://recsys.acm.org/recsys24/">RecSys conference in Bari</a> from Sardinia. Like all cycle tours with hours to be spent in the saddle, there are plenty of kilometres to mull over things. RecSys is about all things Recommender Systems — the algorithms that power most of what we see on our phones / the web — what to watch on Netflix or listen to on Spotify, recommended content on Instagram or TikTok, what to buy on Amazon.. the list is endless. Every app you use has a recommender engine built into it. And recommenders work by being <strong>personal</strong> — they filter huge piles of content to find just the 0.001% that will appeal to you.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CK8Zoq5krCpDGXUC.png" /><figcaption>An epic tour across Sardinia and Italy in perfect weather!</figcaption></figure><p>For years, I’ve mostly ignored the published performance of various stock market indices — the NASDAQ, S&amp;P 500, FTSE 100 or a “just buy the world” all-world ETF like <a href="https://www.vanguardinvestor.co.uk/investments/vanguard-ftse-all-world-ucits-etf-usd-accumulating/overview">VWRP</a> / <a href="https://www.vanguardinvestor.co.uk/investments/vanguard-ftse-all-world-ucits-etf-usd-distributing/portfolio-data">VWRL</a> — telling myself that my investing style is better and anyway, the aggregate timing of purchases / sales would skew any comparison.</p><p>The unvarnished truth is that I just didn’t want the reckoning that such a comparison would bring. But on the cycle trip I realised that the reckoning is needed. Like training for cycling or running, if you don’t measure then what are you improving? In essence, I need a <strong>personalised</strong> performance report to power my future recommended stock market strategy.</p><p>There’s little to no Machine Learning in this post, just data crunching and statistics in Python and the use of two beautifully elegant functions <a href="https://pandas.pydata.org/docs/reference/api/pandas.merge_asof.html">merge_asof</a> and <a href="https://pypi.org/project/pyxirr/">pyxirr</a> to save writing lots of code.</p><h3>XIRR</h3><p>There are many metrics to measure investment performance, but the most relevant for most portfolios and investors is Extended Internal Rate of Return or XIRR. XIRR returns the internal rate of return for a schedule of cash flows that is not necessarily periodic. That’s important when most investments are not stable and periodic — they are made when cash is added or re-invested which is different for everyone.</p><p>XIRR will tell you this basic stat for every holding in your portfolio — “your annualised return for this holding is X%”, regardless of how long the holding period is, when you bought, how much you bought, or how frequently you bought. It’s an incredibly useful investing statistic.</p><p>Put another way, if you have dripped £10,000, £100,000 or £1,000,000 into a portfolio over a large timeframe (10 years+) as funds allowed then XIRR will <strong>annualise</strong> the return on the funds you have invested.</p><p>XIRR is remorseless — it cuts through all the noise and marketing and gives one, easy to digest number that sums up investment performance. For a portfolio, it can be calculated both per stock holding and as a total weighted number. Thus it shows overall performance and also the big winners and losers behind the total number (if you’re a stock picker).</p><p>What is unacceptable to me is that virtually <strong>no online platform I use in the UK actually reports XIRR</strong>! Moneywiz (see below) also doesn’t calculate XIRR! They either focus on total return (disregarding length of time holding an investment) or capital growth (ignoring income via dividends which is very important for the UK indices). I want to know the exact XIRR for each investment in my portfolio and the total XIRR for the portfolio overall.</p><p>In summary, knowing your XIRR is key to improving future performance. Think of it as VO2 max for running.</p><p>Both Microsoft Excel and Google Sheets have an XIRR function readily available and I <em>could</em> just put my data in there and go at it. But I’ve got over 2,600 transactions to check and also I want to do more..</p><p>What I really want is the ability to run multiple <strong>virtual</strong> portfolios alongside a real portfolio. In essence to answer the question — “here’s what you could have had if you had tracked the S&amp;P 500 or FTSE 100 with the same money”.</p><p>Here’s a short example to illustrate how XIRR can compress capital and income together for a stock holding into one number that still clearly conveys investment performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*asvaDiBkLwWtk6l3wO4Nfg.png" /><figcaption>Table 1. XIRR example.</figcaption></figure><p>Read on to see how to calculate your own personalised XIRR and run virtual portfolios..</p><p>The plan of attack is pretty simple:</p><ol><li>(Part 1) Load my own data into a data structure suitable for calculating XIRR.</li><li>(Part 1) Write or acquire an XIRR function.</li><li>(Part 1) Run and report the analysis.</li><li>(Part 2) Load the reference data into a mirror data structure for the same reason.</li><li>(Part 2) For every buy and sell transaction I made in the real portfolio, make a twin matching transaction in the virtual portfolio.</li><li>(Part 2) For every distribution that the virtual portfolio makes, add it to the portfolio so that dividends contribute to the virtual XIRR.</li></ol><p>All the code is written in Python with heavy use of the excellent <a href="https://pandas.pydata.org/">pandas</a> library. Our core data structure will be the pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html">DataFrame</a>.</p><p>We need two sets of data to compare — in this case my own transactions and a canonical dataset modelling the target index. I chose the FTSE 100 as the initial comparison, but as we’ll see later, any index can be plugged in pretty easily.</p><p>Getting at my own data is pretty easy — it’s all in <a href="https://www.wiz.money/">Moneywiz</a>. It’s a solid piece of personal finance software, albeit more focused on things like budgeting and tagging that I don’t use. Moneywiz updates prices dynamically (using the Yahoo Finance API I’m pretty sure) and also has good UK bank coverage via Saltedge, when other competitors are more US-centric.</p><p>If you are a coder and want to slice and dice your own data as per this article, then the single-best thing about Moneywiz is the ability to take a snapshot export. Inside this export zip file is a SQLite database containing some pretty gnarly tables for internal use only. The table we need is ZSYNCOBJECT and through trial and error here are the SQL queries to get buy / sell transactions as well as income (dividends, special returns):</p><pre># This SQL query retrieves all of the buy and sell transactions.<br>buys_sells_query = f&quot;&quot;&quot;<br>  SELECT ZACCOUNT2, ZINVESTMENTHOLDING, ZFEE2, ZDATE1,ZAMOUNT1,<br>  ZNUMBEROFSHARES1, ZPRICEPERSHARE1,ZSYMBOL1,ZDESC2<br>  FROM ZSYNCOBJECT<br>  WHERE ZACCOUNT2 IN ({include_accounts_list})<br>  AND ZSYMBOL1 IN ({include_tickers_list})<br>  ORDER BY ZDATE1 ASC<br>  &quot;&quot;&quot;</pre><p>And to get the income transactions, same table but different columns:</p><pre># This SQL query retrieves income  - dividends, return of capital etc.<br>income_query = f&quot;&quot;&quot;<br>  SELECT ZDATE1, ZACCOUNT2, ZINVESTMENTSYMBOL, ZAMOUNT1, ZDESC2<br>  FROM ZSYNCOBJECT<br>  WHERE ZINVESTMENTSYMBOL IS NOT NULL<br>  AND ZACCOUNT2 IN ({include_accounts_list})<br>  AND ZINVESTMENTSYMBOL IN ({include_tickers_list}) COLLATE NOCASE<br>  ORDER BY ZDATE1 ASC<br>  &quot;&quot;&quot;</pre><p>I used a simple factory design pattern to model the Moneywiz connector and support other datasources in the future:</p><pre># The DataConnector class models how the core df_prices and df_income dataframes<br># should be built as well as a way to get the current open positions.<br># A working impl. for Moneywiz is provided.<br>class DataConnector:<br>    def get_data(self):<br>        raise NotImplementedError(&quot;Subclasses should implement this!&quot;)<br><br>    def get_open_positions(self):<br>        raise NotImplementedError(&quot;Subclasses should implement this!&quot;)<br><br>    def get_txns(ticker):<br>        raise NotImplementedError(&quot;Subclasses should implement this!&quot;)</pre><p>Now we need to write or acquire an XIRR implementation. It would actually be quite gnarly code to write. We would need to use <a href="https://en.wikipedia.org/wiki/Newton%27s_method">Newton’s method</a>. In numerical analysis, Newton’s method is an iterative technique used to find roots (or zeros) of a real-valued function. In this case, it’s used to find the interest rate (XIRR) that makes the NPV (Net Present Value) of the cashflows equal to zero. Luckily, someone has already done this for us via <a href="https://github.com/Anexen/pyxirr">PyXIRR</a> “Rust-powered collection of financial functions”, so once we have the DataFrame populated with ‘Date’ and ‘Amount’ columns, we simply call:</p><pre>try:<br>      # xirr only wants these two columns<br>      df = df[[&quot;Date&quot;, &quot;Amount&quot;]]<br>      xirr_val = xirr(df)<br>      if xirr_val is None:<br>          log.error(&quot;Problem in XIRR calc 1&quot;)<br>          # eyeball / save out the data<br>          # print(df)<br>          df.to_csv(&quot;pak.csv&quot;, index=False)<br>      log.info(f&quot;{xirr_val=}&quot;)<br>  except InvalidPaymentsError as ipe:<br>      log.error(&quot;Problem in XIRR calc 2&quot;, ipe)</pre><p>Note the native support for DataFrames by the xirr() function — nice!</p><p>Below is the main driving function that loads and preprocesses the transaction data, sets up the reporting DataFrame and loops over each ticker in turn calculating XIRR over both capital growth (or loss) and income.</p><p>The code should come across as both simple and readable. The more complicated parts in fact relate to an early effort to add UK CGT (Capital Gains Tax) exposure given the impending budget of doom at the end of October 2024.</p><pre>def run_xirr(args):<br>    # Stores the stats (as a dict) for each individual stock as we loop over them.<br>    # Converted to a DF at the end and is the main printed output of this code.<br>    results = []<br>    # Holds the txns for each individual stock as we loop over them<br>    # Merged at the end into one large DF to calc overall portfolio XIRR<br>    all_dfs = []<br><br>    connector = DataConnectorFactory.get_connector(args.source)<br><br>    df_buys_sells, df_income = connector.get_data()<br>    df_buys_sells, df_income = pre_process_actual(df_buys_sells, df_income)<br><br>    df_open = connector.get_open_positions()<br>    df_open = pre_process_open(df_open)<br><br>    s_tickers = df_buys_sells.ZSYMBOL1.value_counts()<br><br>    # The main loop over each position held in the portfolio<br>    for ticker, _ in s_tickers.items():<br>        if ticker in print_list:<br>            log.info(f&quot;Processing {ticker}&quot;)<br>        capital, income, taxable_ratio, share_count, df = connector.get_txns(ticker)<br>        if ticker in print_list:<br>            log.info(f&quot;{ticker}, {taxable_ratio=}, {capital=}&quot;)<br>            print(<br>                f&quot;{df[[&#39;Date&#39;, &#39;Amount&#39;, &#39;taxable_shares&#39;, &#39;nontaxable_shares&#39;, &#39;taxable&#39;]]}&quot;<br>            )<br><br>        curr_val = add_open_position(ticker, share_count, df_open, df)<br>        # crude calculation of tax payable..<br>        if curr_val &gt; 0:<br>            taxable = (curr_val + capital) * taxable_ratio<br>        else:<br>            # TODO handle shares that have been sold<br>            taxable = 1<br>        # Add total curr_val to capital to get capital position<br>        capital += curr_val<br>        if ticker in print_list:<br>            # Some rudimentary support for calculating CGT exposure<br>            log.info(f&quot;{ticker}, {curr_val=}&quot;)<br>            log.info(f&quot;{ticker}, {taxable=}&quot;)<br>            log.info(f&quot;{ticker}, {taxable_ratio=}&quot;)<br>        overall = df.Amount.sum()<br><br>        df = df.sort_values(by=&quot;Date&quot;)<br>        df = df.reset_index(drop=True)<br>        if ticker in print_list:<br>            log.info(f&quot;{df=}&quot;)<br><br>        # My Moneywiz instance holds a couple of Vodafone divi payments<br>        # *before* any purchase for the date range in question - remove these<br>        df = check_rogue(df, ticker)<br><br>        if ticker in print_list:<br>            log.info(f&quot;=====DF GOING INTO XIRR for {ticker} =====&quot;)<br>            log.info(f&quot;{df[[&#39;Date&#39;, &#39;Amount&#39;]]=}&quot;)<br>            df.to_csv(f&quot;{ticker}.csv&quot;, index=False)<br>        try:<br>            curr_xirr = xirr(df[[&quot;Date&quot;, &quot;Amount&quot;]])<br>        except InvalidPaymentsError:<br>            log.error(f&quot;Problem in XIRR calc for {ticker}&quot;)<br>            log.error(f&quot;{df=}&quot;)<br>        if curr_xirr is None:<br>            log.error(f&quot;Problem in XIRR calc for {ticker}&quot;)<br>            log.error(f&quot;{df=}&quot;)<br><br>        # Use the sign to distinguish between monies invested (-)<br>        # and income generated (+)<br>        df.loc[df[&quot;Amount&quot;] &lt; 0, &quot;invested&quot;] = df[&quot;Amount&quot;]<br>        df.loc[df[&quot;Amount&quot;] &gt; 0, &quot;income&quot;] = df[&quot;Amount&quot;]<br><br>        all_dfs.append(df)<br>        # Work out how many years since the very first purchase<br>        # of the current ticker<br>        years = (today - df.Date.iloc[0]).days / 365<br>        if ticker in print_list:<br>            log.info(f&quot;{taxable=}&quot;)<br>        results.append(<br>            {<br>                &quot;Ticker&quot;: ticker,<br>                &quot;XIRR&quot;: curr_xirr * 100,<br>                &quot;Curr value&quot;: curr_val,<br>                &quot;Overall&quot;: overall,<br>                &quot;Capital&quot;: capital,<br>                &quot;CGT&quot;: taxable,<br>                &quot;Dividends&quot;: income,<br>                &quot;Years&quot;: years,<br>                &quot;Cost&quot;: float(df.invested.sum()),<br>                &quot;Income&quot;: float(df.income.sum()),<br>            }<br>        )<br><br>    df_results = pd.DataFrame(results)<br>    # TR = Total Return<br>    df_results[&quot;TR&quot;] = -(df_results.Income + df_results.Cost) / df_results.Cost<br>    # These cols are no longer needed<br>    df_results = df_results.drop(columns=[&quot;Cost&quot;, &quot;Income&quot;])<br><br>    # Let the user specify which col to sort by on the cmdline<br>    df_results = df_results.sort_values(by=args.order)<br>    # Use print instead of log so we get col headers aligned correctly<br>    print(f&quot;{df_results}&quot;)<br><br>    # See who is still to be covered<br>    # covered = set(df_results.Ticker)<br>    # missing = current_tickers.difference(covered)<br>    # if len(missing) &gt; 0:<br>    #     log.info(f&quot;Still to add in, {missing}&quot;)<br><br>    df_all = pd.concat(all_dfs)<br>    log.info(f&quot;{df_all.shape=}&quot;)<br>    # This is the portfolio-level XIRR<br>    overall_xirr = xirr(df_all[[&quot;Date&quot;, &quot;Amount&quot;]])<br><br>    # Check for unused txns<br>    df_buy_sells_unused = df_buys_sells[df_buys_sells.used == 0]<br>    if len(df_buy_sells_unused) &gt; 0:<br>        log.info(f&quot;{len(df_buy_sells_unused)} unused buy/sell txns&quot;)<br>    df_income_unused = df_income[df_income.used == 0]<br>    if len(df_income_unused) &gt; 0:<br>        log.info(f&quot;{len(df_income_unused)} unused income txns / {len(df_income)} total&quot;)<br>        log.info(f&quot;{df_income_unused.ZINVESTMENTSYMBOL.value_counts()}&quot;)<br>    log.info(f&quot;Overall XIRR, {overall_xirr:.5f}&quot;)<br>    log.info(f&quot;Indicative CGT exposure, {df_results.CGT.sum():.2f}&quot;)</pre><h3>Conclusion</h3><p>This first post gets the base XIRR analysis up and running, motivating the reader as to why it is well worth doing. Part two will dig into relative performance by supporting virtual portfolios that track the real portfolio for indices like the S&amp;P 500, FTSE 100 etc.</p><p>The complete code will be published on <a href="https://github.com/hsheil">Github</a> once it’s been refactored. For now, this post just serves to show the main concepts.</p><p><em>Originally published at </em><a href="https://hsheil.github.io/investing/2024/10/21/personalised-xirr-0.html"><em>https://hsheil.github.io</em></a><em> on October 21, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40c06dc6fa75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Java needs for true Machine / Deep Learning support]]></title>
            <link>https://medium.com/@hsheil/what-java-needs-for-true-machine-deep-learning-support-1571ffdbb594?source=rss-3fa04a4eae53------2</link>
            <guid isPermaLink="false">https://medium.com/p/1571ffdbb594</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Humphrey Sheil]]></dc:creator>
            <pubDate>Sun, 04 Nov 2018 14:09:03 GMT</pubDate>
            <atom:updated>2018-11-04T23:21:47.633Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Recently I gave a talk on the present and future of <a href="https://www.technologytransfer.eu/event/1831/Machine_Learning_for_the_Enterprise_International_Conference.html">machine / deep learning (ML / DL)in the enterprise</a>. In an enterprise setting, the questions and topics are more applied than a research conference — for example how do I get my team started in ML and how best to integrate ML with existing systems we run. Afterwards, in the panel discussion the topic of Java and machine learning came up.</p><p>Java is noticeably absent in the machine learning space. Virtually no ML frameworks are built in Java (there is <a href="https://deeplearning4j.org/">DL4J</a> but I genuinely don’t know anyone who uses it, <a href="https://mxnet.apache.org/">MXNet</a> has a Scala API but not a Java one and it’s not written in Java, Tensorflow has an <a href="https://www.tensorflow.org/install/lang_java">incomplete Java API</a>), however Java has a massive footprint in the enterprise, representing perhaps trillions of dollars invested globally over the last 20 years in every conceivable domain — financial services, trading, e-commerce, telcos — the list is endless. For machine learning, the “first among equals” programming language is not Java, but Python. Personally, I enjoy coding in both Python and Java, but <a href="https://twitter.com/frankgreco">Frank Greco</a> posed an interesting question that got me thinking:</p><blockquote>What would Java need to compete with Python in ML? What if Java got serious about truly supporting machine learning?</blockquote><h3>Is it important?</h3><p>Let’s motivate this discussion. Since 1998, Java has been at the top table as far as multiple enterprise evolutions and revolutions has been concerned — the web, mobile, browser vs native, messaging, i18n and l10n globalisation support, scaling out and supporting every kind of enterprise information store you care to mention, from relational databases to Elasticsearch.</p><p>That level of unconditional support prompts a very healthy can-do, roll-up-your-sleeves-and-code-it kind of culture on Java teams. There is no magic component or API that cannot be augmented or replaced by a good Java team.</p><p>But this is not the case in machine learning. Instead, Java teams have two options:</p><ol><li>Re-train / co-train in Python.</li><li>Use a vendor API to add a machine learning capability to your enterprise system.</li></ol><p>Neither of these options is really that palatable. The first requires significant upfront time and investment plus ongoing maintenance costs, while the second risks vendor lock-in, vendor de-support, introduces third-party components (with a network hop price to pay) to perhaps a performance-critical system and requires you to share data outside your organisation boundaries — a no-go for some.</p><p>Most damaging of all in my opinion, is the potential for <em>cultural attrition</em> — teams can’t change code they don’t understand or can’t maintain, so there is a dereliction of duty and someone else picks up the heavy lifting— Java-only teams run the risk of being left behind in the next big wave coming for enterprise computing — the machine learning wave.</p><p>So it is important and desirable for the Java programming language and platform to have first-class machine learning support. Without it, Java runs the risk of being slowly replaced by languages that do support ML well over the next 5–10 years.</p><h3>Why is Python so dominant in ML?</h3><p>First, let’s consider why Python is the dominant language in machine learning and deep learning.</p><p>I suspect it all started from a fairly innocuous feature — slicing support for lists. This support is extensible: any Python class implementing the <em>__getitem__</em> and <em>__setitem__</em> methods can be sliced using this syntax. The snippet below shows how powerful and natural this Python feature is..</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17cda311fcd362ed1d12b6156ddc84c3/href">https://medium.com/media/17cda311fcd362ed1d12b6156ddc84c3/href</a></iframe><p>Of course, there’s more. Python code is more terse and brief when compared to older Java code. Exceptions are supported but are unchecked, and developers can easily code throwaway Python scripts to try stuff out without getting sucked into the Java mindset of “everything is a class”. It’s easy to get cranking with Python..</p><p>But now the main factor in my opinion — although the Python community made a dogs dinner in maintaining cohesion between 2.7 and 3, they did a far better job in building a well-designed, fast numeric computing library — <a href="http://www.numpy.org/">NumPy</a>. Numpy is built around the <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.ndarray.html">ndarray</a> — the N-dimensional array object. Directly from the docs: “<em>NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers</em>”. Everything in NumPy follows from getting your data into an ndarray and then performing operations on it. NumPy supports multiple types of indexing, broadcasting, vectorisation for speed and in general allows developers to easily create and manipulate large arrays of numbers.</p><p>The next snippet shows ndarray <a href="https://docs.scipy.org/doc/numpy-1.15.1/user/basics.indexing.html">indexing</a> and <a href="https://docs.scipy.org/doc/numpy-1.15.0/user/basics.broadcasting.html">broadcasting</a> in action, core operations in ML / DL.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31943d3123e89b8406160e61e9bc7649/href">https://medium.com/media/31943d3123e89b8406160e61e9bc7649/href</a></iframe><p>Dealing with large multi-dimensional arrays of numbers is the beating heart of machine learning coding, and especially deep learning. Deep neural networks are lattices of nodes and edges modelled by numbers. Run-time operations when training a network or performing inference on it require fast matrix multiplication.</p><p>NumPy has facilitated and enabled so much more —<a href="http://scikit-learn.org/stable/"> scipy</a>, <a href="https://pandas.pydata.org/">pandas</a> and many other libraries that rely on NumPy. The leading deep learning libraries (<a href="https://www.tensorflow.org/">Tensorflow</a> from Google, <a href="https://pytorch.org/">PyTorch</a> from Facebook) are heavily invested in Python. Tensorflow has other APIs for Go, Java and JavaScript, but they are incomplete and regarded as unstable. PyTorch was originally written in Lua, and experienced a big jump in popularity when they moved from that fairly niche language to the main Python ML ecosystem in 2017.</p><h3>Drawbacks to Python</h3><p>Python isn’t a perfect language — in particular the most popular Python runtime — CPython — has a Global Interpreter Lock (<a href="https://wiki.python.org/moin/GlobalInterpreterLock">GIL</a>) so scaling is not straightforward. Moreover, Python DL frameworks like PyTorch and Tensorflow still hand off core methods to opaque implementations. For example, the <a href="https://developer.nvidia.com/cudnn">cuDNN library</a> from NVidia has a profound influence on the scope of the <a href="https://pytorch.org/docs/stable/nn.html#rnn">RNN / LSTM implementation</a> in PyTorch. RNN and LSTM is a very important DL technique for business applications in particular as they specialise in classifying and predicting over sequential, variable-length sequences — e.g. web clickstreams, text snippets, user events and more.</p><p>To be fair to Python, this opacity / restriction applies to almost any ML / DL framework that is not written in either C or C++. Why? Because in order to obtain the maximum performance for core, hig-frequency operations like matrix multiplication, developers go as “close to the metal” as they can.</p><h3>What does Java need to do to compete?</h3><p>I propose that there are three primary additions to the Java platform which if present, would prompt the sprouting of a healthy and thriving machine learning ecosystem in Java:</p><p>1. Add native indexing / slicing support in the core language to compete with Python ease of use and expressive power, probably centred around the existing ordered collection <a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html">List&lt;E&gt; interface</a>. This support would also need to admit overloading to support point #2.</p><p>2. Build a <strong>Tensor</strong> implementation— probably in the java.math package but also bridging across to the Collections API. This set of classes and interfaces would act as the equivalent of the ndarray, and would provide additional indexing support — specifically the <a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.indexing.html">three types of NumPy indexing</a>: field access, basic slicing and advanced indexing essential for coding ML.</p><p>3. Support broadcasting — scalars and Tensors of arbitrary (but compatible) dimensions.</p><p>If these three things were in place in the core Java language and runtime, it would open up the road to build “<strong>NumJava</strong>”, the equivalent to NumPy. <a href="http://openjdk.java.net/projects/panama/">Project Panama</a> could also be used to provide vectorised, low-level access to fast tensor operations running on CPUs, GPUs, TPUs and beyond to help Java ML be the fastest around.</p><p>I’m not suggesting these additions are trivial — far from it, but the potential upside to the Java platform is enormous.</p><p>The snippet below shows how our NumPy broadcasting and indexing example could look in NumJava with a Tensor class, with slicing syntax supported in the core language, and respecting the current restriction on operator overloading.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c20abbe3b6b30a8d68e3abf8bbbcb42c/href">https://medium.com/media/c20abbe3b6b30a8d68e3abf8bbbcb42c/href</a></iframe><h3>A vision and call to action</h3><p>We all know ML is going to change the world of business, just as the relational database, internet and mobile did. There’s plenty of hype around, but equally some papers and results are emerging that are strongly compelling. <a href="https://arxiv.org/abs/1712.01208">This paper for example</a>, promises a future where our optimal database, web and application server configs will be learned and tuned in the background using machine learning. You won’t even have to deploy ML to see it in your systems, one of your vendors is sure to do it for you.</p><p>From the pragmatic starting point outlined in this post, we could have as many machine / deep learning frameworks written in Java and running on the JRE as we have web, persistence or XML parsers — just imagine that! We could envisage Java frameworks with support for <a href="http://cs231n.github.io/convolutional-networks/">convolutional neural networks</a> (CNNs) for leading-edge computer vision, recurrent neural network implementations like <a href="http://colah.github.io/posts/2015-08-Understanding-LSTMs/">LSTM</a> for sequential datasets (essential to business), with cutting-edge ML features such as auto-differentiation and more. These frameworks would then engender and power the next generation of enterprise-class systems — all running seamlessly beside existing Java systems, using the same tooling — IDEs, testing frameworks, continuous integration. And importantly, being written and maintained by the same people. If you’re a fan of Java, what’s not to like about that?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1571ffdbb594" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Movidius Neural Compute Stick and Raspberry 3 — quick start guide]]></title>
            <link>https://medium.com/@hsheil/movidius-neural-compute-stick-and-raspberry-3-quick-start-guide-a89ff5e1d7ca?source=rss-3fa04a4eae53------2</link>
            <guid isPermaLink="false">https://medium.com/p/a89ff5e1d7ca</guid>
            <category><![CDATA[neural-compute-stick]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[movidius]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <dc:creator><![CDATA[Humphrey Sheil]]></dc:creator>
            <pubDate>Sat, 11 Nov 2017 22:05:01 GMT</pubDate>
            <atom:updated>2017-11-11T22:53:31.410Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been wanting to try out the <a href="https://www.anandtech.com/show/11649/intel-launches-movidius-neural-compute-stick">Movidius Neural Compute Stick</a> (NCS) for a while now and decided to combine it with a Raspberry Pi 3 — the idea being of course to move the setup to a mobile-capable chassis (wheeled or winged!) in the near future.</p><p>They are selling like hot cakes here in the UK — either that or the manufacturing batches are small. <a href="http://uk.rs-online.com/web/p/processor-microcontroller-development-kits/1393655/">RS Online</a> got their latest batch in last week and they are sold out already -they’ve sold out twice in the last couple of months..</p><p>Hardware-wise, £120+VAT gets you a NCS, a Raspberry Pi 3 and v2 camera module for the Pi. The OS and SDK are free of course so that’s a relatively small outlay for a fun Deep Learning project..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*a52zOF6eglFJ2EQbkhsUvA.jpeg" /><figcaption>£120 for a mobile deep learning dev kit.</figcaption></figure><p>I found the Movidius documentation to be either missing or incomplete — a lot of links indexed by Google now 404, the forums are pretty quiet and the Youtube videos and other resources imply that a host PC running full Ubuntu is required. That’s not the case — it is possible to do a full install straight onto your Raspberry Pi 3 as we outline below. So the steps are as follows (all of these steps were executed on the Pi, we did not use a host PC at all):</p><p>1. Install Raspbian on to your Pi— we installed <a href="https://www.raspberrypi.org/downloads/raspbian/">Stretch with Desktop</a> straight from the website.</p><p>2. Next, clone the ncsdk repo from the Movidius organisation on Github:</p><pre>git clone <a href="https://github.com/movidius/ncsdk.git">https://github.com/movidius/ncsdk.git</a></pre><p>Quick note: this won’t be the only repo you need to get up and running quickly (see below).</p><p>3. Make sure you run install.sh using bash as it has “bashisms” — so “sudo bash install.sh”. Now we need to wait as the Pi CPU is pretty underpowered for what comes next..</p><p>4. scikit-image takes ~30 mins to compile — be patient, have a coffee and a biscuit.</p><p>5. Caffe takes ~1 hour to compile (and looks like it will run out of RAM but doesn’t — it uses ~800 MB and a Pi 3 has 1 GB so we’re ok here) — be even more patient, partaking coffee and biscuits as necessary..</p><p>6. Once install.sh is finished test your installation by running this file (<a href="https://github.com/movidius/ncsdk/blob/master/examples/apps/hello_ncs_py/hello_ncs.py">https://github.com/movidius/ncsdk/blob/master/examples/apps/hello_ncs_py/hello_ncs.py</a>) e.g.</p><pre>python hello_ncs.py </pre><p>You should see output like:</p><pre>Hello NCS! Device opened normally.<br>Goodbye NCS! Device closed normally.<br>NCS device working.</pre><p>We now have a working Neural Compute Stick!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzb60PM1_cmRH6vP3Es53Q.jpeg" /></figure><p>7. Now run</p><pre>make all</pre><p>in the examples subdir to download and build some models to test (the pre-trained weights are downloaded from dl.caffe.berkeleyvision.org). This will build three models — GoogLeNet, AlexNet and SqueezeNet. These models are trained on ImageNet so they can recognise objects from the 1,000 categories that comprise the ImageNet corpus. You could in fact build just one of these models — we want to compare relative performance though so we built all of them. This step will need to download the pre-trained weight matrices for each model and also compile the Caffe model into the internal NCS format, so the time taken will depend on the speed of your network connection.</p><p>8. Now we need our second Movidius repo — clone the ncappzoo GH repo to get stream_infer.py (this is the same script referred to in <a href="https://www.youtube.com/watch?v=f39NFuZAj6s">this video</a>) — otherwise you’ll need OpenCV which will take **4 hours!!!** to build and you will also need to write Python code to access the video stream — not a problem but we don’t need to do it in this quick start guide. So it’s:</p><pre>git clone <a href="https://github.com/movidius/ncappzoo">https://github.com/movidius/ncappzoo</a></pre><p>9. Make sure you run</p><pre>sudo modprobe bcm2835-v4l2</pre><p>to get the v2 camera module loaded as the /dev/video0 device, otherwise the python script will simply hang as it wants to access the camera using this handle.</p><p>10. As per the Youtube video I linked to above, you’ll need to</p><pre>sudo apt install gir1.2-gstreamer-1.0 git1.2-gst-plugins-base-1.0 python3-gst-1.0</pre><p>No, I have no idea why these packages have such friendly and easy to remember names either. This gives us the windowing system API that stream_infer.py wants to use.</p><p>11. Ok, now we can finally see how the NCS runs our target model!! Run stream_infer.py from the ncappzoo/app/stream_infer directory. We loaded in the GoogleNet model — make sure you use the right image dimensions required by your model (we need 224x224x3 for GoogleNet) or the code will error with a re-shaping problem (ValueError: cannot reshape array of size XXXX into shape (224, 224, 3)).</p><p>Here’s a running example — safety pin is a <a href="http://image-net.org/challenges/LSVRC/2014/browse-synsets">category</a> from ImageNet and the NCS running GoogleNet classifies it with ease (95%). Cool..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFjCm1GI5FYjTMmt4AbPVw.jpeg" /></figure><p>PS The NCS runs pretty hot!</p><p>PPS TODOs — generate a PR back into the repo for two things:</p><p>(a) Get the scripts to use make -j4 to run at least a bit more quickly when compiling on the Pi 3</p><p>(b) Get the scripts to be a bit more arch-aware for the Pi 3 platform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a89ff5e1d7ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BMVA — Human Activity Recognition and Monitoring workshop mini-review]]></title>
            <link>https://medium.com/@hsheil/bmva-human-activity-recognition-and-monitoring-workshop-mini-review-f2bae20cef89?source=rss-3fa04a4eae53------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2bae20cef89</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bmva]]></category>
            <dc:creator><![CDATA[Humphrey Sheil]]></dc:creator>
            <pubDate>Thu, 09 Nov 2017 21:42:46 GMT</pubDate>
            <atom:updated>2017-11-13T11:33:43.941Z</atom:updated>
            <content:encoded><![CDATA[<p>Yesterday I attended the <a href="http://www.bmva.org/meetings">BMVA</a> technical meeting on <a href="https://www.eventbrite.co.uk/e/bmva-technical-meeting-human-activity-recognition-and-monitoring-registration-29604339376#">Human Activity Recognition and Monitoring</a>. I have a fairly atypical motivation to attend events like these as I’m not a computer vision researcher, but am using Machine Learning (currently comparing Deep Learning classifiers to other ML classifier types like Gradient Boosted Machines). It’s interesting to attend ML events that are not directly related to my work — they often engender new ideas and perspectives to help me break out of whatever local minimum I currently find myself in!</p><p>At the risk of making a gross simplification, Deep Learning bifurcates into:</p><p>1. Computer vision, using convolutional neural networks (CNNs) or residual networks — e.g. even AlphaGo Zero uses CNNs and resnets in the context of reinforcement learning.</p><p>2. Everything else, using recurrent neural networks (RNNs).</p><p>I work mainly in #2 in the Ecommerce / Information Retrieval (IR) domain (prediction, classification, recommender systems, ranking), so gaining an appreciation of #1 is beneficial.</p><p>A number of the presenters referenced and used the term <em>personalisation</em> in a very different context than I’m used to. Personalisation can mean many things to many people — in the IR domain, personalisation means making search query results more relevant or beneficial to the user — increasing some measure of utility. It was interesting seeing personalisation applied to a personal robot in the videos from <a href="http://www.imperial.ac.uk/people/y.demiris">Yiannis Demiris</a>!</p><p>So taking that utility metric and porting it to different domains makes for very different personalisation — Demiris showed work where sick children get a personalised robot to help them navigate a hospital garden, or help with physical therapy exercises, while James Charles referenced personalisation as a way to increase the performance of the pose estimation task (see below).</p><p>Lastly on this work, Demiris presented work where conventional Deep Learning formed the lower layers of an inference stack with the top of this stack occupied by a non-Deep Learning rules engine / programming language which he said improved performance. I found this interesting and a bit controversial. If we compare this hybrid, hierarchical approach to let’s say what Hinton and Bengio talk about in season 1 podcast 5 of <a href="http://www.thetalkingmachines.com/">The Talking Machines</a> series — such a hierarchical approach shouldn’t be necessary — the distributed representations or embeddings learned by the deep net should be enough.</p><p>Next up was <a href="https://scholar.google.co.uk/citations?hl=en&amp;user=OZ6QiRwAAAAJ&amp;view_op=list_works&amp;sortby=pubdate">James Charles</a>, describing work on <a href="https://arxiv.org/abs/1511.06676">Personalizing Human Video Pose Estimation</a>. This is nice work where a “personalized ConvNet pose estimator that automatically adapts itself to the uniqueness of a person’s appearance to improve pose estimation in long videos”. So for example, once the network is shown the groundtruth for pose estimation plus distinctive markers worn by the subject such as a watch or baseball cap, model performance can be improved over SOTA using these personalised markers.</p><p>The <a href="http://www.irc-sphere.ac.uk/">Sphere project in Bristol</a> was the subject of another keynote from Ian Craddock. It shows what the creative reach and ambition of a team can be given enough funding (£20 million) and time (5 years) to go out, design and build something truly world-changing. In Sphere they are building a large-scale (100 families) system to gather data from family homes to target medical conditions that are chronic and not acute — the big three in the UK are depression (£8 billion per annum cost), dementia (costs the UK £80 billion per year and growing) and diabetes (on track to use up 17% of the NHS annual budget and growing). Chronic conditions subvert and frustrate traditional ML techniques in interesting ways, e.g. dementia develops over decades so point-in-time scans are useless. Craddock covered the large amount of unenviable ground-work that is needed before any interesting experiments can take place — how to address privacy concerns and ethics considerations, logistical planning when building hardware and software at distributed scale, and training comp. sci. staff and researchers on how to deal with human subjects.</p><p><a href="https://scholar.google.com/citations?user=ZWfuPHUAAAAJ&amp;hl=en">Girmaw Abebe</a> used a data analysis pipeline to manually and automatically extract features from FPV (First Person View) and IMU (Inertial Measurement Unit) data streams using CNNs and LSTM which I found interesting — the LSTM component was used to bump up accuracy on the temporal element of the image sequence with the CNN handling the usual image segmentation.</p><p>The last talk by researchers at Kingston used <a href="https://www.researchgate.net/publication/320305673_Fall_detection_using_myoskeletal_model_simulation">a software simulator to create a falling dataset</a> — something which is by its very nature difficult to create realistically. Fall detection is getting a good amount of attention by UK universities (the <a href="http://www.wikicfp.com/cfp/servlet/event.showcfp?eventid=61672&amp;copyownerid=96405">UKCI workshop in Cardiff</a> this year also had a couple of papers on it) and I imagine world-wide as well — with an ever-ageing population, fall detection in the home will become more important. I learned from this talk that there are people on Youtube who video themselves hyperventilating until they pass out which provides useful training data for this task?!?!</p><p>There were more papers, keynotes and posters and time permitting I’ll write up more of my notes on these soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2bae20cef89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Review: Vitus Bikes Energie Cyclo X Bike — Apex 1x11 2018]]></title>
            <link>https://medium.com/@hsheil/review-vitus-bikes-energie-cyclo-x-bike-apex-1x11-2018-617dc5dda75d?source=rss-3fa04a4eae53------2</link>
            <guid isPermaLink="false">https://medium.com/p/617dc5dda75d</guid>
            <category><![CDATA[cycling]]></category>
            <dc:creator><![CDATA[Humphrey Sheil]]></dc:creator>
            <pubDate>Thu, 02 Nov 2017 16:20:45 GMT</pubDate>
            <atom:updated>2017-11-02T16:29:11.788Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been in the market for a winter bike for a while now. My main bike is a <a href="https://www.decathlon.co.uk/ultra-720-af-road-bike-ultegra-id_8331274.html">B’TWIN Ultra 720 AF</a> which I’m really happy with but it does have a few drawbacks for winter use — it doesn’t have mudguard eyelets, maxes out at 28 mm tyre width and most importantly of all, doesn’t have disc brakes which are all-important when it’s wet underfoot.</p><p>I waited patiently for B’TWIN to release a disc braked bike, but <a href="https://www.decathlon.co.uk/ultra-520-af-gf-road-bike-rival-disc-id_8390785.html?opeco=opeco:VF-Product-Cycling-Road-Bikes&amp;type=opeco">when they did</a> it wasn’t really what I wanted — no mudguard eyelets and a SRAM groupset, instead of Shimano (and I wanted Shimano 105 or better).</p><p>After lots of looking at CUBE (too heavy for the money), Dolan (frames not thru-axles, not convinced about the length of the frame guarantee), Canyon (bad stories about quality) and various other brands, I stumbled across the Vitus brand on <a href="http://chainreactioncycles.com/">chainreactioncycles.com</a>. It’s also rocking a SRAM groupset but in a 1x11 configuration which is becoming more and more popular. On paper it’s light enough, has thru-axles front and back, hydraulic disc brakes, mudguard eyelets and 35mm tyres for autumn / winter cycling. Long story short I bought it sight unseen in a size L frame..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k0mLyEF_psizAPl7BtORgg.jpeg" /><figcaption>More relaxed frame geometry than my road bike, and comes well packed out of the box.</figcaption></figure><p>The bike arrived really well packed and padded in a large box, but the fork paintwork had been damaged in the factory / while packing as well as the cable housing to the rear derailleur. Those two chunks out were annoying, but this is a winter bike to be used and abused, not a high days of summer road bike.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdNFyAVq6Axsp5DrVRkVrg.jpeg" /><figcaption>A chunk of paint knocked out of the fork, hidden behind the packaging..</figcaption></figure><p>What annoyed me far more was the state the rear derailleur was delivered in — the high stop had not been set at all and I wrapped the chain around the rear cassette on my first test outing. Not impressed and I don’t see why cycle vendors cannot do a better job on basic setup. All of the <a href="http://www.chainreactioncycles.com/vitus-bikes-energie-cyclo-x-bike-apex-1x11-2018/rp-prod159446">reviews</a> for the bike also mention bad gear indexing so this seems to be a common problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdYkeIXqeiHwXwslkF6usA.jpeg" /><figcaption>Bad first outing — wrapped the chain behind the cassette due to non-existent setup from the factory..</figcaption></figure><p>To cycle, I think the knobbly tyres might be holding back the bike a bit (higher rolling resistance), but I’ll give them the benefit of the doubt for now. I’m used to the excellent Continental 4000 S II tyres but I want a good winter tyre for leaves etc. The top tube feels longer than my current bike so the riding position is actually more aero, although the seat and bars are in roughly the same place. Long story short, it rides fine so far..</p><p>So the bike itself is what I wanted — the 35 mm tyres are very comfy, the 1x11 SRAM groupset is a bit agricultural (heavier, clunkier shifts) compared to the 2x11 Ultegra groupset on the Ultra 720, but I expected that. I’m not that impressed with the brakes yet — I find I have to squeeze them hard to stop so maybe the pads need to bed in, I also want to adjust the reach on the front lever. Weight-wise and at this price point, you will struggle to do better than this bike, and to get thru-axles as well for the discs is a bonus. Overall, I’m happy with the bike, unhappy with the setup and looking forward to getting some winter kilometres laid down!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=617dc5dda75d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep learning and machine learning]]></title>
            <link>https://medium.com/data-science/deep-learning-and-machine-learning-c1101debe0c?source=rss-3fa04a4eae53------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1101debe0c</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Humphrey Sheil]]></dc:creator>
            <pubDate>Tue, 15 Aug 2017 19:19:13 GMT</pubDate>
            <atom:updated>2017-08-15T19:58:16.139Z</atom:updated>
            <content:encoded><![CDATA[<p>14 Jul 2015</p><p><em>This blog post is a more informal discourse on a formal exercise I’m currently engaged in — the background literature review for my PhD. As such, it is very link-rich — the journey I am documenting here is intrinsically made up from the work of others. This post may also be interpreted as an attempt to convince my supervisors </em><a href="http://www.cs.cf.ac.uk/contactsandpeople/staffpage.php?emailname=o.f.rana"><em>Prof. Omer Rana</em></a><em> and </em><a href="https://www.maynoothuniversity.ie/faculty-science-engineering/our-people/ronan-reilly"><em>Prof Ronan Reilly</em></a><em> that I am actually getting stuff done instead of reading papers and debugging </em><a href="https://github.com/torch/torch7/wiki/Cheatsheet"><em>Torch7</em></a><em> / </em><a href="http://deeplearning.net/software/theano/"><em>Theano</em></a><em> code. But this is not the case :)</em></p><h3>Machine Learning — background</h3><p>The field of Machine Learning is highly active at present. Week by week, month by month, previous records are <a href="http://www.technologyreview.com/news/537436/baidus-artificial-intelligence-supercomputer-beats-google-at-image-recognition/">tumbling</a> and then tumbling again (although <a href="http://www.nytimes.com/2015/06/04/technology/computer-scientists-are-astir-after-baidu-team-is-barred-from-ai-competition.html?_r=1">rules are being broken</a> along the way). Libraries implement algorithms that are optimised for GPU hardware using Nvidia’s <a href="http://www.nvidia.co.uk/object/cuda-parallel-computing-uk.html">CUDA</a> and researchers can either buy <a href="http://maxwell.nvidia.com/titan-x">hardware from Nvidia</a>, or rent machines in the cloud <a href="https://aws.amazon.com/blogs/aws/new-g2-instance-type-with-4x-more-gpu-power/">an hour at a time</a>. Coders at home / small companies can now train very large models on extremely large data sets that only a much larger company could contemplate doing <a href="http://www.cs.stanford.edu/~acoates/papers/CoatesHuvalWangWuNgCatanzaro_icml2013.pdf">just 3–4 years ago</a>.</p><p>Why is this important? Well, the simplest definition of Machine Learning is <em>software that improves its own performance over time when measured against a specified task</em>. That sentence describes a breed of software very different to what we are all used to at present — operating systems, browsers and most applications do not meaningfully modify their behaviour based on “experience” — they repeatably do exactly the same thing over and over again. Having software that is trainable — that can learn — is an immensely valuable capability as we will see later on.</p><p>In my opinion, Machine Learning represents one of the grand challenges of our time, up there with understanding the <a href="http://en.wikipedia.org/wiki/The_Fabric_of_Reality">fabric of reality</a> or what is <a href="http://www.newscientist.com/article/dn25471-spark-of-life-metabolism-appears-in-lab-without-cells.html#.VW9NHlxVhBd">life itself</a>.</p><h3>Machine Learning != Deep Learning (except it kind of is right now)</h3><p>Machine Learning is not Deep Learning (it’s a superset of it) but recently (and especially in mainstream media) the two terms have become synonymous. Deep Learning is a <em>branch</em> of Machine Learning that stems from <a href="http://en.wikipedia.org/wiki/Artificial_neural_network">Artifical Neural Networks</a> — in my opinion the most interesting of all ML branches because of biological plausibility (a mapping to a similar function or characteristic in the human brain) and the roadmap / treasure trove of ideas it provides to researchers. ANNs have been wildly popular and deeply unpopular by turn since the 1960s, as first hype outstripped reality and then practitioners caught up again (Minsky and Papert’s devaluing of ANNs in the 1969 book <a href="http://en.wikipedia.org/wiki/Perceptrons_%28book%29">Perceptrons</a> still echoes through the field today even though it was refuted).</p><p>Referencing Minsky here is appropriate — until recently talking about symbolic logic as implemented in <a href="http://www.swi-prolog.org/">Prolog</a> and <a href="https://common-lisp.net/">Lisp</a> was as acceptable (even more so) as neural networks. But like neural nets, Prolog and LISP have fallen out of fashion. From a software engineering point of view however, they are seductive. Prolog for example deals with easy to understand facts and rules as follows:</p><pre>likes(joe, fish).<br>likes(joe, mary).<br>likes(mary, book).<br>likes(john, book).</pre><p>When we “consult” the system with questions, Prolog uses resolution refutation to answer it, so we get:</p><pre>?- likes(mary,fish).<br>no<br><em>&quot;no&quot; means nothing matches the question, no does not mean false.</em></pre><p>But Prolog is slow and the rules / facts databases became unmanageable. Prolog / Lisp suffered their own <a href="http://en.wikipedia.org/wiki/Fifth_generation_computer#Failure">AI winter in Japan</a> as non-specialised hardware outstripped the elegant dedicated hardware (they were basically outperformed by Moore’s Law). Recently, researchers at <a href="http://arxiv.org/pdf/1502.05698v5.pdf">Google have built</a> deep learning systems focusing on the same space which display promising results but their inner workings are not as obvious / clear as a (albeit simple) Prolog equivalent. That’s neither a good or bad thing — in a nutshell it is a restatement of the old <a href="https://web.media.mit.edu/~minsky/papers/SymbolicVs.Connectionist.html">Symbolics vs Connectionist</a> debate. In practice, hard results count and right now neural networks are winning that debate..</p><p>The following schematic shows the concentric grouping / subsets of Artificial Intelligence to provide a truer picture of the relationship between deep learning and machine learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*Pd1Zvdngagm16niU.png" /></figure><p>Figure 1. A schematic depicting the relationships between different sub-fields in Artificial Intelligence, from <a href="http://www-labs.iro.umontreal.ca/~bengioy/DLbook/intro.html">Bengio’s book</a>.</p><p>Neural networks have their problems — among them the <a href="https://web.media.mit.edu/~minsky/papers/SymbolicVs.Connectionist.html">Problem of Opacity</a>. Although visualisation tools exist, for the most part neural networks look like, and are, large lattices of floating point numbers. The casual observer will make no more sense from them than by looking at the human brain, which isn’t much good when trying to integrate a neural network into a working softare system.</p><h3>So what is a neural network?</h3><p>Haykin’s <a href="http://www.amazon.co.uk/Neural-Networks-Learning-Machines-International/dp/0131293761/ref=sr_1_1?ie=UTF8&amp;qid=1433363604&amp;sr=8-1&amp;keywords=simon+haykin">canonical text</a> defines a neural network as follows:</p><p>“A massively parallel distributed processor made up of simple processing units that has a natural propensity for storing experiential knowledge and making it available for use”.</p><p>Those simple processing units are neurons. The standard model of a neuron was proposed by McCulloch and Pitts in 1943 and hasn’t really changed much since. A neuron accepts a vector of inputs X, those inputs are weighted and an optional bias b (not depicted in the figure) and generates an output or activation based on some function (many different functions are used depending on the characteristics desired) applied to the weights. The diagram below depicts this stylised neuron.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*stzFSutf9G3E0Nmq.png" /></figure><p>Figure 2. The standard (McCulloch-Pitts) model of a single neuron.</p><p>Real-world neural networks have many thousands of these neurons, and together they provide the store of experiential knowledge and most usefully of all, the ability to understand new, unseen data in the context of previous data already seen. GPUs are ideally suited to train neural networks as they too are massively parallel as the diagram below clearly demonstrates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IG0lnHB3_S-NHt7D.png" /></figure><p>Figure 3. The Titan X GPU from Nvidia with 3,072 CUDA cores.</p><h3>A personal history of neural networks</h3><p>I first encountered neural networks in 1997 — my final year project combined <a href="http://www.ra.cs.uni-tuebingen.de/SNNS/">SNNS</a> (an ancestor of Torch7 / Theano) and <a href="http://www.sciencedirect.com/science/article/pii/0925231294900639">Simderella</a> to create a 6 DoF robotic arm that “learned by seeing”. We taught the network to nest cups — just as a child would do. In fact, as the network trained, it displayed a progression of complexity in nesting strategies (linear -&gt; pre-stacking) exactly as <a href="http://www.ncbi.nlm.nih.gov/pubmed/24777522">Piaget documented</a> for real children. This project was also intended to be a stepping stone to further work inspired by the development of <a href="http://en.wikipedia.org/wiki/Broca%27s_area">Broca’s area</a> in the human brain, whereby if we pre-train or condition a neural network on simple tasks, it is more successful at learning more complex tasks. Pre-training / conditioning is an important heuristic to consider when training deep nets (see below). In hindsight, I suspect that I over-trained the hell out of this network for my end of project demo to ensure accuracy in finding the cups on the simple 20x20 retina I used! In 1997 (subjectively speaking), neural networks were seen as elegant from a computer science perspective but suspiciously close to psychology and software engineering could harvest much better (and understandable) results from techniques like <a href="http://en.wikipedia.org/wiki/Case-based_reasoning">Case-based Reasoning</a>, inference, decision trees and so on.</p><p>In 2003, my M.Sc. again focused on neural networks but almost as a side-show to the main event (distributed computing). The primary thrust of this work was to show how a cluster of heterogenous compute nodes could effectively replicate a very well-known benchmark <a href="http://www.ncbi.nlm.nih.gov/pubmed/3172241">Predicting the secondary structure of globular proteins using neural network models by Qian and Sejnowski, 1998</a> with near linear speed-up using a tuple-based architecture based on <a href="http://en.wikipedia.org/wiki/Linda_%28coordination_language%29">Linda</a> from <a href="http://cpsc.yale.edu/people/david-gelernter">David Gelernter</a>. As an aside, this work used only feed-forward neural networks — recurrent networks and certainly LSTM would produce better results due to their ability to retain information across the input sequence of amino acids.</p><p>In 2003, urban myths existed about investment banks using neural nets to predict the stock market and to monitor portfolio risks. If true, then I put it to the reader that the events of 2008 demonstrate that these neural networks may have found an unfortunate series of local minima..</p><p>In 2006, the world changed. <a href="http://www.cs.toronto.edu/~hinton/">Geoffrey Hinton</a>, <a href="http://www.iro.umontreal.ca/~bengioy/yoshua_en/index.html">Yoshua Bengio</a> and <a href="http://yann.lecun.com/">Yann LeCun</a> started stacking neural networks in layers — each layer extracted important / relevant features from its input and passed these features to the layer above it. In addition, focus shifted to a generative model from a straightforward classifier — in effect the main task of the network became generating the input data at increasing levels of abstraction (via stacks) so that useful features were extracted. These were significant breakthroughs, and the timing was fortuitous — on the hardware side, Nvidia (and AMD but OpenCL is all but dead for deep learning) were making GPU cards available as computing resources accessed via <a href="http://www.nvidia.co.uk/object/cuda-parallel-computing-uk.html">CUDA</a>. Even today, we are still in a golden age because of this trifecta confluence:</p><ol><li>A core idea (neural networks) with a training algorithm <a href="http://psych.stanford.edu/~jlm/papers/PDP/Volume%201/Chap8_PDP86.pdf">Backpropagation: Rumelhart, Hinton, Williams</a> intrinsically amenable to parallelisation.</li><li>Intrinsically parallel hardware (GPUs) to train these neural networks on.</li><li>More and larger data sets (both labeled and unlabeled) to provide as input to neural networks.</li></ol><p>In March 2013, <a href="http://www.wired.com/2013/03/google_hinton/">Hinton joined Google</a> and in December 2013, <a href="https://www.facebook.com/yann.lecun/posts/10151728212367143">LeCun joined Facebook</a>. Both companies, Baidu and more are investing heavily into deep learning to automatically categorise, understand and translate rich content on the web — text, images, video, speech.. <em>Why</em> you would do this is obvious — social platforms become more relevant, mobile phones become more powerful and useful, ads become more targeted, Ecommerce sites deliver better search results, recommendations are genuinely useful — the possibilities are endless. And simply having Google and Facebook working in this area is responsible for a lot of the current (both accurate and inaccurate) mainstream media coverage on Artificial Intelligence.</p><p>This leads us nicely onto what neural networks are typically used for.</p><h3>Practical applications</h3><p>Simply put, neural networks extract features and patterns from data they are trained on — often features and patterns that a human will not see. Then, a trained neural network can be presented with <em>new, unseen</em> data and make predictions. This generalisation step is very useful, especially for <a href="http://en.wikipedia.org/wiki/Recurrent_neural_network">Recurrent Neural Networks</a> which can absorb data <em>over time</em>, i.e. encode temporal information or sequences. Neural networks are getting awfully good at:</p><ul><li>Image parsing (edge detection, object detection and classification)</li><li>Scene understanding</li><li>Speech recognition</li><li>Natural Language Processing (NLP)</li><li>Language translation</li><li>Playing simple video games</li><li>Classification and clustering of multi-label systems</li><li>Prediction of temporal sequences.</li></ul><p>For specific use cases, ANNs sometimes can and will be out-performed, often by simpler / older techniques. It is always wise to construct a problem such that it admits the use of multiple ML techniques so that peer to peer comparisons can be made. Nevertheless, in computer vision and sequence translation in particular, deep learning approaches dominate the various leaderboards.</p><p>More generally, if a neural network N can be trained on a system S and events E occurring in that system from time step 0 up to the current time step t e.g. E = {e0, .. , et} and can then provide reasonable to good predictions on what will happen in e(t+1), e(t+2) etc., then this has wide applicability — in Ecommerce, personalised medicine, inventory management — you name it, there is a need for this kind of prediction. This is a fundamental attraction of neural networks (and often overlooked / undervalued versus understanding an image and its elements).</p><h3>Neural network frailties</h3><p>Make no mistake, neural nets are frustrating things to work with. Neural networks are:</p><ol><li>Difficult to train (inordinate length of time, average end-performance achieved).</li><li>Remarkably sensitive to how the inputs are presented so that the right features can be extracted (ICLR is an entire conference devoted to Representation Learning) — <a href="http://arxiv.org/pdf/1206.5538.pdf">Bengio, Courville and Vincent</a> have compiled a nice review on the intricacies.</li><li>The initial state of the weights can have a dramatic (positive and negative) impact on end-performance.</li><li>Amenable to “rules of thumb” which are sprinkled throughout the literature and discovered / rediscovered / reinvented: for example — curriculum learning, reversing input sequences, tuning the learning rate, . This is not a complete list by any means..</li></ol><p>Despite all of this, neural networks in various forms have demonstrated class-leading results in many different domains. That is why they are interesting and that is why researchers and companies persist with them in my opinion. Their complex, esoteric nature is more than outweighed by the results they yield.</p><h3>“State of the nation” in deep learning — ICLR 2015</h3><p>It’s instructive to look at the subject matter presented at the very latest conferences in a research field to see what the current “state of the nation” of that field is. Machine Learning is no different, and the last conference I attended was <a href="http://www.iclr.cc/doku.php?id=iclr2015:main">ICLR 2015</a> in San Diego, California just a few weeks ago. As already noted in <a href="http://www.machinedlearnings.com/2015/05/iclr-2015-review.html?utm_source=twitterfeed&amp;utm_medium=twitter">other reviews of ICLR</a>, all of the papers presented are available on <a href="http://arxiv.org/">Arxiv</a>, which is fantastic. And it’s great to see the authors of those papers present their work or getting to talk them directly in the poster sessions. There are many other excellent conferences — <a href="https://nips.cc/Conferences/current">NIPS</a>, <a href="http://www.kdd.org/kdd2015/">KDD</a>, <a href="http://ijcai-15.org/">IJCAI</a> — I choose ICLR as it is freshest in my mind!</p><p>Firstly, the <a href="http://deeplearning.net/datasets/">datasets</a> used to date are starting to <a href="http://culurciello.github.io/tech/2015/05/17/image-rec.html">struggle</a>.</p><p>Secondly, researchers are looking for common reference points against which to grade the latest systems under development. <a href="http://arxiv.org/pdf/1502.05698v5.pdf">Toy tasks</a> is a nice example of this with a clear lineage from <a href="http://ronan.collobert.com/pub/matos/2009_curriculum_icml.pdf">curriculum learning</a>. A paper under review for ICLR 2015 but I guess not accepted was <a href="http://arxiv.org/pdf/1409.2329v4.pdf">Recurrent neural network regularization</a>. What I like most about this paper is the <a href="https://github.com/wojzaremba/lstm">code on Github</a> — a great way to match up data in the paper with reproducible output.</p><p><a href="http://arxiv.org/abs/1412.7580">Fast Convolutional Nets With fbfft: A GPU Performance Evaluation</a> demonstrated how GPUs can be driven even harder when training deep nets and there is already another version of this library in the works (hint: use 16-bit floats instead of 32!) It’s not hard to imagine Nvidia producing dedicated hardware for the deep learning community in the future if further divergent optimisations are identified..</p><p>Finally, a personal favourite of mine purely from an intuition perspective is <a href="http://arxiv.org/pdf/1410.3916.pdf">Memory Networks</a>. It has low biological plausiblity (or certainly this aspect is not explored in the paper) but high practical application. We can easily imagine a variant of this architecture which learned to access business facts held in SQL / NoSQL databases for example, or to access Prolog-like facts and rules.</p><h3>The commoditisation of Machine Learning</h3><p>Machine Learning has crossed a rubicon of sorts and it is now seen as a must-have for business applications. The traditional applications of speech and computer vision will continue, but ML will also become ubiquitous in POBAs (Plain Old Business Applications). This commoditisation of ML is already happening:</p><ol><li><a href="http://azure.microsoft.com/en-gb/services/machine-learning/">Microsoft (this year)</a></li><li><a href="https://cloud.google.com/prediction/docs">Google (2011, little adoption)</a></li><li><a href="https://aws.amazon.com/blogs/aws/amazon-machine-learning-make-data-driven-decisions-at-scale/">Amazon (this year)</a></li></ol><p>Many smaller services also exist and we can expect to see consolidation over time as winners emerge. For those engineers who want to consume ML locally, there are services such as:</p><p>The bane of ML practitioners is hyperparameter selection (aka the god parameter — the config flag that makes your beautiful neural network work brilliantly or little better than a random guess). In fact, <a href="http://www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf">Bergstra and Bengio demonstrated</a> that randomly guessing hyperparameters is often a “good enough” strategy as algorithms are typically sensitive to just one or two hyperparameters. More recently, Snoek et al <a href="http://papers.nips.cc/paper/4522-practical-bayesian-optimization-of-machine-learning-algorithms.pdf">applied Bayesian priors</a> with Gaussian processes to further refine this approach (I guess I’d call it intelligent randomness plus learning). <a href="https://github.com/HIPS/Spearmint">Spearmint</a> — the implementation built has been spun off into a <a href="https://www.whetlab.com/">startup</a> with a nice <a href="https://www.whetlab.com/docs/getting-started">API</a>. Given that some deep nets take ~two weeks to train, <em>any</em> quicker path to the optimal hyperparameters is advantageous.</p><h3>Future directions in the field</h3><p>It is clear that the software tooling around Machine Learning is pretty immature when compared to the theory. Researchers write and publish papers — not production-strength code. So comparing Machine Learning to other branches of Computer Science (operating systems, networking, data storage, search) shows that a lot of work needs to be done in this area.</p><p>At the risk of inordinate bet-hedging, the next breakthrough will either come from an existing approach (see how popular Long Short Term Memory aka <a href="http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf">LSTM</a> from Schmidhuber and Hochreiter became in 2014 / 2015 after 15 years in the wilderness) or new thinking, probably inspired by a biological construct. Geoffrey Hinton’s <a href="http://techtv.mit.edu/collections/bcs/videos/30698-what-s-wrong-with-convolutional-nets">current work on capsules / manifold learning</a> is a good example of this. It would certainly seem promising for researchers to see what ideas / techniques exist in the literature that were abandoned due to computational intractability which might now be more tractable!</p><p>It is possible that all we have to do is stack networks ever higher (900+ layers deep?) as per the <a href="http://arxiv.org/pdf/1505.00387.pdf">Highway Networks paper from Srivastava, Greff and Schmidhuber</a> to keep advancing but my sense is that there is only so much distance left in the “deep” approach. Anyway, anecdotally six layers appears optimum at present (but <a href="http://arxiv.org/abs/1409.4842">GoogLeNet</a> uses 22 or 27 depending on how you count them).</p><p>It is a little strange that Backpropagation combined with Stochastic Gradient Descent (SGD) is still the best / canonical learning algorithm used. It has certainly stood the test of time since 1986 and is very GPU-friendly. Current research seems focused on network <em>architecture</em> but it seems inevitable that a resurgence in learning algorithms will also take place.</p><p>Most neural nets are trained by a teacher — we reward the net with a low error for good outputs and penalise it for bad outputs. This approach works well enough, but requires nicely-labelled data, often a luxury or simply not possible to attain. Google Deepmind are championing reinforcement learning as a way to develop systems that transfer well across problems (in their <a href="https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf">seminal paper to date</a>, a single neural net learned / generalised enough to play <em>all</em> of the Atari games).</p><p>Finally, it is reasonable to expect a reduction in complexity of neural networks, if not theory then certainly in practice and usage. Using <a href="http://www.cs.toronto.edu/~fritz/absps/cvq.pdf">Minimum Description Length</a> or <a href="http://en.wikipedia.org/wiki/VC_dimension">Vapnik–Chervonenkis dimension</a> as a measure, we are interested in building the simplest, most compact neural network (concretely, with the fewest parameters) to solve a given problem or task. Simpler networks will also train more quickly — a very nice benefit in practice.</p><h3>Recap / summary</h3><p>This ended up being a longer blog post than I intended! Part historical journey, part overview on Machine Learning with a noticeable deep learning bent, it is a more informal literature review than the one I’m currently also writing up for my PhD.</p><p>The pace of innovation in this field is high — there are four / five major conferences each year and each conference brings new announcements and breakthroughs. There is a real confluence of software engineering, fast, scalable hardware and good theories at present.</p><p>Deep learning / neural networks might not be the single unifying theory to bring all of AI together (there are simply too many unknowns and previous failures), but I suspect that it will have a profound influence on the development of AI for at least the next decade.</p><h3>Further reading</h3><p>If you’re still interested in Machine Learning (why would you not be?!) I think it’s fair to say that you simply cannot do enough reading in this field — the foundations are well-established but the frontiers are being pushed and challenged every day. This blog post contains many, many interesting links and in addition to that I would strongly recommend the Reddit ML AMAs from key thought leaders / practitioners in the space if you want to learn more. They are (in no priority order — they all make for excellent, insightful reading):</p><ol><li><a href="http://www.reddit.com/r/MachineLearning/comments/32ihpe/ama_andrew_ng_and_adam_coates/">Andrew Ng and Adam Coates (4/15/2015)</a></li><li><a href="http://www.reddit.com/r/MachineLearning/comments/2xcyrl/i_am_j%C3%BCrgen_schmidhuber_ama/">Jürgen Schmidhuber (3/4/2015)</a></li><li><a href="http://www.reddit.com/r/MachineLearning/comments/2lmo0l/ama_geoffrey_hinton/">Geoffrey Hinton (11/10/2014)</a></li><li><a href="http://www.reddit.com/r/MachineLearning/comments/2fxi6v/ama_michael_i_jordan/">Michael Jordan (9/10/2014)</a></li><li><a href="http://www.reddit.com/r/MachineLearning/comments/25lnbt/ama_yann_lecun/">Yann LeCun (5/15/2014)</a></li><li><a href="http://www.reddit.com/r/MachineLearning/comments/1ysry1/ama_yoshua_bengio/">Yoshua Bengio (2/27/2014)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1101debe0c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deep-learning-and-machine-learning-c1101debe0c">Deep learning and machine learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Differentiable Neural Computers (DNCs) — Nature article thoughts]]></title>
            <link>https://medium.com/data-science/humphrey-sheil-differentiable-neural-computers-dncs-nature-article-thoughts-bd22939c2d97?source=rss-3fa04a4eae53------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd22939c2d97</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Humphrey Sheil]]></dc:creator>
            <pubDate>Tue, 15 Aug 2017 19:12:44 GMT</pubDate>
            <atom:updated>2017-08-15T19:22:04.029Z</atom:updated>
            <content:encoded><![CDATA[<p>17 Oct 2016</p><p>The addition of working memory to artificial neural networks (ANNs) is an obvious upgrade when we compare ANNs to the Von Neumann CPU architecture, and one that came to the fore in the RAM (Reasoning, Attention, Memory) <a href="http://www.thespermwhale.com/jaseweston/ram/">workshop</a> at NIPS last year (which was packed to the rafters). Obvious and building however are two different things..</p><p>The <a href="http://www.nature.com/articles/nature20101.epdf?author_access_token=ImTXBI8aWbYxYQ51Plys8NRgN0jAjWel9jnR3ZoTv0MggmpDmwljGswxVdeocYSurJ3hxupzWuRNeGvvXnoO8o4jTJcnAyhGuZzXJ1GEaD-Z7E6X_a9R-xqJ9TfJWBqz">recent paper from Google Deepmind</a> on Differentiable Neural Computers or DNCs represents another significant step in the journey to add working memory to ANNs, so it’s worth taking a more in-depth look at it.</p><h3>The Times They Are A Changin</h3><p>In homage to the newly-minted <a href="https://www.theguardian.com/music/2016/oct/15/bob-dylan-deserves-nobel-laureate-literature-singular-talent">nobel prize winner</a> Bob Dylan, we use his 1964 classic title to draw attention to the stunning changes reconfiguring the landscape in neural networks at present.</p><p><a href="http://www.movidius.com/">Movidius</a> has been acquired by Intel — their tagline “Visual Sensing for the Internet of Things” gives a clue to their focus — their VPU or Vision Processing Unit which can execute both TensorFlow or Caffe neural network models.</p><p>Intel themselves are <a href="https://twitter.com/soumithchintala/status/786569573365538816">preparing the Linux kernel</a> for new x86 instructions, dedicated to running neural networks on CPUs as opposed to GPUs (Intel has been lagging Nvidia in this area for a long time).</p><p>Nvidia are still the clear hardware leader in terms of adoption and public performance — they have bet big on deep learning and at GTC 2016 this year it was the cornerstone of the conference — from the <a href="https://blogs.nvidia.com/blog/2016/07/11/how-nvidia-built-dgx-1/">DGX-1</a> to the <a href="https://devblogs.nvidia.com/parallelforall/cuda-8-features-revealed/">CUDA 8</a> / <a href="https://developer.nvidia.com/cudnn">cuDNN 5.x</a> releases.</p><p>Finally we know that Google has their own TPUs (Tensor Processing Units) but not much about them, or how they measure up to GPUs or CPUs.</p><p>Simply put, hardware is morphing to run larger neural networks more efficiently, and using less power. Every major software company now has links to academic institutions and are actively working to apply deep learning / neural computing to their platforms and products.</p><p>This level of hardware and software activity in the field of neural computing is completely unprecedented, and shows no sign of abating. How then does the DNC paper play into all of this activity, if at all?</p><h3>Differentiable Neural Computers</h3><p>What then, are DNCs? Breaking down the paper, we get the following key points:</p><ul><li>At its core, a DNC is “just” a recurrent neural network (RNN).</li><li>This RNN however is allowed to read / write / update locations in memory (M) — the RNN stores vectors or tensors of data of size W with M having N rows of size W, so M = N*W.</li><li>The DNC uses <em>differentiable attention</em> to decide where to read from / write to / update existing rows in memory. This is a key point as this now enables well-understood learning algorithms such as Stochastic Gradient Descent (SGD) to be used to train the DNC.</li><li>The memory bank M is associative — the implementation uses cosine similarity so that partial as well as exact matches are supported.</li><li>There is another data structure (named L) which is separate to the memory M. L is used to provide temporal context and links by remembering the order of memory reads and writes. Therefore “L” is simply a linked list which allows the DNC to remember the order in which it read or wrote information to “M”.</li></ul><p>Lastly, I find it intriguing to see the references to cognitive computing / biological plausibility in the papers (not common in this space — a hangover of the connectionism vs computationalism <a href="https://en.wikipedia.org/wiki/Connectionism#Connectionism_vs._computationalism_debate">debate</a> of the 1990s) — multiple references to similarities between the DNC and the hippocampus, or how synapses can encode temporal context and links.</p><p>The following image is taken from the Deepmind blog post and clearly shows the RNN, read and write heads, N*W memory (M) and the linked list encoding temporal associations in M, L.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AWk7d6UMzQvqzIfY.png" /></figure><h3>What about Memory Networks from Weston et al?</h3><p>Weston et al at Facebook have also been working hard in this space. The diagram below is from their June 2016 <a href="https://arxiv.org/abs/1606.03126">Arxiv paper</a> and this paper is the latest in a line of work on memory networks going back to 2014, and perhaps the memory component is inspired / motivated by earlier work on <a href="http://www.thespermwhale.com/jaseweston/papers/wsabie-ijcai.pdf">WSABIE</a>.</p><p>The Nature paper better expounds on the generality of their solution (covering document analysis and understanding, dialogue, graph planning etc.), but this does not necessarily mean that the <em>approach</em> is better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4ZkV7JqVjWPhV4Cf.png" /></figure><h3>Impact and Relevance</h3><p>In my opinion, DNCs / RAM represent the single biggest advance in recurrent architectures since LSTM. The addition of memory, coupled with a well-defined mechanism to differentiate and thus train over it clearly improves the ability of RNNs to perform more complex tasks such as planning, as evidenced in the paper on the <a href="https://research.facebook.com/research/babi/">bAbl dataset</a> or London underground tasks.</p><p>Business applications can make very significant use of DNCs and architectures like them. The ability to plan, or to arrive at a better understanding of large documents has big implications for decision support systems, data analytics, project management and information retrieval. It is not difficult to imagine a DNC plugin for ElasticSearch and Solr for example, or a DNC edition of Microsoft Project Server.</p><p>Couple that software support with a burgeoning native CPU instruction set support for tensor-centric operations coupled with ongoing GPU improvements and TPUs and the future for neural computing is set to grow brighter and brighter.</p><h3>Future work?</h3><p><a href="https://en.wikipedia.org/wiki/SHRDLU">SHRDLU</a> from Winograd is widely regarded as a high point in AI, reached in 1972 and not substantially bettered or replicated since then (<a href="http://icml.cc/2015/tutorials/icml2015-nlu-tutorial.pdf">Liang, ICML 2015 slides 100–105</a>). Does the Mini-SHRDLU block puzzle experiments referenced on page three of the Nature article point to the next substantial research area for Deepmind — to improve on SHRDLU performance from 1972?</p><p><em>Originally published at </em><a href="http://humphreysheil.com/blog/differentiable-neural-computers-dncs-nature-article-thoughts"><em>humphreysheil.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd22939c2d97" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/humphrey-sheil-differentiable-neural-computers-dncs-nature-article-thoughts-bd22939c2d97">Differentiable Neural Computers (DNCs) — Nature article thoughts</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>