Code Monkey home page Code Monkey logo

text-gcn's Introduction

Text-GCN

PWC License: MIT codebeat badge

A PyTorch implementation of "Graph Convolutional Networks for Text Classification." (AAAI 2019)

text_gcn

For an introduction to the paper check out my blog post. Also checkout my blog post about using Text GCN to classify tweets for asian prejudice during COVID-19.

Abstract

Text classification is an important and classical problem in natural language processing. There have been a number of studies that applied convolutional neural networks (convolution on regular grid, e.g., sequence) to classification. However, only a limited number of studies have explored the more flexible graph convolutional neural networks (convolution on non-grid, e.g., arbitrary graph) for the task. In this work, we propose to use graph convolutional networks for text classification. We build a single text graph for a corpus based on word co-occurrence and document word relations, then learn a Text Graph Convolutional Network (Text GCN) for the corpus. Our Text GCN is initialized with one-hot representation for word and document, it then jointly learns the embeddings for both words and documents, as supervised by the known class labels for documents. Our experimental results on multiple benchmark datasets demonstrate that a vanilla Text GCN without any external word embeddings or knowledge outperforms state-of-the-art methods for text classification. On the other hand, Text GCN also learns predictive word and document embeddings. In addition, experimental results show that the improvement of Text GCN over state-of-the-art comparison methods become more prominent as we lower the percentage of training data, suggesting the robustness of Text GCN to less training data in text classification.

This repository contains a PyTorch implementation of

Graph Convolutional Networks for Text Classification. Liang Yao, Chengsheng Mao, Yuan Luo. AAAI, 2019. [Paper]

A reference Tensorflow implementation is accessible [here].

Requirements

This repo uses python 3.6 and the following PyTorch packages:

  • torch==1.3.1
  • torch-cluster==1.2.4
  • torch-geometric==1.1.2
  • torch-scatter==1.1.2
  • torch-sparse==0.4.0
  • torchvision==0.4.0

I also use comet.ml for experiment tracking

Included Datasets

The included datasets are a twitter asian prejudice dataset, reuters 8, and AG's news topic classification dataset.

For a new dataset, prepare a [dataset_name]_labels.txt and [dataset_name]_sentences.txt in /data/corpus in which each line corresponds to a document and its corresponding label. Use prep_data.py to further clean [dataset_name]_sentences.txt. The script will generate a [dataset_name]_sentences_clean.txt

The following is an example of the constructed text graph for the twitter dataset. Green represents text nodes and red represents document nodes. twitter text graph

Running the model

To run the model simply change the model and dataset configurations in config.py. You can also enter your own cometml information to see the results and experiment running in the browser. After model configuration, simply run

$ python main.py

Results

Some initial results I have obtained using hyperparameters from the TextGCN paper are

Dataset F1-Weighted Accuracy
twitter_asian_prejudice 0.723 0.754
r8_presplit 0.962 0.963
ag_presplit 0.907 0.907

Try playing around with the hyperparameters or include your own dataset!

text-gcn's People

Contributors

codekgu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

text-gcn's Issues

Node label one hot encoded

Hi, I'm working with Wordnet and Graph Neural Network. How it was possible to encode in one hot encoding format a complete vocabulary? For example, I have 250k different words. How many words do you use for your model?
Thanks fin advance!

Error in model_text_gnn.py when using the expand method

