-
Notifications
You must be signed in to change notification settings - Fork 59
A Classification Example in Forte Pipeline using CNN Classifier and Bert Classifier #336
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ziqian98
wants to merge
57
commits into
asyml:master
Choose a base branch
from
ziqian98:lzq_new_classification
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 13 commits
Commits
Show all changes
57 commits
Select commit
Hold shift + click to select a range
c575f12
LZQ:Add Classification Task__CNN
ziqian98 aac73a6
LZQ: Reader and Reader Test
ziqian98 c9a4771
LZQ:Update main train
ziqian98 ff24adc
LZQ:Update CNN model
ziqian98 9b28b8d
LZQ: Update minor bugs in main train
ziqian98 f2acf1a
LZQ: Update minor bugs in main predict
ziqian98 b74d77c
LZQ: Update for minor changes
ziqian98 9ae5fb4
LZQ: update minor changes in main_train
ziqian98 a73d7e6
LZQ: Add Bert in Classification Task
ziqian98 3b215e9
LZQ: Add Bert in Classification Prediction
ziqian98 7480e5a
LZQ: Merge data augmentation feature with main_train_cnn
ziqian98 83cbea7
LZQ: Add reader for merging data_augmentation feature
ziqian98 456f66d
Merge branch 'master' into lzq_new_classification
hunterhector 7ccffee
Reform main train
ziqian98 9b8d1aa
LZQ: Reform redaer
ziqian98 7f560d7
LZQ: Delete old files
ziqian98 9ba6808
LZQ: Delete old augmentation reader
ziqian98 cad9fb7
LZQ: Upload imdb data samples to lzq_new_classification
ziqian98 63740ec
LZQ: Format
ziqian98 7830f81
LZQ: Format
ziqian98 d1cac8d
LZQ: Format main_train
ziqian98 92354a0
LZQ: Add Classification Data
ziqian98 fe70efc
LZQ: Add config_data yml file
ziqian98 c2efe83
LZQ: Add config model yml file
ziqian98 8897bdc
LZQ: Add config predict yml
ziqian98 a116684
LZQ: Add cnn model
ziqian98 2b9bc33
LZQ: Add prediction
ziqian98 04b0992
LZQ: Add utilility function
ziqian98 1ccd9b1
LZQ: Format cnn
ziqian98 e91633d
LZQ: Format main predict
ziqian98 f0d09df
LZQ: Format util
ziqian98 fd5141c
LZQ: Format cnn
ziqian98 ff779c8
LZQ: format CNN
ziqian98 acaf94e
LZQ: Format IMDB Reader
ziqian98 87a8bd5
LZQ: Format imdb reader
ziqian98 37f9b4d
LZQ: Format imdb reader
ziqian98 80fbef4
LZQ: Modify inputs of collect in reader
ziqian98 084f841
LZQ: Format reader
ziqian98 5c7e7a0
LZQ: Add Readme file
ziqian98 7d18628
LZQ: Update Train
ziqian98 d905307
LZQ: Fix label prediction problems
ziqian98 2ae2621
LZQ: Add testing accuracy
ziqian98 e6f3aea
LZQ: train format
ziqian98 dc45084
LZQ: update predict
ziqian98 a6e2388
LZQ: Reader for new API
ziqian98 2b5da59
LZQ: update train for new API
ziqian98 f19a07b
LZQ: Format train for new API
ziqian98 ab56bb2
LZQ: update reader test for new API
ziqian98 8eba3c0
LZQ: Format train
ziqian98 08bb2ad
LZQ: Format model cnn
ziqian98 045bdda
LZQ: Format main train
ziqian98 3b4b10e
LZQ: Remove a util function
ziqian98 692faa3
Reform the extractor and add mask
ziqian98 1f94612
LZQ: both pisitvie and negetavie keys are contained
ziqian98 75c5ab6
LZQ: Update for sentiment dictionary keys
ziqian98 59d6464
LZQ: change the way of adding data aug processor
ziqian98 bcaf655
LZQ: Add a data_aug flag
ziqian98 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| # Copyright 2020 The Forte Authors. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """This file predict the ner tag for conll03 dataset.""" | ||
|
|
||
| import torch | ||
| from texar.torch.modules.embedders import WordEmbedder | ||
| from texar.torch.modules.classifiers.conv_classifiers import Conv1DClassifier | ||
| from torch import nn | ||
| from texar.torch.data import Batch | ||
|
|
||
| def pad_each_bach(word, max_sen_len): | ||
| batch_size = word.shape[0] | ||
| curr_len = word.shape[1] | ||
| word_list = word.tolist() | ||
|
|
||
| # Line 0 in word_embedding_table is padding vec | ||
| for i in range(batch_size): | ||
| for j in range(max_sen_len-curr_len): | ||
| word_list[i].append(0) | ||
|
|
||
| return torch.LongTensor(word_list) | ||
|
|
||
|
|
||
| class CNN_Classifier(nn.Module): | ||
| def __init__(self, in_channels, word_embedding_table): | ||
| super().__init__() | ||
| self.embedder = WordEmbedder(init_value=word_embedding_table) | ||
|
|
||
| self.classifier = \ | ||
| Conv1DClassifier(in_channels=in_channels, | ||
| in_features=word_embedding_table.size()[0]) | ||
|
|
||
| self.max_sen_len = in_channels | ||
|
|
||
| def forward(self, batch: Batch): | ||
| word = batch["text_tag"]["data"] | ||
|
|
||
| word_pad = pad_each_bach(word, self.max_sen_len) | ||
|
|
||
| word_pad_embed = self.embedder(word_pad) | ||
|
|
||
| logits, pred = self.classifier(word_pad_embed) | ||
|
|
||
| return logits, pred | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| # Copyright 2020 The Forte Authors. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """This file predict the ner tag for conll03 dataset.""" | ||
|
|
||
| import yaml | ||
| import torch | ||
| from forte.pipeline import Pipeline | ||
| from forte.predictor import Predictor | ||
| from ft.onto.base_ontology import Sentence | ||
| from forte.data.readers.imdb_reader import IMDBReader | ||
|
|
||
| def pad_each_bach(word, max_sen_len): | ||
|
ziqian98 marked this conversation as resolved.
Outdated
|
||
| batch_size = word.shape[0] | ||
| curr_len = word.shape[1] | ||
| word_list = word.tolist() | ||
|
|
||
| # Line 0 in word_embedding_table is padding vec | ||
| for i in range(batch_size): | ||
| for j in range(max_sen_len-curr_len): | ||
| word_list[i].append(0) | ||
|
|
||
| return torch.LongTensor(word_list) | ||
|
|
||
|
|
||
| def predict_forward_fn(model, batch): | ||
| '''Use model and batch data to predict label.''' | ||
| word = batch["text_tag"]["data"] | ||
| logits, pred = model(pad_each_bach(word, 500)) | ||
| pred = pred.numpy() | ||
| print(pred) | ||
|
ziqian98 marked this conversation as resolved.
Outdated
|
||
| return {"label_tag": pred} | ||
|
|
||
|
|
||
| config_predict = yaml.safe_load(open("config_predict.yml", "r")) | ||
|
ziqian98 marked this conversation as resolved.
|
||
| saved_model = torch.load(config_predict['model_path']) | ||
|
ziqian98 marked this conversation as resolved.
|
||
| train_state = torch.load(config_predict['train_state_path']) | ||
|
|
||
| reader = IMDBReader() | ||
| predictor = Predictor(batch_size=config_predict['batch_size'], | ||
| model=saved_model, | ||
| predict_forward_fn=predict_forward_fn, | ||
| feature_resource=train_state['feature_resource']) | ||
| #evaluator = CoNLLNEREvaluator() | ||
|
ziqian98 marked this conversation as resolved.
Outdated
|
||
|
|
||
| pl = Pipeline() | ||
| pl.set_reader(reader) | ||
| pl.add(predictor) | ||
| #pl.add(evaluator) | ||
| pl.initialize() | ||
|
|
||
| for pack in pl.process_dataset(config_predict['test_path']): | ||
| print("---- pack ----") | ||
| for instance in pack.get(Sentence): | ||
| sentence = instance.text | ||
| predicts = [] | ||
| for entry in pack.get(Sentence, instance): | ||
| predicts.append(entry.speaker) | ||
| print('---- example -----') | ||
| print("sentence: ", sentence) | ||
| print("predict sentiment: ", predicts) | ||
| #print(evaluator.get_result()) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| # Copyright 2020 The Forte Authors. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """This file predict the ner tag for conll03 dataset.""" | ||
|
ziqian98 marked this conversation as resolved.
Outdated
|
||
|
|
||
| import yaml | ||
| import torch | ||
| import examples.Classification_new.cnn | ||
| from forte.pipeline import Pipeline | ||
| from forte.predictor import Predictor | ||
| from ft.onto.base_ontology import Sentence | ||
| from forte.data.readers.imdb_reader import IMDBReader | ||
|
|
||
|
|
||
| def predict_forward_fn(model, batch): | ||
| '''Use model and batch data to predict label.''' | ||
| logits, pred = model(batch) | ||
| pred = pred.numpy() | ||
| print(pred) | ||
| return {"label_tag": pred} | ||
|
|
||
|
|
||
| config_predict = yaml.safe_load(open("config_predict.yml", "r")) | ||
| saved_model = torch.load(config_predict['model_path']) | ||
| train_state = torch.load(config_predict['train_state_path']) | ||
|
|
||
| reader = IMDBReader() | ||
| predictor = Predictor(batch_size=config_predict['batch_size'], | ||
| model=saved_model, | ||
| predict_forward_fn=predict_forward_fn, | ||
| feature_resource=train_state['feature_resource']) | ||
| #evaluator = CoNLLNEREvaluator() | ||
|
|
||
| pl = Pipeline() | ||
| pl.set_reader(reader) | ||
| pl.add(predictor) | ||
| #pl.add(evaluator) | ||
| pl.initialize() | ||
|
|
||
| for pack in pl.process_dataset(config_predict['test_path']): | ||
| print("---- pack ----") | ||
| for instance in pack.get(Sentence): | ||
| sentence = instance.text | ||
| predicts = [] | ||
| for entry in pack.get(Sentence, instance): | ||
| predicts.append(entry.speaker) | ||
| print('---- example -----') | ||
| print("sentence: ", sentence) | ||
| print("predict sentiment: ", predicts) | ||
| #print(evaluator.get_result()) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.