Heterogeneous Graph Contrastive Learning With Meta-Path Contexts and Adaptively Weighted Negative Samples

Heterogeneous graph contrastive learning has received wide attention recently. Some existing methods use meta-paths, which are sequences of object types that capture semantic relationships between objects, to construct contrastive views. However, most of them ignore the rich meta-path context information that describes how two objects are connected by meta-paths. Further, they fail to distinguish negative samples, which could adversely affect the model performance. To address the problems, we propose MEOW, which considers both meta-path contexts and weighted negative samples. Specifically, MEOW constructs a coarse view and a fine-grained view for contrast. The former reflects which objects are connected by meta-paths, while the latter uses meta-path contexts and characterizes details on how the objects are connected. Then, we theoretically analyze the InfoNCE loss and recognize its limitations for computing gradients of negative samples. To better distinguish negative samples, we learn hard-valued weights for them based on node clustering and use prototypical contrastive learning to pull close embeddings of nodes in the same cluster. In addition, we propose a variant model AdaMEOW that adaptively learns soft-valued weights of negative samples to further improve node representation. Finally, we conduct extensive experiments to show the superiority of MEOW and AdaMEOW against other state-of-the-art methods.


I. INTRODUCTION
H ETEROGENEOUS information networks (HINs) are prevalent in the real world, such as social networks, citation networks, and knowledge graphs.In HINs, nodes (objects) are of different types to represent entities and edges (links) are also of multiple types to characterize various relations between entities.For example, in Facebook, we have entities like users, posts, photos and groups; users can publish posts, upload photos and join groups.Compared with homogeneous graphs where all the nodes and edges are of a single type, HINs contain richer semantics and more complicated structural information.To further enrich the information of HINs, nodes are usually associated with labels.Since object labeling is costly, graph neural networks (GNNs) [1]- [3] have recently been applied for classifying nodes in HINs and have shown to achieve superior performance.
Despite the success, most existing heterogeneous graph neural network (HGNN) models require a large amount of training data, which is difficult to obtain.To address the problem, selfsupervised learning, which is in essence unsupervised learning, has been applied in HINs [4], [5].The core idea of selfsupervised learning is to extract supervision from data itself and learn high-quality representations with strong generalizability for downstream tasks.In particular, contrastive learning, as one of the main self-supervised learning types, has recently received significant attention.Contrastive learning aims to construct positive and negative pairs for contrast, following the principle of maximizing the mutual information (MI) [6] between positive pairs while minimizing that between negative pairs.Although some graph contrastive learning methods for HINs have already been proposed [4], [5], [7], most of them suffer from the following two main challenges: contrastive view construction and negative sample selection.
On the one hand, to construct contrastive views, some methods utilize meta-paths [8], [9].A meta-path, which is a sequence of object types, captures the semantic relation between objects in HINs.For example, if we denote the object types User and Group in Facebook as "U" and "G", respectively, the meta-path User-Group-User (UGU) expresses the co-participation relation.Specifically, two users u 1 and u 2 are UGU-related if a path instance u 1 − g − u 2 exists, where g is a group object and describes the contextual information on how u 1 and u 2 are connected.The use of meta-paths can identify a set of path-based neighbors that are semantically related to a given object and provide different views for contrast.However, existing contrastive learning methods omit the contextual information in each meta-path view.For example, HeCo [9] takes meta-paths as views, but it only uses the fact that two objects are connected by meta-paths and discards the contexts of how they are semantically connected, which we will call meta-path contexts and can be very influential in the classification task.For example, a group can provide valuable hints on a user's topic interests.Therefore, contrasting metapath views with rich contexts is a necessity.
On the other hand, negative sample selection is another challenge to be addressed.Note that most existing graph contrastive learning methods [10]- [12] are formulated in a sampled noise contrastive estimation framework.For each node in a view, random negative sampling from the rest of intraview and inter-view nodes is widely adopted.However, this could introduce many easy negative samples and false negative samples.For easy negative samples, they are less informative and easily lead to the vanishing gradient problem [13], while the false negative samples can adversely affect the learning arXiv:2212.13847v3[cs.LG] 5 Apr 2024 process for providing incorrect information.Recently, there exist some works [13]- [15] that seek to identify hard negative samples for improving the discriminative power of encoders in HINs.Despite their success, most of them fail to distinguish hard negatives from false ones.While ASA [14] is proposed to solve the issue, it is specially designed for the link prediction task and can only generate negative samples for objects based on one type of relation in HINs, which restricts its wide applicability.Since there is not a clear cut boundary between false negatives and hard ones, how to balance the exploitation of hard negative and false negative remains to be investigated.
In this paper, to solve the two challenges, we propose a heterogeneous graph contrastive learning method MEOW with meta-path contexts and weighted negative samples.Based on meta-paths, we construct two novel views for contrast: the coarse view and the fine-grained view.The coarse view expresses that two objects are connected by meta-paths, while the fine-grained view utilizes meta-path contexts and describes how they are connected.In the coarse view, we simply aggregate all the meta-paths and generate node embeddings that are taken as anchors.In the fine-grained view, we construct positive and negative samples for each anchor.Specifically, for each meta-path, we first generate nodes' embeddings based on the meta-path induced graph.To further improve the generalizability of the model, we introduce noise by performing graph perturbations, such as edge masking and feature masking, on the meta-path induced graph to derive an augmented one, based on which we also generate node embeddings.In this way, each meta-path generates two embedding vectors for each node.After that, for each node, we fuse different embeddings from various meta-paths to generate its final embedding vector.Then for each anchor, its embedding vector in the fine-grained view is taken as a positive sample while those of other nodes are considered as negative samples.Subsequently, based on theoretical analysis, we recognize that the InfoNCE loss lacks the ability to discriminate negative samples that have the same similarity with an anchor during training.Therefore, we perform node clustering and use the results to grade the weights of negative samples in MEOW to distinguish negative samples.To further boost the model performance, we employ prototypical contrastive learning [16], where the cluster centers, i.e., prototype vectors, are used as positive/negative samples.This helps learn compact embeddings for nodes in the same cluster by pushing nodes close to their corresponding prototype vectors and far away from other prototype vectors.In addition, since the weights are hard-valued in MEOW, we further propose a variant model called AdaMEOW that can adaptively learn the soft-valued weights of negative samples, making negative samples more personalized and improving the learning ability of node representations.Finally, we summarize our contributions as: • We propose a novel heterogeneous graph contrastive learning model MEOW, which constructs a coarse view and a fine-grained view for contrast based on meta-paths, respectively.The former shows objects are connected by meta-paths, while the latter employs meta-path contexts and expresses how objects are connected by meta-paths.
• We recognize the limitation of the InfoNCE loss based on theoretical analysis and propose a contrastive loss function with weighted negative samples to better distinguish negative samples.• We distinguish negative samples by performing node clustering and using the results to grade their weights.
Based on the clustering results, we also introduce prototypical contrastive learning to help learn compact embeddings of nodes in the same cluster.Further, we propose a variant model, namely, AdaMEOW, which adaptively learns soft-valued weights for negative samples.

II. RELATED WORK A. Heterogeneous Graph Neural Network
Heterogeneous graph neural network (HGNN) has recently received much attention and there have been some models proposed.For example, HetGNN [17] aggregates information from neighbors of the same type with bi-directional LSTM to obtain type-level neighbor representations, and then fuses these neighbor representations with the attention mechanism.HGT [18] designs Transformer-like attention architecture to calculate mutual attention of different neighbors.HAN [2] employs both node-level and semantic-level attention mechanisms to learn the importance of neighbors under each metapath and the importance of different meta-paths, respectively.Considering meta-path contexts information, MAGNN [3] improves HAN by employing a meta-path instance encoder to incorporate intermediate semantic nodes.Further, Graph Transformer Networks (GTNs) [19] are capable of generating new graph structures, which can identify useful connections between unconnected nodes in the original graph and learn effective node representation in the new graphs.Despite the success, most of these methods are semi-supervised, which heavily relies on labeled objects.

B. Graph Contrastive Learning (GCL)
Contrastive learning aims to construct positive and negative pairs for contrast, whose goal is to pull close positive pairs while pushing away negative ones.Recently, some works have applied contrastive learning to graphs [20], [21].In particular, most of these approaches use data augmentation to construct contrastive views and adopt the following three main contrast mechanisms: (1) node-node contrast [22]- [24]; (2) graphgraph contrast [10], [25]; (3) node-graph contrast [26], [27].For example, GRACE [11] treats two augmented graphs by node feature masking and edge removing as two contrastive views and then pulls the representation of the same nodes close while pushing the remaining nodes apart.Inspired by SimCLR [28] in the visual domain, GraphCL [29] further extends this idea to graph-structured data, which relies on node dropping and edge perturbation to generate two perturbed graphs and then maximizes the two graph-level mutual information (MI).Moreover, DGI [30] is the first approach to propose the contrast between node-level embeddings and graphlevel embeddings, which allows graph encoders to learn local and global semantic information.In heterogeneous graphs, HeCo [9] takes two views from network schema and metapaths to generate node representations and perform contrasts between nodes.HDGI [31] extends DGI to HINs and learns high-level node representations by maximizing MI between local and global representations.However, most of these methods select negative samples by random sampling, which will introduce false negatives.These samples will adversely affect the learning process, so we need to distinguish them from hard negatives.

C. Hard Negative Sampling
In contrastive learning, easy negative samples are easily distinguished from anchors, while hard negative ones are similar to anchors.Recent studies [32] have shown that contrastive learning can benefit from hard negatives, so there are some works that explore the construction of hard negatives.The most prominent method is based on mixup [33], a data augmentation strategy for creating convex linear combinations between samples.In the area of computer vision, Mochi [34] measures the distance between samples by inner product and randomly selects two samples from N nearest ones to be combined by mixup as synthetic negative samples.Further, CuCo [35] uses cosine similarity to measure the difference of nodes in homogeneous graphs.In heterogeneous graphs, STENCIL [15] uses meta-path-based Laplacian positional embeddings and personalized PageRank scores for modeling local structural patterns of the meta-path-induced view.However, these methods either fail to distinguish hard negative samples from false ones or are built on one type of relation in HINs, which restricts the wide applicability of these models.

III. PRELIMINARY
In this section, we formally define some related concepts used in this paper.

