NLP 学習 | NLP を知る

NLP のデモ ツールと前処理手法

自然言語処理(自然言語処理、英語: Natural Language Processing 、略称 NLP )は、人工知能および言語学の一分野である。この分野では、自然言語を処理および使用する方法について説明します。自然言語処理には、基本的に認知、理解、生成、その他の部分を含む多くの側面とステップが含まれます。
今日から私は皆さんと一緒に、自然言語処理の基本的な知識と古典的なモデルを学び、深層学習というもう 1 つの魔法の分野を探求していきます。

1 自然言語の楽しさを体験できる小さなツール:パイプライン

Pipeline は、さまざまな NLP タスク用に Hugging Face によって開発された深層学習パッケージです。その主な貢献は、テキストの前処理、モデル構築、結果表現の主要なプロセスをカプセル化し、エンドツーエンドの入出力を実現し、ほぼすべてのメインストリームの事前トレーニング済みモデルをサポートします。
この実験では主に、 Pipeline の感情分析、テキスト翻訳、要約抽出の3 つの機能を選択し、実際のアプリケーションでの例を使用してテストします。

1.1 感情分析

センチメント分析は、主観的なテキストを感情的な色で分析、処理、要約、推論するプロセスであり、主に映画の興行収入の予測、株価動向、世論分析、サービスや製品の改善、ユーザーエクスペリエンスの理解に使用されます。この実験における感情分析の入力と出力を表 1 に示します。
ここに画像の説明を挿入

感情分析のコード スニペットは次のとおりです。

