stellargraph/stellargraph

View on GitHub
demos/basics/loading-numpy.ipynb

Summary

Maintainability
Test Coverage
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# Loading data into StellarGraph from NumPy\n",
    "\n",
    "> This demo explains how to load data from NumPy into a form that can be used by the StellarGraph library. [See all other demos](../README.md).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1",
   "metadata": {
    "nbsphinx": "hidden",
    "tags": [
     "CloudRunner"
    ]
   },
   "source": [
    "<table><tr><td>Run the latest release of this notebook:</td><td><a href=\"https://mybinder.org/v2/gh/stellargraph/stellargraph/master?urlpath=lab/tree/demos/basics/loading-numpy.ipynb\" alt=\"Open In Binder\" target=\"_parent\"><img src=\"https://mybinder.org/badge_logo.svg\"/></a></td><td><a href=\"https://colab.research.google.com/github/stellargraph/stellargraph/blob/master/demos/basics/loading-numpy.ipynb\" alt=\"Open In Colab\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\"/></a></td></tr></table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {},
   "source": [
    "[The StellarGraph library](https://github.com/stellargraph/stellargraph) supports loading graph information from NumPy. [NumPy](https://www.numpy.org) is a library for working with data arrays.\n",
    "\n",
    "If your data can easily be loaded into a NumPy array, this is a great way to load it that has minimal overhead and offers the most control.\n",
    "\n",
    "This notebook walks through loading three kinds of graphs.\n",
    "\n",
    "- homogeneous graph with feature vectors\n",
    "- homogeneous graph with feature tensors\n",
    "- heterogeneous graph with feature vectors and tensors\n",
    "\n",
    "> StellarGraph supports loading data from many sources with all sorts of data preprocessing, via [Pandas](https://pandas.pydata.org) DataFrames, [NumPy](https://www.numpy.org) arrays, [Neo4j](https://neo4j.com) and [NetworkX](https://networkx.github.io) graphs. This notebook demonstrates loading data from NumPy. See [the other loading demos](README.md) for more details.\n",
    "\n",
    "This notebook only uses NumPy for the node features, with Pandas used for the edge data. The details and options for loading edge data in this format are discussed in [the \"Loading data into StellarGraph from Pandas\" demo](loading-pandas.ipynb).\n",
    "\n",
    "Additionally, if the node features are in a complicated format for loading and/or requires significant preprocessing, loading via Pandas is likely to be more convenient.\n",
    "\n",
    "The [documentation](https://stellargraph.readthedocs.io/en/stable/api.html#stellargraph.StellarGraph) for the `StellarGraph` class includes a compressed reminder of everything discussed in this file, as well as explanations of all of the parameters.\n",
    "\n",
    "The `StellarGraph` class is available at the top level of the `stellargraph` library:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "3",
   "metadata": {
    "nbsphinx": "hidden",
    "tags": [
     "CloudRunner"
    ]
   },
   "outputs": [],
   "source": [
    "# install StellarGraph if running on Google Colab\n",
    "import sys\n",
    "if 'google.colab' in sys.modules:\n",
    "  %pip install -q stellargraph[demos]==1.3.0b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4",
   "metadata": {
    "nbsphinx": "hidden",
    "tags": [
     "VersionCheck"
    ]
   },
   "outputs": [],
   "source": [
    "# verify that we're using the correct version of StellarGraph for this notebook\n",
    "import stellargraph as sg\n",
    "\n",
    "try:\n",
    "    sg.utils.validate_notebook_version(\"1.3.0b\")\n",
    "except AttributeError:\n",
    "    raise ValueError(\n",
    "        f\"This notebook requires StellarGraph version 1.3.0b, but a different version {sg.__version__} is installed.  Please see <https://github.com/stellargraph/stellargraph/issues/1172>.\"\n",
    "    ) from None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "from stellargraph import StellarGraph"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6",
   "metadata": {},
   "source": [
    "## Loading via NumPy\n",
    "\n",
    "A StellarGraph has two basic components:\n",
    "\n",
    "- nodes, with feature arrays or tensors\n",
    "- edges, consisting of a pair of nodes as the source and target, and feature arrays or tensors\n",
    "\n",
    "A NumPy array consists of a large number of values of a single type. It is thus appropriate for the feature arrays in nodes, but not as useful for edges, because the source and target node IDs may be different. Thus, node data can be input as a NumPy array directly, but edge data cannot. The latter still uses Pandas."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {},
   "source": [
    "## Sequential numeric graph structure\n",
    "\n",
    "As with the Pandas demo, we'll be working with a square graph. For simplicity, we'll start with a graph where the identifiers of nodes are sequential integers starting at 0:\n",
    "\n",
    "```\n",
    "0 -- 1\n",
    "| \\  |\n",
    "|  \\ |\n",
    "3 -- 2\n",
    "```\n",
    "\n",
    "The edges of this graph can easily be encoded as the rows of a Pandas DataFrame:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>source</th>\n",
       "      <th>target</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>3</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>4</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   source  target\n",
       "0       0       1\n",
       "1       1       2\n",
       "2       2       3\n",
       "3       3       0\n",
       "4       0       2"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "square_numeric_edges = pd.DataFrame(\n",
    "    {\"source\": [0, 1, 2, 3, 0], \"target\": [1, 2, 3, 0, 2]}\n",
    ")\n",
    "square_numeric_edges"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10",
   "metadata": {},
   "source": [
    "## Homogeneous graph with sequential IDs and feature vectors\n",
    "\n",
    "Now, suppose we have some feature vectors associated with each node in our square graph. For instance, maybe node `0` has features `[1, -0.2]`. This can come in the form of a 4 × 2 matrix, with one row per node, with row `0` being features for the `0` node, and so on. Filling out the rest of the example data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "11",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1. , -0.2],\n",
       "       [ 2. ,  0.3],\n",
       "       [ 3. ,  0. ],\n",
       "       [ 4. , -0.5]], dtype=float32)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "feature_array = np.array(\n",
    "    [[1.0, -0.2], [2.0, 0.3], [3.0, 0.0], [4.0, -0.5]], dtype=np.float32\n",
    ")\n",
    "feature_array"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12",
   "metadata": {},
   "source": [
    "Because our nodes have IDs `0`, `1`, ..., we can construct the `StellarGraph` by passing in the feature array directly, along with the edges:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "13",
   "metadata": {},
   "outputs": [],
   "source": [
    "square_numeric = StellarGraph(feature_array, square_numeric_edges)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14",
   "metadata": {},
   "source": [
    "The `info` method ([docs](https://stellargraph.readthedocs.io/en/stable/api.html#stellargraph.StellarGraph.info)) gives a high-level summary of a `StellarGraph`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "15",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "StellarGraph: Undirected multigraph\n",
      " Nodes: 4, Edges: 5\n",
      "\n",
      " Node types:\n",
      "  default: [4]\n",
      "    Features: float32 vector, length 2\n",
      "    Edge types: default-default->default\n",
      "\n",
      " Edge types:\n",
      "    default-default->default: [5]\n",
      "        Weights: all 1 (default)\n",
      "        Features: none\n"
     ]
    }
   ],
   "source": [
    "print(square_numeric.info())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16",
   "metadata": {},
   "source": [
    "On this square, it tells us that there's 4 nodes of type `default` (a homogeneous graph still has node and edge types, but they default to `default`), with 2 features, and one type of edge that touches it. It also tells us that there's 5 edges of type `default` that go between nodes of type `default`. This matches what we expect: it's a graph with 4 nodes and 5 edges and one type of each.\n",
    "\n",
    "The default node type and edge types can be set using the `node_type_default` and `edge_type_default` parameters to `StellarGraph(...)`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "17",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "StellarGraph: Undirected multigraph\n",
      " Nodes: 4, Edges: 5\n",
      "\n",
      " Node types:\n",
      "  corner: [4]\n",
      "    Features: float32 vector, length 2\n",
      "    Edge types: corner-line->corner\n",
      "\n",
      " Edge types:\n",
      "    corner-line->corner: [5]\n",
      "        Weights: all 1 (default)\n",
      "        Features: none\n"
     ]
    }
   ],
   "source": [
    "square_numeric_named = StellarGraph(\n",
    "    feature_array,\n",
    "    square_numeric_edges,\n",
    "    node_type_default=\"corner\",\n",
    "    edge_type_default=\"line\",\n",
    ")\n",
    "print(square_numeric_named.info())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18",
   "metadata": {},
   "source": [
    "## Non-sequential graph structure\n",
    "\n",
    "Requiring node identifiers to always be sequential integers from 0 is restrictive. Most real-world graphs don't have such neat IDs. For instance, maybe our graph instead uses strings as IDs:\n",
    "\n",
    "```\n",
    "a -- b\n",
    "| \\  |\n",
    "|  \\ |\n",
    "d -- c\n",
    "```\n",
    "\n",
    "As before, these edges get encoded as a DataFrame:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "19",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>source</th>\n",
       "      <th>target</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0</td>\n",
       "      <td>a</td>\n",
       "      <td>b</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>1</td>\n",
       "      <td>b</td>\n",
       "      <td>c</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>2</td>\n",
       "      <td>c</td>\n",
       "      <td>d</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>3</td>\n",
       "      <td>d</td>\n",
       "      <td>a</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>4</td>\n",
       "      <td>a</td>\n",
       "      <td>c</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  source target\n",
       "0      a      b\n",
       "1      b      c\n",
       "2      c      d\n",
       "3      d      a\n",
       "4      a      c"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "square_edges = pd.DataFrame(\n",
    "    {\"source\": [\"a\", \"b\", \"c\", \"d\", \"a\"], \"target\": [\"b\", \"c\", \"d\", \"a\", \"c\"]}\n",
    ")\n",
    "square_edges"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20",
   "metadata": {},
   "source": [
    "## Homogeneous graph with non-numeric IDs and feature vectors\n",
    "\n",
    "With non-sequential, non-numeric IDs, we cannot use a NumPy array directly, because we need to know which row of the array corresponds to which node. This is done with the `IndexedArray` ([docs](https://stellargraph.readthedocs.io/en/stable/api.html#stellargraph.IndexedArray)) type. It is a much simplified Pandas DataFrame, that is generalised to be more than 2-dimensional. It is available at the top level of `stellargraph`, and supports an `index` parameter to define the mapping from row to node. The `index` should have one element per row of the NumPy array."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "21",
   "metadata": {},
   "outputs": [],
   "source": [
    "from stellargraph import IndexedArray"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "22",
   "metadata": {},
   "outputs": [],
   "source": [
    "indexed_array = IndexedArray(feature_array, index=[\"a\", \"b\", \"c\", \"d\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "23",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "StellarGraph: Undirected multigraph\n",
      " Nodes: 4, Edges: 5\n",
      "\n",
      " Node types:\n",
      "  corner: [4]\n",
      "    Features: float32 vector, length 2\n",
      "    Edge types: corner-line->corner\n",
      "\n",
      " Edge types:\n",
      "    corner-line->corner: [5]\n",
      "        Weights: all 1 (default)\n",
      "        Features: none\n"
     ]
    }
   ],
   "source": [
    "square_named = StellarGraph(\n",
    "    indexed_array, square_edges, node_type_default=\"corner\", edge_type_default=\"line\",\n",
    ")\n",
    "print(square_named.info())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "24",
   "metadata": {},
   "source": [
    "As before, there's 4 nodes, each with features of length 2."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "25",
   "metadata": {},
   "source": [
    "## Homogeneous graph with non-numeric IDs and feature tensors\n",
    "\n",
    "Some algorithms work with than just a feature vector associated with each node. For instance, if each node corresponds to a weather station, one might have a time series of observations like \"temperature\" and \"pressure\" associated with each node. This is modelled by having a multidimensional feature for each node.\n",
    "\n",
    "Time series algorithms within StellarGraph expect the tensor to be shaped like `nodes × time steps × variates`. For the weather station example, `nodes` is the number of weather stations, `time steps` is the number of points within each series and `variates` is the number of observations at each time step.\n",
    "\n",
    "For our square graph, we might have time series of length three, containing two observations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "26",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[ 1.  , -0.2 ],\n",
       "        [ 1.  ,  0.1 ],\n",
       "        [ 0.9 ,  0.1 ]],\n",
       "\n",
       "       [[ 2.  ,  0.3 ],\n",
       "        [ 1.9 ,  0.31],\n",
       "        [ 2.1 ,  0.32]],\n",
       "\n",
       "       [[ 3.  ,  0.  ],\n",
       "        [10.  ,  0.  ],\n",
       "        [ 3.  ,  0.  ]],\n",
       "\n",
       "       [[ 4.  , -0.5 ],\n",
       "        [ 0.  , -1.  ],\n",
       "        [ 1.  , -3.  ]]], dtype=float32)"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "feature_tensors = np.array(\n",
    "    [\n",
    "        [[1.0, -0.2], [1.0, 0.1], [0.9, 0.1]],\n",
    "        [[2.0, 0.3], [1.9, 0.31], [2.1, 0.32]],\n",
    "        [[3.0, 0.0], [10.0, 0.0], [3.0, 0.0]],\n",
    "        [[4.0, -0.5], [0.0, -1.0], [1.0, -3.0]],\n",
    "    ],\n",
    "    dtype=np.float32,\n",
    ")\n",
    "feature_tensors"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "27",
   "metadata": {},
   "outputs": [],
   "source": [
    "indexed_tensors = IndexedArray(feature_tensors, index=[\"a\", \"b\", \"c\", \"d\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "28",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "StellarGraph: Undirected multigraph\n",
      " Nodes: 4, Edges: 5\n",
      "\n",
      " Node types:\n",
      "  corner: [4]\n",
      "    Features: float32 tensor, shape (3, 2)\n",
      "    Edge types: corner-line->corner\n",
      "\n",
      " Edge types:\n",
      "    corner-line->corner: [5]\n",
      "        Weights: all 1 (default)\n",
      "        Features: none\n"
     ]
    }
   ],
   "source": [
    "square_tensors = StellarGraph(\n",
    "    indexed_tensors, square_edges, node_type_default=\"corner\", edge_type_default=\"line\",\n",
    ")\n",
    "print(square_tensors.info())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "29",
   "metadata": {},
   "source": [
    "We can see that the features of the `corner` nodes are now listed as a tensor, with shape 3 × 2, matching the array we created above."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30",
   "metadata": {},
   "source": [
    "## Heterogeneous graphs\n",
    "\n",
    "Some graphs have multiple types of nodes.\n",
    "\n",
    "For example, an academic citation network that includes authors might have `wrote` edges connecting `author` nodes to `paper` nodes, in addition to the `cites` edges between `paper` nodes. There could be `supervised` edges between `author`s ([example](https://academictree.org)) too, or any number of additional node and edge types. A knowledge graph (aka RDF, triple stores or knowledge base) is an extreme form of an heterogeneous graph, with dozens, hundreds or even thousands of edge (or relation) types. Typically in a knowledge graph, edges and their types represent the information associated with a node, rather than node features.\n",
    "\n",
    "`StellarGraph` supports all forms of heterogeneous graphs.\n",
    "\n",
    "A heterogeneous `StellarGraph` can be constructed in a similar way to a homogeneous graph, except we pass a dictionary with multiple elements instead of a single element like we did in the \"homogeneous graph with features\" section and others above. For a heterogeneous graph, a dictionary has to be passed; passing a single `IndexedArray` does not work.\n",
    "\n",
    "Let's return to the square graph from earlier:\n",
    "\n",
    "```\n",
    "a -- b\n",
    "| \\  |\n",
    "|  \\ |\n",
    "d -- c\n",
    "```\n",
    "\n",
    "### Feature arrays\n",
    "\n",
    "Suppose `a` is of type `foo`, and no features, but `b`, `c` and `d` are of type `bar` and have two features each, e.g. for `b`, `0.4, 100`. Since the features are different shapes (`a` has zero), they need to be modeled as different types, with separate `IndexedArray`s."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "31",
   "metadata": {},
   "outputs": [],
   "source": [
    "square_foo = IndexedArray(index=[\"a\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "32",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[4.e-01, 1.e+02],\n",
       "       [1.e-01, 2.e+02],\n",
       "       [9.e-01, 3.e+02]])"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bar_features = np.array([[0.4, 100], [0.1, 200], [0.9, 300]])\n",
    "bar_features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "33",
   "metadata": {},
   "outputs": [],
   "source": [
    "square_bar = IndexedArray(bar_features, index=[\"b\", \"c\", \"d\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34",
   "metadata": {},
   "source": [
    "We have the information for the two node types `foo` and `bar` in separate DataFrames, so we can now put them in a dictionary to create a `StellarGraph`. Notice that `info()` is now reporting multiple node types, as well as information specific to each."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "35",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "StellarGraph: Undirected multigraph\n",
      " Nodes: 4, Edges: 5\n",
      "\n",
      " Node types:\n",
      "  bar: [3]\n",
      "    Features: float64 vector, length 2\n",
      "    Edge types: bar-default->bar, bar-default->foo\n",
      "  foo: [1]\n",
      "    Features: none\n",
      "    Edge types: foo-default->bar\n",
      "\n",
      " Edge types:\n",
      "    foo-default->bar: [2]\n",
      "        Weights: all 1 (default)\n",
      "        Features: none\n",
      "    bar-default->bar: [2]\n",
      "        Weights: all 1 (default)\n",
      "        Features: none\n",
      "    bar-default->foo: [1]\n",
      "        Weights: all 1 (default)\n",
      "        Features: none\n"
     ]
    }
   ],
   "source": [
    "square_foo_and_bar = StellarGraph({\"foo\": square_foo, \"bar\": square_bar}, square_edges)\n",
    "print(square_foo_and_bar.info())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36",
   "metadata": {},
   "source": [
    "Node IDs (the DataFrame index) needs to be unique across all types. For example, renaming the `a` corner to `b` like `square_foo_overlap` in the next cell, is not accepted and a `StellarGraph(...)` call will throw an error"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "37",
   "metadata": {},
   "outputs": [],
   "source": [
    "square_foo_overlap = IndexedArray(index=[\"b\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "38",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Uncomment to see the error\n",
    "# StellarGraph({\"foo\": square_foo_overlap, \"bar\": square_bar}, square_edges)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39",
   "metadata": {},
   "source": [
    "If the node IDs aren't unique across types, one way to make them unique is to add a string prefix. You'll need to add the same prefix to the node IDs used in the edges too. Adding a prefix can be done by replacing the index:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "40",
   "metadata": {},
   "outputs": [],
   "source": [
    "square_foo_overlap_prefix = IndexedArray(\n",
    "    square_foo_overlap.values, index=[f\"foo-{s}\" for s in square_foo_overlap.index]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "41",
   "metadata": {},
   "outputs": [],
   "source": [
    "square_bar_prefix = IndexedArray(\n",
    "    square_bar.values, index=[f\"bar-{s}\" for s in square_bar.index]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42",
   "metadata": {},
   "source": [
    "### Feature tensors\n",
    "\n",
    "Nodes of different types can have features of completely different shapes, not just vectors of different lengths. For instance, suppose our `foo` node (`a`) has the multi-variate time series from above as a feature."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "43",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[ 1. , -0.2],\n",
       "        [ 1. ,  0.1],\n",
       "        [ 0.9,  0.1]]])"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "foo_tensors = np.array([[[1.0, -0.2], [1.0, 0.1], [0.9, 0.1]]])\n",
    "foo_tensors"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "44",
   "metadata": {},
   "outputs": [],
   "source": [
    "square_foo_tensors = IndexedArray(foo_tensors, index=[\"a\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "45",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "StellarGraph: Undirected multigraph\n",
      " Nodes: 4, Edges: 5\n",
      "\n",
      " Node types:\n",
      "  bar: [3]\n",
      "    Features: float64 vector, length 2\n",
      "    Edge types: bar-default->bar, bar-default->foo\n",
      "  foo: [1]\n",
      "    Features: float64 tensor, shape (3, 2)\n",
      "    Edge types: foo-default->bar\n",
      "\n",
      " Edge types:\n",
      "    foo-default->bar: [2]\n",
      "        Weights: all 1 (default)\n",
      "        Features: none\n",
      "    bar-default->bar: [2]\n",
      "        Weights: all 1 (default)\n",
      "        Features: none\n",
      "    bar-default->foo: [1]\n",
      "        Weights: all 1 (default)\n",
      "        Features: none\n"
     ]
    }
   ],
   "source": [
    "square_foo_tensors_and_bar = StellarGraph(\n",
    "    {\"foo\": square_foo_tensors, \"bar\": square_bar}, square_edges\n",
    ")\n",
    "print(square_foo_tensors_and_bar.info())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46",
   "metadata": {},
   "source": [
    "We can now see that the `foo` node is listed as having a feature tensor, as desired."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "You hopefully now know more about building node features for a `StellarGraph` in various configurations via NumPy arrays.\n",
    "\n",
    "For more details on graphs with directed, weighted or heterogeneous edges, see [the \"Loading data into StellarGraph from Pandas\" demo](loading-pandas.ipynb). All of the examples there work with `IndexedArray` instead of Pandas DataFrames for the node features.\n",
    "\n",
    "Revisit this document to use as a reminder, or [the documentation](https://stellargraph.readthedocs.io/en/stable/api.html#stellargraph.StellarGraph) for the `StellarGraph` class.\n",
    "\n",
    "Once you've loaded your data, you can start doing machine learning: a good place to start is the [demo of the GCN algorithm on the Cora dataset for node classification](../node-classification/gcn-node-classification.ipynb). Additionally, StellarGraph includes [many other demos of other algorithms, solving other tasks](../README.md)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48",
   "metadata": {
    "nbsphinx": "hidden",
    "tags": [
     "CloudRunner"
    ]
   },
   "source": [
    "<table><tr><td>Run the latest release of this notebook:</td><td><a href=\"https://mybinder.org/v2/gh/stellargraph/stellargraph/master?urlpath=lab/tree/demos/basics/loading-numpy.ipynb\" alt=\"Open In Binder\" target=\"_parent\"><img src=\"https://mybinder.org/badge_logo.svg\"/></a></td><td><a href=\"https://colab.research.google.com/github/stellargraph/stellargraph/blob/master/demos/basics/loading-numpy.ipynb\" alt=\"Open In Colab\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\"/></a></td></tr></table>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}