I encountered an error in the code when running the program, specifically in the model_text_gnn.py file. The error message I received is as follows:
Traceback (most recent call last):
File "main.py", line 44, in
main()
File "main.py", line 20, in main
saved_model, model = train(train_data, val_data, saver)
File "C:\Users\hm\Downloads\Text-GCN-master\Text-GCN-master\train.py", line 25, in train
loss, preds_train = model(pyg_graph, train_data)
File "C:\Users\hm\anaconda3\lib\site-packages\torch\nn\modules\module.py", line 1190, in _call_impl
return forward_call(*input, **kwargs)
File "C:\Users\hm\Downloads\Text-GCN-master\Text-GCN-master\model_text_gnn.py", line 36, in forward
outs = layer(ins, pyg_graph)
File "C:\Users\hm\anaconda3\lib\site-packages\torch\nn\modules\module.py", line 1190, in _call_impl
return forward_call(*input, **kwargs)
File "C:\Users\hm\Downloads\Text-GCN-master\Text-GCN-master\model_text_gnn.py", line 106, in forward
x = self.conv(ins, pyg_graph.edge_index)
File "C:\Users\hm\anaconda3\lib\site-packages\torch\nn\modules\module.py", line 1190, in _call_impl
return forward_call(*input, **kwargs)
File "C:\Users\hm\Downloads\Text-GCN-master\Text-GCN-master\model_text_gnn.py", line 258, in forward
edge_index, norm = GCNConv.norm(edge_index, x.size(0), edge_weight,
File "C:\Users\hm\Downloads\Text-GCN-master\Text-GCN-master\model_text_gnn.py", line 244, in norm
deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes)
File "C:\Users\hm\anaconda3\lib\site-packages\torch_scatter\scatter.py", line 29, in scatter_add
return scatter_sum(src, index, dim, out, dim_size)
File "C:\Users\hm\anaconda3\lib\site-packages\torch_scatter\scatter.py", line 11, in scatter_sum
index = broadcast(index, src, dim)
File "C:\Users\hm\anaconda3\lib\site-packages\torch_scatter\utils.py", line 12, in broadcast
src = src.expand(other.size())
RuntimeError: expand(torch.LongTensor{[2, 30947]}, size=[30947]): the number of sizes provided (1) must be greater or equal to the number of dimensions in the tensor (2)

IndexError

Traceback (most recent call last):
File "main.py", line 44, in
main()
File "main.py", line 20, in main
saved_model, model = train(train_data, val_data, saver)
File "/content/drive/MyDrive/GCN/Text-GCN/train.py", line 13, in train
model = create_model(train_data)
File "/content/drive/MyDrive/GCN/Text-GCN/model_factory.py", line 17, in create_model
return model_ctors[name](layer_info, dataset)
File "/content/drive/MyDrive/GCN/Text-GCN/model_factory.py", line 32, in create_text_gnn
weights[k] = min_weight / float(v)
IndexError: list assignment index out of range

Label of nodes belonging to vocab words

lets assume i have 5000 documents and their 5000 integer labels and in this corpus we got 14000 unique words.
according to paper total num of nodes will be ==> total documents + vocab size = 5000+14000= 19000 nodes
but for documents we know the labels ,how are you creating the labels for vocab word (nodes)
can u clarify on this

AssertionError

(base) C:\Users\Ramy\Downloads\Compressed\Text-GCN-master\Text-GCN-master>python main.py
text_gcn: {'pred_type': 'softmax', 'node_embd': 'gcn', 'layer_dims': [10, 4], 'class_weights': True, 'dropout': True}

