|
| 1 | +# BlueGraph: unifying Python framework for graph analytics and co-occurrence analysis. |
| 2 | + |
| 3 | +# Copyright 2020-2021 Blue Brain Project / EPFL |
| 4 | + |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | + |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +from collections import namedtuple |
| 17 | +import warnings |
| 18 | +import pandas as pd |
| 19 | + |
| 20 | +from gensim.models.poincare import PoincareModel |
| 21 | + |
| 22 | +from bluegraph.core.embed.embedders import GraphElementEmbedder |
| 23 | +from bluegraph.backends.params import (GENSIM_PARAMS, |
| 24 | + DEFAULT_GENSIM_PARAMS) |
| 25 | + |
| 26 | + |
| 27 | +GensimGraph = namedtuple('GensimGraph', 'graph graph_configs') |
| 28 | + |
| 29 | + |
| 30 | +class GensimNodeEmbedder(GraphElementEmbedder): |
| 31 | + |
| 32 | + _transductive_models = [ |
| 33 | + "poincare", |
| 34 | + "word2vec" |
| 35 | + ] |
| 36 | + |
| 37 | + def __init__(self, model_name, directed=True, include_type=False, |
| 38 | + feature_props=None, feature_vector_prop=None, |
| 39 | + edge_weight=None, **model_params): |
| 40 | + if directed is False and model_name == "poincare": |
| 41 | + raise GraphElementEmbedder.FittingException( |
| 42 | + "Poincare embedding can be performed only on directed graphs: " |
| 43 | + "undirected graph was provided") |
| 44 | + super().__init__( |
| 45 | + model_name=model_name, directed=directed, |
| 46 | + include_type=include_type, |
| 47 | + feature_props=feature_props, |
| 48 | + feature_vector_prop=feature_vector_prop, |
| 49 | + edge_weight=edge_weight, **model_params) |
| 50 | + |
| 51 | + @staticmethod |
| 52 | + def _generate_graph(pgframe, graph_configs): |
| 53 | + """Generate backend-specific graph object.""" |
| 54 | + return GensimGraph(pgframe, graph_configs) |
| 55 | + |
| 56 | + def _dispatch_model_params(self, **kwargs): |
| 57 | + """Dispatch training parameters.""" |
| 58 | + params = {} |
| 59 | + for k, v in kwargs.items(): |
| 60 | + if k not in GENSIM_PARAMS[self.model_name]: |
| 61 | + warnings.warn( |
| 62 | + f"GensimNodeEmbedder's model '{self.model_name}' " |
| 63 | + f"does not support the training parameter '{k}', " |
| 64 | + "the parameter will be ignored", |
| 65 | + GraphElementEmbedder.FittingWarning) |
| 66 | + else: |
| 67 | + params[k] = v |
| 68 | + |
| 69 | + for k, v in DEFAULT_GENSIM_PARAMS.items(): |
| 70 | + if k not in params: |
| 71 | + params[k] = v |
| 72 | + return params |
| 73 | + |
| 74 | + def _fit_transductive_embedder(self, train_graph): |
| 75 | + """Fit transductive embedder (no model, just embeddings).""" |
| 76 | + |
| 77 | + model_params = {**self.params} |
| 78 | + del model_params["epochs"] |
| 79 | + |
| 80 | + if self.model_name == "poincare": |
| 81 | + model = PoincareModel( |
| 82 | + train_graph.graph.edges(), **model_params) |
| 83 | + |
| 84 | + model.train(epochs=self.params["epochs"]) |
| 85 | + |
| 86 | + embedding = pd.DataFrame( |
| 87 | + [ |
| 88 | + (n, model.kv.get_vector(n)) |
| 89 | + for n in train_graph.graph.nodes() |
| 90 | + ], |
| 91 | + columns=["@id", "embedding"] |
| 92 | + ).set_index("@id") |
| 93 | + return embedding |
| 94 | + |
| 95 | + def _fit_inductive_embedder(self, train_graph): |
| 96 | + """Fit inductive embedder (predictive model and embeddings).""" |
| 97 | + raise NotImplementedError( |
| 98 | + "Inductive models are not implemented for gensim-based " |
| 99 | + "node embedders") |
| 100 | + |
| 101 | + def _predict_embeddings(self, graph, nodes=None): |
| 102 | + """Fit inductive embedder (predictive model and embeddings).""" |
| 103 | + raise NotImplementedError( |
| 104 | + "Inductive models are not implemented for gensim-based " |
| 105 | + "node embedders") |
| 106 | + |
| 107 | + @staticmethod |
| 108 | + def _save_predictive_model(model, path): |
| 109 | + pass |
| 110 | + |
| 111 | + @staticmethod |
| 112 | + def _load_predictive_model(path): |
| 113 | + pass |
0 commit comments