<?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 Dor Bernsohn on Medium]]></title>
        <description><![CDATA[Stories by Dor Bernsohn on Medium]]></description>
        <link>https://medium.com/@dorbernsohn?source=rss-d99af427a932------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oGj1HZOrJ3EW2dY_C-i0uw.jpeg</url>
            <title>Stories by Dor Bernsohn on Medium</title>
            <link>https://medium.com/@dorbernsohn?source=rss-d99af427a932------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:37:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dorbernsohn/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[Exploring Graph Neural Networks (GNN) — Applications in Python Package Analysis]]></title>
            <link>https://medium.com/@dorbernsohn/exploring-graph-neural-networks-gnn-applications-in-python-package-analysis-dc9f6d1e0be5?source=rss-d99af427a932------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc9f6d1e0be5</guid>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Dor Bernsohn]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 06:25:17 GMT</pubDate>
            <atom:updated>2024-06-25T09:42:20.780Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Graph Neural Networks (GNN) — Applications in Python Package Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPDhLCSP33wPLXnfz6bohQ.png" /></figure><h3>Introduction to Graph Neural Networks (GNN)</h3><p>Graph Neural Networks (GNN) represent a significant advancement in the field of machine learning and data science, particularly for data structured in graph form. They have gained popularity for their ability to model complex relationships and interdependencies within data. This post delves into the intricacies of GNNs, focusing on their application in Python package analysis — a domain where dependencies and interconnections are abundant.</p><h4>Core Concepts of GNN</h4><p>GNNs are distinct from traditional neural networks due to their ability to process graph structures directly. This is crucial in scenarios where data points (nodes) have explicit relationships (edges), as in social networks, biochemical structures, or software packages.</p><p>GNNs operate by aggregating information from a node’s neighbors, iteratively updating their representations. This process allows GNNs to capture both local structures and global graph properties, making them highly effective for tasks like node classification, link prediction, and graph classification.</p><h4>Types of GNN Task</h4><p>GNNs can be categorized based on the level at which they operate:</p><ol><li><strong>Node Classification:</strong> This task involves predicting properties or classes of individual nodes. For instance, in a social network, it might involve classifying users based on their activities or connections.</li><li><strong>Edge Classification:</strong> Here, the goal is to predict properties or the existence of edges between nodes. In recommendation systems, this could mean predicting whether a user would like a particular item.</li><li><strong>Graph Classification:</strong> This involves understanding and predicting properties of entire graphs. In chemical informatics, this might mean predicting the properties of a molecule.</li></ol><h4>Mathematics Behind GNN</h4><p>GNNs use a process known as ‘message passing’, where nodes aggregate and transform feature information from their neighbors. This iterative process allows nodes to gather information from a broader neighborhood over successive layers.</p><p>Mathematically, this can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*Q_N4j4erAeiMnE4s-Hgj4w.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*ZjSaKaYmDKlYNepWwnL7Mw.png" /></figure><h3>Application: Python Package Analysis</h3><p>In the experiment, we used GNNs to map the complex landscape of Python packages, where packages are nodes, and their dependencies form the edges.</p><h4>Data Collection and Preprocessing</h4><p>The first step was to gather data on Python packages from the Python Package Index (PyPI). We then preprocessed this data to construct a graph where nodes represent individual packages and edges represent dependencies between them.</p><pre>def fetch_package_data() -&gt; List[Dict[str, Any]]:<br>    &quot;&quot;&quot;<br>    Fetches package data from PyPI.<br><br>    Returns:<br>        List[Dict[str, Any]]: A list of dictionaries containing package information.<br>    &quot;&quot;&quot;<br>    package_list = []<br>    BASE_URL = (<br>        &quot;https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3&amp;page=&quot;<br>    )<br>    DEPENDANCY_URL = &quot;https://pypi.org/pypi/{}/json&quot;<br><br>    for i in tqdm(range(0, 502)):<br>        try:<br>            fp = urllib.request.urlopen(BASE_URL + str(i))<br>        except urllib.error.HTTPError as err:<br>            print(f&quot;\n{BASE_URL + str(i)}, {err}&quot;)<br>            break<br><br>        mybytes = fp.read()<br>        mystr = mybytes.decode(&quot;utf8&quot;)<br>        fp.close()<br>        soup = BeautifulSoup(mystr, &quot;html.parser&quot;)<br>        items = soup.findAll(&quot;a&quot;, {&quot;class&quot;: &quot;package-snippet&quot;})<br><br>        for child_soup in items:<br>            package_name = child_soup.find(<br>                &quot;span&quot;, {&quot;class&quot;: &quot;package-snippet__name&quot;}<br>            ).get_text()<br>            description = child_soup.find(<br>                &quot;p&quot;, {&quot;class&quot;: &quot;package-snippet__description&quot;}<br>            ).get_text()<br>            json = requests.get(DEPENDANCY_URL.format(package_name)).json()<br><br>            if &quot;message&quot; in json and json[&quot;message&quot;].lower() == &quot;not found&quot;:<br>                continue<br><br>            dependancies = (<br>                [re.split(&quot;[^a-zA-Z-_]&quot;, x)[0] for x in json[&quot;info&quot;][&quot;requires_dist&quot;]]<br>                if json[&quot;info&quot;][&quot;requires_dist&quot;]<br>                else []<br>            )<br><br>            package_list.append(<br>                {<br>                    &quot;name&quot;: package_name,<br>                    &quot;description&quot;: description,<br>                    &quot;dependancies&quot;: dependancies,<br>                    &quot;topic&quot;: [<br>                        x.split(&quot;::&quot;)[1].strip()<br>                        for x in json[&quot;info&quot;][&quot;classifiers&quot;]<br>                        if x.lower().startswith(&quot;topic&quot;)<br>                    ],<br>                    &quot;intended audience&quot;: [<br>                        x.split(&quot;::&quot;)[-1].strip()<br>                        for x in json[&quot;info&quot;][&quot;classifiers&quot;]<br>                        if x.lower().startswith(&quot;intended audience&quot;)<br>                    ],<br>                }<br>            )<br><br>    return package_list</pre><p>This process involved extracting package metadata, including descriptions and lists of dependencies, which served as the foundation for our graph.</p><h4>Model Architecture</h4><p>We designed a GNN model with several Graph Convolutional Network (GCN) layers, suitable for node classification tasks. The GCN layers enable the model to learn node representations by aggregating information from their neighbors.</p><pre>class GNN(torch.nn.Module):<br>    &quot;&quot;&quot;<br>    Graph Neural Network model using GCNConv layers.<br><br>    Args:<br>        hidden_channels (int): Number of hidden channels.<br>        num_topics (int): Number of topics.<br>        num_audiences (int): Number of audiences.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, hidden_channels: int, num_topics: int, num_audiences: int):<br>        super(GNN, self).__init__()<br>        self.conv1 = GCNConv(768, hidden_channels)<br>        self.conv2 = GCNConv(hidden_channels, hidden_channels)<br>        self.out_topic = torch.nn.Linear(hidden_channels, num_topics)<br>        self.out_audience = torch.nn.Linear(hidden_channels, num_audiences)<br><br>    def forward(<br>        self, x: torch.Tensor, edge_index: torch.Tensor<br>    ) -&gt; Tuple[torch.Tensor, torch.Tensor]:<br>        &quot;&quot;&quot;<br>        Forward pass of the GNN.<br><br>        Args:<br>            x (torch.Tensor): Node feature matrix.<br>            edge_index (torch.Tensor): Graph edge index.<br><br>        Returns:<br>            Tuple[torch.Tensor, torch.Tensor]: Topic and audience output tensors.<br>        &quot;&quot;&quot;<br>        x = self.conv1(x, edge_index)<br>        x = F.relu(x)<br>        x = self.conv2(x, edge_index)<br>        x = F.relu(x)<br>        return self.out_topic(x), self.out_audience(x)</pre><p>The model aimed to classify nodes (packages) based on features derived from their descriptions and dependency relationships.</p><h4>Training and Optimization</h4><p>I trained our GNN model using a dataset split into training, validation, and test sets. The training process involved optimizing a loss function that measured the accuracy of our model’s predictions against known classifications.</p><pre>def train_gnn(<br>    global_data: Data, num_topics: int, num_audiences: int, num_epochs: int = 100<br>) -&gt; GNN:<br>    &quot;&quot;&quot;<br>    Trains a Graph Neural Network (GNN) using the provided global data.<br><br>    Parameters:<br>    - global_data (Data): Graph data object containing node features, edge indices, and topic and audience labels.<br>    - num_topics (int): Number of unique topics.<br>    - num_audiences (int): Number of unique intended audiences.<br>    - num_epochs (int, optional): Number of training epochs. Default is 100.<br><br>    Returns:<br>    GNN: Trained GNN model.<br>    &quot;&quot;&quot;<br>    device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>    gnn_model = GNN(<br>        hidden_channels=128, num_topics=num_topics, num_audiences=num_audiences<br>    ).to(device)<br>    optimizer = Adam(gnn_model.parameters(), lr=0.01)<br>    criterion = BCEWithLogitsLoss()<br><br>    global_data = global_data.to(device)<br><br>    for epoch in range(num_epochs):<br>        optimizer.zero_grad()<br>        out_topic, out_audience = gnn_model(global_data.x, global_data.edge_index)<br><br>        loss_topic = criterion(<br>            out_topic[global_data.train_mask],<br>            global_data.y_topic[global_data.train_mask],<br>        )<br>        loss_audience = criterion(<br>            out_audience[global_data.train_mask],<br>            global_data.y_audience[global_data.train_mask],<br>        )<br><br>        loss = loss_topic + loss_audience<br>        loss.backward()<br>        optimizer.step()<br><br>    return gnn_model</pre><p>I also employed techniques like dropout and regularization to prevent overfitting and enhance the model’s generalization capabilities.</p><h4>Model Evaluation</h4><p>After training, i evaluated the model’s performance on unseen data. We used metrics such as accuracy, precision, and recall to assess how well our model could classify packages based on their dependencies.</p><pre>def evaluate_model(model, data: Data) -&gt; None:<br>    &quot;&quot;&quot;<br>    Evaluate a GNN model on the given data.<br><br>    Parameters:<br>    - model: The trained GNN model.<br>    - data (Data): Graph data object containing node features, edge indices, and topic and audience labels.<br><br>    Returns:<br>    None<br>    &quot;&quot;&quot;<br>    model.eval()<br>    with torch.no_grad():<br>        out_topic, out_audience = model(data.x, data.edge_index)<br><br>        # Convert the logits to probabilities<br>        out_topic_prob = torch.sigmoid(out_topic)<br>        out_audience_prob = torch.sigmoid(out_audience)<br><br>        # Convert probabilities to binary predictions<br>        out_topic_pred = (out_topic_prob &gt; 0.5).float()<br>        out_audience_pred = (out_audience_prob &gt; 0.5).float()<br><br>        # Compute accuracy and F1-score for &#39;topic&#39;<br>        acc_topic = accuracy_score(<br>            data.y_topic[data.test_mask].cpu(), out_topic_pred[data.test_mask].cpu()<br>        )<br>        f1_topic = f1_score(<br>            data.y_topic[data.test_mask].cpu(),<br>            out_topic_pred[data.test_mask].cpu(),<br>            average=&quot;micro&quot;,<br>        )<br><br>        # Compute accuracy and F1-score for &#39;audience&#39;<br>        acc_audience = accuracy_score(<br>            data.y_audience[data.test_mask].cpu(),<br>            out_audience_pred[data.test_mask].cpu(),<br>        )<br>        f1_audience = f1_score(<br>            data.y_audience[data.test_mask].cpu(),<br>            out_audience_pred[data.test_mask].cpu(),<br>            average=&quot;micro&quot;,<br>        )<br><br>        print(f&quot;Topic - Accuracy: {acc_topic}, F1-score: {f1_topic}&quot;)<br>        print(f&quot;Audience - Accuracy: {acc_audience}, F1-score: {f1_audience}&quot;)</pre><h4>Insights and Visualization</h4><p>To gain insights from our model, we visualized the graph, highlighting the intricate web of dependencies among Python packages. This visualization helped us understand community structures and key nodes (packages) within the graph.</p><pre>def plot_graph(edge_index, package_list: List[Dict[str, str]]) -&gt; None:<br>    &quot;&quot;&quot;<br>    Plot a graph using NetworkX and Plotly with the given edge index and package list.<br><br>    Parameters:<br>    - edge_index: Edge indices of the graph.<br>    - package_list (List[Dict[str, str]]): List of dictionaries representing packages, each containing &#39;name&#39;.<br><br>    Returns:<br>    None<br>    &quot;&quot;&quot;<br>    G = nx.Graph()<br>    edge_list = edge_index.t().tolist()<br>    G.add_edges_from(edge_list)<br><br>    # Create a mapping of node indices to package names<br>    index_to_package = {<br>        idx: package[&quot;name&quot;] for idx, package in enumerate(package_list)<br>    }<br><br>    # Get positions for the nodes in G<br>    pos = nx.spring_layout(G)<br><br>    # Extract x and y coordinates<br>    x_nodes = [pos[k][0] for k in G.nodes()]<br>    y_nodes = [pos[k][1] for k in G.nodes()]<br><br>    # Create edges<br>    edge_x = []<br>    edge_y = []<br>    for edge in edge_list:<br>        x0, y0 = pos[edge[0]]<br>        x1, y1 = pos[edge[1]]<br>        edge_x.extend([x0, x1, None])<br>        edge_y.extend([y0, y1, None])<br><br>    # Create edge trace<br>    edge_trace = go.Scatter(<br>        x=edge_x,<br>        y=edge_y,<br>        line=dict(width=0.5, color=&quot;#888&quot;),<br>        hoverinfo=&quot;none&quot;,<br>        mode=&quot;lines&quot;,<br>    )<br><br>    # Create node trace<br>    node_trace = go.Scatter(<br>        x=x_nodes,<br>        y=y_nodes,<br>        mode=&quot;markers+text&quot;,<br>        hoverinfo=&quot;text&quot;,<br>        marker=dict(<br>            showscale=True,<br>            size=10,<br>            colorbar=dict(<br>                thickness=15,<br>                title=&quot;Node Connections&quot;,<br>                xanchor=&quot;left&quot;,<br>                titleside=&quot;right&quot;,<br>            ),<br>        ),<br>        text=[index_to_package[i] for i in range(len(pos))],<br>        textposition=&quot;top center&quot;,<br>    )<br><br>    # Create the figure<br>    fig = go.Figure(<br>        data=[edge_trace, node_trace],<br>        layout=go.Layout(<br>            showlegend=False,<br>            hovermode=&quot;closest&quot;,<br>            margin=dict(b=0, l=0, r=0, t=0),<br>            xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),<br>            yaxis=dict(showgrid=False, zeroline=False, showticklabels=False),<br>        ),<br>    )<br>    fig.write_html(&quot;pypi.html&quot;)<br>    fig.show()</pre><p><a href="https://html-preview.github.io/?url=https://github.com/DorBernsohn/pypi-dep-classification-gnn/blob/main/pypi.html">https://html-preview.github.io/?url=https://github.com/DorBernsohn/pypi-dep-classification-gnn/blob/main/pypi.html</a></p><h3>Conclusion</h3><p>Through this comprehensive exploration, I’ve seen how GNNs can effectively model and analyze graph-structured data. The application in Python package analysis highlights the potential of GNNs in extracting meaningful insights from complex, interconnected data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc9f6d1e0be5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Correlation: A Deep Dive into Essential Methods for Data Scientists]]></title>
            <link>https://medium.com/@dorbernsohn/understanding-correlation-a-deep-dive-into-essential-methods-for-data-scientists-640a840f9a2a?source=rss-d99af427a932------2</link>
            <guid isPermaLink="false">https://medium.com/p/640a840f9a2a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[correlation]]></category>
            <dc:creator><![CDATA[Dor Bernsohn]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 16:42:31 GMT</pubDate>
            <atom:updated>2024-06-18T16:42:31.832Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aUAJEbyxr0BpLI5V" /></figure><h3>Intro</h3><p>As a data scientist, correlation is a fundamental concept that is used to understand the relationship between two or more variables. Correlation analysis is a statistical method that measures the strength of the relationship between two variables and the direction of this relationship. It is an important tool for exploring relationships between variables in large datasets and helps data scientists to identify trends, patterns, and relationships that may be hidden within the data.</p><p>There are many different methods for calculating correlation, each with its own strengths and weaknesses. In this review, we will take a closer look at some of the most commonly used correlation methods. We will discuss the mathematical foundations of each method, its strengths and weaknesses, and the appropriate use cases for each method.</p><h3>Pearson’s Correlation Coefficient</h3><p>Pearson’s Correlation Coefficient is a measure of the linear association between two continuous variables. It measures the strength and direction of a linear relationship between two variables.</p><p>A data scientist might use Pearson’s Correlation Coefficient to determine whether a relationship exists between two variables and, if so, the nature of that relationship. For example, one might want to determine if there is a relationship between the height and weight of a population.</p><p>The Pearson’s Correlation Coefficient ranges from -1 to 1, where values close to 1 indicate a strong positive linear relationship between the variables, values close to -1 indicate a strong negative linear relationship, and values close to 0 indicate no linear relationship.</p><p>It’s important to note that Pearson’s Correlation Coefficient assumes that the relationship between the variables is linear. If the relationship is not linear, the coefficient may not accurately reflect the true relationship between the variables. In such cases, other correlation measures, such as Spearman’s Rank Correlation Coefficient, should be used.</p><p>Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*S4T9bS3hPWD7r0ZGL6bGaQ.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*eCNupIIm2XhmgpVzR48L-w.png" /></figure><pre>import numpy as np<br>from scipy import stats<br>import matplotlib.pyplot as plt<br><br>method_name = &quot;Pearson&#39;s Correlation Coefficient&quot;<br><br>fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 10))<br><br># Generate linear data<br>np.random.seed(0)<br>x = np.random.normal(0, 1, 100)<br>y = x + np.random.normal(0, 0.5, 100)<br><br># Calculate Pearson&#39;s Correlation Coefficient for linear data<br>correlation, p = stats.pearsonr(x, y)<br><br># Plot linear data<br>axes[0].scatter(x, y)<br>axes[0].set_xlabel(&#39;x&#39;)<br>axes[0].set_ylabel(&#39;y&#39;)<br>axes[0].set_title(f&quot;Linear Data Correlation: {correlation:.2f}&quot;)<br><br># Generate non-linear data<br>x = np.random.normal(0, 1, 100)<br>y = x**2 + np.random.normal(0, 0.5, 100)<br><br># Calculate Pearson&#39;s Correlation Coefficient for non-linear data<br>correlation, p = stats.pearsonr(x, y)<br><br># Plot non-linear data<br>axes[1].scatter(x, y)<br>axes[1].set_xlabel(&#39;x&#39;)<br>axes[1].set_ylabel(&#39;y&#39;)<br>axes[1].set_title(f&quot;Non-Linear Data Correlation: {correlation:.2f}&quot;)<br><br>x = np.linspace(1, 100, 100)<br>y = np.log(x) + np.random.normal(0, 0.1, 100)<br><br># Calculate Pearson&#39;s Correlation Coefficient for non-linear data<br>correlation, p = stats.pearsonr(x, y)<br><br># Plot non-linear data<br>axes[2].scatter(x, y)<br>axes[2].set_xlabel(&#39;x&#39;)<br>axes[2].set_ylabel(&#39;y&#39;)<br>axes[2].set_title(f&quot;Non-Linear Data Correlation: {correlation:.2f}&quot;)<br><br>fig.suptitle(method_name, fontsize=16)<br>fig.tight_layout()<br>fig.subplots_adjust(top=0.88)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTPG0o_gwF37_HkRi0GqJg.png" /></figure><h3>Spearman’s Rank Correlation Coefficient</h3><p>Spearman’s Rank Correlation Coefficient is a measure of the monotonic association between two continuous or ordinal variables. It measures the strength and direction of a monotonic relationship between two variables.</p><p>A data scientist might use Spearman’s Rank Correlation Coefficient when they want to determine if there is a relationship between two variables, but the relationship is not necessarily linear. For example, One might want to determine if there is a relationship between IQ scores and test performance, where a high IQ score might result in higher test performance, but the relationship between the two variables may not be linear.</p><p>Spearman’s Rank Correlation Coefficient is calculated based on the rankings of the two variables, rather than their actual values. This makes it well-suited for data that may not have a linear relationship, but still has a monotonic relationship (i.e. the variables increase or decrease together, but not necessarily at a constant rate).</p><p>The Spearman’s Rank Correlation Coefficient ranges from -1 to 1, where values close to 1 indicate a strong positive monotonic relationship between the variables, values close to -1 indicate a strong negative monotonic relationship, and values close to 0 indicate no monotonic relationship.</p><p>It is a useful alternative to Pearson’s Correlation Coefficient when the relationship between the variables is not linear.</p><p>Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*MTVTceuSwt7TjjTLJR932w.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*xRn4mlbcrXesW4cuWCHA7w.png" /></figure><pre>import numpy as np<br>from scipy import stats<br>import matplotlib.pyplot as plt<br><br>method_name = &quot;Spearman&#39;s Rank Correlation Coefficient&quot;<br><br>fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 5))<br><br># Generate linear data<br>np.random.seed(0)<br>x = np.random.normal(0, 1, 100)<br>y = x + np.random.normal(0, 0.5, 100)<br><br># Calculate Spearman&#39;s Rank Correlation Coefficient for linear data<br>correlation, p = stats.spearmanr(x, y)<br><br># Plot linear data<br>axes[0].scatter(x, y)<br>axes[0].set_xlabel(&#39;x&#39;)<br>axes[0].set_ylabel(&#39;y&#39;)<br>axes[0].set_title(f&quot;Linear Data Correlation: {correlation:.2f}&quot;)<br><br># Generate non-linear data<br>x = np.random.normal(0, 1, 100)<br>y = x**2 + np.random.normal(0, 0.5, 100)<br><br># Calculate Spearman&#39;s Rank Correlation Coefficient for non-linear data<br>correlation, p = stats.spearmanr(x, y)<br><br># Plot non-linear data<br>axes[1].scatter(x, y)<br>axes[1].set_xlabel(&#39;x&#39;)<br>axes[1].set_ylabel(&#39;y&#39;)<br>axes[1].set_title(f&quot;Non-Linear Data Correlation: {correlation:.2f}&quot;)<br><br># Generate monotonic data<br>x = np.linspace(1, 100, 100)<br>y = np.log(x) + np.random.normal(0, 0.1, 100)<br><br># Calculate Spearman&#39;s Rank Correlation Coefficient for monotonic data<br>correlation, p = stats.spearmanr(x, y)<br><br># Plot monotonic data<br>axes[2].scatter(x, y)<br>axes[2].set_xlabel(&#39;x&#39;)<br>axes[2].set_ylabel(&#39;y&#39;)<br>axes[2].set_title(f&quot;Monotonic Data Correlation: {correlation:.2f}&quot;)<br><br>fig.suptitle(method_name, fontsize=16)<br>fig.tight_layout()<br>fig.subplots_adjust(top=0.88)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGdsVmlnfxxqk9YeqbIBCQ.png" /></figure><h3>Kendall’s Tau Rank Correlation Coefficient</h3><p>The Kendall’s Tau Rank Correlation Coefficient is a non-parametric statistical measure of the strength and direction of the association between two variables. Unlike the Pearson’s correlation coefficient, which measures linear relationships, the Kendall’s Tau rank correlation measures monotonic relationships, meaning that as one variable increases, the other variable either increases or decreases in a consistent manner, without necessarily being a straight line.</p><p>Kendall’s Tau measures the number of concordant and discordant pairs in the ranked data. A concordant pair is defined as two pairs (x1, y1) and (x2, y2) such that x1 &lt; x2 and y1 &lt; y2 or x1 &gt; x2 and y1 &gt; y2. Discordant pairs are defined as pairs such that x1 &lt; x2 and y1 &gt; y2 or x1 &gt; x2 and y1 &lt; y2. Kendall’s Tau is calculated as the ratio of the number of concordant pairs to the total number of pairs, minus the ratio of discordant pairs to the total number of pairs.</p><p>Kendall’s Tau is a robust measure of correlation and is less sensitive to outliers than Pearson’s correlation. It is also a good choice for datasets with non-normal distributions and can handle tied ranks. However, it is less sensitive to the strength of the relationship and may not be as effective as Pearson’s correlation in detecting linear relationships.</p><p>Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKhx3di8MEl-i2ZRTj8HWA.png" /></figure><pre>import numpy as np<br>from scipy import stats<br>import matplotlib.pyplot as plt<br><br>method_name = &quot;Kendall&#39;s Tau Rank Correlation Coefficient&quot;<br><br>fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 5))<br><br># Generate linear data<br>np.random.seed(0)<br>x = np.random.normal(0, 1, 100)<br>y = x + np.random.normal(0, 0.5, 100)<br><br># Calculate Kendall&#39;s Tau Rank Correlation Coefficient for linear data<br>correlation, p = stats.kendalltau(x, y)<br><br># Plot linear data<br>axes[0].scatter(x, y)<br>axes[0].set_xlabel(&#39;x&#39;)<br>axes[0].set_ylabel(&#39;y&#39;)<br>axes[0].set_title(f&quot;Linear Data Correlation: {correlation:.2f}&quot;)<br><br># Generate non-linear data<br>x = np.random.normal(0, 1, 100)<br>y = x**2 + np.random.normal(0, 0.5, 100)<br><br># Calculate Kendall&#39;s Tau Rank Correlation Coefficient for non-linear data<br>correlation, p = stats.kendalltau(x, y)<br><br># Plot non-linear data<br>axes[1].scatter(x, y)<br>axes[1].set_xlabel(&#39;x&#39;)<br>axes[1].set_ylabel(&#39;y&#39;)<br>axes[1].set_title(f&quot;Non-Linear Data Correlation: {correlation:.2f}&quot;)<br><br>x = np.linspace(1, 100, 100)<br>y = np.log(x) + np.random.normal(0, 0.1, 100)<br><br># Calculate Spearman&#39;s Rank Correlation Coefficient for monotonic data<br>correlation, p = stats.kendalltau(x, y)<br><br># Plot monotonic data<br>axes[2].scatter(x, y)<br>axes[2].set_xlabel(&#39;x&#39;)<br>axes[2].set_ylabel(&#39;y&#39;)<br>axes[2].set_title(f&quot;Monotonic Data Correlation: {correlation:.2f}&quot;)<br><br>fig.suptitle(method_name, fontsize=16)<br>fig.tight_layout()<br>fig.subplots_adjust(top=0.88)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBtBngZDu3wDNPqpQLIf0w.png" /></figure><h3>Point-Biserial Correlation Coefficient</h3><p>The Point-Biserial Correlation Coefficient is a type of correlation coefficient used to measure the association between a binary variable and a continuous variable. The binary variable is typically represented as a dichotomous variable, with two levels (e.g. yes/no, male/female). The continuous variable can be any numerical variable.</p><p>The Point-Biserial Correlation Coefficient measures the difference between the means of the continuous variable for each level of the binary variable. If the means of the continuous variable are significantly different between the two levels of the binary variable, then there is a positive or negative association between the two variables, depending on the direction of the difference.</p><p>Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*x5C17QbKkk61o319OYvOLQ.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*ziW8Nhrk6R0OwekXd6uyoQ.png" /></figure><pre>import scipy.stats as stats<br>data = np.array([[4, 2, -2, 1, 8, -6, -9, -8, 11, 13, 12, -14],<br>        [1, 2, 2, 4, 9, 8, 9, 6, 14, 12, 13, 12],<br>        [1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0]]).transpose()<br>df = pd.DataFrame(data)<br>df = df.rename(columns={0: &#39;x&#39;, 1: &#39;y&#39;, 2: &#39;label&#39;})<br><br>x_point_biserial, x_p_value = stats.pointbiserialr((df[&#39;label&#39;] == 1), df[&#39;x&#39;])<br>y_point_biserial, y_p_value = stats.pointbiserialr((df[&#39;label&#39;] == 1), df[&#39;y&#39;])<br><br>res_df = pd.DataFrame({&#39;Variable&#39;: [&#39;x&#39;, &#39;y&#39;], &#39;Correlation&#39;: [x_point_biserial, y_point_biserial], &#39;P-Value&#39;: [x_p_value, y_p_value]})<br>res_df[&#39;Rejected Null-Hypothesis&#39;] = res_df[&#39;P-Value&#39;].apply(lambda x: x &lt; 0.05)<br><br>method_name = &quot;Point-Biserial Correlation Coefficient&quot;<br>fig, ax = plt.subplots()<br><br>colors = {0:&#39;red&#39;, 1:&#39;blue&#39;}<br><br><br>ax.scatter(df[&#39;x&#39;], df[&#39;y&#39;], c=df[&#39;label&#39;].map(colors))<br>ax.set_xlabel(&#39;x&#39;)<br>ax.set_ylabel(&#39;y&#39;)<br>ax.set_title(f&quot;X Correlation: {x_point_biserial:.2f}, Y Correlation: {y_point_biserial:.2f}&quot;)<br>fig.suptitle(method_name, fontsize=16)<br>fig.tight_layout()<br>fig.subplots_adjust(top=0.8)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sehaqg2kZgq3zzn-X7ZB1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/0*cQuDdYdGkNh5OXzz.png" /></figure><h3>Phi Coefficient — Matthews correlation coefficient (MCC)</h3><p>Both the Phi Coefficient and the Matthews Correlation Coefficient (MCC) are measures of association between two binary variables. They are used to evaluate the performance of a binary classification model by comparing its predicted labels to the true labels. The Phi Coefficient is a correlation coefficient that measures the degree of association between two binary variables, usually represented as a 2x2 contingency table. The Matthews Correlation Coefficient (MCC) is another measure of association between two binary variables, but it is considered to be a more balanced measure than the Phi Coefficient, especially when the data is imbalanced.</p><p>The Phi Coefficient is calculated as the ratio of the number of cases where both binary variables are present to the total number of cases, minus the ratio of cases where both binary variables are absent to the total number of cases. If the number of cases where both binary variables are present is higher than expected by chance, then the Phi Coefficient is positive and indicates a positive association between the two binary variables. If the number of cases where both binary variables are absent is higher than expected by chance, then the Phi Coefficient is negative and indicates a negative association between the two binary variables.</p><p>The Phi Coefficient is a useful measure of association for binary variables, especially in situations where the sample size is small. It is less sensitive to outliers and does not require a normal distribution of the data.</p><p>Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*0zf-CI_SGWrZ6BNTrEjhkw.png" /></figure><p>Where:</p><ul><li>n11𝑛11, n10𝑛10, n01𝑛01, n00𝑛00, are non-negative counts of numbers of observations that sum to n𝑛, the total number of observations.</li></ul><p>Another use case for this correlation is when we have imbalanced binary classification and we want to measure the accuracy by calculating the:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*LRFvukK3mXjVsLzwcQn1eg.png" /></figure><ul><li>A score of -1 denotes complete disagreement between predicted and actual classes.</li><li>0 is equivalent to making a completely arbitrary guess.</li><li>A score of 1 denotes total agreement between predicted and actual classes.</li></ul><pre>from sklearn.metrics import matthews_corrcoef<br>#define array of actual classes<br>actual = np.repeat([1, 0], repeats=[20, 380])<br><br>#define array of predicted classes<br>pred = np.repeat([1, 0, 1, 0], repeats=[15, 5, 5, 375])<br><br>#calculate Matthews correlation coefficient<br>matthews_corrcoef(actual, pred)</pre><p><a href="https://www.statology.org/matthews-correlation-coefficient-python/#:~:text=model%20in%20Python%3A-,import%20numpy%20as%20np,-from%20sklearn.">Source</a></p><h3>Goodman and Kruskal’s Gamma</h3><p>Goodman and Kruskal’s Gamma (also known as Gamma) is a rank-based correlation coefficient that measures the association between two ordinal variables. Ordinal variables are variables that can be ordered or ranked, but the distances between the levels are not necessarily equal. For example, education levels (e.g. high school, bachelor’s degree, master’s degree) are an example of ordinal variables.</p><p>Gamma measures the strength and direction of the association between two ordinal variables by calculating the ratio of concordant to discordant pairs of observations. A concordant pair is a pair of observations where the rank of one variable is higher when the rank of the other variable is also higher, and the rank of one variable is lower when the rank of the other variable is also lower. A discordant pair is a pair of observations where the rank of one variable is higher when the rank of the other variable is lower, or vice versa. The Gamma coefficient ranges from -1 to 1, with a value of 1 indicating a perfect positive association between the two variables, a value of -1 indicating a perfect negative association, and a value of 0 indicating no association.</p><p>Goodman and Kruskal’s Gamma is commonly used in ordinal data analysis, such as when studying the association between two categorical variables with ordered categories. It is a useful measure of association when the data does not meet the assumptions of other correlation measures, such as when the data is not normally distributed or when the sample size is small.</p><p>Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*L4Kq3UKkO6Dpcy-tTNwhGw.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*ixtdJKIvHhVgLawV70FDaw.png" /></figure><h3>Partial Correlation</h3><p>Partial correlation is a statistical method used to measure the strength of the relationship between two variables, while adjusting for the influence of one or more additional variables. The partial correlation coefficient represents the correlation between two variables after removing the effects of the other variables that are being adjusted for.</p><p>Partial correlation is useful when analyzing complex relationships between multiple variables, where it is important to disentangle the specific relationship between two variables from the influences of other variables. It is often used in fields such as psychology, epidemiology, and economics, where multiple confounding factors need to be considered in order to interpret the relationships between variables accurately.</p><pre>import numpy as np<br>from scipy import stats, linalg<br><br>def partial_corr(C):<br>    &quot;&quot;&quot;<br>    Returns the sample linear partial correlation coefficients between pairs of variables in C, controlling <br>    for the remaining variables in C.<br>    Parameters<br>    ----------<br>    C : array-like, shape (n, p)<br>        Array with the different variables. Each column of C is taken as a variable<br>    Returns<br>    -------<br>    P : array-like, shape (p, p)<br>        P[i, j] contains the partial correlation of C[:, i] and C[:, j] controlling<br>        for the remaining variables in C.<br>    &quot;&quot;&quot;<br>    <br>    C = np.asarray(C)<br>    p = C.shape[1]<br>    P_corr = np.zeros((p, p), dtype=np.float)<br>    for i in range(p):<br>        P_corr[i, i] = 1<br>        for j in range(i+1, p):<br>            idx = np.ones(p, dtype=np.bool)<br>            idx[i] = False<br>            idx[j] = False<br>            beta_i = linalg.lstsq(C[:, idx], C[:, j])[0]<br>            beta_j = linalg.lstsq(C[:, idx], C[:, i])[0]<br><br>            res_j = C[:, j] - C[:, idx].dot( beta_i)<br>            res_i = C[:, i] - C[:, idx].dot(beta_j)<br>            <br>            corr = stats.pearsonr(res_i, res_j)[0]<br>            P_corr[i, j] = corr<br>            P_corr[j, i] = corr<br>        <br>    return P_corr<br><br>data = np.array([[4, 2, 2, 1, 8, 6, 9, 8, 11, 13, 12, 14],<br>        [1, 2, 2, 4, 9, 8, 9, 6, 14, 12, 13, 12],<br>        [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]]).transpose()<br>partial_corr(data)<br>array([[1.        , 0.93699911, 0.19315731],<br>       [0.93699911, 1.        , 0.02766727],<br>       [0.19315731, 0.02766727, 1.        ]])</pre><p><a href="https://gist.github.com/fabianp/9396204419c7b638d38f">Helpful Thread</a></p><h3>Kremer’s Rho (Kendall’s Tau concordance correlation)</h3><p>Kremer’s Rho, also known as Kendall’s Tau concordance correlation, is a non-parametric statistical measure used to evaluate the correlation between two sets of continuous or ordinal data. It is used when the assumptions of linearity and normality made by traditional methods, such as Pearson’s correlation coefficient, are not met.</p><p>Kremer’s Rho measures the degree of concordance between two sets of observations. Concordance refers to the extent to which the ranks of the values in one set correspond to the ranks of the values in the other set. If the two sets of observations are perfectly correlated, the Kremer’s Rho will be 1. If there is no correlation between the sets, the Kremer’s Rho will be 0. A negative Kremer’s Rho indicates a negative correlation between the sets.</p><p>Compared to other techniques, Kremer’s Rho is less sensitive to outliers and can handle non-normal distributions, making it a useful tool in situations where traditional methods may fail.</p><h4>Helper Functions</h4><pre>import pandas as pd<br>import numpy as np<br>from typing import List, Tuple, Callable<br><br>def run_correlation(df: pd.DataFrame, cols: List[str], corr_func: Callable) -&gt; pd.DataFrame:<br>    &quot;&quot;&quot;<br>    Calculates the pairwise correlations between columns of a pandas DataFrame.<br>    <br>    Args:<br>    df: pandas.DataFrame, the data to be analyzed.<br>    cols: List[str], a list of column names in the DataFrame to be analyzed.<br>    corr_func: Callable, a function to calculate the desired correlation between two columns.<br>    <br>    Returns:<br>    pandas.DataFrame, a DataFrame with the correlation values.<br>    &quot;&quot;&quot;<br>    resultant = pd.DataFrame(data=[(1 for i in range(len(cols))) for i in range(len(cols))], <br>                             columns=list(cols))<br>    resultant.set_index(pd.Index(list(cols)), inplace = True)<br><br>    for i in cols:<br>        for j in cols:<br>            if i != j:<br>                resultant.loc[i,j] = np.round(corr_func(df[i], df[j]), 2)<br><br>def get_date(n: int, ratio: int) -&gt; Tuple[List[str], List[str]]:<br>    &quot;&quot;&quot;<br>    Returns two lists of strings with the length of `n` and `n // ratio`<br>    <br>    Args:<br>    n: int, the length of the first list.<br>    ratio: int, the ratio used to calculate the length of the second list.<br>    <br>    Returns:<br>    Tuple[List[str], List[str]], a tuple containing two lists of strings.<br>    &quot;&quot;&quot;<br>    x = [&#39;1&#39;] * n + [&#39;2&#39;] * (n // ratio)<br>    y = [&#39;3&#39;] * n + [&#39;4&#39;] * (n // ratio)<br>    return x, y</pre><h3>Cramers V</h3><p>Cramer’s V is a measure of association between two nominal variables. It is a modification of the chi-square statistic used for contingency tables, which is a table that displays the frequency distribution of two variables. Cramer’s V ranges from 0 to 1, where 0 indicates no association between the two variables and 1 indicates a strong association.</p><p>Let a sample of size n of the simultaneously distributed variables A and B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*WzD0uZTrq9XeloIo6w6Jqg.png" /></figure><p>Cramér’s V is computed by taking the square root of the chi-squared statistic divided by the sample size and the minimum dimension minus 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*Yq0kV1w8YyfNa2e7HiW85g.png" /></figure><p>where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*Hgcdj6o9Ua_5l1Sdi1jiQg.png" /></figure><p><a href="https://en.wikipedia.org/wiki/Cram%C3%A9r%27s_V">Source</a></p><pre>import scipy.stats as ss<br><br>def cramers_v(x: pd.Series, y: pd.Series) -&gt; float:<br>    &quot;&quot;&quot;calculate Cramers V statistic for categorial-categorial association.<br>        uses correction from Bergsma and Wicher,<br>        Journal of the Korean Statistical Society 42 (2013): 323-328<br><br>    Args:<br>        x (pd.Series): variable1<br>        y (pd.Series): variable2<br><br>    Returns:<br>        float: the correletion between variable1 to variable2<br>    &quot;&quot;&quot;     <br>    confusion_matrix = pd.crosstab(x,y)<br>    chi2 = ss.chi2_contingency(confusion_matrix)[0]<br>    n = confusion_matrix.sum().sum()<br>    phi2 = chi2/n<br>    r,k = confusion_matrix.shape<br>    phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1))<br>    rcorr = r-((r-1)**2)/(n-1)<br>    kcorr = k-((k-1)**2)/(n-1)<br>    return np.sqrt(phi2corr/min((kcorr-1),(rcorr-1)))<br><br>n = 500<br>ratio = 4<br>x, y = get_date(n, ratio)<br>print(run_correlation(pd.DataFrame({&quot;x&quot;: x, &quot;y&quot;: y}), [&quot;x&quot;, &quot;y&quot;], cramers_v))<br>0.99<br># skewed dataset<br>n = 500<br>ratio = 500<br>x, y = get_date(n, ratio)<br>print(run_correlation(pd.DataFrame({&quot;x&quot;: x, &quot;y&quot;: y}), [&quot;x&quot;, &quot;y&quot;], cramers_v))<br>0.5<br># very small dataset<br>n = 4<br>ratio = 4<br>x, y = get_date(n, ratio)<br>print(run_correlation(pd.DataFrame({&quot;x&quot;: x, &quot;y&quot;: y}), [&quot;x&quot;, &quot;y&quot;], cramers_v))<br>0</pre><h3>Theil’s U statistic (Uncertainty coefficient)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*yoo4Ef39xz_LeAAqUE_UDw.png" /></figure><p><a href="https://en.wikipedia.org/wiki/Uncertainty_coefficient#:~:text=In%20statistics%2C%20the%20uncertainty%20coefficient,the%20concept%20of%20information%20entropy.">Source</a></p><pre>from typing import Any, List<br>from collections import Counter<br><br>def remove_incomplete_samples(x, y):<br>    x = [v if v is not None else np.nan for v in x]<br>    y = [v if v is not None else np.nan for v in y]<br>    arr = np.array([x, y]).transpose()<br>    arr = arr[~np.isnan(arr).any(axis=1)].transpose()<br>    if isinstance(x, list):<br>        return arr[0].tolist(), arr[1].tolist()<br>    else:<br>        return arr[0], arr[1]<br><br>def conditional_entropy(x,<br>                        y,<br>                        log_base: float = math.e):<br>    &quot;&quot;&quot;<br>    Calculates the conditional entropy of x given y: S(x|y)<br>    Wikipedia: https://en.wikipedia.org/wiki/Conditional_entropy<br>    Parameters:<br>    -----------<br>    x : list / NumPy ndarray / Pandas Series<br>        A sequence of measurements<br>    y : list / NumPy ndarray / Pandas Series<br>        A sequence of measurements<br>    nan_strategy : string, default = &#39;replace&#39;<br>        How to handle missing values: can be either &#39;drop&#39; to remove samples<br>        with missing values, or &#39;replace&#39; to replace all missing values with<br>        the nan_replace_value. Missing values are None and np.nan.<br>    nan_replace_value : any, default = 0.0<br>        The value used to replace missing values with. Only applicable when<br>        nan_strategy is set to &#39;replace&#39;.<br>    log_base: float, default = e<br>        specifying base for calculating entropy. Default is base e.<br>    Returns:<br>    --------<br>    float<br>    &quot;&quot;&quot;<br>    x, y = remove_incomplete_samples(x, y)<br>    y_counter = Counter(y)<br>    xy_counter = Counter(list(zip(x, y)))<br>    total_occurrences = sum(y_counter.values())<br>    entropy = 0.0<br>    for xy in xy_counter.keys():<br>        p_xy = xy_counter[xy] / total_occurrences<br>        p_y = y_counter[xy[1]] / total_occurrences<br>        entropy += p_xy * math.log(p_y / p_xy, log_base)<br>    return entropy<br><br>def theils_u(x: List[Any], y: List[Any]) -&gt; float:<br>    &quot;&quot;&quot;<br>    Calculates Theil&#39;s U, a measure of inequality of a distribution.<br>    <br>    Parameters:<br>        x (List[Any]): The first list of data.<br>        y (List[Any]): The second list of data.<br><br>    Returns:<br>        float: The Theil&#39;s U value.<br>    &quot;&quot;&quot;<br>    s_xy = conditional_entropy(x,y)<br>    x_counter = Counter(x)<br>    total_occurrences = sum(x_counter.values())<br>    p_x = list(map(lambda n: n/total_occurrences, x_counter.values()))<br>    s_x = ss.entropy(p_x)<br>    if s_x == 0:<br>        return 1<br>    else:<br>        return (s_x - s_xy) / s_x<br><br>a = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;]<br>b = [&quot;one&quot;, &quot;one&quot;, &quot;two&quot;, &quot;two&quot;]<br><br>example = pd.DataFrame({&quot;A&quot;: a, &quot;B&quot;: b})<br>example_cols = []<br>for col in example.columns:<br>    <br>    example[f&#39;{col}_code&#39;] = example[col].astype(&#39;category&#39;).cat.codes<br>    example[f&#39;{col}_code&#39;] = example[f&#39;{col}_code&#39;].replace({-1: max(example[f&#39;{col}_code&#39;].unique()) + 1})<br>    example_cols.append(f&#39;{col}_code&#39;)<br>print(run_correlation(example, example_cols, theils_u))<br>        A_code  B_code<br>A_code       1     0.5<br>B_code       1     1.0</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=640a840f9a2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding the Needle in the Legal Haystack]]></title>
            <link>https://medium.com/darrowai/finding-the-needle-in-the-legal-haystack-030090eb370d?source=rss-d99af427a932------2</link>
            <guid isPermaLink="false">https://medium.com/p/030090eb370d</guid>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[legaltech]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Dor Bernsohn]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 16:37:43 GMT</pubDate>
            <atom:updated>2024-07-01T14:33:46.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_g5_Rsy4zCtPQlqZbAZbw.jpeg" /></figure><p>The complexity of legal data poses significant challenges for professionals tasked with navigating vast archives of cases, statutes, and legal precedents. Advanced case embeddings offer a sophisticated approach to mitigating these challenges, transforming unwieldy legal texts into structured, analyzable data. In the following sections, we will delve into the types of legal case embeddings, examine their various applications, and discuss both the advantages they offer and the challenges they present.</p><h3>Overcoming Challenges with Advanced Case Embeddings</h3><p>Embeddings are computational techniques designed to convert information into numerical vectors, enabling algorithms to process this data efficiently. These embeddings support a range of tasks from semantic search to pattern recognition. There are two primary types of embeddings: dense and sparse embeddings.</p><ul><li><strong>Dense Embeddings:</strong> These involve representing data in continuous vector spaces, where each dimension captures some semantic meaning. Dense embeddings are typically learned through neural networks and can capture intricate relationships within the data, making them powerful for various natural language processing (NLP) tasks.</li><li><strong>Sparse Embeddings:</strong> These involve representing data in high-dimensional vector spaces, often with many dimensions having a value of zero. Sparse embeddings are useful for capturing specific, discrete pieces of information, such as word occurrences in documents.</li></ul><p>Below is an overview of the primary types of embeddings utilized in legal analytics.</p><h4>Metadata Embeddings</h4><p>Metadata embeddings distill case information — such as jurisdiction, court name, parties involved, and case filing dates — into numerical vectors. Jurisdiction embeddings elucidate the legal boundaries and context, whereas embeddings of court data highlight the specific venue, which is essential for identifying trends within jurisdictions. Party embeddings provide differentiation between the entities involved, whether they are individuals or corporations. Finally, embeddings for dates capture the chronological sequence, offering insights that go beyond the mere filing date to include important milestones that may affect the case trajectory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSXXu-y2qORtMe29rAIlzA.png" /><figcaption>Metadata Embeddings</figcaption></figure><h4>Law-Specific Embeddings</h4><p>This method involves extracting and encoding detailed legal information from case documents into a structured, analyzable format. Three main parts to process:</p><ul><li><strong>Allegations</strong>: The specific claims and legal issues brought forth by the plaintiff, which provide the foundational context of the case.</li><li><strong>Statutes</strong>: The written laws applicable to the case, which may be cited to support the allegations or defenses.</li><li><strong>Precedents</strong>: Prior judicial decisions that bear relevance to the current case, offering a historical legal context that may influence its outcome.</li></ul><p>Each of these data points is converted into numerical vectors. The allegations are parsed to identify the key legal issues at stake. Statutes are coded to reflect the relevant laws that the court must consider. Precedents are analyzed to include the weight of historical decisions.</p><p>Through this process, each segment of legal information is synthesized into a composite embedding, representing the complex network of legal reasoning and principles pertinent to the case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mX8l04B8SjOY3vJp__K5RA.png" /><figcaption>Law-Specific Embeddings</figcaption></figure><h4>Citation Graph Embeddings</h4><p>The Citation Graph utilizes the power of embeddings to map the relationships between cases based on their citations. By representing each case as a node in a network, and each citation as a link between nodes, this graph visually demonstrates how different cases influence one another. This is particularly useful for understanding the precedence and authority of cases, as well as the legal reasoning that spans multiple cases. Algorithms can analyze these networks to detect influential cases, common legal foundations, and emerging trends in case law.</p><p>In practice, Citation Graphs can help legal researchers quickly identify landmark cases and understand the structure of legal arguments within a specific area of law. They also make it easier to predict how future cases might be decided based on past citations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*EBJkmqxIBp18ODQPsHX20Q.png" /><figcaption>Graph Embeddings</figcaption></figure><h4>Legal Entities Graph Embeddings</h4><p>In the Legal Entities Graph, relationships among various specific legal entities — such as Violations, Defendants, Laws, Locations, Outcomes, and Evidence — are meticulously mapped. Each of these entities is represented as a node within the graph. Connections between these nodes (edges) illustrate legal interactions such as the application of laws to particular violations, the roles of defendants in those violations, and how different pieces of evidence are linked to outcomes in distinct locations. This structured visualization aids in revealing the intricate web of legal dependencies and interactions.</p><h4>Temporal Embeddings</h4><p>Temporal embeddings are vital for understanding how the sequence and timing of events influence legal case outcomes. This technique translates the chronological progression of legal actions — such as filing dates, evidence submissions, and hearing schedules — into numerical representations.</p><h4>Hybrid Graph Embeddings</h4><p>Hybrid graph embeddings integrate various types of embeddings into a unified, graph-based model, offering a holistic view of legal data. This approach combines elements such as citation patterns, legal entity relationships, and temporal data to capture a comprehensive feature space of legal interactions. By synthesizing multiple data dimensions, hybrid graph embeddings provide a deeper insight into the complex network of legal precedents, entities, and procedural timelines, enhancing the ability to analyze and predict outcomes in the legal field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7OWY-9DOhi0uJGlNGxLvQ.png" /><figcaption>Hybrid Graph Embeddings</figcaption></figure><h3>Exploring Hypothetical Scenarios to Enhance Embedding Spaces: Leveraging Counterfactual Cases with Detailed Legal Elements</h3><p>Exploring counterfactual hypothetical scenarios offers a unique opportunity to enrich the embedding space in legal research. Detailed yet theoretical cases can be constructed, structured into nodes and edges representing legal entities such as Violations, Defendants, Laws, Locations, Outcomes, and Evidence. Each scenario is built with comprehensive elements including facts, allegations, and crucial legal components, organized into a dynamic, graph-based model. This method generates embeddings that encapsulate a diverse array of legal intricacies and variables, providing deep insights into the interplay and impact of various legal factors on case outcomes.</p><p>These hypothetical scenarios, though not grounded in real cases, allow for a sophisticated analysis of how different factors might influence legal decisions. For example, scenarios can map out how a “Violation” such as “Failure to Present Terms Clearly” might interact with a “Defendant” like a business under specific “Laws” and in particular “Locations,” leading to various “Outcomes” supported by “Evidence” such as subscription agreements. This structured approach facilitates a nuanced exploration of legal information, enhancing implicit search capabilities and in-depth analysis across a wide spectrum of legal possibilities.</p><p>In practice, this method enables legal professionals to conduct “what-if” analyses, providing valuable insights into how a case might have been decided under different circumstances. Such analyses are invaluable for legal education, strategy planning, and understanding the flexibility and limits of the law, ultimately broadening the scope of legal understanding and uncovering hidden correlations, patterns, and trends within legal datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fA9Q7wiUY1OrRWZyz7hAHQ.png" /></figure><p>The JSON content illustrates a series of “what-if” scenarios, crucial for conducting hypothetical legal analyses. These scenarios are meticulously structured with nodes and edges representing different legal entities such as Violations, Defendants, Laws, Locations, Outcomes, and Evidence. Each scenario explores potential legal outcomes of specific violations under predefined conditions, aiding in the understanding of how various factors might influence legal decisions in a controlled, theoretical framework. This structured approach enables legal professionals to simulate and analyze complex legal interactions, thereby enhancing strategic planning and educational insights within the legal field.</p><pre>{<br>    &quot;scenario_1&quot;: {<br>        &quot;nodes&quot;: [<br>            {&quot;id&quot;: &quot;Violation&quot;, &quot;label&quot;: &quot;Failure to Present Terms Clearly&quot;},<br>            {&quot;id&quot;: &quot;Defendant&quot;, &quot;label&quot;: &quot;Business&quot;},<br>            {&quot;id&quot;: &quot;Law&quot;, &quot;label&quot;: &quot;Automatic Renewal Law&quot;},<br>            {&quot;id&quot;: &quot;Location&quot;, &quot;label&quot;: &quot;California&quot;},<br>            {&quot;id&quot;: &quot;Outcome&quot;, &quot;label&quot;: &quot;Potential Legal Action for Non-Compliance&quot;},<br>            {&quot;id&quot;: &quot;Evidence&quot;, &quot;label&quot;: &quot;Subscription Agreement Lacking Clear Terms&quot;}<br>        ],<br>        &quot;edges&quot;: [<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Defendant&quot;, &quot;relation&quot;: &quot;committed by&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Law&quot;, &quot;relation&quot;: &quot;violates&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Location&quot;, &quot;relation&quot;: &quot;occurred in&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Outcome&quot;, &quot;relation&quot;: &quot;results in&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Evidence&quot;, &quot;relation&quot;: &quot;supported by&quot;}<br>        ]<br>    },<br>    &quot;scenario_2&quot;: {<br>        &quot;nodes&quot;: [<br>            {&quot;id&quot;: &quot;Violation&quot;, &quot;label&quot;: &quot;Charging Without Affirmative Consent&quot;},<br>            {&quot;id&quot;: &quot;Defendant&quot;, &quot;label&quot;: &quot;Business&quot;},<br>            {&quot;id&quot;: &quot;Law&quot;, &quot;label&quot;: &quot;Automatic Renewal Law&quot;},<br>            {&quot;id&quot;: &quot;Location&quot;, &quot;label&quot;: &quot;California&quot;},<br>            {&quot;id&quot;: &quot;Outcome&quot;, &quot;label&quot;: &quot;Potential Legal Action for Unauthorized Charges&quot;},<br>            {&quot;id&quot;: &quot;Evidence&quot;, &quot;label&quot;: &quot;Consumer Complaints of Unauthorized Charges&quot;}<br>        ],<br>        &quot;edges&quot;: [<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Defendant&quot;, &quot;relation&quot;: &quot;committed by&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Law&quot;, &quot;relation&quot;: &quot;violates&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Location&quot;, &quot;relation&quot;: &quot;occurred in&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Outcome&quot;, &quot;relation&quot;: &quot;results in&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Evidence&quot;, &quot;relation&quot;: &quot;supported by&quot;}<br>        ]<br>    },<br>    &quot;scenario_3&quot;: {<br>        &quot;nodes&quot;: [<br>            {&quot;id&quot;: &quot;Violation&quot;, &quot;label&quot;: &quot;Failure to Provide Easy Cancellation&quot;},<br>            {&quot;id&quot;: &quot;Defendant&quot;, &quot;label&quot;: &quot;Business&quot;},<br>            {&quot;id&quot;: &quot;Law&quot;, &quot;label&quot;: &quot;Automatic Renewal Law&quot;},<br>            {&quot;id&quot;: &quot;Location&quot;, &quot;label&quot;: &quot;California&quot;},<br>            {&quot;id&quot;: &quot;Outcome&quot;, &quot;label&quot;: &quot;Potential Legal Action for Impeding Cancellation&quot;},<br>            {&quot;id&quot;: &quot;Evidence&quot;, &quot;label&quot;: &quot;Lack of or Hard to Find Cancellation Option&quot;}<br>        ],<br>        &quot;edges&quot;: [<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Defendant&quot;, &quot;relation&quot;: &quot;committed by&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Law&quot;, &quot;relation&quot;: &quot;violates&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Location&quot;, &quot;relation&quot;: &quot;occurred in&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Outcome&quot;, &quot;relation&quot;: &quot;results in&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Evidence&quot;, &quot;relation&quot;: &quot;supported by&quot;}<br>        ]<br>    },<br>    &quot;scenario_4&quot;: {<br>        &quot;nodes&quot;: [<br>            {&quot;id&quot;: &quot;Violation&quot;, &quot;label&quot;: &quot;Not Providing Required Notices&quot;},<br>            {&quot;id&quot;: &quot;Defendant&quot;, &quot;label&quot;: &quot;Business&quot;},<br>            {&quot;id&quot;: &quot;Law&quot;, &quot;label&quot;: &quot;Automatic Renewal Law&quot;},<br>            {&quot;id&quot;: &quot;Location&quot;, &quot;label&quot;: &quot;California&quot;},<br>            {&quot;id&quot;: &quot;Outcome&quot;, &quot;label&quot;: &quot;Potential Legal Action for Failure to Notify&quot;},<br>            {&quot;id&quot;: &quot;Evidence&quot;, &quot;label&quot;: &quot;Consumer Reports of No Pre-Renewal Notification&quot;}<br>        ],<br>        &quot;edges&quot;: [<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Defendant&quot;, &quot;relation&quot;: &quot;committed by&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Law&quot;, &quot;relation&quot;: &quot;violates&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Location&quot;, &quot;relation&quot;: &quot;occurred in&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Outcome&quot;, &quot;relation&quot;: &quot;results in&quot;},<br>            {&quot;source&quot;: &quot;Violation&quot;, &quot;target&quot;: &quot;Evidence&quot;, &quot;relation&quot;: &quot;supported by&quot;}<br>        ]<br>    }<br>}</pre><h3>Conclusions</h3><p>This exploration of advanced case embeddings has demonstrated their transformative potential in legal analytics. By converting complex legal documents into structured, analyzable data, these technologies enhance capabilities in semantic search, pattern recognition, and predictive analytics. The integration of various embedding types allows for sophisticated “what-if” analyses, enabling legal professionals to simulate and evaluate potential legal outcomes under different scenarios. Advanced case embeddings significantly improve the efficiency and quality of legal research and outcomes, representing a notable advancement in the application of technology within the legal field.</p><p>At <a href="https://darrow.ai/">Darrow.ai</a>, we’re building a vision of frictionless justice with cutting-edge algorithms. Embeddings are the cornerstone of this effort. In this blog, we review how we’ve tailored embeddings specifically for the legal field.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=030090eb370d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/darrowai/finding-the-needle-in-the-legal-haystack-030090eb370d">Finding the Needle in the Legal Haystack</a> was originally published in <a href="https://medium.com/darrowai">DarrowAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>