ratsgo / nlpbook Goto Github PK
View Code? Open in Web Editor NEWpratical tips for Natural Language Processing
Home Page: https://ratsgo.github.io/nlpbook
License: Other
pratical tips for Natural Language Processing
Home Page: https://ratsgo.github.io/nlpbook
License: Other
안녕하세요.
책 보면서 막히는 부분이 있어서 글남깁니다.
책에 적혀있는대로 실습을 한 후, 마지막 웹 서비스 시작하기 단계에서
링크가 Running on http://127.0.0.1:5000/ <<이거 하나만 뜨는데,
왜 그러는건가요??
안녕하세요 작가님!
85쪽 수식3-7 설명할 때, 단어 임베딩 차원수를 언급하셨는데,
단어 임베딩 차원수가 의미하는 것이 뭔가요? 83쪽 그림을 봐도 단어 임베딩 차원수가 뭘 의미하는 것인지 잘 모르겠어요
pratical tips for Natural Language Processing
https://ratsgo.github.io/nlpbook/docs/language_model/tr_self_attention/
개요
개체명 인식 튜토리얼을 작성한다
pratical tips for Natural Language Processing
안녕하세요 작가님 덕분에 많이 배우고 있습니다.
다만 실습을 따라가던 도중에 몇가지 문제가 생겨 연락드립니다.
ImportError: /usr/local/lib/python3.7/dist-packages/_XLAC.cpython-37m-x86_64-linux-gnu.so: undefined symbol: _ZNK3c1010TensorImpl7stridesEv
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.
진행환경은 코랩에서 진행하였고, 이에 대한 대응으로 ratsnlp 문서를 찾아 읽어보았습니다. 과정에서
from ratsnlp.nlpbook.classification.arguments import ClassificationTrainArguments 로 문서에 나와있어 진행했으나, 동일한 문제가 발생하였고, 이후 torch의 문제라는 이야기도 있어 !pip install mmcv-full -f 를 통해 업데이트를 했으나 동일한 문제가 지속되고 있어 문의드립니다.
항상 많은 도움 감사합니다.
pratical tips for Natural Language Processing
https://ratsgo.github.io/nlpbook/docs/generation/inference1/
안녕하세요 좋은 코드 및 지식 공유해주셔서 무한한 감사드립니다. 다름이 아니라 튜토리얼 따라서 쭉 해보다가 train.txt 와 val.txt에 자체 데이터셋 넣어서 해보려고 했는데 (형식은 원래와 같이 하였습니다)
학습 데이터 셋 구성에서 자체 txt파일 크기가 너무 큰지 (7G가량) python이 killed되어버리고 진행이 안되는데
혹시 이 부분 어떻게 해결할 수 있을까요?
pratical tips for Natural Language Processing
안녕하세요.
2장 BPE 관련해서 질문이 있습니다.
45쪽에서 BPE 어휘 집합 구축하기에서는 토큰을 바이그램 쌍으로 빈도를 계산해서 병합 우선순위를 결정했습니다.
그런데 실습에서 (55쪽) 한글을 유니코드 바이트로 변환하고 병합 우선순위를 보면 문자 길이가 다양합니다.
바이트 기준 BPE를 적용하면 문자 길이가 다양해질 수 있는 건가요? 즉 앞에서처럼 바이그램(2개)가 아니라 여러 개의 길이로 나뉘어서 빈도를 계산하게 되는건가요?
답변 부탁드리겠습니다!
감사합니다.
개요
문서 검색 튜토리얼을 작성한다
안녕하세요! 자연어처리를 공부하고 있는 학생입니다.
책을 참고하면서 직접 코랩노트북에 코드를 작성하면서 공부를 진행하고 있는데,
p149 4단계 부분에서 부정(positive)이 서술되어 있는 부분을 발견했습니다.
이 부분이 오 기술되어 있는 것일까요?
아니면 부정 위치일 때 해당 문장이 부정이나(긍정으로 인식), 반대일 때 긍정이나(긍정으로 인식) 이 되도록 pred값을 만든다는 것일까요?
안녕하세요^^
BERT와 GPT로 배우는 자연어 처리 8장에서, 문장 생성 모델 파인튜닝하기의 데이터를 NSMC가 아닌, 제 개인 txt파일로 학습을 시키려고 하는 중에 다음과 같은 오류가 발생해 문의드립니다.
(교재에서 NSMC 말뭉치를 사용하려면 Korpora를 사용하라고 했는데, 저와 같이 이미 데이터가 있는 경우에는 사용하지 않아도 되는 건지, 혹시 Korpora를 사용하지 않아서 오류가 발생한 것인지 궁금합니다.)
아래는 전체 코드 입니다.
https://github.com/jeein2222/gradProject/blob/lyrics/generation_train.ipynb
코드4-26 입력후에 다음과 같은 오류가 뜨는데 어떻게 해결하면 되죠?
(코드는 저자님 코랩파일을 드라이브로 복사해서 그대로 사용했습니다.)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/usr/local/lib/python3.7/dist-packages/urllib3/connectionpool.py", line 354, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/usr/lib/python3.7/http/client.py", line 1281, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/lib/python3.7/http/client.py", line 1327, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/usr/lib/python3.7/http/client.py", line 1276, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/usr/lib/python3.7/http/client.py", line 1036, in _send_output
self.send(msg)
File "/usr/lib/python3.7/http/client.py", line 976, in send
self.connect()
File "/usr/local/lib/python3.7/dist-packages/urllib3/connection.py", line 181, in connect
conn = self._new_conn()
File "/usr/local/lib/python3.7/dist-packages/urllib3/connection.py", line 168, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7ff604cfd990>: Failed to establish a new connection: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/usr/local/lib/python3.7/dist-packages/urllib3/connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/local/lib/python3.7/dist-packages/urllib3/util/retry.py", line 399, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=4040): Max retries exceeded with url: /api/tunnels (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7ff604cfd990>: Failed to establish a new connection: [Errno 111] Connection refused'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 1177, in run
self.function(*self.args, **self.kwargs)
File "/usr/local/lib/python3.7/dist-packages/flask_ngrok.py", line 70, in start_ngrok
ngrok_address = _run_ngrok()
File "/usr/local/lib/python3.7/dist-packages/flask_ngrok.py", line 35, in _run_ngrok
tunnel_url = requests.get(localhost_url).text # Get the tunnel information
File "/usr/local/lib/python3.7/dist-packages/requests/api.py", line 76, in get
return request('get', url, params=params, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/requests/sessions.py", line 530, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.7/dist-packages/requests/sessions.py", line 643, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=4040): Max retries exceeded with url: /api/tunnels (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7ff604cfd990>: Failed to establish a new connection: [Errno 111] Connection refused'))
안녕하세요. 좋은 책을 만나게 되어 기쁜 마음으로 공부하고 있습니다.
그런데 4-3에서 플라스크 웹서비스 개시에서 계속 로딩만 되고 실행이 되지 않습니다.
실행하면 아래와 같이 나오네요. 어떻게 하면 될지 알려주시면 감사하겠습니다.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/usr/local/lib/python3.7/dist-packages/urllib3/connectionpool.py", line 354, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/usr/lib/python3.7/http/client.py", line 1281, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/lib/python3.7/http/client.py", line 1327, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/usr/lib/python3.7/http/client.py", line 1276, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/usr/lib/python3.7/http/client.py", line 1036, in _send_output
self.send(msg)
File "/usr/lib/python3.7/http/client.py", line 976, in send
self.connect()
File "/usr/local/lib/python3.7/dist-packages/urllib3/connection.py", line 181, in connect
conn = self._new_conn()
File "/usr/local/lib/python3.7/dist-packages/urllib3/connection.py", line 168, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7f0cae896810>: Failed to establish a new connection: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/usr/local/lib/python3.7/dist-packages/urllib3/connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/local/lib/python3.7/dist-packages/urllib3/util/retry.py", line 399, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=4040): Max retries exceeded with url: /api/tunnels (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f0cae896810>: Failed to establish a new connection: [Errno 111] Connection refused'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 1177, in run
self.function(*self.args, **self.kwargs)
File "/usr/local/lib/python3.7/dist-packages/flask_ngrok.py", line 70, in start_ngrok
ngrok_address = _run_ngrok()
File "/usr/local/lib/python3.7/dist-packages/flask_ngrok.py", line 35, in _run_ngrok
tunnel_url = requests.get(localhost_url).text # Get the tunnel information
File "/usr/local/lib/python3.7/dist-packages/requests/api.py", line 76, in get
return request('get', url, params=params, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/requests/sessions.py", line 530, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.7/dist-packages/requests/sessions.py", line 643, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=4040): Max retries exceeded with url: /api/tunnels (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f0cae896810>: Failed to establish a new connection: [Errno 111] Connection refused'))
pratical tips for Natural Language Processing
https://ratsgo.github.io/nlpbook/docs/language_model/transformers/
우선 훌륭한 교재 써주셔서 감사합니다. 덕분에 비교적 쉽게 NLP에 접근할 수 있습니다. 직접 하나하나 써서 구글 colab에서 돌려보고 있습니다.
그런데 30쪽 코드 1-5, train_dataloader 변수를 정의하면서 collate_fn=nlpbook.data_collator 부분에서 nlpbook.data_collator가 정의되지 않았다는 오류가 뜨더라고요. 그래서 3번째 줄에 ratsnlp에서 nlpbook을 따로 불러와야 하지 않나 싶더라고요.
from ratsnlp import nlpbook
를 추가했더니 위 오류가 뜨지 않고 실행되었습니다. 혹시 한 번 확인해주실 수 있으실까요
이렇게 nlpbook을 로드해야 뒤에 trainer를 정의할 때도 사용할 수 있을 것 같기도 하고요. trainer = nlpbook.get_trainer(args)
그림 8-11에는 집(0.75), 책(0.23), 사람(0.02)이라고 표시되어 있는데, 그 아래 내용에는 책(0.75), 집(0.23), 사람(0.02)로 표시되어 있습니다. 어느 것이 맞는 건가요? 그리고 템퍼러쳐 스케일링을 적용해도 확률이 높은 값으로 선택하면 그림 8-11의 "그 책 읽"이 아니라 "그 책 이" 나와야 하는 것 아닌가요?
introduction
introduction > deep learning
introduction > transfer learning
introduction > pipeline
preprocess > byte pair encoding
aaabdaaadac
를 Z
로 만들면 길이가 1인 데이터가 만들어지지 않느냐는 질문이 생길 수 있습니다. 또한 처음에 aa
를 병합하는 것이 아니라 aaa
를 병합하면 더 짧아지지 않느냐는 질문, 2번째 병합 시 ab
가 아닌 Za
를 병합하면 어떻게 되느냐 (tie) 의 질문이 나올 것 같습니다. 아래처럼 예시와 설명을 바꾸면 어떨까요?
- aaabdaaabacabaa
바이트 페어 인코딩은 데이터에 등장한 글자를 사전으로 구성하며, 연속된 두 글자를 한 글자로 병합합니다. 이 문자열에서는 `aa` 가 가장 많이 등장하였으므로 이를 `Z` 로 병합(치환)하면 위의 문자열을 다음과 같이 압축할 수 있습니다.
- `ZabdZabacabZ`
이 문자열은 한번 더 압축 가능합니다. 살펴보니 `ab` 가 가장 많이 나타났으므로 이를 `Y` 로 병합(치환)합니다. 다음과 같습니다.
- `ZYdZYacYZ`
BPE 수행 이전에는 원래 데이터를 표현하기 위한 사전은 길이가 1인 3개 글자(a, b, c)로 구성되었습니다. 수행 이후엔 그 크기가 5개(a, b, c, Z, Y)로 늘었습니다. 반면 데이터의 길이는 15개에서 9로 줄었습니다. 길이가 2인 글자를 추가하여 (+2 x 2) 길이를 -6 으로 줄였습니다. 이처럼 BPE는 사전 크기를 지나치게 늘리지 않으면서도 각 데이터를 효율적으로 압축할 수 있도록 합니다.
바이트 페어 인코딩
세부 챕터와 BPE 어휘 집합 구축
세부 챕터의 내용이 겹칩니다. BPE 어휘 집합 구축
내 각 단계의 디테일을 위의 Z
, Y
가 만들어진 경우로 설명한 듯 합니다. 이 책의 설명 상세 수준을 본다면 바이트 페어 인코딩
의 수준을 중심으로 통합하는게 좋을 듯 합니다. 통합한다면 위의 예시에서 Z
, Y
의 빈도수를 중심으로 아래와 같은 예시를 만들어 주는게 어떨까요?log(#ab/N) - log(#a/N) - log(#b/N)
, #a
는 a 의 빈도수, N
은 현재 데이터의 글자 길이merges.txt
와 vocab.txt
라는 두 개의 파일이 만들어지지만, 워드피스 토크나이저는 vocab.txt
파일만 만들어집니다.preprocessing > vocab tutorial
vocab tutorial
-> Tutorial for training tokenizer
tokenization tutorial
소챕터에 모두 등장합니다. Introduction 을 꼭 참고하라고 강조하는 것으로 정리하는게 더 좋을 듯 합니다.워드피스
부분의 링크 주소가 깨졌습니다.preprocessing > tokenization tutorial
Tokenization tutorial
-> Tutorial for tokenizing texts
preprocess > tokenization
소챕터와 다른 말투의 표현들이 자주 등장하여 따로 쓰인 챕터처럼 어투가 느껴집니다. 하나의 어투로 다듬어지면 더 좋을 듯 합니다.아래의 문장을 코랩이 아닌 로컬 주피터 노트북에서 실행하면 에러가 발생합니다.
from transformers import BertTokenizer
tokenizer=BertTokenizer.from_pretrained(
args.pretrained_model_name,
do_lower_case=False,)
에러의 내용은 다음과 같습니다.
SSLError: HTTPSConnectionPool(host='huggingface.co', port=443)
인증서를 받아보기도 하고 여러 git clone으로 kcbert-base를 다운받아보는 방법도 사용해보고 다양하게 시도를 해봤습니다.
계속 실패하는데, 로컬에서 사용하려면 어떻게 해야할지 문의드립니다.
감사합니다.
코랩에서 제목처럼 패키지를 가져올 때 에러가 생기네요. 에러내용은 아래와 같습니다.
SystemError Traceback (most recent call last)
in ()
----> 1 from ratsnlp.nlpbook.classification import nsmcCorpus
32 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/core/framework/resource_handle_pb2.py in ()
148 ,
149 'DESCRIPTOR' : _RESOURCEHANDLEPROTO,
--> 150 'module' : 'tensorflow.core.framework.resource_handle_pb2'
151 # @@protoc_insertion_point(class_scope:tensorflow.ResourceHandleProto)
152 })
SystemError: google/protobuf/pyext/descriptor.cc:358: bad argument to internal function
pratical tips for Natural Language Processing
pratical tips for Natural Language Processing
https://ratsgo.github.io/nlpbook/docs/introduction/transfer/
from ratsnlp.nlpbook.classification import ClassificationTrainArguments
이 현재 안되는거 같습니다.
오류 메시지 : ImportError: cannot import name 'get_num_classes' from 'torchmetrics.utilities.data' (/usr/local/lib/python3.7/dist-packages/torchmetrics/utilities/data.py)
어떻게 해결하면 좋을까요?
제가 bert 모델로 학습한 결과 파일을 저장하는 경로로 책과 똑같이 이렇게 했습니다.
args = ClassificationTrainArguments(
pretrained_model_name = 'beomi/kcbert-base',
downstream_corpus_name = 'nsmc',
downstream_model_dir='/gdrive/MyDrive/연구전략_파이썬공부/BERT와GPT로배우는자연어처리/checkpoint-doccls',
batch_size = 32 if torch.cuda.is_available() else 4,
learning_rate=5e-5,
max_seq_length=128,
epochs=1,
tpu_cores=0 if torch.cuda.is_available() else 8,
seed=7
)
그리고 학습을 시켰는데요 이런 메시지가 나오는데 ckpt로 저장된 파일은 안 보입니다.ㅡㅜ
LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]
/usr/local/lib/python3.7/dist-packages/pytorch_lightning/core/optimizer.py:381: RuntimeWarning: Found unsupported keys in the optimizer configuration: {'scheduler'}
f"Found unsupported keys in the optimizer configuration: {set(extra_keys)}", category=RuntimeWarning
혹시나 해서 Korpora 폴더의 nsmc 폴더에 갔는데 파일이 4개 있는데요 혹시 이게 그 체크포인트파일(ckpt) 인가요? 도와주세요ㅜㅡ
cached_test_BertTokenizer_128_nsmc_document-classification.lock
cached_test_BertTokenizer_128_nsmc_document-classification
doc-cls-train-colab 에서 발생하는 오류입니다.
import torch
from ratsnlp.nlpbook.classification import ClassificationTrainArguments
args = ClassificationTrainArguments(
pretrained_model_name="beomi/kcbert-base",
downstream_corpus_name="nsmc",
downstream_model_dir="/gdrive/My Drive/nlpbook/checkpoint-doccls",
batch_size=32 if torch.cuda.is_available() else 4,
learning_rate=5e-5,
max_seq_length=128,
epochs=3,
tpu_cores=0 if torch.cuda.is_available() else 8,
seed=7,
)
위와 같이 실행했는데 다음과 같은 오류가 발생했습니다.
ImportError Traceback (most recent call last)
in ()
1 import torch
----> 2 from ratsnlp.nlpbook.classification import ClassificationTrainArguments
3
4 args = ClassificationTrainArguments(
5 pretrained_model_name="beomi/kcbert-base",
6 frames
/usr/local/lib/python3.7/dist-packages/ratsnlp/nlpbook/init.py in ()
1 from .utils import *
----> 2 from .trainer import *
3 from .data_utils import *
/usr/local/lib/python3.7/dist-packages/ratsnlp/nlpbook/trainer.py in ()
1 import os
2 import torch
----> 3 from pytorch_lightning import Trainer
4 from pytorch_lightning.callbacks import ModelCheckpoint
5
/usr/local/lib/python3.7/dist-packages/pytorch_lightning/init.py in ()
18 _PROJECT_ROOT = os.path.dirname(_PACKAGE_ROOT)
19
---> 20 from pytorch_lightning import metrics # noqa: E402
21 from pytorch_lightning.callbacks import Callback # noqa: E402
22 from pytorch_lightning.core import LightningDataModule, LightningModule # noqa: E402
/usr/local/lib/python3.7/dist-packages/pytorch_lightning/metrics/init.py in ()
13 # limitations under the License.
14
---> 15 from pytorch_lightning.metrics.classification import ( # noqa: F401
16 Accuracy,
17 AUC,
/usr/local/lib/python3.7/dist-packages/pytorch_lightning/metrics/classification/init.py in ()
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
---> 14 from pytorch_lightning.metrics.classification.accuracy import Accuracy # noqa: F401
15 from pytorch_lightning.metrics.classification.auc import AUC # noqa: F401
16 from pytorch_lightning.metrics.classification.auroc import AUROC # noqa: F401
/usr/local/lib/python3.7/dist-packages/pytorch_lightning/metrics/classification/accuracy.py in ()
16 from torchmetrics import Accuracy as _Accuracy
17
---> 18 from pytorch_lightning.metrics.utils import deprecated_metrics
19
20
/usr/local/lib/python3.7/dist-packages/pytorch_lightning/metrics/utils.py in ()
20 from torchmetrics.utilities.data import dim_zero_mean as _dim_zero_mean
21 from torchmetrics.utilities.data import dim_zero_sum as _dim_zero_sum
---> 22 from torchmetrics.utilities.data import get_num_classes as _get_num_classes
23 from torchmetrics.utilities.data import select_topk as _select_topk
24 from torchmetrics.utilities.data import to_categorical as _to_categorical
ImportError: cannot import name 'get_num_classes' from 'torchmetrics.utilities.data' (/usr/local/lib/python3.7/dist-packages/torchmetrics/utilities/data.py)
174페이지에 개체명 태그 수와 종류는 데이터를 제작할 때 자유롭게 정할 수 있다고 언급됐는데, 어떻게 할 수 있는지 알려주시거나 혹 도움이 되는 자료나 교제를 알려 줄 수 있나요?
개요
질의 응답 튜토리얼을 작성한다
안녕하세요, 질문이 있습니다.
종이책은 이미 출판사와 계약이 되어 있나요?
예정 출간일은 언제쯤일까요?
코드 4-26
from ratsnlp.nlpbook.classification import get_web_service_app app = get_web_service_app(inference_fn) app.run()
를 실행할 때 url에 접속하면
'Welcome to ngrok!
Before you can serve HTML content, you must sign up for an ngrok account and install your authtoken.'
이라는 경고창이 뜨고 진행되지 않습니다.
pratical tips for Natural Language Processing
개요
2-2장 바이트 페어 인코딩 설명 내용의 코드 확인
개요
문장 생성 튜토리얼을 작성한다
pratical tips for Natural Language Processing
Chapter4. [4-4 모델환경설정 사전 작업]에서 실행 문제가 발생하였습니다
`
import torch
from ratsnlp.nlpbook.classification import ClassificationTrainArguments
args = ClassificationTrainArguments(
pretrained_model_name="beomi/kcbert-base",
downstream_corpus_name="nsmc",
downstream_model_dir="/content/drive/MyDrive/BERTandGPT/Chapter4",
batch_size=32 if torch.cuda.is_available() else 4,
learning_rate=5e-5,
max_seq_length=128,
epochs=3,
tpu_cores=0 if torch.cuda.is_available() else 8,
seed=7,
)
`
기존의 코드를 그대로 실행하면 아래와 같은 에러 메세지가 출력됩니다 (경로는 제 활동에 맞게 변경하였습니다)
ImportError: /usr/local/lib/python3.7/dist-packages/_XLAC.cpython-37m-x86_64-linux-gnu.so: undefined symbol: _ZN2at13_foreach_erf_EN3c108ArrayRefINS_6TensorEEE
리서치 결과, colab의 일부 설정 변경에 따라 사전에 pip install 과정이 필요하게 되었습니다
(출처 : pytorch/xla#3215)
`
!pip install cloud-tpu-client==0.10 https://storage.googleapis.com/tpu-pytorch/wheels/torch_xla-1.9-cp37-cp37m-linux_x86_64.whl
!pip install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchtext==0.10.0 -f https://download.pytorch.org/whl/cu111/torch_stable.html
`
해당 작업이 생각보다 시간이 걸리므로 런타임에 유의하셔야 합니다
위의 pip install 과정을 마친 후 정상 작동을 확인하였습니다
개요
문서 분류 튜토리얼을 구축한다
안녕하세요, 책 보고 실습코드 따라하던 중 오류가 생겨 문의드립니다.
저는 코랩에서 실행하고 있고,
!pip install ratsnlp
!pip install tensorflow
!pip install torch
한 이후에 실습 코드 1-1을 실행하니
from ratsnlp.nlpbook.classification import ClassificationTrainArguments
args = ClassificationTrainArguments(
pretrained_model_name = "beomi/kcbert-base",
downstream_corpus_name = "nsmc",
downstream_corpus_root_dir = "/root/Korpora",
downstream_model_dir = "/gdrive/My Drive/nlpbook/checkpoint-doccls",
learning_rate = 5e-5,
batch_size = 32,
)
SystemError Traceback (most recent call last)
in ()
1 #!pip install torchmetrics==0.7.3
----> 2 from ratsnlp.nlpbook.classification import ClassificationTrainArguments
3 args = ClassificationTrainArguments(
4 pretrained_model_name = "beomi/kcbert-base",
5 downstream_corpus_name = "nsmc",
32 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/core/framework/resource_handle_pb2.py in ()
148 ,
149 'DESCRIPTOR' : _RESOURCEHANDLEPROTO,
--> 150 'module' : 'tensorflow.core.framework.resource_handle_pb2'
151 # @@protoc_insertion_point(class_scope:tensorflow.ResourceHandleProto)
152 })
SystemError: google/protobuf/pyext/descriptor.cc:358: bad argument to internal function
이런 오류가 뜨는데 구글링을 해봐도 해결이 되지 않아 문의드립니다.
개요
colab 환경이 변화무쌍하게 바뀌므로 정상 동작하는 의존성 라이브러리 종류 및 버전을 기록해 둔다
특히 colab 환경은 cuda, tpu 등 백엔드 환경에 맞춰서 tensorflow, torch 버전(torchtext, torchvision 등)을 유지하기 때문에 torch 등 기본 라이브러리 버전을 임의로 변경해선 안된다
개요
문장 쌍 분류(sentence pair classification) 튜토리얼을 개발한다
완전 초보입니다 (그야말로 책 그대로 따라서 입력해보는 수준....)
112쪽 코드 3-10에 있는 코드 그대로 실행하면 아래와 같은 에러 메시지가 나옵니다. ㅠㅠ
NameError Traceback (most recent call last)
in ()
2 from torch.optim import Adam
3
----> 4 optimizer = Adam(model.parameters(), lr=model.learning_rate)
NameError: name 'model' is not defined
어떻게 하면 좋을까요?
안녕하세요,
bert와 gpt로 배우는 자연어처리 책을 보고 따라하면서 정말 많이 도움이 되었습니다. 감사합니다.
제가 이 책을 보고 실습을 해보는 과정에서 개인적으로 여쭤보고 싶은 것이 있어서 issues에 글을 남기게 되었습니다.
8장에서 nsmc로 파인튜닝한 gpt모델을 가지고 문장생성을 하는데, 혹시 프롬프트에 감정(긍정 혹은 부정)을 입력했을때
한개의 문장 생성이 아닌, 여러개의 문장을 출력해 보고 싶다면, 어떤 부분을 어떻게 바꿔야 하는지 궁금해서 여쭤봅니다.
감사합니다.
import torch
from ratsnlp.nlpbook.classification import ClassificationTrainArguments
args = ClassificationTrainArguments(
pretrained_model_name="beomi/kcbert-base",
downstream_task_name="pair-classification",
downstream_corpus_name="klue-nli",
downstream_model_dir="/gdrive/My Drive/nlpbook/checkpoint-paircls",
batch_size=32 if torch.cuda.is_available() else 4,
learning_rate=5e-5,
max_seq_length=64,
epochs=5,
tpu_cores=0 if torch.cuda.is_available() else 8,
seed=7,
)
위의 코드를 실행하면...
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
[<ipython-input-6-4b9d2cce98b4>](https://localhost:8080/#) in <module>()
1 import torch
----> 2 from ratsnlp.nlpbook.classification import ClassificationTrainArguments
3 args = ClassificationTrainArguments(
4 pretrained_model_name="beomi/kcbert-base",
5 downstream_task_name="pair-classification",
6 frames
[/usr/local/lib/python3.7/dist-packages/pytorch_lightning/metrics/utils.py](https://localhost:8080/#) in <module>()
20 from torchmetrics.utilities.data import dim_zero_mean as _dim_zero_mean
21 from torchmetrics.utilities.data import dim_zero_sum as _dim_zero_sum
---> 22 from torchmetrics.utilities.data import get_num_classes as _get_num_classes
23 from torchmetrics.utilities.data import select_topk as _select_topk
24 from torchmetrics.utilities.data import to_categorical as _to_categorical
ImportError: cannot import name 'get_num_classes' from 'torchmetrics.utilities.data' (/usr/local/lib/python3.7/dist-packages/torchmetrics/utilities/data.py)
---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.
To view examples of installing some common dependencies, click the
"Open Examples" button below.
---------------------------------------------------------------------------
우의 에러가 뜨는데 어떻게 고치나요?
pratical tips for Natural Language Processing
교재 206페이지의 아래 트레이너 정의를 하였을 때
trainer = nlpbook.get_trainer(args)
다음과 같은 에러가 나옵니다.
MisconfigurationException Traceback (most recent call last)
in ()
----> 1 trainer = nlpbook.get_trainer(args)
4 frames
/usr/local/lib/python3.7/dist-packages/pytorch_lightning/trainer/connectors/accelerator_connector.py in _set_parallel_devices_and_init_accelerator(self)
513 ]
514 raise MisconfigurationException(
--> 515 f"{self.accelerator.class.qualname} can not run on your system"
516 " since the accelerator is not available. The following accelerator(s)"
517 " is available and can be passed into accelerator
argument of"
MisconfigurationException: TPUAccelerator can not run on your system since the accelerator is not available. The following accelerator(s) is available and can be passed into accelerator
argument of Trainer
: ['cpu'].
혹시 어떻게 해결하면 될까요?
답변 부탁드립니다.
안녕하세요.
책을 잘 보고 있습니다.
4장 영화리뷰를 실행해 보려고 하는데,
fit() 실행 부분에서 안되고 있어서
해결 방법이 궁금합니다.
EPOCH 진행바가 생기는 부분까지 왔는데,
epoch 0% 에 멈춰있으면서,
이상하게 .py 파일이 계속 다시 실행되는 것 같습니다.
아래의 소스와 실행 결과입니다.
print('start')
if name == 'main':
import torch
from ratsnlp.nlpbook.classification import ClassificationTrainArguments
args = ClassificationTrainArguments(
pretrained_model_name='beomi/kcbert-base',
downstream_corpus_name='nsmc',
downstream_model_dir='downstream_model',
batch_size=32,
learning_rate=5e-5,
max_seq_length=128,
epochs=3,
tpu_cores=0,
seed=7
)
from ratsnlp import nlpbook
nlpbook.set_seed(args)
nlpbook.set_logger(args)
from Korpora import Korpora
Korpora.fetch(corpus_name=args.downstream_corpus_name,
root_dir=args.downstream_corpus_root_dir,
force_download=False)
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained(
args.pretrained_model_name,
do_lower_case=False
)
from ratsnlp.nlpbook.classification import NsmcCorpus, ClassificationDataset
corpus = NsmcCorpus()
train_dataset = ClassificationDataset(
args=args,
corpus=corpus,
tokenizer=tokenizer,
mode='train'
)
print(train_dataset[0])
from torch.utils.data import DataLoader, RandomSampler
train_dataloader = DataLoader(
train_dataset,
batch_size=args.batch_size,
sampler=RandomSampler(train_dataset, replacement=False),
collate_fn=nlpbook.data_collator,
drop_last=False,
num_workers=args.cpu_workers,
)
from torch.utils.data import SequentialSampler
val_dataset = ClassificationDataset(
args=args,
corpus=corpus,
tokenizer=tokenizer,
mode='test'
)
val_dataloader = DataLoader(
val_dataset,
batch_size=args.batch_size,
sampler=SequentialSampler(val_dataset),
collate_fn=nlpbook.data_collator,
drop_last=False,
num_workers=args.cpu_workers
)
from transformers import BertConfig, BertForSequenceClassification
pretrained_model_config = BertConfig.from_pretrained(
args.pretrained_model_name,
num_labels=corpus.num_labels,
)
model = BertForSequenceClassification.from_pretrained(
args.pretrained_model_name,
config=pretrained_model_config
)
from ratsnlp.nlpbook.classification import ClassificationTask
task = ClassificationTask(model, args)
trainer = nlpbook.get_trainer(args)
trainer.fit(task,train_dataloader,val_dataloader)
실행결과
start
set seed: 7
INFO:ratsnlp:Training/evaluation parameters ClassificationTrainArguments(pretrained_model_name='beomi/kcbert-base', downstream_task_name='document-classification', downstream_corpus_name='nsmc', downstream_corpus_root_dir='/content/Korpora', downstream_model_dir='downstream_model', max_seq_length=128, save_top_k=1, monitor='min val_loss', seed=7, overwrite_cache=False, force_download=False, test_mode=False, learning_rate=5e-05, epochs=3, batch_size=32, cpu_workers=64, fp16=False, tpu_cores=0)
[Korpora] Corpus nsmc
is already installed at D:\content\Korpora\nsmc\ratings_train.txt
[Korpora] Corpus nsmc
is already installed at D:\content\Korpora\nsmc\ratings_test.txt
INFO:ratsnlp:Loading features from cached file /content/Korpora\nsmc\cached_train_BertTokenizer_128_nsmc_document-classification [took 4.358 s]
ClassificationFeatures(input_ids=[2, 2170, 832, 5045, 17, 17, 7992, 29734, 4040, 10720, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], attention_mask=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], token_type_ids=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], label=0)
INFO:ratsnlp:Loading features from cached file /content/Korpora\nsmc\cached_test_BertTokenizer_128_nsmc_document-classification [took 1.545 s]
Some weights of the model checkpoint at beomi/kcbert-base were not used when initializing BertForSequenceClassification: ['cls.predictions.transform.LayerNorm.weight', 'cls.seq_relationship.weight', 'cls.predictions.decoder.weight', 'cls.predictions.transform.dense.bias', 'cls.predictions.transform.dense.weight', 'cls.predictions.transform.LayerNorm.bias', 'cls.seq_relationship.bias', 'cls.predictions.bias', 'cls.predictions.decoder.bias']
This IS expected if you are initializing BertForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
This IS NOT expected if you are initializing BertForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).
Some weights of BertForSequenceClassification were not initialized from the model checkpoint at beomi/kcbert-base and are newly initialized: ['classifier.bias', 'classifier.weight']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
GPU available: True, used: True
TPU available: False, using: 0 TPU cores
IPU available: False, using: 0 IPUs
HPU available: False, using: 0 HPUs
Missing logger folder: D:\data-stock\NLP\downstream_model\lightning_logs
LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]
C:\Anaconda3\envs\trans.gpu2\lib\site-packages\pytorch_lightning\core\optimizer.py:380: RuntimeWarning: Found unsupported keys in the optimizer configuration: {'scheduler'}
rank_zero_warn(
| Name | Type | Params
108 M Trainable params
0 Non-trainable params
108 M Total params
435.680 Total estimated model params size (MB)
Epoch 0: 0%| | 0/6251 [00:00<?, ?it/s]
start
start
start
start
start
start
start
start
start
start
start
연구원들과 파이썬 학습을 하고 있습니다.
GPT3 실습으로 전문가 특강을 해 주실수 있는지요?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.