Elasticsearch:在满意度调查中实现并使用情绪分析器

2,403 阅读9分钟

如果你通过博客或新闻关注 Elastic,你已经知道在最新版本的 Elasticsearch 中已经提供了用于自然语言处理 (NLP) 的资源。事实上,在我之前的博客文章中,我已经推出了很多关于 NLP 的博文。请详细阅读 “Elastic:开发者上手指南” 中的 “NLP - 自然语言处理” 部分。在今天的练习中,我们将进一步使用一个例子来展示如何使用一个情感分析器来识别情绪。我们可以针对用户的反馈进行统计:positive,nagative 或者 neutral。

满意度调查

在满意度调查中,我们有如下的 4 个问题:

1)How do you rate the customer service provided by the company?

答案有四个:Very good, Good, Bad, Too bad

2)The information about the product/service was passed on clearly and correctly?

答案有两个:A: Yes, Not

3)How would you describe our product(s)/service(s)?

答案有八个:Reliable, Very expensive, Cheap and good, Very qualified, Useful, Little qualified, is not reliable, Ineffective

4)How satisfied are you with our company?

答案有五个:Very satisfied, Satisfied, not very satisfied, Dissatisfied, Very unsatisfied,

模型

我们将使用 DistilBERT base uncased finetuned SST-2 模型。这个也是在之前文章 “Elasticsearch:如何部署 NLP:情绪分析示例” 中所使用的模型。这个模型。我们可以使用如下的一个例子来进行查看:

从上面的例子中,我们可以看出来。给定一个句子,它可以帮我们进行情绪判断:正面或者负面。

安装 

如果你还没有安装好自己的 Elasticsearch 及 Kibana,我们可以按照如下的方式来安装一个没有安全的 Elasticsearch 集群:

docker-compose.yml



1.  version: '3.8'

3.  services:

5.    elasticsearch:
6.      image: docker.elastic.co/elasticsearch/elasticsearch:8.6.2
7.      container_name: elasticsearch-8.6.2
8.      environment:
9.        - node.name=elasticsearch
10.        - xpack.security.enabled=false
11.        - discovery.type=single-node
12.        - "ES_JAVA_OPTS=-Xms1g -Xmx1g"
13.      ulimits:
14.        memlock:
15.          soft: -1
16.          hard: -1
17.      volumes:
18.        - esdata1:/usr/share/elasticsearch/data
19.      ports:
20.        - 9200:9200

22.    kibana:
23.      image: docker.elastic.co/kibana/kibana:8.6.2
24.      container_name: kibana-8.6.2
25.      restart: always
26.      environment:
27.        ELASTICSEARCH_URL: "http://elasticsearch:9200"
28.      ports:
29.        - 5601:5601
30.      depends_on:
31.        - elasticsearch

33.  volumes:
34.    esdata1:
35.      driver: local


我们使用如下的命令来启动:

docker-compose up


1.  from elasticsearch import Elasticsearch
2.  from pathlib import Path
3.  from eland.ml.pytorch import PyTorchModel
4.  from eland.ml.pytorch.transformers import TransformerModel

7.  def get_client_es():
8.      return Elasticsearch(
9.          hosts=[{'scheme': 'http', 'host': 'localhost', 'port': 9200}],
10.          request_timeout=300,
11.          verify_certs=False
12.      )

15.  if __name__ == '__main__':
16.      tm = TransformerModel("distilbert-base-uncased-finetuned-sst-2-english", "text_classification")
17.      tmp_path = "models"
18.      Path(tmp_path).mkdir(parents=True, exist_ok=True)
19.      model_path, config, vocab_path = tm.save(tmp_path)
20.      ptm = PyTorchModel(get_client_es(), tm.elasticsearch_model_id())
21.      ptm.import_model(model_path=model_path, config_path=None, vocab_path=vocab_path, config=config)


等上述的命令完成后,我们的 Elasticsearch 将可以在地址 http://localhost:9200 进行访问。 我们可以在 http://localhost:5601 访问 Kibana。

上传模型

我们在本地创建如下的 Python 代码及 requirements.txt 文件:

requirements.txt



1.  elasticsearch~=8.6.2
2.  path
3.  eland~=8.3.0
4.  torch==1.11
5.  transformers
6.  sentence-transformers>=2.1.0


main.py



1.  from elasticsearch import Elasticsearch
2.  from pathlib import Path
3.  from eland.ml.pytorch import PyTorchModel
4.  from eland.ml.pytorch.transformers import TransformerModel

7.  def get_client_es():
8.      return Elasticsearch(
9.          hosts=[{'scheme': 'http', 'host': 'localhost', 'port': 9200}],
10.          request_timeout=300,
11.          verify_certs=False
12.      )

15.  if __name__ == '__main__':
16.      tm = TransformerModel("distilbert-base-uncased-finetuned-sst-2-english", "text_classification")
17.      tmp_path = "models"
18.      Path(tmp_path).mkdir(parents=True, exist_ok=True)
19.      model_path, config, vocab_path = tm.save(tmp_path)
20.      ptm = PyTorchModel(get_client_es(), tm.elasticsearch_model_id())
21.      ptm.import_model(model_path=model_path, config_path=None, vocab_path=vocab_path, config=config)


我们按照如下步骤来运行:

pip3 install -r requirements.txt

我们接下来按照如下的命令来上传模型: 

python main.py 

从上面的输出中,我们可以看出来当前的 License 是不对的。我们需要按照如下的方式来启动白金版试用:

 

 

 

 

这样我们就启动了白金版试用功能。

我们再次运行上面的命令:

 python main.py 

这样,将下载模型并执行上传。 在上传过程中,你将在控制台上看到如下消息: 

上面显示我们的下载及上传是成功的。

我们回到 Kibana 的界面进行查看:

 

 

 

点击上面的 Start Deployment:

 

 

这样,我们就成功地启动了模型。我们可以通过如下的 API 来检查已经安装的模型:

GET /_ml/trained_models/

创建 index mapping

我们接下来创建如下的一个索引 mapping:



1.  PUT survey
2.  {
3.    "mappings": {
4.      "properties": {
5.        "user": {
6.          "type": "text"
7.        },
8.        "question_A": {
9.          "properties": {
10.            "question": {
11.              "type": "text"
12.            },
13.            "answer": {
14.              "type": "text"
15.            }
16.          }
17.        },
18.        "question_B": {
19.          "properties": {
20.            "question": {
21.              "type": "text"
22.            },
23.            "answer": {
24.              "type": "text"
25.            }
26.          }
27.        },
28.        "question_C": {
29.          "properties": {
30.            "question": {
31.              "type": "text"
32.            },
33.            "answer": {
34.              "type": "text"
35.            }
36.          }
37.        },
38.        "question_D": {
39.          "properties": {
40.            "question": {
41.              "type": "text"
42.            },
43.            "answer": {
44.              "type": "text"
45.            }
46.          }
47.        }
48.      }
49.    }
50.  }


该索引的映射由 question 字段和 user 字段组成。 你可能会觉得奇怪,我有几个字段来定义 questions 而不是使用列表,但不幸的是,我在将推理处理器与列表一起使用时遇到了问题。 

推理处理器 - inference processor

现在让我们进入最酷的部分。 通过索引 answer,我们将推断出每个 answer 的分类是什么。 在这部分中,我们将使用推理处理器,该处理器将使用 distilbert-base-uncased-finetuned-sst-2-english 模型,分析响应并在 form_answer_predicted 字段中设置分类。

对于每个答案,我们都会有评分,然后我添加了脚本处理器以根据答案生成最终用户满意度。

Ingest pipeline 将是这样的:



1.  PUT _ingest/pipeline/text-answer-mode-analysis
2.  {
3.    "description": "Apply response analyzer using a sentiment analysis model",
4.    "processors": [
5.      {
6.        "inference": {
7.          "model_id": "distilbert-base-uncased-finetuned-sst-2-english",
8.          "target_field": "question_A.form_answer_predicted",
9.          "field_map": {
10.            "question_A.answer": "text_field"
11.          }
12.        }
13.      },
14.      {
15.        "inference": {
16.          "model_id": "distilbert-base-uncased-finetuned-sst-2-english",
17.          "target_field": "question_B.form_answer_predicted",
18.          "field_map": {
19.            "question_B.answer": "text_field"
20.          }
21.        }
22.      },
23.      {
24.        "inference": {
25.          "model_id": "distilbert-base-uncased-finetuned-sst-2-english",
26.          "target_field": "question_C.form_answer_predicted",
27.          "field_map": {
28.            "question_C.answer": "text_field"
29.          }
30.        }
31.      },
32.      {
33.        "inference": {
34.          "model_id": "distilbert-base-uncased-finetuned-sst-2-english",
35.          "target_field": "question_D.form_answer_predicted",
36.          "field_map": {
37.            "question_D.answer": "text_field"
38.          }
39.        }
40.      },
41.      {
42.        "script": {
43.          "lang": "painless",
44.          "source": """
45.              int countPositive, countNegative = 0; 
46.              ArrayList list = new ArrayList();
47.              list.add(ctx['question_A'].form_answer_predicted.predicted_value);
48.              list.add(ctx['question_B'].form_answer_predicted.predicted_value);
49.              list.add(ctx['question_C'].form_answer_predicted.predicted_value);
50.              list.add(ctx['question_D'].form_answer_predicted.predicted_value);
51.              for (int i = 0; i < list.size(); i++) {
52.                if(list[i].equals("POSITIVE")) {
53.                  countPositive++;
54.                } else {
55.                  countNegative++
56.                }
57.              }
58.              if(countPositive > countNegative) {
59.                ctx['user_satisfaction'] = "POSITIVE"
60.              } else if (countPositive == countNegative) {
61.                ctx['user_satisfaction'] = "NEUTRAL"
62.              } else {
63.                ctx['user_satisfaction'] = "NEGATIVE"
64.              }
65.            """
66.        }
67.      }
68.    ]
69.  }


