<?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 David Wells on Medium]]></title>
        <description><![CDATA[Stories by David Wells on Medium]]></description>
        <link>https://medium.com/@david.arthur.wells?source=rss-1636482b3cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ESB5pwVk5lnsmcpe.jpg</url>
            <title>Stories by David Wells on Medium</title>
            <link>https://medium.com/@david.arthur.wells?source=rss-1636482b3cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:46:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@david.arthur.wells/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[By any means]]></title>
            <link>https://medium.com/@david.arthur.wells/by-any-means-8ffbbb603e93?source=rss-1636482b3cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ffbbb603e93</guid>
            <category><![CDATA[rankings]]></category>
            <category><![CDATA[mean]]></category>
            <dc:creator><![CDATA[David Wells]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 20:48:24 GMT</pubDate>
            <atom:updated>2024-10-13T20:48:24.413Z</atom:updated>
            <content:encoded><![CDATA[<h4>The impact of different averages on rankings</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*BimtaN0szdPqNA8iQLGQTw.png" /><figcaption>Comparison of arithmetic mean, geometric mean, harmonic mean, and Euclidean distance</figcaption></figure><p>When making choices, we usually can’t have everything. For instance we may wish to pick the option that balances quality and cost. To simplify this decision we could rank our options by the average of quality and cost, that way we can rank them based on one number. The average, formally the arithmetic mean, is the most common way to do this but there are other options. In this post we’ll compare different ways to combine two (or more) metrics and what impact our choice makes.</p><p>Here we have our example dataset and we want to rank each point. Larger values of x and y should lead to a higher ranking. It’s obvious which point is first, it’s up in the top right corner. But which of the next two should be 2nd? Or of the next set of three, 4th? This is where combining the x and y values makes rankings much easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Pg839jJ3eECiXaK-sBayQQ.png" /></figure><p>We’ll compare the arithmetic mean (which is what we usually think of when we say “average”) with two other flavours of mean: geometric and harmonic. We’ll also look at the Euclidean distance (a.k.a. L2-norm). Fortunately, there are simple functions for all of these as they are common mathematical operations.</p><pre># Function to make a coloured grid<br>def make_grid(minimum, maximum, func):<br>    x = y = np.arange(minimum, maximum)<br>    z = [func([i,j]) for j in y for i in x]<br>    Z = np.array(z).reshape(len(x), -1)<br>    return Z<br><br># The functions to combine x and y<br>rankers = {<br>    &#39;Mean&#39;: np.mean,<br>    &#39;Geometric mean&#39;: gmean,<br>    &#39;Harmonic mean&#39;: hmean,<br>    &#39;Euclidean&#39;: np.linalg.norm<br>}<br><br># Calculate and plot grid for each function<br>levels = 10<br>for name, f in rankers.items():<br>    fig,ax = plt.subplots()<br>    Z = make_grid(0, 100, f)<br>    ax.contourf(Z, cmap=&quot;plasma&quot;, levels=levels)<br>    ax.scatter([50, 75], [50, 25], c=[&quot;black&quot;, &quot;white&quot;])<br>    ax.set_title(name)<br>    ax.set_box_aspect(1)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*R29XEpP4IQI1mfpEXWXd9g.png" /></figure><p>In these plots the back ground colour indicates the combined score of any point in the x, y plot. Yellow is a high score, blue is a low score. Regions of the same colour have the same score. In each plot the black point is 50,50 and the white point is 75,25. For the arithmetic mean the increase in x is exactly offset by the equal decrease in y; both points have the same combined score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*UGAXlPIko37k720SV9fCBA.png" /></figure><p>For the geometric mean the increase in x is not enough to account for the decreases in y (even though both values are changed by the same amount). This means that points with similar values for x and y are preferred over those biased to x or y. So using the geometric mean to rank points will select those that score highly in both metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*sqcULcUr7u_laLJ5U2f46Q.png" /></figure><p>The harmonic mean is similar to the geometric mean but with a more extreme bias in favour of scoring well in both metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*S0YcpGISdFr3jADy1xzKrQ.png" /></figure><p>The Euclidean distance does the opposite to the geometric and harmonic means, it prefers points that are all one score or the other. You can see that increasing x by 25 more than makes up for the decrease in y (also of 25) as the white point has a higher rank.</p><pre>gc[&#39;Mean&#39;] = gc[[&#39;new_cases_perc&#39;,&#39;deaths_perc&#39;]].apply(np.mean, axis=1)<br>gc[&#39;Geometric mean&#39;] = gc[[&#39;new_cases_perc&#39;,&#39;deaths_perc&#39;]].apply(gmean, axis=1)<br>gc[&#39;Harmonic mean&#39;] = gc[[&#39;new_cases_perc&#39;,&#39;deaths_perc&#39;]].apply(hmean, axis=1)<br>gc[&#39;Euclidean&#39;] = gc[[&#39;new_cases_perc&#39;,&#39;deaths_perc&#39;]].apply(np.linalg.norm, axis=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*5VJnE2oFCCRQHmtBZyildg.png" /></figure><p>So, how should you rank your options? The geometric and harmonic means are good if you want your best ranked options to score well in multiple categories. These means are also less sensitive to extreme values than the traditional mean. The Euclidean distance is good for the opposite, you want an option which specialises in a few scores. The traditional mean is good if you don’t care how it gets its points. The traditional mean is also easiest to explain!</p><p>Hopefully this gives you a bit of insight into what these different means are actually doing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ffbbb603e93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring cancer types with neo4j]]></title>
            <link>https://medium.com/data-science/exploring-cancer-types-with-neo4j-43acf161362f?source=rss-1636482b3cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/43acf161362f</guid>
            <category><![CDATA[graph-database]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[David Wells]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 14:42:48 GMT</pubDate>
            <atom:updated>2024-08-17T14:42:48.181Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to identify and visualise clusters in knowledge graphs</h4><p>In this post we’ll identify and visualise different clusters of cancer types by analysing <a href="https://disease-ontology.org/">disease ontology</a> as a knowledge graph. Specifically we’ll set up neo4j in a docker container, import the ontology, generate graph clusters and embeddings, before using dimension reduction to plot these clusters and derive some insights. Although we’re using `disease_ontology` as an example, the same steps can be used to explore any ontology or graph database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*cyPXbMwIchXgN4RNND-cuA.png" /><figcaption>Cancer types viewed as embeddings and coloured by cluster, image by author</figcaption></figure><h3>Ontology set up</h3><p>In a graph database, rather than storing data as rows (like a spreadsheet or relational database) data is stored as nodes and relationships between nodes. For example in the figure below we see that melanoma and carcinoma are SubCategories Of cell type cancer tumour (shown by the SCO relationship). With this kind of data we can clearly see that melanoma and carcinoma are related even though this is not explicitly stated in the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/0*gxmEb9fGdrGnhzUG" /><figcaption>Graph database example, image by author</figcaption></figure><p>Ontologies are a formalised set of concepts and relationships between those concepts. They are much easier for computers to parse than free text and therefore easier to extract meaning from. Ontologies are widely used in biological sciences and you may find an ontology you’re interested in at<a href="https://obofoundry.org/"> https://obofoundry.org/</a>. Here we’re focusing on the disease ontology which shows how different types of diseases relate to each other.</p><p>Neo4j is a tool for managing, querying and analysing graph databases. To make it easier to set up we’ll use a docker container.</p><pre>docker run \<br> -it - rm \<br> - publish=7474:7474 - publish=7687:7687 \<br> - env NEO4J_AUTH=neo4j/123456789 \<br> - env NEO4J_PLUGINS=&#39;[&quot;graph-data-science&quot;,&quot;apoc&quot;,&quot;n10s&quot;]&#39; \<br> neo4j:5.17.0</pre><p>In the above command the `-publish` flags set ports to let python query the database directly and let us access it through a browser. The `NEO4J_PLUGINS` argument specifies which plugins to install. Unfortunately, the windows docker image doesn’t seem to be able to handle the installation, so to follow along you’ll need to install neo4j desktop manually. Don’t worry though, the other steps should all still work for you.</p><p>While neo4j is running you can access your database by going to http://localhost:7474/ in your browser, or you can use the python driver to connect as below. Note that we’re using the port we published with our docker command above and we’re authenticating with the username and password we also defined above.</p><pre>URI = &quot;bolt://localhost:7687&quot;<br>AUTH = (&quot;neo4j&quot;, &quot;123456789&quot;)<br>driver = GraphDatabase.driver(URI, auth=AUTH)<br>driver.verify_connectivity()</pre><p>Once you have your neo4j database set up, it’s time to get some data. The neo4j plug-in n10s is built to import and handle ontologies; you can use it to embed your data into an existing ontology or to explore the ontology itself. With the cypher commands below we first set some configs to make the results cleaner, then we set up a uniqueness constraint, finally we actually import disease ontology.</p><pre>CALL n10s.graphconfig.init({ handleVocabUris: &quot;IGNORE&quot; });<br>CREATE CONSTRAINT n10s_unique_uri FOR (r:Resource) REQUIRE r.uri IS UNIQUE;<br>CALL n10s.onto.import.fetch(http://purl.obolibrary.org/obo/doid.owl, RDF/XML);</pre><p>To see how this can be done with the python driver, check out the full code here <a href="https://github.com/DAWells/do_onto/blob/main/import_ontology.py">https://github.com/DAWells/do_onto/blob/main/import_ontology.py</a></p><p>Now that we’ve imported the ontology you can explore it by opening http://localhost:7474/ in your web browser. This lets you explore a little of your ontology manually, but we’re interested in the bigger picture so lets do some analysis. Specifically we will do Louvain clustering and generate fast random projection embeddings.</p><h3>Clusters and embeddings</h3><p>Louvain clustering is a clustering algorithm for networks like this. In short, it identifies sets of nodes that are more connected to each other than they are to the wider set of nodes; this set is then defined as a cluster. When applied to an ontology it is a fast way to identify a set of related concepts. Fast random projection on the other hand produces an embedding for each node, i.e. a numeric vector where more similar nodes have more similar vectors. With these tools we can identify which diseases are similar and quantify that similarity.</p><p>To generate embeddings and clusters we have to “project” the parts of our graph that we are interested in. Because ontologies are typically very large, this subsetting is a simple way to speed up computation and avoid memory errors. In this example we are only interested in cancers and not any other type of disease. We do this with the cypher query below; we match the node with the label “cancer” and any node that is related to this by one or more SCO or SCO_RESTRICTION relationships. Because we want to include the relationships between cancer types we have a second MATCH query that returns the connected cancer nodes and their relationships.</p><pre>MATCH (cancer:Class {label:&quot;cancer&quot;})&lt;-[:SCO|SCO_RESTRICTION *1..]-(n:Class)<br>WITH n<br>MATCH (n)-[:SCO|SCO_RESTRICTION]-&gt;(m:Class)<br>WITH gds.graph.project(<br>    &quot;proj&quot;, n, m, {}, {undirectedRelationshipTypes: [&#39;*&#39;]}<br>) AS g<br>RETURN g.graphName AS graph, g.nodeCount AS nodes, g.relationshipCount AS rels</pre><p>Once we have the projection (which we have called “proj”) we can calculate the clusters and embeddings and write them back to the original graph. Finally by querying the graph we can get the new embeddings and clusters for each cancer type which we can export to a csv file.</p><pre>CALL gds.fastRP.write(<br>  &#39;proj&#39;,<br>  {embeddingDimension: 128, randomSeed: 42, writeProperty: &#39;embedding&#39;}<br>) YIELD nodePropertiesWritten<br><br>CALL gds.louvain.write(<br>  &quot;proj&quot;,<br>  {writeProperty: &quot;louvain&quot;}<br>) YIELD communityCount<br><br>MATCH (cancer:Class {label:&quot;cancer&quot;})&lt;-[:SCO|SCO_RESTRICTION *0..]-(n)<br>RETURN DISTINCT<br>  n.label as label,<br>  n.embedding as embedding,<br>  n.louvain as louvain</pre><h3>Results</h3><p>Let’s have a look at some of these clusters to see which type of cancers are grouped together. After we’ve loaded the exported data into a pandas dataframe in python we can inspect individual clusters.</p><p>Cluster 2168 is a set of pancreatic cancers.</p><pre>nodes[nodes.louvain == 2168][&quot;label&quot;].tolist()<br>#array([&#39;&quot;islet cell tumor&quot;&#39;,<br>#       &#39;&quot;non-functioning pancreatic endocrine tumor&quot;&#39;,<br>#       &#39;&quot;pancreatic ACTH hormone producing tumor&quot;&#39;,<br>#       &#39;&quot;pancreatic somatostatinoma&quot;&#39;,<br>#       &#39;&quot;pancreatic vasoactive intestinal peptide producing tumor&quot;&#39;,<br>#       &#39;&quot;pancreatic gastrinoma&quot;&#39;, &#39;&quot;pancreatic delta cell neoplasm&quot;&#39;,<br>#       &#39;&quot;pancreatic endocrine carcinoma&quot;&#39;,<br>#       &#39;&quot;pancreatic non-functioning delta cell tumor&quot;&#39;], dtype=object)</pre><p>Cluster 174 is a larger group of cancers but mostly carcinomas.</p><pre>nodes[nodes.louvain == 174][&quot;label&quot;]<br>#array([&#39;&quot;head and neck cancer&quot;&#39;, &#39;&quot;glottis carcinoma&quot;&#39;,<br>#       &#39;&quot;head and neck carcinoma&quot;&#39;, &#39;&quot;squamous cell carcinoma&quot;&#39;,<br>#...<br>#       &#39;&quot;pancreatic squamous cell carcinoma&quot;&#39;,<br>#       &#39;&quot;pancreatic adenosquamous carcinoma&quot;&#39;,<br>#...<br>#       &#39;&quot;mixed epithelial/mesenchymal metaplastic breast carcinoma&quot;&#39;,<br>#       &#39;&quot;breast mucoepidermoid carcinoma&quot;&#39;], dtype=object)p</pre><p>These are sensible groupings, based on either organ or cancer type, and will be useful for visualisation. The embeddings on the other hand are still too high dimensional to be visualised meaningfully. Fortunately, TSNE is a very useful method for dimension reduction. Here, we use TSNE to reduce the embedding from 128 dimensions down to 2, while still keeping closely related nodes close together. We can verify that this has worked by plotting these two dimensions as a scatter plot and colouring by the Louvain clusters. If these two methods agree we should see nodes clustering by colour.</p><pre>from sklearn.manifold import TSNE<br><br>nodes = pd.read_csv(&quot;export.csv&quot;)<br>nodes[&#39;louvain&#39;] = pd.Categorical(nodes.louvain)<br><br>embedding = nodes.embedding.apply(lambda x: ast.literal_eval(x))<br>embedding = embedding.tolist()<br>embedding = pd.DataFrame(embedding)<br><br>tsne = TSNE()<br>X = tsne.fit_transform(embedding)<br><br>fig, axes = plt.subplots()<br>axes.scatter(<br>    X[:,0],<br>    X[:,1],<br>    c  = cm.tab20(Normalize()(nodes[&#39;louvain&#39;].cat.codes))<br>)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*DPhPuCOxKdYOSyVA" /><figcaption>TSNE projection of Cancer embeddings coloured by cluster, image by author</figcaption></figure><p>Which is exactly what we see, similar types of cancer are grouped together and visible as clusters of a single colour. Note that some nodes of a single colour are very far apart, this is because we’re having to reuse some colours as there are 29 clusters and only 20 colours. This gives us a great overview of the structure of our knowledge graph, but we can also add our own data.</p><p>Below we plot the frequency of cancer type as node size and the mortality rate as the opacity (<a href="https://doi.org/10.3322/caac.21834">Bray et al 2024</a>). I only had access to this data for a few of the cancer types so I’ve only plotted those nodes. Below we can see that liver cancer does not have an especially high incidence over all. However, incidence rates of liver cancer are much higher than other cancers within its cluster (shown in purple) like oropharynx, larynx, and nasopharynx.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/0*3mTZ8_1FBGM4T9Z7" /><figcaption>Frequency and mortality of cancers coloured by cluster, image by author</figcaption></figure><h3>Conclusions</h3><p>Here we have used the disease ontology to group different cancers into clusters which gives us the context to compare these diseases. Hopefully this little project has shown you how to visually explore an ontology and add that information to your own data.</p><p>You can check out the full code for this project at <a href="https://github.com/DAWells/do_onto">https://github.com/DAWells/do_onto</a>.</p><h3>References</h3><blockquote>Bray, F., Laversanne, M., Sung, H., Ferlay, J., Siegel, R. L., Soerjomataram, I., &amp; Jemal, A. (2024). Global cancer statistics 2022: GLOBOCAN estimates of incidence and mortality worldwide for 36 cancers in 185 countries. CA: a cancer journal for clinicians, 74(3), 229–263.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43acf161362f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/exploring-cancer-types-with-neo4j-43acf161362f">Exploring cancer types with neo4j</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>