Definition 1. Heterogeneous Information Network (HIN).
An HIN is defined as a graph G = (V, E), where V is a set of nodes and E is a set of edges, each represents a binary relation between two nodes in V. Further, G is associated with two mappings: (1) node type mapping function ϕ : V → T and (2) edge type mapping function ψ : E → R, where T and R denote the sets of node and edge types, respectively.
between nodes of types T 1 and T l+1 , where • denotes the composition operator on relations.If two nodes x i and x j are related by the composite relation R, then there exists a path that connects x i to x j in G, denoted by p xi⇝xj .Moreover, the sequence of nodes and edges in p xi⇝xj matches the sequence of types T 1 , ..., T l+1 and relations R 1 , ..., R l according to the node type mapping ϕ and the edge type mapping ψ, respectively.We say that p xi⇝xj is a path instance of P, denoted by p xi⇝xj ⊢ P. Definition 3. Meta-path Context [1].Given two objects x i and x j that are related by a meta-path P, the meta-path context is the set of path instances of P between x i and x j .Definition 4. Heterogeneous Graph Contrastive Learning.Given an HIN G, our task is to learn node representations by constructing positive and negative pairs for contrast.In this paper, we only focus on one type of nodes, which are considered as target nodes.

IV. METHODOLOGY
In this section, we introduce our method MEOW and the variant model AdaMEOW.The general model diagram is shown in Fig. 1.We perform feature transformation and neighbor filtering as preprocessing steps.First, we map the feature vectors of each different type of nodes into the same dimension (Step ①) and identify a set of neighbors for nodes based on each meta-path (Step ②).Then, we construct a coarse view by aggregating all meta-paths (Step ③), while constructing a fine-grained view with each meta-path's contextual semantic information (Step ④).After that, we fuse different embeddings from various meta-paths in the fine-grained view through the attention mechanism (Step ⑤).We take node embeddings in the coarse view as anchors and those in the fine-grained view as the positive and negative samples.To be capable of distinguishing false negative samples and hard negative samples, we perform clustering and assign weights to the negative samples with the clustering results (Step ⑥).Finally, to further boost the model performance, we use prototypical contrastive learning to calculate the contrastive loss and prototypical loss based on the node embedding vectors under coarse view and fine-grained view and the clustering results (Step ⑦).In addition, to further obtain adaptive negative sample weights, we propose the variant AdaMEOW with MLP to learn the weights instead of clustering and calculate the contrastive loss.Next, we describe each component in detail.

A. Node Feature Transformation
Since an HIN is composed of different types of nodes and each type has its own feature space, we need to first preprocess node features to transform them into the same space.Specifically, for each object x i in type T , we use the type-specific mapping matrix W (1) T to transform the raw features of x i into: where h i ∈ R d is the projected initial embedding vector of x i , σ(•) is an activation function, and b T denotes the bias vector.

B. Neighbor Filtering
Given an object x, meta-paths can be used to derive its multi-hop neighbors with specific semantics.When metapaths are long, the number of related neighbors to x could be numerous.Directly aggregating information from these neighbors to generate x's embedding will be time-consuming.On the other hand, the irrelevant neighbors of x cannot provide useful information to predict x's label and they could adversely affect the quality of the generated embedding of x.Therefore, we filter x's meta-path induced neighbors and select the most relevant to x. Inspired by [1], we adopt PathSim [36] to measure the similarity between objects.Specifically, given a meta-path P, the similarity between two objects x i and x j of the same type w.r.t.P is computed by:

Contrast Encoder
where p xi⇝xj is a path instance between x i and x j .Based on the similarities, for each object, we select its top-K neighbors with the largest similarity.The removal of irrelevant neighbors can significantly reduce the number of neighbors for each object, which further improves the model efficiency.After neighbor filtering, the induced adjacency matrix by meta-path P is denoted as A P .

C. Coarse View
We next construct coarse view to describe which objects are connected by meta-paths.Given a set of meta-paths, each meta-path P can induce its own adjacency matrix A P .To provide a coarse view on the connectivity between objects by meta-paths, we fuse the meta-path induced adjacency matrices and define , where m is the number of meta-paths and where |V | is the number of target nodes.After that, we feed node embeddings calculated by Equation 1 and A into a two-layer GCN encoder to get the representations of nodes in the coarse view.Specifically, for node x i , we can get its coarse representation z c i :

D. Fine-grained View
The fine-grained view characterizes how two objects are connected by meta-paths, which is in contrast with the coarse view.Given a meta-path set PS = {P 1 , ..., P m }, for each meta-path P u ∈ PS, let P u = T 0 T 1 ...T l , where the meta-path length is l + 1.The meta-path can link objects of type T 0 to that of type T l via a series of intermediate object types.Since meta-path contexts are composed of path instances and capture details on how two objects are connected, we utilize meta-path contexts to learn fine-grained representations for objects.However, when l is large, due to the numerous path instances between two objects, directly handling each path instance as MAGNN [3] could significantly degenerate the model efficiency, as pointed out in [1].We instead use objects in the intermediate types of meta-path P u to leverage the information of meta-path contexts.Specifically, given a metapath P u and an object x i of type T 0 , we denote N Tj i as x i 's j-hop neighbor set w.r.t.P u .Then we generate x i 's initial fine-grained embedding by aggregating information from all its j-hop neighbors with j ≤ l.Formally, we have where the learnable parameter matrix W (2) uj corresponds to the j-hop neighbors w.r.t.P u .After that, we put the node embedding h Pu i that aggregates the meta-path context information and the adjacency matrix under the meta-path A Pu into a twolayer GCN encoder to generate x i 's fine-grained embedding: Note that the encoder here is the same as that used in the coarse view (see Equation 3).Further, to improve the model generalizability, we introduce noise to the meta-path induced graph by performing graph augmentation, such as edge masking and feature masking.After the perturbed graph is generated, we feed it into Equation 5 to generate the node embedding z Pu i .In this way, for each meta-path P u and an object x i , we generate two embeddings z Pu i , z Pu i .Given a meta-path set PS = {P 1 , ..., P m }, we can generate Z i = {z Pu i , z Pu i |P u ∈ PS} for node x i from various metapaths.Finally, we fuse these embeddings by the attention mechanism: ) Here, we measure the weight of each node type.V is the set of target nodes, W att ∈ R d×d is the weight matrix, b att is the bias vector and β s denotes the attention weight.We can generate x i 's fine-grained embedding vector z f i :

E. Theoretical analysis on the InfoNCE loss
In contrastive learning, different negative samples have different characteristics, so their impact should not be the same.For a given anchor, some negative samples are easy to distinguish, while some hard negative samples may have a certain degree of similarity with the anchor but belong to a different class.Therefore, in order to keep negative samples away from the anchor, it is necessary to distinguish the effects of different negative samples on the anchor.With this in mind, we first propose Theorem 1.
Theorem 1.Consider the contrastive learning InfoNCE loss [6] that uses dot product to measure node similarity, denoted as L. Let f (x) represent the learned embedding of node x.Given x i as an anchor, x k as its positive sample and x t1 , x t2 as its two negative samples, with back propagation, we can get: Proof.The contrastive loss function InfoNCE is defined as: where sim(f (x i ), f (x j )) measures the similarity between node embeddings f (x i ) and f (x j ), τ is a hyperparamter denotes the temperature and n is the number of negative samples.
Typically, the dot product is used as a similarity function, and the InfoNCE loss can be further simplified as: (9) For a particular negative sample x t , t = 1, 2, • • • , n, the gradient of the negative sample x t is: For all the negative samples of anchor x i , the gradient only depends on f (x i ) T f (x t ).This is because f (x i ) determines the direction of back propagation, and τ is equal for all the negative samples.We can thus derive inequality (1) in Theorem 1, which states that if f In addition, we can also compute the gradient of the positive sample by taking its derivative.
We observe that compared to positive samples, Equation 10for negative samples has an additional softmax term, whose value ranges between 0 and 1.So we can derive inequality The equation holds if and only if the softmax term equals one, which is generally very difficult to satisfy.
From Theorem 1, easy negative samples that are less similar to the anchor lead to smaller gradient magnitude, while hard negative samples can derive larger gradient magnitude.This is because easy negative samples are already far enough from the anchor and we don't need to pay much attention to them.However, hard negative samples need larger gradients to push them apart.Further, the comparison between Equation 10and Equation 11shows that the gradient magnitude of positive samples is generally much larger than that of negative samples, due to the additional softmax term that is generally smaller than 1 in Equation 10.In summary, in each epoch, compared to negative samples with lower similarity to the anchor, negative ones with higher similarity will be more violently pushed away from the anchor.On the other hand, positive samples will have a larger update magnitude than negative samples, resulting in a closer proximity to the anchor.
We next randomly select a paper and an author as the anchor node from the ACM dataset [37] and the DBLP dataset [3], respectively, and study the relationship between node similarity and gradient magnitude of loss functions w.r.t.negative samples.As shown in Figure 2, the orange curves in both subfigures show that the gradient magnitude of the InfoNCE loss is proportionally to the similarity between negative samples with the anchor node, which is consistent with Equation 10.Although the InfoNCE loss can distinguish samples from different classes to some extent, the gradient magnitude only depends on node similarity, which lacks the flexibility to capture the variability in node embeddings.For example, suppose there are three samples whose representations are: x 1 (1, 1), x 2 (1, 0) and x 3 (0, 1), respectively.We take x 1 as the anchor.For the sample pairs (x 1 , x 2 ) and (x 1 , x 3 ), their similarity values are both 1, but the semantic information contained in x 2 and x 3 is completely different, and even opposite to each other.This should further lead to different gradient update directions.Therefore, using only node similarity to determine the gradient of a negative sample is insufficient.We thus need to introduce other metrics to capture the fine-grained information of embeddings of negative samples.

F. The MEOW model
In this section, we perform contrastive learning to learn node embeddings with the constructed coarse view and fine-grained view and propose our loss function with additional weights for negative sample pairs.Before contrast, we use a projection head (one-layer MLP) to map node embedding vectors to the space where contrastive loss can be applied.Specifically, for x i , we have: After that, we take representations in the coarse view as anchors and construct the positive and negative samples from the fine-grained view.For each node x i , we take z c i as the anchor, z f i as the corresponding positive sample, and all other node representations in the fine-grained view as negative samples.Further, to utilize hard negatives and mitigate the adverse effect of false negatives, we learn the importance of negative samples.In particular, we perform node clustering based on the fine-grained representations for M times, where the number of clusters are set as Then, we assign different weights to negative samples of a node based on the clustering results.Intuitively, when the number of clusters is set large, each cluster will become compact.Then compared with hard negatives, false negatives and easy negatives are more likely to be assigned in the same cluster and different clusters with the anchor node, respectively.Therefore, we use γ ij to denote the weight of node x j as a negative sample to node x i and set it as a function F of clustering results.
For simplicity, we define the function F to count the number of times that the sample x j and the anchor x i are in different  clusters.We denote , where C r is the r-th clustering result.In particular, we can understand γ ij as the push strength.For false negatives, γ ij should be small to ensure that they will not be pushed away from the anchor.For hard negatives, γ ij is expected to be much larger because in this way, the anchor and hard negatives can be discriminated.Since easy samples are distant from the anchor, the model will be insensitive to γ ij in a wide range of values.Then based on γ ij , we can formulate our contrastive loss function as where τ is a temperature parameter.Similar as Theorem 1, we also analyze our loss function from the perspective of gradient in the back propagation process.
Theorem 2. For the proposed loss function in Equation 13, we use node embedding function f (•) to overload z.Then given an anchor node x i with positive sample x k and one of its negative sample x t , the gradient of L con i w.r.t.f (x) at x t is Proof.Similar as the InfoNCE loss, our proposed loss function L con i for anchor x i can be simplified as: The gradient of the positive sample is the same as the InfoNCE loss, and the derivative of the representation of the negative sample x t can be obtained as: The gradient magnitude now has an additional learnable parameter γ it for x t , which assigns personalized weights to negative samples sharing the same similarity with the anchor.
Compared to the original InfoNCE loss, our proposed loss function relies not only on the similarity between anchor and negative samples, but also on the characterization of anchor and negative samples during the optimization process.This can be further combined with the characterization of node pairs to adaptively adjust the push strength in the hidden space, thus improving the quality of the representation.For example, negative samples x 2 (1, 0) and x 3 (0, 1) have the same similarity values with anchor x 1 (1, 1).The learnable weights γ 12 and γ 13 makes them more distinguishable, and the gradients of the two are different during backpropagation.
To further make embeddings of nodes in the same cluster more compactly distributed in the latent space, we introduce an additional prototypical contrastive learning loss function.In the r-th clustering, we consider the prototype vector c r i , i.e., the cluster center, corresponding to node x i as a positive sample and other prototype vectors as negative samples and define: where θ r i is a temperature parameter and represents the concentration estimate of the cluster C i r that contains node x i .Following [16], we calculate , where Q is the number of nodes in the cluster and α is a smoothing parameter to ensure that small clusters do not have an overlylarge θ.Finally, we formulate our objective function L as: where V is the set of target nodes and λ controls the relative importance of the two terms.The loss function can be optimized by stochastic gradient descent.To prevent overfitting, we further regularize all the weight matrices W mentioned above.The whole training procedure of the MEOW model is summarized in Algorithm 1.

G. The AdaMEOW model
The weights we calculate in MEOW based on the clustering results can actually provide more fine-grained differentiations of negative samples.However, these weights are hard values and could limit node representation learning.Therefore, it is necessary to explore alternative approaches that can better facilitate flexible weight calculations, thereby enhancing the overall performance of the model.Instead of clustering, we propose an enhanced model AdaMEOW with an adaptive approach to learn soft-valued weights.Specifically, we apply a two-layer MLP to learn the weights according to the node representations under both the coarse and fined-grained views, which is formally formulated as: (1) Ada are the learnable parameter matrices and b Ada are the bias vectors.Note that σ (1) is the Tanh function and σ (2) is the sigmoid function, which ensures that the weights are soft values ranging from 0 and 1. H(z c i , z f j ) is a pooling function between z c i under the coarse view and z f i under the fine-grained view, and we use SUM as the pooling function.The overall objective is given by: where γ ij is a soft-valued weight between anchor x i and negative sample x j .We distinguish it from the hard-valued weight by using the tilde (∼) symbol.For each anchor node, the two-layer MLP can adaptively learn the weights of negative samples, and further lead to more informative gradients for them.As shown by the blue dots in Figure 2, optimizing Equation 19 allows for a more diverse set of gradient magnitudes for the same node similarity values.This further shows that γ ij can capture the individual characteristics of different negative samples and their corresponding gradients are not only determined by the similarity with the anchor.The contrastive part of the AdaMEOW model is summarized in Algorithm 2.

