基本的な特徴量抽出

Pythonで学ぶNLPの特徴量エンジニアリング

Rounak Banik

Data Scientist

文字数

"I don't know." # 13 characters
# 文字数を計算
text = "I don't know."
num_char = len(text)

# 文字数を出力
print(num_char)
13
# 'num_chars' 特徴量を作成
df['num_chars'] = df['review'].apply(len)
Pythonで学ぶNLPの特徴量エンジニアリング

単語数

# 文字列を単語に分割
text = "Mary had a little lamb."
words = text.split()

# 単語のリストを表示
print(words)
['Mary', 'had', 'a', 'little', 'lamb.']
# 単語数を表示
print(len(words))
5
Pythonで学ぶNLPの特徴量エンジニアリング

単語数

# 文字列中の単語数を返す関数
def word_count(string):
    # 文字列を単語に分割
    words = string.split()

    # 単語リストの長さを返す
    return len(words)
# dfにnum_words特徴量を作成
df['num_words'] = df['review'].apply(word_count)

Pythonで学ぶNLPの特徴量エンジニアリング

平均単語長

# 平均単語長を返す関数
def avg_word_length(x):

# 文字列を単語に分割 words = x.split()
# 各単語の長さを計算しリスト化 word_lengths = [len(word) for word in words]
# 平均単語長を計算 avg_word_length = sum(word_lengths)/len(words)
# 平均単語長を返す return(avg_word_length)
Pythonで学ぶNLPの特徴量エンジニアリング

平均単語長

# 新しい特徴量 avg_word_length を作成
df['avg_word_length'] = df['review'].apply(doc_density)
Pythonで学ぶNLPの特徴量エンジニアリング

特殊な特徴量

 

Datacampのツイート

Pythonで学ぶNLPの特徴量エンジニアリング

ハッシュタグとメンション

# ハッシュタグ数を返す関数
def hashtag_count(string):

# 文字列を単語に分割 words = string.split()
# ハッシュタグのリストを作成 hashtags = [word for word in words if word.startswith('#')]
# ハッシュタグ数を返す return len(hashtags)
hashtag_count("@janedoe This is my first tweet! #FirstTweet #Happy")
2
Pythonで学ぶNLPの特徴量エンジニアリング

その他の特徴量

  • 文の数
  • 段落の数
  • 先頭が大文字の単語
  • 全て大文字の単語
  • 数値の出現数
Pythonで学ぶNLPの特徴量エンジニアリング

Ayo berlatih!

Pythonで学ぶNLPの特徴量エンジニアリング

Preparing Video For Download...