在本章中,我们将使用本书第1部分中描述的数据.该数据的文字描述了自由职业者的概况,以及他们以美元收费的小时费率.以下部分的想法是为了适应一个给出自由职业者技能的模型,我们能够预测其每小时工资.
以下代码显示如何转换原始文本在这种情况下,用户的技能在一个单词矩阵包中.为此,我们使用名为tm的R库.这意味着对于语料库中的每个单词,我们使用每个变量的出现次数创建变量.
library(tm)library(data.table) source('text_analytics/text_analytics_functions.R') data = fread('text_analytics/data/profiles.txt') rate = as.numeric(data$rate) keep = !is.na(rate) rate = rate[keep] ### Make bag of words of title and body X_all = bag_words(data$user_skills[keep]) X_all = removeSparseTerms(X_all, 0.999) X_all # <> # Non-/sparse entries: 4057/549101 # Sparsity : 99% # Maximal term length: 80 # Weighting : term frequency - inverse document frequency (normalized) (tf-idf) ### Make a sparse matrix with all the data X_all <- as_sparseMatrix(X_all)
现在我们将文本表示为稀疏矩阵,我们可以拟合一个给出稀疏解的模型.这种情况的一个很好的替代方案是使用LASSO(最小绝对收缩和选择算子).这是一个回归模型,能够选择最相关的特征来预测目标.
train_inx = 1:200X_train = X_all[train_inx, ] y_train = rate[train_inx] X_test = X_all[-train_inx, ] y_test = rate[-train_inx] # Train a regression model library(glmnet) fit <- cv.glmnet(x = X_train, y = y_train, family = 'gaussian', alpha = 1, nfolds = 3, type.measure = 'mae') plot(fit) # Make predictions predictions = predict(fit, newx = X_test) predictions = as.vector(predictions[,1]) head(predictions) # 36.23598 36.43046 51.69786 26.06811 35.13185 37.66367 # We can compute the mean absolute error for the test data mean(abs(y_test - predictions)) # 15.02175
现在我们有一个模型可以预测一组技能自由职业者的小时工资.如果收集到更多数据,模型的性能将会提高,但实现此管道的代码将是相同的.