Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 2개 있습니다.)
스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
; https://www.sysnet.pe.kr/2/0/13363

스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
; https://www.sysnet.pe.kr/2/0/13375




파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실습

다음의 강좌에서,

Transformers (신경망 언어모델 라이브러리) 강좌
; https://wikidocs.net/book/8056

1장 2절의 내용에,

2. 🤗Transformers가 할 수 있는 일들
; https://wikidocs.net/166787

포함된 코드를 구글 Colab에서 수행한 결과를 나열해 봅니다. ^^

!pip install transformers

from transformers import pipeline

classifier = pipeline("sentiment-analysis")

classifier("I've been waiting for a HuggingFace course my whole life.")

classifier(["I've been waiting for a HuggingFace course my whole life.", "I hate this so much!"])

# 실행 결과
[{'label': 'POSITIVE', 'score': 0.9598048329353333},
 {'label': 'NEGATIVE', 'score': 0.9994558691978455}]

from transformers import pipeline

classifier = pipeline("zero-shot-classification")
classifier(
    "This is a course about the Transformers library",
    candidate_labels=["education", "politics", "business"],
)

# 실행 결과
{'sequence': 'This is a course about the Transformers library',
 'labels': ['education', 'business', 'politics'],
 'scores': [0.8445989489555359, 0.11197412759065628, 0.04342695698142052]}

from transformers import pipeline

generator = pipeline("text-generation")
generator("In this course, we will teach you how to")

# 실행 결과
[{'generated_text': "In this course, we will teach you how to use NLP with the following tasks. In this course, we will work with a computer running NLP. I'm using the npc-get system to find your NPM scripts and to start"}]

from transformers import pipeline

generator = pipeline("text-generation", model="distilgpt2")    # distilgpt2 모델을 로드한다.
generator(
    "In this course, we will teach you how to",
    max_length=30,
    num_return_sequences=2,
)

# 실행 결과
[{'generated_text': 'In this course, we will teach you how to create a simple and fun web design using Photoshop for building a simple website.\n\n\n\nThe'},
 {'generated_text': 'In this course, we will teach you how to apply the following basic concepts to your life (see below). This course aims to help you to choose'}]

from transformers import pipeline

unmasker = pipeline("fill-mask")
unmasker("This course will teach you all about  models.", top_k=3)

# 실행 결과
[{'score': 0.19619806110858917,
  'token': 30412,
  'token_str': ' mathematical',
  'sequence': 'This course will teach you all about mathematical models.'},
 {'score': 0.04052723944187164,
  'token': 38163,
  'token_str': ' computational',
  'sequence': 'This course will teach you all about computational models.'},
 {'score': 0.03301795944571495,
  'token': 27930,
  'token_str': ' predictive',
  'sequence': 'This course will teach you all about predictive models.'}]

from transformers import pipeline

ner = pipeline("ner", grouped_entities=True)
ner("My name is Sylvain and I work at Hugging Face in Brooklyn.")

# 실행 결과
[{'entity_group': 'PER',
  'score': 0.9981694,
  'word': 'Sylvain',
  'start': 11,
  'end': 18},
 {'entity_group': 'ORG',
  'score': 0.9796019,
  'word': 'Hugging Face',
  'start': 33,
  'end': 45},
 {'entity_group': 'LOC',
  'score': 0.9932106,
  'word': 'Brooklyn',
  'start': 49,
  'end': 57}]

from transformers import pipeline

question_answerer = pipeline("question-answering")
question_answerer(
    question="Where do I work?",
    context="My name is Sylvain and I work at Hugging Face in Brooklyn",
)

# 실행 결과
{'score': 0.6949767470359802, 'start': 33, 'end': 45, 'answer': 'Hugging Face'}

from transformers import pipeline

summarizer = pipeline("summarization")
summarizer(
    """
    America has changed dramatically during recent years. Not only has the number of 
    graduates in traditional engineering disciplines such as mechanical, civil, 
    electrical, chemical, and aeronautical engineering declined, but in most of 
    the premier American universities engineering curricula now concentrate on 
    and encourage largely the study of engineering science. As a result, there 
    are declining offerings in engineering subjects dealing with infrastructure, 
    the environment, and related issues, and greater concentration on high 
    technology subjects, largely supporting increasingly complex scientific 
    developments. While the latter is important, it should not be at the expense 
    of more traditional engineering.

    Rapidly developing economies such as China and India, as well as other 
    industrial countries in Europe and Asia, continue to encourage and advance 
    the teaching of engineering. Both China and India, respectively, graduate 
    six and eight times as many traditional engineers as does the United States. 
    Other industrial countries at minimum maintain their output, while America 
    suffers an increasingly serious decline in the number of engineering graduates 
    and a lack of well-educated engineers.
    """
)

