AWS Sagemaker |如何训练文本数据 |对于机票分类

AWS Sagemaker | how to train text data | For ticket classification

我是 Sagemaker 的新手,不确定如何在 AWS sagemaker 中对文本输入进行分类,

假设我有一个 Dataframe 有两个字段,如 'Ticket' 和 'Category',都是文本输入,现在我想拆分它的测试和训练集并上传到 Sagemaker 训练模型中。

X_train, X_test, y_train, y_test = model_selection.train_test_split(fewRecords['Ticket'],fewRecords['Category'])

现在因为我要进行TD-IDF特征提取,然后转换成数值,所以进行这个操作

tfidf_vect = TfidfVectorizer(analyzer='word', token_pattern=r'\w{1,}', max_features=5000)
tfidf_vect.fit(fewRecords['Category'])
xtrain_tfidf =  tfidf_vect.transform(X_train)
xvalid_tfidf =  tfidf_vect.transform(X_test)

当我想在 Sagemaker 中上传模型以便执行下一步操作时

buf = io.BytesIO()
smac.write_numpy_to_dense_tensor(buf, xtrain_tfidf, y_train)
buf.seek(0)

我遇到了这个错误

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-36-8055e6cdbf34> in <module>()
      1 buf = io.BytesIO()
----> 2 smac.write_numpy_to_dense_tensor(buf, xtrain_tfidf, y_train)
      3 buf.seek(0)

~/anaconda3/envs/python3/lib/python3.6/site-packages/sagemaker/amazon/common.py in write_numpy_to_dense_tensor(file, array, labels)
     98             raise ValueError("Label shape {} not compatible with array shape {}".format(
     99                              labels.shape, array.shape))
--> 100         resolved_label_type = _resolve_type(labels.dtype)
    101     resolved_type = _resolve_type(array.dtype)
    102 

~/anaconda3/envs/python3/lib/python3.6/site-packages/sagemaker/amazon/common.py in _resolve_type(dtype)
    205     elif dtype == np.dtype('float32'):
    206         return 'Float32'
--> 207     raise ValueError('Unsupported dtype {} on array'.format(dtype))

ValueError: Unsupported dtype object on array

除了这个例外,我不清楚这是否是正确的方法,因为 TfidfVectorizer 将系列转换为 Matrix。

代码在我的本地机器上预测得很好,但不确定如何在 Sagemaker 上做同样的事情,那里提到的所有例子都太长了,不适合仍然接触到 SciKit Learn 的人

TfidfVectorizer的输出是一个scipy稀疏矩阵,而不是一个简单的numpy数组。

所以要么使用不同的函数,例如:

write_spmatrix_to_sparse_tensor

"""Writes a scipy sparse matrix to a sparse tensor"""

有关详细信息,请参阅 this issue

OR 首先将 TfidfVectorizer 的输出转换为密集的 numpy 数组,然后使用上面的代码

xtrain_tfidf =  tfidf_vect.transform(X_train).toarray()   
buf = io.BytesIO()
smac.write_numpy_to_dense_tensor(buf, xtrain_tfidf, y_train)
...
...