in _save_conf_code
Logging to C:\Users\Ramy\Downloads\Compressed\Text-GCN-master\Text-GCN-master\logs\TextGNN_ag_presplit_0.8_0.1_0.1_2022-07-22T08-02-04.424720
Loaded from C:\Users\Ramy\Downloads\Compressed\Text-GCN-master\Text-GCN-master\save\split\ag_presplit_train_val_test_3_window_size_10.klepto
(129620, 129620)
Traceback (most recent call last):
File "C:\Users\Ramy\Downloads\Compressed\Text-GCN-master\Text-GCN-master\main.py", line 44, in
main()
File "C:\Users\Ramy\Downloads\Compressed\Text-GCN-master\Text-GCN-master\main.py", line 20, in main
saved_model, model = train(train_data, val_data, saver)
File "C:\Users\Ramy\Downloads\Compressed\Text-GCN-master\Text-GCN-master\train.py", line 13, in train
model = create_model(train_data)
File "C:\Users\Ramy\Downloads\Compressed\Text-GCN-master\Text-GCN-master\model_factory.py", line 17, in create_model
return model_ctors[name](layer_info, dataset)
File "C:\Users\Ramy\Downloads\Compressed\Text-GCN-master\Text-GCN-master\model_factory.py", line 35, in create_text_gnn
return TextGNN(
File "C:\Users\Ramy\Downloads\Compressed\Text-GCN-master\Text-GCN-master\model_text_gnn.py", line 21, in init
assert layer_dim_list[-1] == num_labels
AssertionError

AttributeError: 'int' object has no attribute 'new_full'

I have tried to run this code in colab, everything fine until i got an error when trying to run main function, here is the details :

Logging to /content/logs/TextGNN_twitter_asian_prejudice_small_0.8_0.1_0.1_2022-07-31T22-02-48.769172
Trying to load but no file /content/save/split/twitter_asian_prejudice_small_train_80_val_10_test_10_seed_3_window_size_10.klepto
Trying to load but no file /content/save/all/twitter_asian_prejudice_small_all_window_10.klepto
100%
1503/1503 [00:00<00:00, 15779.03it/s]
Saving to /content/save/all/twitter_asian_prejudice_small_all_window_10.klepto
Saving to /content/save/split/twitter_asian_prejudice_small_train_80_val_10_test_10_seed_3_window_size_10.klepto
(1183, 1183)
Number params:  237604

AttributeError                            Traceback (most recent call last)
[<ipython-input-22-263240bbee7e>](https://localhost:8080/#) in <module>()
----> 1 main()

9 frames
[<ipython-input-21-6463f33e79c1>](https://localhost:8080/#) in main()
     10     if COMET_EXPERIMENT:
     11         with COMET_EXPERIMENT.train():
---> 12             saved_model, model = train(train_data, val_data, saver)
     13     else:
     14         saved_model, model = train(train_data, val_data, saver)

[<ipython-input-18-4c4921548f33>](https://localhost:8080/#) in train(train_data, val_data, saver)
     18         model.train()
     19         model.zero_grad()
---> 20         loss, preds_train = model(pyg_graph, train_data)
     21         loss.backward()
     22         optimizer.step()

[/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in _call_impl(self, *input, **kwargs)
   1128         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1129                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1130             return forward_call(*input, **kwargs)
   1131         # Do not call functions when jit is used
   1132         full_backward_hooks, non_full_backward_hooks = [], []

[<ipython-input-14-a3723756fb22>](https://localhost:8080/#) in forward(self, pyg_graph, dataset)
     31         for i, layer in enumerate(self.layers):
     32             ins = acts[-1]
---> 33             outs = layer(ins, pyg_graph)
     34             acts.append(outs)
     35 

[/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in _call_impl(self, *input, **kwargs)
   1128         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1129                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1130             return forward_call(*input, **kwargs)
   1131         # Do not call functions when jit is used
   1132         full_backward_hooks, non_full_backward_hooks = [], []

[<ipython-input-14-a3723756fb22>](https://localhost:8080/#) in forward(self, ins, pyg_graph)
    101                 x = self.conv(ins, pyg_graph.edge_index, edge_weight=pyg_graph.edge_attr)
    102             else:
--> 103                 x = self.conv(ins, pyg_graph.edge_index)
    104         else:
    105             x = self.conv(ins, pyg_graph.edge_index)

[/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in _call_impl(self, *input, **kwargs)
   1128         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1129                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1130             return forward_call(*input, **kwargs)
   1131         # Do not call functions when jit is used
   1132         full_backward_hooks, non_full_backward_hooks = [], []

[<ipython-input-14-a3723756fb22>](https://localhost:8080/#) in forward(self, x, edge_index, edge_weight)
    254         if not self.cached or self.cached_result is None:
    255             edge_index, norm = GCNConv.norm(edge_index, x.size(0), edge_weight,
--> 256                                             self.improved, x.dtype)
    257             self.cached_result = edge_index, norm
    258 

[<ipython-input-14-a3723756fb22>](https://localhost:8080/#) in norm(edge_index, num_nodes, edge_weight, improved, dtype)
    231 
    232         edge_index, edge_weight = remove_self_loops(edge_index, edge_weight)
--> 233         edge_index = add_self_loops(edge_index, num_nodes)
    234         loop_weight = torch.full((num_nodes, ),
    235                                  1 if not improved else 2,

[/usr/local/lib/python3.7/dist-packages/torch_geometric/utils/loop.py](https://localhost:8080/#) in add_self_loops(edge_index, edge_attr, fill_value, num_nodes)
    123     if edge_attr is not None:
    124         if fill_value is None:
--> 125             loop_attr = edge_attr.new_full((N, ) + edge_attr.size()[1:], 1.)
    126 
    127         elif isinstance(fill_value, (int, float)):

AttributeError: 'int' object has no attribute 'new_full'

Why this can happen? can you give me a solution?

Building graph

How to build the graph?, and what is the result that can be viewed in gephi?. I didn't see any output after running the script

AttributeError: 'int' object has no attribute 'numel'

When I run !python3 main.py, I get this error. Its Python 3.7 and all latest version of torch libraries in Google Colab. Won't this work with the latest versions? Is it must that I must use the versions specified in the used library version list?
Please help me out.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.