コード例 #1
0
ファイル: demo_gin.py プロジェクト: tianSKY12/tf_geometric
def construct_graph(graph_dict):
    return tfg.Graph(
        x=create_fake_node_features(graph_dict["num_nodes"]),
        edge_index=graph_dict["edge_index"],
        y=graph_dict[
            "graph_label"]  # graph_dict["graph_label"] is a list with one int element
    )
コード例 #2
0
def construct_graph(graph_dict):
    return tfg.Graph(
        x=convert_node_labels_to_one_hot(graph_dict["node_labels"]),
        edge_index=graph_dict["edge_index"],
        y=graph_dict[
            "graph_label"]  # graph_dict["graph_label"] is a list with one int element
    )
コード例 #3
0
    def __init__(self, sess, ob_space, ac_space, n_env, n_steps, n_batch,
                 graph):
        super(GATPolicy, self).__init__(sess, ob_space, ac_space, n_env,
                                        n_steps, n_batch)
        cluster_info = nx.get_node_attributes(graph, 'cluster')
        node_attr = np.zeros(shape=(len(cluster_info), 2), dtype=np.float32)
        for key, value in cluster_info.items(
        ):  # Try having all 0s for not-controller
            node_attr[key][1] = value

        edge_weights = nx.get_edge_attributes(graph, 'weight')
        edge_attr = np.empty(shape=(len(edge_weights), ), dtype=np.float32)
        edges = np.array(graph.edges).T
        i = 0
        for key, value in edge_weights.items():
            assert (edges[0][i], edges[1][i]) == key
            edge_attr[i] = value
            i += 1

        edges, [edge_attr] = tfg.utils.graph_utils.convert_edge_to_directed(
            edges, [edge_attr])
        self.graph = tfg.Graph(x=node_attr,
                               edge_index=edges,
                               edge_weight=edge_attr)
        print([self.graph.x, self.graph.edge_index, self.graph.edge_weight])
        print(self.graph.x.shape)
        print(self.graph.edge_index.shape)
        print(self.graph.edge_weight.shape)
        print(self.graph)
        #self.graph.x = tf.placeholder(tf.int16, shape=(len(cluster_info),))
        #print(self.graph.x)
        self.graph.convert_data_to_tensor()
        gcn0 = tfg.layers.GCN(16, activation=tf.nn.relu)
        #gcn1 = tfg.layers.GCN(128)

        h = gcn0([self.graph.x, self.graph.edge_index, self.graph.edge_weight])
        h = gcn1([h, self.graph.edge_index, self.graph.edge_weight],
                 cache=self.graph.cache)
        print(h)
        self.q_values = action_out
        self._setup_init()

        def step(self, obs, state=None, mask=None, deterministic=True):
            q_values, actions_proba = self.sess.run(
                [self.q_values, self.policy_proba], {self.obs_ph: obs})
            if deterministic:
                actions = np.argmax(q_values, axis=1)
            else:
                # Unefficient sampling
                # TODO: replace the loop
                # maybe with Gumbel-max trick ? (http://amid.fish/humble-gumbel)
                actions = np.zeros((len(obs), ), dtype=np.int64)
                for action_idx in range(len(obs)):
                    actions[action_idx] = np.random.choice(
                        self.n_actions, p=actions_proba[action_idx])

            return actions, q_values, None
コード例 #4
0
def construct_graph(
    graph_dict
):  #构建图,将节点类别的one_hot作为节点特征(num_nodes, 37),将图的类别标签作为图的ground_truth(1,)
    return tfg.Graph(
        x=convert_node_labels_to_one_hot(graph_dict["node_labels"]),
        edge_index=graph_dict["edge_index"],
        y=graph_dict[
            "graph_label"]  # graph_dict["graph_label"] is a list with one int element
    )
コード例 #5
0
def construct_graph(
    graph_dict
):  #构建图,将节点类别的one_hot作为节点特征(num_nodes, 37),将图的类别标签作为图的ground_truth(1,)
    return tfg.Graph(
        x=keras.utils.to_categorical(graph_dict["node_labels"],
                                     num_node_labels),
        edge_index=graph_dict["edge_index"],
        y=graph_dict[
            "graph_label"]  # graph_dict["graph_label"] is a list with one int element
    )
コード例 #6
0
def build_word_graph(num_words, pmi_model, embedding_size):
    x = tf.Variable(tf.random.truncated_normal([num_words, embedding_size], stddev=1 / np.sqrt(embedding_size)),
                    dtype=tf.float32)
    edges = []
    edge_weight = []
    for (word0, word1) in pmi_model.pair_counter.keys():
        pmi = pmi_model.transform(word0, word1)
        if pmi > 0:
            edges.append([word0, word1])
            edge_weight.append(pmi)
            edges.append([word1, word0])
            edge_weight.append(pmi)
    edge_index = np.array(edges).T
    return tfg.Graph(x=x, edge_index=edge_index, edge_weight=edge_weight)
