title: How to fetch triples in a knowledge graph by subject in Tensorflow?
body: <p>I am working on a knowledge graph dataset, which has triples of the format , i.e., triples of subject, predicate and object.</p>
  
  <p>Say, the knowledge graph looks as follows:</p>
  
  <pre><code>X = np.array([['a', 'y', 'b'],
                ['b', 'y', 'a'],
                ['a', 'y', 'c'],
                ['c', 'y', 'a'],
                ['a', 'y', 'd'],
                ['c', 'y', 'd'],
                ['b', 'y', 'c'],
                ['f', 'y', 'e']])
  </code></pre>
  
  <p>In the loss function, it iterates over each triple:</p>
  
  <pre><code>x_pos_tf = tf.cast(dataset_iterator.get_next(), tf.int32)
  </code></pre>
  
  <p>(where:</p>
  
  <pre><code>dataset_iterator = dataset.make_one_shot_iterator()
  </code></pre>
  
  <p>)</p>
  
  <p>Now, for each triple, I wish to fetch all the triples from the knowledge graph which have the same subject as the triple in question. For example: for triple (a,y,b)I wish to fetch ((a,y,c),(a,y,d)). [Note: Not including the triple being evaluated].</p>
  
  <p>I have carried out this operation using numpy lists, by making a dictionary data structure for the knowledge graph as follows:</p>
  
  <pre><code>d = {s: [tuple(x) for x in X if x[0] == s] for s in np.unique(X[:, 0])}
  </code></pre>
  
  <p>This returns a dictionary of the format:</p>
  
  <pre><code>d={'f': [('f', 'y', 'e')],
     'c': [('c', 'y', 'a'), ('c', 'y', 'd')],
     'a': [('a', 'y', 'b'), ('a', 'y', 'c'), ('a', 'y', 'd')],
     'b': [('b', 'y', 'a'), ('b', 'y', 'c')]}
  </code></pre>
  
  <p>And then, I do a simple lookup for any triple as follows:</p>
  
  <pre><code>return list({triple for x in x_to_score for triple in self.d[x[0]]} - set(x_to_score))
  </code></pre>
  
  <p>where <code>x_to_score</code> is the triple being evaluated.</p>
  
  <p>This returns a list <code>[('a','y','c'), ('a','y','d')]</code> for the sample triple ('a','y','b'), as an example.</p>
  
  <p>However, the problem now is, as I iterate over the triples (i.e. a batch of triples processed at onece), they need to be passed as tensors, therefore I cannot do numpy operations or list comprehensions to do this.</p>
  
  <p>I need to process the triple to be evaluated as a tensor, and then return a list of tensors for the result as well.</p>
  
  <p>As I am new to tensorflow, I am unable to figure out how to go about this.</p>
  
  <p>Further, this needs to work for evaluating a batch of triples.</p>
  
  <p>I have tried the <code>tf.slice()</code> operation for fetching the subject, and some <code>tf.sets()</code> functions, but am not able to figure it out, as I am very new to tensorflow.</p>
  
  <p>Any help will be appreciated! Thank you.</p>