H. Complexity analysis
The major time complexity in our proposed model comes from GCN and MLP.Let d max be the maximum initial dimensions of different types of nodes and d A be the average number of non-zero entries in each row of the adjacency matrix for each meta-path induced graph.In Section IV-A, The time complexity for MLP is O(Bd max d) where B denotes the batch size and d is the dimension of the projected initial embedding vector.The GCN encoder used in the construction of the two views has a time complexity of O(Bd A d + Bd 2 ).After constructing the views, the time complexity of the contrastive loss function is O(B 2 d).For MEOW, node clustering requires O(t(k Compute the normalized adjacency matrix: Calculate temperature parameter θ r ; 21: end for 22: Construct L con , L proto , L using Eq.10-12; 23: Optimize L to update all parameters in the model.24: V. EXPERIMENTS

A. Datasets
To evaluate the performance of MEOW, we employ four real-world datasets: ACM [37], DBLP [3], Aminer [38] and Algorithm 2 The AdaMEOW model Input: The heterogeneous graph G = (V, E); the number of node type |T |; the number of target node |V |; the feature matrix X 1 , X 2 , • • • , X |T | ; a pre-defined meta-path set PS; Output: Target node embeddings for downstream tasks.1: ▷ The same steps as in Algorithm 1, from line 1 to line 16; 2: // Contrastive part 3: Calculate the weights of negative sample pairs γ ij using Eq.13; 4: Construct L based on weights using Eq.14; 5: Optimize L to update all parameters in the model.
IMDB [39].The four datasets are benchmark HINs.We next define a classification task for each dataset.
• ACM: ACM is an academic paper dataset.The dataset contains 4019 papers (P), 7167 authors (A), and 60 subjects (S).Links include P-A (an author publishes a paper) and P-S (a paper is based on a subject).We use PAP and PSP as meta-paths.Paper features are the bag-of-words representation of keywords.Our task is to classify papers into three areas: database, wireless communication, and data mining.
• DBLP: DBLP is extracted from the computer science bibliography website.The dataset contains 4057 authors (A), 14328 papers (P), 20 conferences (C) and 7723 terms (T).Links include A-P (an author publishes a paper), P-T (a paper contains a term) and P-C (a paper is published on a conference).We consider the meta-path set {APA, APCPA, APTPA}.Each author is described by a bag-of-words vector of their paper keywords.Our task is to classify authors into four research areas: Database, Data Mining, Artificial Intelligence and Information Retrieval.
• AMiner: Aminer is a bibliographic graphs.The dataset contains 6564 papers (P), 13329 authors (A) and 35890 references (R).Links include P-A (an author publishes a paper) and P-R (a reference for a paper).We consider the meta-path set {PAP, PRP}.Our task is to classify papers into four research areas.
• IMDB: As a subset of Internet Movie Database, the dataset contains 4275 moives (M), 5432 actors (A), 2083 directios (D) and 7313 keywords (K).Links include M-A (an actor stars in a movie), M-D (a director directs a movie) and M-K (a movie contains a keyword).We consider the meta-path set {MAM, MDM, MKM}.Our task is to classify movies into three classes, i.e., Action, Comedy and Drama.

B. Baselines
We compare MEOW with 9 other state-of-the-art methods, which can be grouped into three categories: •[Methods specially designed for homogeneous graphs]: GraphSAGE [20] aggregates information from a fixed number of neighbors to generate nodes' embedding.GAE [40] is a generative method that generates representations by reconstructing the adjacency matrix.DGI [30] maximizes the agree- ment between node representations and a global summary vector.
•[Semi-supervised learning methods in HINs]: HAN [2] is proposed to learn node representations using node-level and semantic-level attention mechanisms.
•[Unsupervised learning methods in HINs]: HERec [41] utilizes the skip-gram model on each meta-path to embed induced graphs.HetGNN [42] aggregates information from different types of neighbors based on random walk with start.DMGI [27] constructs contrastive learning between the original network and a corrupted network on each meta-path and adds a consensus regularization to fuse node embeddings from different meta-paths.Mp2vec [43] generates nodes' embedding vectors by performing meta-path-based random walks.HeCo [9] constructs two views with meta-paths and network schema to perform contrastive learning across them.
In particular, HeCo is the state-of-the-art heterogeneous contrastive learning model.

C. Experimental Setup
We implement MEOW with PyTorch and adopt the Adam optimizer to train the model.We fine-tune the learning rate from {5e-4, 6e-4, 7e-4}, the penalty weight on the l 2 -norm regularizer from {0, 1e-4, 1e-3} and the patience for early stopping from 10 to 40 with step size 5, i.e., we stop training if the total loss does not decrease for patience consecutive epochs.We set the dropout rate ranging from 0.0 to 0.9, and the temperature τ in Eq. 13 from 0.1 to 1.0, both with step size 0.1.We set K in the neighbor filtering based on the average number of connections of all the objects under each metapath.For data augmentation, we fine-tune the masking rate for both features and edges from 0.0 to 0.6 with step size 0.1.We perform node clustering twice and set α = 5 in all datasets.Further, we set the number of clusters U to {100, 300}, {200, 700}, {500, 1200}, and {100, 500} in ACM, DBLP, Aminer and IMDB, respectively.We fine-tune the regularization weights λ in prototypical contrastive learning from {0.1, 1, 10}.For Aminer, since nodes are not associated with features, we first run metapath2vec with the default parameter settings from the original codes provided by the authors to construct nodes' initial feature vectors.For fair comparison, we set the embedding dimension as 64 and randomly run the experiments 10 times, and report the average results for all the methods.For other competitors, their results are directly reported from [9].We run all the experiments on a server with 32G memory and a single Tesla V100 GPU.We provide our  code and data here: https://github.com/jianxiangyu/MEOW.

D. Node Classification
We use the learned node embeddings to train a linear classifier to evaluate our model.We randomly choose 20, 40, 60 labeled nodes per class as training set, and 1000 nodes as validation set and 1000 nodes for testing.We use Macro-F1, Micro-F1 and AUC as evaluation metrics.For all the metrics, the larger the value, the better the model performance.The results are reported in Table I.From the table, we see that MEOW achieves the suboptimal performance on ACM, DBLP and IMDB, and performs very well on Aminer in all the data splits.This shows the importance of meta-path contextual information and the validity of the contrastive views we designed.Compared with the state-of-the-art graph contrastive learning model Heco, MEOW achieves better performance on ACM, DBLP and IMDB.For example, the Macro-F1 score and the Micro-F1 score of Heco is 90.64% and 91.59% with 60 labeled nodes per class on DBLP, while MEOW is 93.49% and 94.13%.These results show the effectiveness of MEOW.While MEOW performs slightly worse than Heco in Macro-F1 and Micro-F1 on Aminer, it outperforms Heco in the AUC scores.This can be explained by the label imbalance on Aminer.Specifically, the number of objects in the label which has the maximum number of nodes is ∼ 7 times more than that in the label which has the minimum number of nodes.It is well known that when labeled objects are imbalanced, AUC is a more accurate metric than the other two.This further verifies that MEOW is effective.
AdaMEOW achieves the best performance in most 36 cases.On the basis of MEOW, AdaMEOW has been improved on each dataset, especially IMDB.In the IMDB dataset, with 20 labeled nodes per class, the Micro-F1 score of AdaMEOW is 62.91% and the Macro-F1 score is 63.13% while the runnersup scores are only 56.89% and 57.01%.This can demonstrate that adaptive weights have stronger learning capability on datasets with more noise.

E. Node Clustering
We further perform K-means clustering to verify the quality of learned node embeddings.We adopt normalized mutual information (NMI) and adjusted rand index (ARI) as the evaluation metrics.For both metrics, the larger, the better.The results are reported in Table II.As we can see, on the ACM dataset, MEOW obtains about 16% improvements on NMI and 25% improvements on ARI compared to the best of the benchmark methods, demonstrating the superiority of our model.This is because the prototypical contrastive learning drives node representations to be more compact in the same cluster, which helps boost node clustering.AdaMEOW can further make the boundaries between classes more distinct, resulting in better performance than MEOW.

F. Ablation Study
We conduct an ablation study on MEOW and AdaMEOW to understand the characteristics of its main components.To show the importance of the prototypical contrastive learning regularization, we train the model with L con only and call this variant MEOW wp (without prototypical contrastive learning).To demonstrate the importance of distinguishing negative samples with different characteristics, another variant is to not learn the weights of negative samples.We call this MEOW ww (without weight).Moreover, we update nodes' embeddings by aggregating information without considering meta-path contexts in the fine-grained view and call this variant MEOW nc (no context).This helps us understand the importance of including meta-path contexts in heterogeneous graph contrastive learning.We report the results of 40 labeled nodes per class, which is shown in Fig. 4. From these figures, MEOW achieves better performance than MEOW wp.This is because the prototypical contrastive learning can drive nodes of the same label to be more compact in the latent space, which leads to better classification results.MEOW outperforms MEOW ww on three datasets.This further demonstrates the advantage of weighted negative samples.In addition, MEOW beats MEOW nc in all cases.This shows that when using meta-paths, the inclusion of meta-path contexts is essential for effective heterogeneous graph contrastive learning.The AdaMEOW model outperforms others in most cases.This demonstrates the significance of capturing the characteristics of negative samples and the effectiveness of learning their weights adaptively.

G. Hyper-parameter Analysis
We further perform a sensitivity analysis on the hyperparameters of our method.In particular, we study three main hyper-parameters in MEOW: the number of selected relevant neighbor in Pathsim , the relative importance λ of the two components of the loss function in Eq. 17 on the ACM dataset and the number of clusters mentioned in Eq. 13 and Eq.16.In our experiments, we vary one parameter each time with others fixed.Figure 5 illustrates the results of the first two hyperparameters with 20, 40, 60 labeled nodes per class w.r.t. the Micro-F1 scores.(Results on Macro-F1 and AUC scores exhibit similar trends, and thus are omitted for space limitation.) Figure 6 displays the Macro-f1, Micro-f1, and AUC scores with 40 labeled nodes per class for the number of clusters.The diagonal represents the results for clustering once, while the off-diagonal entries represent the results for clustering twice.From the figure, we see that 1) In the case of meta-path PAP (Paper-Author-Paper), the more neighbors selected, the better the performance of the model.However, for meta-path PSP (Paper-Subject-Paper), we find that the Micro-F1 score first rises and then drops, as the number of neighbors increases.This is because the co-authored papers are more likely to be in the same area, while papers in the same subject could be from different research domains.With the increase of neighbors, more noisy connections induced by PSP could degrade the model performance.
2) For the weight λ that controls the importance of the prototypical contrastive loss function, MEOW gives very stable performances over a wide range of parameter values.The Micro-F1 score largely decreases when λ is large enough.This is because a larger λ will encourage more compactness within each class.However, this may cause some hard samples to be assigned to the incorrect clusters and cannot be corrected during the training process, resulting in misclassification.
3) From the heat map, we can observe that when the clustering size is small, samples from different classes may mix within the same cluster, which is detrimental to both contrastive loss and prototypical loss, resulting in poor model performance.When the clustering size is too large, each node forms a cluster with its most similar node, or even each node forms an individual cluster.In this case, the prototypical loss and contrastive loss become similar, resulting in the weighted contrastive loss not having a significant impact and causing a slight decrease in performance.

