python與自然語言處理(六):中文文字轉影象
阿新 • • 發佈:2019-01-07
最近使用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,執行成功。