コード例 #7
0
def build_combined_graph(word_graph, sequences, embedding_size):
    num_words = word_graph.num_nodes
    x = tf.zeros([len(sequences), embedding_size], dtype=tf.float32)
    edges = []
    edge_weight = []
    for i, sequence in enumerate(sequences):
        doc_node_index = num_words + i
        for word in sequence:
            edges.append([doc_node_index, word])  # only directed edge
            edge_weight.append(1.0)  # use BOW instaead of TF-IDF

    edge_index = np.array(edges).T
    x = tf.concat([word_graph.x, x], axis=0)
    edge_index = np.concatenate([word_graph.edge_index, edge_index], axis=1)
    edge_weight = np.concatenate([word_graph.edge_weight, edge_weight], axis=0)
    return tfg.Graph(x=x, edge_index=edge_index, edge_weight=edge_weight)
コード例 #8
0
ファイル: demo_gae.py プロジェクト: zzhzaihq/tf_geometric
# undirected edges can be used for evaluation
undirected_train_edge_index, undirected_test_edge_index, _, _ = edge_train_test_split(
    edge_index=graph.edge_index,
    test_size=0.15
)

# use negative_sampling with replace=False to create negative edges for test
undirected_test_neg_edge_index = negative_sampling(
    num_samples=undirected_test_edge_index.shape[1],
    num_nodes=graph.num_nodes,
    edge_index=graph.edge_index,
    replace=False
)

# for training, you should convert undirected edges to directed edges for correct GCN propagation
train_graph = tfg.Graph(x=graph.x, edge_index=undirected_train_edge_index).convert_edge_to_directed()


embedding_size = 16
drop_rate = 0.2

gcn0 = tfg.layers.GCN(32, activation=tf.nn.relu)
gcn1 = tfg.layers.GCN(embedding_size)
dropout = keras.layers.Dropout(drop_rate)


def encode(graph, training=False):
    h = gcn0([graph.x, graph.edge_index, graph.edge_weight], cache=graph.cache)
    h = dropout(h, training=training)
    h = gcn1([h, graph.edge_index, graph.edge_weight], cache=graph.cache)
    return h
コード例 #9
0
# Make the edge_index directed such that we can use it as the input of GCN
edge_index, [edge_weight] = convert_edge_to_directed(edge_index, [edge_weight])

# We can convert these numpy array as TensorFlow Tensors and pass them to gnn functions
outputs = tfg.nn.gcn(
    tf.Variable(x),
    tf.constant(edge_index),
    tf.constant(edge_weight),
    tf.Variable(tf.random.truncated_normal([20, 2]))  # GCN Weight
)
print(outputs)

# Usually, we use a graph object to manager these information
# edge_weight is optional, we can set it to None if you don't need it
graph = tfg.Graph(x=x, edge_index=edge_index, edge_weight=edge_weight)

# You can easily convert these numpy arrays as Tensors with the Graph Object API
graph.convert_data_to_tensor()

# Then, we can use them without too many manual conversion
outputs = tfg.nn.gcn(
    graph.x,
    graph.edge_index,
    graph.edge_weight,
    tf.Variable(tf.random.truncated_normal([20, 2])),  # GCN Weight
    cache=graph.
    cache  # GCN use caches to avoid re-computing of the normed edge information
)
print(outputs)
                                nrows=max)
    fingerprint = fingerprint.drop(columns=['compoundID'])

    reactions = np.array(reactions.T)
    a = np.ones(shape=reactions.shape)
    reactions = reactions - a
    reactions = pd.DataFrame(reactions, dtype=np.int64)
    fingerprint = np.array(fingerprint)
    reactions = np.array(reactions)

    return reactions, fingerprint


reactions_all, compounds_fp = load_data(DATA_PATH, FINGERPRINT, 1000)

graph = tfg.Graph(x=compounds_fp, edge_index=reactions_all)

# undirected edges can be used for evaluation
undirected_train_edge_index, undirected_test_edge_index, _, _ = edge_train_test_split(
    edge_index=graph.edge_index, test_size=0.15)

# use negative_sampling with replace=False to create negative edges for test
undirected_test_neg_edge_index = negative_sampling(
    num_samples=undirected_test_edge_index.shape[1],
    num_nodes=graph.num_nodes,
    edge_index=graph.edge_index,
    replace=False)

# convert undirected edges to directed edges for correct GCN propagation
train_graph = tfg.Graph(
    x=graph.x,
コード例 #11
0
# coding=utf-8
import numpy as np
import tf_geometric as tfg
import tensorflow as tf

graph = tfg.Graph(
    x=np.random.randn(5, 20),  # 5 nodes, 20 features,
    edge_index=[[0, 0, 1, 3], [1, 2, 2, 1]]  # 4 undirected edges
)

print("Graph Desc: \n", graph)

graph.convert_edge_to_directed()  # pre-process edges
print("Processed Graph Desc: \n", graph)
print("Processed Edge Index:\n", graph.edge_index)

# Multi-head Graph Attention Network (GAT)
gat_layer = tfg.layers.GAT(units=4, num_heads=4, activation=tf.nn.relu)
output = gat_layer([graph.x, graph.edge_index])
print("Output of GAT: \n", output)