Azure AI Tutorial 8 - Xử Lý Ngôn Ngữ Tự Nhiên Trên Azure

Azure AI Tutorial 8 - Xử Lý Ngôn Ngữ Tự Nhiên Trên Azure

Xử lý ngôn ngữ tự nhiên hay thường nghe với từ khóa NLP nhằm mục đích hổ trợ các ứng dụng có khả năng nhìn thấy, nghe , nói và hiểu thông tin từ người dùng.

Nature Language Processing trên Azure với các dịch vụ như Text analytics, Translation và Language Understanding. Microsoft Azure AI hổ trợ cho lập trình viên phát triển và tích hợp NLP vào ứng dụng của mình một cách dễ dàng.

Microsoft Azure AI (NLP) giúp lập trình viên có thể:

  • Phân tích văn bản, trích xuất thông tin, nhận diện cá thể, vật thể (ví dụ: địa điểm, thời gian, tên người..)
  • Nhận biết cảm xúc văn bản (Đánh giá tích cực, tiêu cực)
  • Hiểu được ngôn ngữ nói.
  • Tự động dịch ngôn ngữ nói và cả chữ viết tay
  • ...

Giờ chúng ta cùng thực hành với Text Analytics service

Azure AI 4.1 Text Analytics trên Azure

Phân tích văn bản (Text Analytics) là gì?

Là đánh giá văn bản, tài liệu, đoạn text đó trên nhiều khía cạnh khác nhau để hiểu rõ hơn nội dung văn bản, tài liệu đó. Ví dụ khi ta đọc 1 đoạn văn bản, chúng ta có thể nhìn thấy, hiểu được các tên người, tên địa điểm, danh từ riêng, một số trường hợp chúng ta còn hiểu được felling của bài viết đang nói tốt, hay nói xấu…

Nào chúng ta đi vào thực hành nhé, hôm nay chúng ta sẽ thực hiện

  1. Tạo Cognitive Service Resource
  2. Tạo notebook và install thư viện cognitive service
  3. Detect ngôn ngữ
  4. Trích xuất cụm từ (Extract Key Phrases)
  5. Xác định cảm xúc (Determine Sentiment)
  6. Extract thông tin chung (tên riêng, ngày tháng...)

Chúng ta có các văn bản như sau:

review1.txt
Good Hotel and staff
The Royal Hotel, London, UK
3/2/2018
Clean rooms, good service, great location near Buckingham Palace and Westminster Abbey, and so on. We thoroughly enjoyed our stay. The courtyard is very peaceful and we went to a restaurant which is part of the same group and is Indian ( West coast so plenty of fish) with a Michelin Star. We had the taster menu which was fabulous. The rooms were very well appointed with a kitchen, lounge, bedroom and enormous bathroom. Thoroughly recommended.
review2.txt
Tired hotel with poor service
The Royal Hotel, London, United Kingdom
5/6/2018
This is a old hotel (has been around since 1950's) and the room furnishings are average - becoming a bit old now and require changing. The internet didn't work and had to come to one of their office rooms to check in for my flight home. The website says it's close to the British Museum, but it's too far to walk.
review3.txt
Good location and helpful staff, but on a busy road.
The Lombard Hotel, San Francisco, USA
8/16/2018
We stayed here in August after reading reviews. We were very pleased with location, just behind Chestnut Street, a cosmopolitan and trendy area with plenty of restaurants to choose from. The
Marina district was lovely to wander through, very interesting houses. Make sure to walk to the San Francisco Museum of Fine Arts and the Marina to get a good view of Golden Gate bridge and the city. On a bus route and easy to get into centre. Rooms were clean with plenty of room and staff were friendly and helpful. The only down side was the noise from Lombard Street so ask to have a room furthest away from traffic noise.

LET'S START

1. Tạo Cognitive Service Resource

2. Tạo notebook và Install thư viện

  • Intall thư viện (Nếu đã có thì bỏ qua bước này nhé)

! pip install azure-cognitiveservices-language-textanalytics

  • Copy key, và endpoint

cog_key = '0afbab280c9f42e589143a683845a0c5'
cog_endpoint = 'https://mvcognitiveservice.cognitiveservices.azure.com/'

3. Detect ngôn ngữ

import os
from azure.cognitiveservices.language.textanalytics import TextAnalyticsClient
from msrest.authentication import CognitiveServicesCredentials

# Get a client for your text analytics cognitive service resource
text_analytics_client = TextAnalyticsClient(endpoint=cog_endpoint,
                                            credentials=CognitiveServicesCredentials(cog_key))

# Analyze the reviews you read from the /data/reviews folder earlier
language_analysis = text_analytics_client.detect_language(documents=reviews)


# print detected language details for each review
for review_num in range(len(reviews)):
    # print the review id
    print(reviews[review_num]['id'])

    # Get the language details for this review
    lang = language_analysis.documents[review_num].detected_languages[0]
    print(' - Language: {}\n - Code: {}\n - Score: {}\n'.format(lang.name, lang.iso6391_name, lang.score))

    # Add the detected language code to the collection of reviews (so we can do further analysis)
    reviews[review_num]["language"] = lang.iso6391_name

Và thành quả là đây:

review1.txt
 - Language: English
 - Code: en
 - Score: 1.0

review2.txt
 - Language: English
 - Code: en
 - Score: 1.0

review3.txt
 - Language: English
 - Code: en
 - Score: 1.0

4. Trích xuất cụm từ (Extract Key Phrases)

Trích xuất cụm từ chính là một trong các kỹ thuật quan trọng để chúng ta hiểu được nội dung văn bản: Ví dụ chúng ta extract thông tin như “Tôi hài lòng” hay “dịch vụ kém”, những keywork này giúp ta phần nào hiểu được thông tin.

key_phrase_analysis = text_analytics_client.key_phrases(documents=reviews)
# print key phrases for each review
for review_num in range(len(reviews)):
    # print the review id
    print(reviews[review_num]['id'])
    # Get the key phrases in this review
    print('\nKey Phrases:')
    key_phrases = key_phrase_analysis.documents[review_num].key_phrases
    # Print each key phrase
    for key_phrase in key_phrases:
        print('\t', key_phrase)
    print('\n')

Xem kết quả nhé:

review1.txt
Key Phrases:
	 Good Hotel
	 good service
	 Clean rooms
	 Royal Hotel
	 great location
	 Buckingham Palace
	 Westminster Abbey
	 fish
	 West coast
	 lounge
	 bedroom
	 enormous bathroom
	 group
	 kitchen
	 London
	 UK
	 taster menu
	 Michelin Star
	 staff
	 courtyard
review2.txt
.....

5. Xác định cảm xúc

Azure xác định cảm xúc và đưa ra chỉ số từ 0 -> 1. 0 nghĩa là đánh giá xấu ;0.5 là trung bình; 1 là tốt

sentiment_analysis = text_analytics_client.sentiment(documents=reviews)
# Print the results for each review
for review_num in range(len(reviews)):

    # Get the sentiment score for this review
    sentiment_score = sentiment_analysis.documents[review_num].score

    # classifiy 'positive' if more than 0.5, 
    if sentiment_score < 0.5:
        sentiment = 'negative'
    else:
        sentiment = 'positive'

    # print file name and sentiment
    print('{} : {} ({})'.format(reviews[review_num]['id'], sentiment, sentiment_score))

Output:

review1.txt : positive (0.9999926686286926)
review2.txt : negative (5.662441253662109e-07)
review3.txt : positive (0.9999995231628418)

6. Extract thông tin chung

Một vài thông tin như tên địa điểm, tên người, ngày tháng, địa chỉ được xem là các thông tin chung. Chúng ta có thể extract riêng những thông tin này để theo dõi.

entity_analysis = text_analytics_client.entities(documents=reviews)

# Print the results for each review
for review_num in range(len(reviews)):
    print(reviews[review_num]['id'])
    # Get the named entitites in this review
    entities = entity_analysis.documents[review_num].entities
    for entity in entities:
        # Only get location entitites
        if entity.type in ['DateTime','Location']:
            link = '(' + entity.wikipedia_url + ')' if entity.wikipedia_id is not None else ''
            print(' - {}: {} {}'.format(entity.type, entity.name, link))

Output:

review1.txt
 - Location: The Royal Hotel (https://en.wikipedia.org/wiki/The_Royal_Hotel)
 - Location: London (https://en.wikipedia.org/wiki/London)
 - DateTime: 3/2/2018 
 - Location: Buckingham Palace (https://en.wikipedia.org/wiki/Buckingham_Palace)
 - Location: Westminster Abbey (https://en.wikipedia.org/wiki/Westminster_Abbey)
 - Location: India (https://en.wikipedia.org/wiki/India)
 - Location: West Coast Main Line (https://en.wikipedia.org/wiki/West_Coast_Main_Line)
review2.txt
 - Location: The Royal Hotel (https://en.wikipedia.org/wiki/The_Royal_Hotel)
 - Location: London (https://en.wikipedia.org/wiki/London)
 - Location: London 
 - Location: United Kingdom 
 - DateTime: 5/6/2018 
 - DateTime: since 1950's 
 - DateTime: now 
 - Location: British Museum (https://en.wikipedia.org/wiki/British_Museum)
review3.txt
.....