H. Case study
In this section, we analyze the learned weights in Equation 19 through experiments.First, we evaluate the advantages of weighted InfoNCE using three cases: NW(no weight),  RW(random weights), and AW(adaptive weights).NW means all weights are set to 1, which is equivalent to regular InfoNCE.RW means we randomly assign a weight between 0 and 1 to each node pair in each epoch.AW refers to our proposed variant model AdaMEOW.As can be seen in Table III, we can observe that compared to NW, using random weights leads to some improvement in results.This is because different weight assignments of node pairs can influence the optimization direction of the model.However, compared to AW, RW lacks stability during training and does not consider the characteristics of the node pairs.Therefore, the results obtained with adaptive weights outperform the other two cases, demonstrating better performance.Second, in Figure 7 we take the maximum, mean, and minimum values of the weights for all node pairs to reflect the dynamic changes of the weights during the training process.We can observe that while there are some fluctuations in the weight changes, overall they exhibit a stable decreasing trend.This is because as the training progresses, the nodes in the latent space gradually acquire more discriminative representations, requiring only small gradient values for fine-tuning.Finally, after training on the ACM dataset for 500 epochs, we randomly select an anchor and show the learned weights for its negative samples in Figure 8.We can see that the overall trend of the weights is consistent with our expectations, as γ ij can adaptively adjust its magnitude based on the characteristics of the samples.For false negative samples with high similarity, γ ij is relatively small to ensure that they are not pushed away from the anchor.For hard negative samples, γ ij is expected to be larger, so that the anchor and hard negative samples can be distinguished.Further, based on Equation 15, for easy negative samples that have small similarity with the anchor, they can be pushed farther only when the weight γ ij is set large.All these results explain the reason why our experiment works better than other baselines.