# 실행 결과
[{'summary_text': ' America has changed dramatically during recent years . The number of engineering graduates in the U.S. has declined in traditional engineering disciplines such as mechanical, civil, electrical, chemical, and aeronautical engineering . Rapidly developing economies such as China and India, as well as other industrial countries in Europe and Asia, continue to encourage and advance engineering .'}]

from transformers import pipeline

translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en")
translator("그동안 너무 잘해 주셔서 감사드립니다.")

# 실행 결과
[{'translation_text': 'Thank you so much for your kindness.'}]

from transformers import pipeline

unmasker = pipeline("fill-mask", model="bert-base-uncased")
result = unmasker("This man works as a [MASK].")
print([r["token_str"] for r in result])

result = unmasker("This woman works as a [MASK].")
print([r["token_str"] for r in result])


# 실행 결과
['carpenter', 'lawyer', 'farmer', 'businessman', 'doctor']
['nurse', 'maid', 'teacher', 'waitress', 'prostitute']




참고로, Colab이 아닌 Windows에서의 python 환경에서 테스트하고 싶다면 우선 python 3.10으로 설치하고,

Python 3.10.0
; https://www.python.org/downloads/release/python-3100/

제 경우에는 "Windows embeddable package (64-bit)"를 다운로드했고 (따라서 _pth 파일과 pip을 별도로 설정한 다음), virtualenv도 마저 설치합니다.

이후 새로운 virtualenv 환경을 만들고,

C:\python\llml> virtualenv test
created virtual environment CPython3.10.0.final.0-64 in 3934ms
  ...[생략]...

활성화시킨 후,

C:\python\llml> cd test
C:\python\llml\test> .\Scripts\activate

(test) C:\python\llml\test>

transformers를 설치합니다.

(test) C:\python\llml\test> python -m pip install "transformers[sentencepiece]"

그런데, 이것만으로는 pipeline 예제를 실행하는 경우 예외가 발생합니다.

Traceback (most recent call last):
  File "C:\python\llml\test\sc1.py", line 3, in 
    unmasker = pipeline("fill-mask", model="bert-base-uncased")
  File "C:\python\llml\test\lib\site-packages\transformers\pipelines\__init__.py", line 788, in pipeline
    framework, model = infer_framework_load_model(
  File "C:\python\llml\test\lib\site-packages\transformers\pipelines\base.py", line 222, in infer_framework_load_model
    raise RuntimeError(
RuntimeError: At least one of TensorFlow 2.0 or PyTorch should be installed. To install TensorFlow 2.0, read the instructions at https://www.tensorflow.org/install/ To install PyTorch, read the instructions at https://pytorch.org/.

메시지에서 의미하듯이 PyTorch (또는 tensorflow)를 설치해야 하는데요,

START LOCALLY
; https://pytorch.org/get-started/locally/

// NVidia CUDA 11.8
python -m pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

// CPU
python -m pip install torch torchvision torchaudio

PyTorch의 경우 지원하는 Compute Platform에 CPU와 CUDA만 있으므로 아쉽게도 AMD 그래픽 카드에서는 사용할 수 없습니다. 하지만, 이미 이 글에서 실습한 코드들의 경우 Model을 직접 훈련시키는 것이 아닌, 이미 훈련된 Model을 사용하는 것에 불과하므로 CPU로도 문제없이 실습이 가능합니다. (3장의 미세 조정 학습까지는!)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/26/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13232정성태1/27/20234825스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233746오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234108개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20235106.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235245.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20234931개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234603.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20233850개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234209Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234410오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20234097개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234324Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234446오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20234011Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20233948VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234530디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234784디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/20236349Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/20235889.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/20235433오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/20235179기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/20235212웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/20234301Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/20234206Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/20234182.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/20224450.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법파일 다운로드1
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...