最近使用word2vec對文本進行向量化表示,然後模仿基于CNN的圖像分類實作文本分類。既然是模仿圖像,那就應該可以将文本用圖像可視化一下,看看量化後的文本是什麼樣子。
python處理圖像的基本子產品是Image庫,由于實驗中使用的是python3,需要安裝的圖像處理庫為Pillow (pip install Pillow / conda install Pillow)。詞向量模型使用的是gensim的word2vec工具,具體操作見這裡。
#-*-coding=utf-8-*-
from gensim import models
import numpy as np
from PIL import Image
text_width = 10
#load word2vec model
word_vector_size =25
base_model_path = './word_vector_'
modelpath = base_model_path+str(word_vector_size)
emotion_model = models.Word2Vec.load(modelpath) #加載詞向量模型
#得到字元向量
def getCharVec(char):
vector = np.zeros(word_vector_size)
if char in emotion_model:
vector[0:word_vector_size] = emotion_model[char]
else: #若詞彙不在詞向量模型中則按正态分布随機初始化
loc,scale = 0,0.5 #均值和标準差
vector[0:word_vector_size] = np.random.normal(loc,scale,word_vector_size)
return vector
#得到句子向量
def getSentenceVec(sentence):
vectors = np.zeros((text_width,word_vector_size))
sentence_array = sentence.split(' ')
for i in range(len(sentence_array)-1):
vector = getCharVec(sentence_array[i])
vectors[i] = vector
return vectors
def drawPic(vectors,savepath):
img = Image.fromarray(vectors)
img.save(savepath)
if __name__ == '__main__':
text1 = '預告片 裡 的 服 化 道 時而 素雅 時而 華貴 曉彤 演繹 的 劉楚玉 演技 提高 很 值得 期待'
text2 = '這部 劇 的 攝影師 和 剪輯師 是不是 已經 做好 了 随時 領 便當 的 準備 了'
if len(text1.split())>text_width:
text_width = len(text1.split())
if len(text2.split())>text_width:
text_width = len(text2.split())
vectors = getSentenceVec(text1)
print(vectors)
drawPic(vectors,'./text1.tiff')
vectors = getSentenceVec(text2)
print(vectors)
drawPic(vectors,'./text2.tiff')
運作後得到的圖像分别為:
text1.tiff
text2.tiff
備注:之是以存儲圖像為tiff格式,是因為數組資料為float類型,直接存為png格式會報錯 can't save mode 'F' image,故參考相關回答将格式改為tiff,運作成功。