VI. CONCLUSION
We studied graph contrastive learning in HINs and proposed the MEOW model, which considers both meta-path contexts and weighted negative samples.Specifically, MEOW constructs a coarse view and a fine-grained view for contrast.In the coarse view, we took node embeddings derived by directly aggregating all the meta-paths as anchors, while in the fine-grained view, we utilized meta-path contexts and constructed positive and negative samples for anchors.Afterwards, we conducted a theoretical analysis of the InfoNCE loss and recognized its limitations for negative sample gradient magnitudes.Therefore, we proposed a weighted loss function for negative samples.In MEOW , we distinguished hard negatives from false ones by performing node clustering and using the results to assign weights to negative samples.Additionally, we introduced prototypical contrastive learning, which helps learn compact embeddings of nodes in the same cluster.Further, we proposed a variant model called AdaMEOW which can adaptively learn soft-valued weights for negative samples instead of hard-valued weights in MEOW.Finally, we conducted extensive experiments to show the superiority of MEOW and AdaMEOW against other SOTA methods.

Fig. 1 .
Fig. 1.The overall framework of the MEOW model.For details of each step, see Section IV.

Fig. 2 .
Fig. 2. The relationship between node similarity sim(•) with a randomly selected anchor and gradient magnitude of loss functions w.r.t.negative samples after training 500 epochs on the (a) ACM dataset and 800 epochs on the (b) DBLP dataset.The orange dots indicate the InfoNCE loss and the blue dots indicate the loss function adopted by AdaMEOW.

Fig. 4 .
Fig. 4. The ablation study results of 40 labeled nodes per class.

Fig. 5 .Fig. 6 .
Fig.5.Hyper-parameter analysis on the ACM dataset.Here, K is the number of selected relevant neighbors w.r.t. a meta-path and λ controls the relative importance of two components of the loss function in Eq. 17.

Fig. 7 .
Fig. 7. Dynamic changes in weights during training on the ACM dataset.

Fig. 8 .
Fig. 8.The relationship between similarity values and learned weights γ ij of negative samples in Equation 19 for a randomly selected anchor after training 500 epochs on the ACM dataset.

•
We conduct extensive experiments comparing MEOW and AdaMEOW with other 9 state-of-the-art methods w.r.t.node classification and node clustering tasks on four public HIN datasets.Our results show that MEOW achieves better performance than other competitors, and AdaMEOW further improved on the basis of MEOW.
where t is the iteration times and node clustering times M ≤ 2 in our experiments.For AdaMEOW, there is an additional MLP with time complexity O(B 2 d 2 ).The heterogeneous graph G = (V, E); the number of node type |T |; the number of target node |V |; the feature matrix X 1 , X 2 , • • • , X |T | ; a pre-defined meta-path set PS; the number of clusters U = {k 1 , k 2 , • • • , k M }; Output: Target node embeddings for downstream tasks.1: // Pre-Process.2: for all P u ∈ PS do 5: 8: ▷ Lines 9-23 correspond to one epoch 9: Transform node feature and get h i in coarse view using f under fine-grained view into k r clusters and get result C r ; 20:

TABLE I QUANTITATIVE
RESULTS (%±σ) ON NODE CLASSIFICATION.WE HIGHLIGHT THE BEST SCORE ON EACH DATASET IN BOLD AND THE RUNNER-UP SCORE

TABLE III CASE
STUDY ON DIFFERENT TYPES OF WEIGHTS ON THE ACM DATASET.