在上面,我们定义了一个叫做 text-answer-mode-analysis 的 ingest pipeline。它把几个问题都分别进行情绪分析,并最终使用 script 处理器来计算出这个人的情绪是:POSITIVE,NEGATIVE 或者是 NEUTRAL 的。

写入文档

我们现在准备索引数据。 我使用 Bulk API来索引数据并将管道设置为在索引时运行。



1.  PUT survey/_bulk?pipeline=text-answer-mode-analysis
2.  {"index": {"_id": 1}}
3.  {"user":"xpto", "question_A": {"question":"How do you rate the customer service provided by the company?", "answer": "good"}, "question_B": {"question":"The information about the product/service was passed on clearly and correctly", "answer": "no"}, "question_C": {"question":"How would you describe our product(s)/service(s)?", "answer": "Useful"}, "question_D": {"question":"How satisfied are you with our company?", "answer": "Dissatisfied"}}
4.  {"index": {"_id": 2}}
5.  {"user":"xpto", "question_A": {"question":"How do you rate the customer service provided by the company?", "answer": "good"}, "question_B": {"question":"The information about the product/service was passed on clearly and correctly", "answer": "yes"}, "question_C": {"question":"How would you describe our product(s)/service(s)?", "answer": "Useful"}, "question_D": {"question":"How satisfied are you with our company?", "answer": "Satisfied"}}
6.  {"index": {"_id": 3}}
7.  {"user":"xpto", "question_A": {"question":"How do you rate the customer service provided by the company?", "answer": "bad"}, "question_B": {"question":"The information about the product/service was passed on clearly and correctly", "answer": "no"}, "question_C": {"question":"How would you describe our product(s)/service(s)?", "answer": "Very expensive"}, "question_D": {"question":"How satisfied are you with our company?", "answer": "Dissatisfied"}}


请注意,在上面的每个文档中,它都含有四个问题,并含有相应的答案。

我们可以通过如下命令来查看被摄入的文档:

GET survey/_search?filter_path=**.hits

上面命令搜索的结果是:



1.  {
2.    "hits": {
3.      "hits": [
4.        {
5.          "_index": "survey",
6.          "_id": "1",
7.          "_score": 1,
8.          "_source": {
9.            "question_C": {
10.              "form_answer_predicted": {
11.                "predicted_value": "POSITIVE",
12.                "prediction_probability": 0.9997634803424444,
13.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
14.              },
15.              "question": "How would you describe our product(s)/service(s)?",
16.              "answer": "Useful"
17.            },
18.            "question_D": {
19.              "form_answer_predicted": {
20.                "predicted_value": "NEGATIVE",
21.                "prediction_probability": 0.9997315864531746,
22.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
23.              },
24.              "question": "How satisfied are you with our company?",
25.              "answer": "Dissatisfied"
26.            },
27.            "question_A": {
28.              "form_answer_predicted": {
29.                "predicted_value": "POSITIVE",
30.                "prediction_probability": 0.9998161198125766,
31.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
32.              },
33.              "question": "How do you rate the customer service provided by the company?",
34.              "answer": "good"
35.            },
36.            "question_B": {
37.              "form_answer_predicted": {
38.                "predicted_value": "NEGATIVE",
39.                "prediction_probability": 0.9964459731735253,
40.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
41.              },
42.              "question": "The information about the product/service was passed on clearly and correctly",
43.              "answer": "no"
44.            },
45.            "user": "xpto",
46.            "user_satisfaction": "NEUTRAL"
47.          }
48.        },
49.        {
50.          "_index": "survey",
51.          "_id": "2",
52.          "_score": 1,
53.          "_source": {
54.            "question_C": {
55.              "form_answer_predicted": {
56.                "predicted_value": "POSITIVE",
57.                "prediction_probability": 0.9997634803424444,
58.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
59.              },
60.              "question": "How would you describe our product(s)/service(s)?",
61.              "answer": "Useful"
62.            },
63.            "question_D": {
64.              "form_answer_predicted": {
65.                "predicted_value": "POSITIVE",
66.                "prediction_probability": 0.9997212937948691,
67.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
68.              },
69.              "question": "How satisfied are you with our company?",
70.              "answer": "Satisfied"
71.            },
72.            "question_A": {
73.              "form_answer_predicted": {
74.                "predicted_value": "POSITIVE",
75.                "prediction_probability": 0.9998161198125766,
76.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
77.              },
78.              "question": "How do you rate the customer service provided by the company?",
79.              "answer": "good"
80.            },
81.            "question_B": {
82.              "form_answer_predicted": {
83.                "predicted_value": "POSITIVE",
84.                "prediction_probability": 0.9997805442484351,
85.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
86.              },
87.              "question": "The information about the product/service was passed on clearly and correctly",
88.              "answer": "yes"
89.            },
90.            "user": "xpto",
91.            "user_satisfaction": "POSITIVE"
92.          }
93.        },
94.        {
95.          "_index": "survey",
96.          "_id": "3",
97.          "_score": 1,
98.          "_source": {
99.            "question_C": {
100.              "form_answer_predicted": {
101.                "predicted_value": "NEGATIVE",
102.                "prediction_probability": 0.965237853665764,
103.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
104.              },
105.              "question": "How would you describe our product(s)/service(s)?",
106.              "answer": "Very expensive"
107.            },
108.            "question_D": {
109.              "form_answer_predicted": {
110.                "predicted_value": "NEGATIVE",
111.                "prediction_probability": 0.9997315864531746,
112.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
113.              },
114.              "question": "How satisfied are you with our company?",
115.              "answer": "Dissatisfied"
116.            },
117.            "question_A": {
118.              "form_answer_predicted": {
119.                "predicted_value": "NEGATIVE",
120.                "prediction_probability": 0.9997823345695842,
121.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
122.              },
123.              "question": "How do you rate the customer service provided by the company?",
124.              "answer": "bad"
125.            },
126.            "question_B": {
127.              "form_answer_predicted": {
128.                "predicted_value": "NEGATIVE",
129.                "prediction_probability": 0.9964459731735253,
130.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
131.              },
132.              "question": "The information about the product/service was passed on clearly and correctly",
133.              "answer": "no"
134.            },
135.            "user": "xpto",
136.            "user_satisfaction": "NEGATIVE"
137.          }
138.        }
139.      ]
140.    }
141.  }


在进行搜索时,你会看到在每个问题中都生成了带有分类的字段,字段 form_answer_predicted。

 1.            "question_B": {
2.              "form_answer_predicted": {
3.                "predicted_value": "NEGATIVE",
4.                "prediction_probability": 0.9964459731735253,
5.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
6.              },

这个表示情绪识别的准确性。

另外,我们的通用分类字段 user_satisfaction 也已创建。 在下面的示例中,由于正面和负面预测的数量相同,我们的状态为“NEUTRAL”:

 1.          "_source": {
2.            "question_C": {
3.              "form_answer_predicted": {
4.                "predicted_value": "POSITIVE",
5.                "prediction_probability": 0.9997634803424444,
6.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
7.              },
8.              "question": "How would you describe our product(s)/service(s)?",
9.              "answer": "Useful"
10.            },
11.            "question_D": {
12.              "form_answer_predicted": {
13.                "predicted_value": "NEGATIVE",
14.                "prediction_probability": 0.9997315864531746,
15.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
16.              },
17.              "question": "How satisfied are you with our company?",
18.              "answer": "Dissatisfied"
19.            },
20.            "question_A": {
21.              "form_answer_predicted": {
22.                "predicted_value": "POSITIVE",
23.                "prediction_probability": 0.9998161198125766,
24.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
25.              },
26.              "question": "How do you rate the customer service provided by the company?",
27.              "answer": "good"
28.            },
29.            "question_B": {
30.              "form_answer_predicted": {
31.                "predicted_value": "NEGATIVE",
32.                "prediction_probability": 0.9964459731735253,
33.                "model_id": "distilbert-base-uncased-finetuned-sst-2-english"
34.              },
35.              "question": "The information about the product/service was passed on clearly and correctly",
36.              "answer": "no"
37.            },
38.            "user": "xpto",
39.            "user_satisfaction": "NEUTRAL"
40.          }
41.        }

好了,今天的文章就写到这里。希望你通过这个例子能对 Elastic Stack 所提供的 NLP 有更多的认识,并在你将来的应用中使用到。