# 1.情感分析代码片段
# 介绍:分析文本情感
# 1.情感分析示例
classifier = pipeline("sentiment-analysis")
classifier_sentence=[
"I like apple",# Positive
"I hate this so much!", # Negative
    "I've been waiting for a HuggingFace course my whole life." ,# Positive
    "Aiming at the real-time detection of multiple objects and micro-objects in large-scene RS images,a cascaded convolutional neural network real-time object-detection framework for RS images is proposed,which integrates visual perception and convolutional memory network reasoning."# Positive]
print("="*27,"情感分析输出{}\n{}".format("="*27,classifier(classifier_sentence)))

出力結果:

======================== 情感分析输出========================
[{
    
    'label': 'POSITIVE', 'score': 0.9995661377906799},
{
    
    'label': 'NEGATIVE', 'score': 0.9994558691978455},
{
    
    'label': 'POSITIVE', 'score': 0.9598046541213989},
{
    
    'label': 'NEGATIVE', 'score': 0.6896899342536926}]

1.2 テキスト翻訳

テキスト翻訳は、コンピューターによって 1 つの自然言語 (ソース言語) を別の自然言語 (ターゲット言語) に変換するプロセスであり、計算言語学の分野の 1 つであり、重要な科学研究価値があります。この実験では、Helsinki-NLP ブランチの opus-mt-en-zh 翻訳モデルが英語と中国語の翻訳に使用されます。コード スニペットは次のとおりです。

# 2.文本翻译代码片段
# 介绍:利用Pipeline中translation功能实现英译汉
# 2.文本翻译
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-zh")
trans_sentence=[
    'The object detection task and the classification task follow the same process in the image feature extraction part of the network',
    'Object detection is a fundamental problem in the field of Computer Vision, which can be widely used in many fields such as environment monitoring,intrusion detection human-machine interaction and so on.'
]
print("="*27,"文本翻译输出{}\n{}".format("="*27,translator(trans_sentence)))

出力結果:

========================= 文本翻译输出========================
[{
    
    'translation_text': '目标探测任务和分类任务在网络图像特征提取部分遵循同样的程序'}, 
{
    
    'translation_text': '物体探测是计算机视野领域的一个基本问题,可广泛用于环境监测、入侵探测人体机械相互作用等许多领域。'}]

1.3 要約の抽出

要約抽出の作業は、主要な情報をできるだけ保持しながら長いテキストを短いテキストに圧縮することであり、大量の情報から有効な情報を迅速かつ正確に取得するために非常に重要です。この実験では、sshleifer ブランチの下の distilbart-cnn-12-6 モデルが概要抽出に使用されます。コード スニペットは次のとおりです。

# 3.摘要提取代码片段
# 介绍:利用Pipeline中summarization功能实现自动摘要
# 3.摘要提取
summarizer = pipeline("summarization")
sum_sentence='Automatic object detection technology based on RS image is an intelligent data analysis method to realize automatic classification and location of RS objects. It is one of the important research directions in the field of RS image interpretation, and has received extensive attention in the civil and military fields. Automatic detection of remote sensing objects has played an important role in many practical applications such as urban planning, traffic safety, environmental monitoring and so on.'
print("="*27,"摘要提取输出{}\n{}".format("="*27,summarizer(sum_sentence)),"="*27)

出力結果:

====================== 摘要提取输出======================
[{
    
    'summary_text': ' Automatic object detection technology based on RS image is an intelligent 
data analysis method . Automatic detection of RS objects has played an important role in many 
practical applications such as urban planning, traffic safety, environmental monitoring and so on.
It has received extensive attention in the civil and military fields .'}] 

2 英語コーパスの前処理と分析

データ分析とデータマイニングでは、通常、事前準備、データクローリング、データ前処理、データ分析、データ可視化、評価と分析のステップを踏む必要があり、このうちデータ前処理はその後のモデル分析の品質に直接影響します。結果が重要です。コーパス前処理とは主にコーパス内に貴重なデータを保持し、ノイズデータを削除することを指しますが、この実験では主にテキスト単語の頻度分析とテキストのベクトル化を使用してコーパス前処理を実現します。

2.1 テキスト単語の頻度分析

2.1.1 英文の単語分割を独自に実現

英語のテキストには自然に単語の分割特性があるため、つまり、英語のテキストは単語間のスペースに応じてフレーズに直接分割でき、アルファベット以外の文字を削除するだけで済みます。そのため、この実験では、このロジックに従って、英語のテキストの単語を独自に編集しました。セグメンテーション機能の主な内容は次のとおりです。

# 4.英文分词代码片段
# 介绍:首先使用空格对特殊字符进行替换,然后使用空格分词,最后将上一步结果中的空格剔除,得到最终的英文文本分词结果
def get_words(input_txt):

    for idx in range(len(input_txt)):
        for ch in '!"#$%&()*+,./:;<=>?@[\\]^_‘{|}~£':
            input_txt[idx] = input_txt[idx].replace(ch, ' ')
        input_txt[idx]=[item for item in filter(lambda x: x != '', input_txt[idx].split(' '))]
        return input_txt

生の入力の場合:

tv future in the hands of viewers with home theatre systems plasma high-definition. tvs  and digital video recorders moving into the living room the way people watch tv will be radically different in five years time.

単語分割後の結果は次のようになります。

'tv', 'future', 'in', 'the', 'hands', 'of', 'viewers', 'with', 'home', 'theatre', 'systems', 'plasma', 'high-definition', 'tvs', 'and', 'digital', 'video', 'recorders', 'moving', 'into', 'the', 'living', 'room', 'the', 'way', 'people', 'watch', 'tv', 'will', 'be', 'radically', 'different', 'in', 'five', 'years', 'time'

事前定義された句読点とスペースの場合、関数が単語をより適切に分割できることがわかります。

2.1.2 語幹抽出とストップワード除去

コーパスの分析プロセスでは、通常、実験結果を妨げるダーティなデータやノイズ フレーズが存在するため、単語で分割されたコーパスのデータ クリーニングが必要になります。たとえば、英語の単語を分割した後、結果に「a」、「the」、「ours」などのダーティ データまたはストップ ワードが含まれる可能性があります。より良い分析結果を得るには、nltk ツールを使用して語幹抽出とストップワード除去を行う必要があります。関連する内容は次のとおりです。

# 5.词干提取及停用词剔除代码片段
# 介绍:对英文文本分词结果进行清洗,主要包括get_stemWords操作和get_stopWords
def get_stemWords(sentences):

    porter_stem = PorterStemmer()
    res=[]
    for words in sentences:
        temp = []
        for word in words:
            temp.append(porter_stem.stem(word))
        res.append(temp)
       return res

def get_stopWords(stem_sentences):

    stop_words = stopwords.words("english")
    for idx in range(len(stem_sentences)):
        stem_sentences[idx]=[word for word in stem_sentences[idx] if not word in stop_words]
    return stem_sentences

単語分割後の結果:

'howard', 'hits', 'back', 'at', 'mongrel', 'jibe', 'michael', 'howard', 'has', 'said', 'a', 'claim', 'by', 'peter', 'hain', 'that', 'the', 'tory', 'leader', 'is', 'acting', 'like', 'an', 'attack'

ステミング出力は次のとおりです。

'howard', 'hit', 'back', 'at', 'mongrel', 'jibe', 'michael', 'howard', 'ha', 'said', 'a', 'claim', 'by', 'peter', 'hain', 'that', 'the', 'tori', 'leader', 'is', 'act', 'like', 'an', 'attack'

ストップワードを削除した結果は次のようになります。

'howard', 'hit', 'back', 'mongrel', 'jibe', 'michael', 'howard', 'ha', 'said', 'claim', 'peter', 'hain', 'tori', 'leader', 'act', 'like', 'attack'

単語セグメンテーションの結果については、語幹抽出により単語を復元して対応する語根を取得でき、ストップワード除去により単語内の干渉データを除去して理想的なテキスト データを取得できることがわかります。

2.1.3 コーパス語彙の生成

後続の TF-IDF 分析でも語彙が使用されることを考慮して、まず語彙を CSV ファイルに書き込み、書き込みプロセス中にタグを直接ベクトル化します: 0- テクノロジー、1- ビジネス、2- スポーツ、3- エンターテイメント、4 -政治

# 6.词表写入代码片段
# 介绍:将清洗后的英文文本分词结果写入csv文件
def write2csv(stopWords,labels):

    contents = []
    for item in stopWords:
        contents.append(" ".join(item))
    with open('fenci_data.csv', "w",newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['contents', 'labels'])
        for idx in range(len(contents)):
            writer.writerow([contents[idx], labels[idx]])

次に、この実験では、nltk の FreqDist を呼び出して、前処理後の単語頻度をカウントし、主に単語分割結果の単語頻度が最も高い 50 単語をカウントします。関数の本体は次のとおりです。

# 7.词频统计代码片段
# 介绍:对清洗后的英文文本分词结果进行词频统计
def get_wordFrequency(stopWords):
    for words in stopWords:
        freq_dist = FreqDist(words)
        # for k, v in freq_dist.items():
        #     print(str(k) + ':' + str(v))
    standard_freq_vector = freq_dist.most_common(50)
    return standard_freq_vector

出力結果:

('howard', 14), ('mr', 13), ('said', 8), ('hi', 8), ('parti', 7), ('labour', 6), ('michael', 5), ('tori', 5), ('tell', 5), ('elect', 5)

2.2 テキストのベクトル化

重み計算とは、文書表現における特徴項目の重要性を特徴重みによって測定し、特徴語に一定の重みを与えて統計的なテキスト特徴語を測定することを指し、TF-IDFはデータ分析や情報処理における古典的な重み計算技術です。TF-IDF 技術の中心的な考え方は、ある特徴語が TF の頻度が高い記事に出現し、他の記事にはめったに出現しない場合、その単語またはフレーズは優れたカテゴリー識別能力を備えており、適切であると考えられます。重みの計算を行うために使用します。
この実験では主に Scikit-Learn の CountVectorizer と TfidfTransformer の 2 つのクラスを使用して、単語頻度と TF-IDF 値を計算します。その中で、CountVectorizer の主な機能は、テキスト単語を単語頻度行列の形式に変換し、fit_transform() 関数を呼び出して各単語の出現数を計算し、TfidfTransformer を使用して TF-IDF 値を実現することです。ベクトル化変数の各単語の TF-IDF 値を行列配列の形式で格納します データの各行はテキスト コーパスを表し、各行の各列は特徴の 1 つに対応する重みを表します。 TF-IDF、各種データ解析アルゴリズムを利用して解析が可能です。

# 8.文本向量化代码片段
# 介绍:将词表中的文本进行向量化
# 特征提取及文本向量化
corpus = TextCollection(stopWords)
name,tf,idf,tf_idf=[],[],[],[]
for item in corpus:
    name.append(item)
    tf.append(corpus.tf(item,corpus))
    idf.append(item)
    tf_idf.append(corpus.tf_idf(item,corpus))
df_dic={
    
    "word":name,"TF value":tf,"IDF value":idf,"TF_IDF":tf_idf}
data = pd.DataFrame(df_dic)

3 TF-IDF と SVM に基づく英語テキスト分類

3.1 データの前処理

データ前処理部分は主にこの記事の 2 番目の部分を指します。これには、テキストの分割、語幹の抽出、ストップワードの削除、テキストのベクトル化などの操作が含まれますが、ここでは繰り返しません。最終的なテキスト ベクトルとそれに対応するラベルを取得する必要があることに注意してください。この部分のメイン コードは次のとおりです。

# 9.数据预处理代码片段
# 介绍:文本数据及标签预处理
def category2label(data):
	# 文本标签转化为数值标签,方便后续分类计算
    status_dict = data['category'].unique().tolist()
    return data['category'].apply(lambda x: status_dict.index(x))


def textProcessing(data):
    # 文本数据转化为TD-IDF向量
    input_txt=data['text']
    words=get_words(input_txt)
    stemWords=get_stemWords(words)
    stopWords=get_stopWords(stemWords)
    data['contents']=stopWords

    contents=[]
    for item in data['contents']:
        contents.append(' '.join(item))

    vectorizer = CountVectorizer()
    transformer = TfidfTransformer()
    tfidf = transformer.fit_transform(vectorizer.fit_transform(contents))
    word = vectorizer.get_feature_names()
    print("单词数量:", len(word))
    X = coo_matrix(tfidf, dtype=np.float32).toarray()
    return X

3.2 データ分割とモデル構築の評価

sklearn の model_selection ライブラリを使用して、前処理されたデータを 7:3 の比率に従ってトレーニング セットとテスト セットに分割し、トレーニング データをモデルのトレーニングに使用し、トレーニング後のモデルの評価にテスト データを使用します。
モデルのトレーニングのために sklearn で SVC 多分類モデルを呼び出し、混同行列を使用してモデルの精度を計算し、モデルを大まかに評価します。この部分のメイン コードは次のとおりです。

# 10.数据划分及模型构建评估
# 介绍:利用划分后的数据进行模型训练及评估
def train_test(X,Y):

    from sklearn.model_selection import train_test_split
    X_train, X_test, y_train, y_test = train_test_split(X,Y,test_size=0.3,random_state=1)
    clf = SVC(probability=True).fit(X_train,y_train)
    y_pred = clf.predict(X_test)
    y_pred_np = np.array(y_pred)
    correct_score = (y_pred_np == y_test).sum()
    print("模型的准确率为:{}".format(100 * correct_score / y_test.shape[0]))
    my_confusion_matrix(y_test,y_pred)

3.3 混同行列を使用した実験結果の分析

図 4 に示すように、混同行列を熱行列に変換します。(1) モデルの全体的な予測効果は良好で、さまざまな種類の予測誤差は小さいことが
わかります。(2) スポーツ、エンターテイメント、ビジネスの誤差はそれぞれ 1、1、2 であり、誤差 5 のテクノロジーや政治よりも予測精度が高い。このうち、サンプルベースが大きいスポーツは、最高の精度。(3) ビジネスクラスを除く他の 4 つのカテゴリの FN 数は 2 であり、サンプルベースが大きいスポーツクラスの再現率が最も高くなっています。



ここに画像の説明を挿入

# 11.绘制混淆矩阵代码片段
# 介绍:利用混淆矩阵绘制热力图
def plot_confusion_matrix(cm, classes, normalize=False, title='confusion matrix', cmap=plt.cm.Blues):
    plt.figure()
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=90)
    plt.yticks(tick_marks, classes)

    plt.axis("equal")

    ax = plt.gca()
    left, right = plt.xlim()
    ax.spines['left'].set_position(('data', left))
    ax.spines['right'].set_position(('data', right))
    for edge_i in ['top', 'bottom', 'right', 'left']:
        ax.spines[edge_i].set_edgecolor("white")

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        num = '{:.2f}'.format(cm[i, j]) if normalize else int(cm[i, j])
        plt.text(j, i, num,
                 verticalalignment='center',
                 horizontalalignment="center",
                 color="white" if num > thresh else "black")


    plt.xlabel('True')
    plt.ylabel('Predict')
    plt.tight_layout()
    plt.savefig('confusion_matrix.png', transparent=True, dpi=800)

    plt.show()

付録: 実験的なソースコードとデータ

WeChat 公開アカウントをフォローしてください: Alchemy Little Genius nlp1
に返信して、実験のソース コードとデータを入手してください

おすすめ

転載: blog.csdn.net/weixin_43427721/article/details/125750737
おすすめ