簡體   English   中英

我如何使用Glove詞嵌入構建模型並使用R中的text2vec對測試數據進行預測

[英]How do i build a model using Glove word embeddings and predict on Test data using text2vec in R

我正在使用GloVe詞嵌入在文本數據上建立分類模型,將其分為兩類(即將每個注釋分為兩類)。 我有兩列,一列包含文本數據(注釋),另一列是二進制Target變量(注釋是否可操作)。 使用text2vec文檔中的以下代碼,我能夠為文本數據生成Glove詞嵌入。

glove_model <- GlobalVectors$new(word_vectors_size = 50,vocabulary = 
glove_pruned_vocab,x_max = 20L)
#fit model and get word vectors
word_vectors_main <- glove_model$fit_transform(glove_tcm,n_iter = 20,convergence_tol=-1)
word_vectors_context <- glove_model$components
word_vectors <- word_vectors_main+t(word_vectors_context)

如何建立模型並針對測試數據生成預測?

text2vec具有標准的predict方法(無論如何仍然像大多數R庫一樣),您可以直接使用它:請參閱文檔

長話短說,只需使用

predictions <- predict(fitted_model, data)

得到它了。

glove_model <- GlobalVectors$new(word_vectors_size = 50,vocabulary = 
glove_pruned_vocab,x_max = 20L)
#fit model and get word vectors
word_vectors_main <- glove_model$fit_transform(glove_tcm,n_iter =20,convergence_tol=-1)
word_vectors_context <- glove_model$components
word_vectors <- word_vectors_main+t(word_vectors_context)

創建單詞嵌入后,建立一個索引,將單詞(字符串)映射到其向量表示形式(數字)

embeddings_index <- new.env(parent = emptyenv())
for (line in lines) {
values <- strsplit(line, ' ', fixed = TRUE)[[1]]    
word <- values[[1]]
coefs <- as.numeric(values[-1])
embeddings_index[[word]] <- coefs
}

接下來,構建一個形狀為(max_words,embedding_dim)的嵌入矩陣,可以將其加載到嵌入層中。

embedding_dim <- 50 (number of dimensions you wish to represent each word).
embedding_matrix <- array(0,c(max_words,embedding_dim))
for(word in names(word_index)){
  index <- word_index[[word]]
  if(index < max_words){
    embedding_vector <- embeddings_index[[word]]
    if(!is.null(embedding_vector)){
      embedding_matrix[index+1,] <- embedding_vector  #words not found in 
the embedding index will all be zeros
    }
  }
}
We can then load this embedding matrix into the embedding layer, build a 
model and then generate predictions.

model_pretrained <- keras_model_sequential() %>% layer_embedding(input_dim = max_words,output_dim = embedding_dim) %>%
                layer_flatten()%>%layer_dense(units=32,activation = "relu")%>%layer_dense(units = 1,activation = "sigmoid")
summary(model_pretrained)

#Loading the glove embeddings in the model
get_layer(model_pretrained,index = 1) %>% 
set_weights(list(embedding_matrix)) %>% freeze_weights()

model_pretrained %>% compile(optimizer = "rmsprop",loss="binary_crossentropy",metrics=c("accuracy"))

history <-model_pretrained%>%fit(x_train,y_train,validation_data = list(x_val,y_val),
                                epochs = num_epochs,batch_size = 32) 

然后使用標准預測功能生成預測。

檢查以下鏈接。 使用詞嵌入在Keras中建立模型

預訓練詞嵌入

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM