尝试实施tesorflow DNN进行文本分类。
tf-idf稀疏IV:
X_train_sam:
<31819x3122 sparse matrix of type '<class 'numpy.float64'>'with 610128 stored elements in Compressed Sparse Row format>
标签为DV:
y_train_sam.values:array(['mexican', 'mexican', 'italian', ..., 'chinese', 'italian','italian'], dtype=object)
使用以下部分将稀疏转换为张量:
def convert_sparse_matrix_to_sparse_tensor(X):
coo = X.tocoo()
indices = np.mat([coo.row, coo.col]).transpose()
return tf.SparseTensorValue(indices, coo.data, coo.shape)
X_train_sam = convert_sparse_matrix_to_sparse_tensor(X_train_sam)
准备建模数据
def train_input_fn(features, labels, batch_size):
dataset = tf.data.Dataset.from_tensors((features, labels))
dataset = dataset.shuffle(1000).repeat().batch(batch_size)
return dataset.make_one_shot_iterator().get_next()
inp = train_input_fn(X_train_sam,y_train_sam.values,batch_size=1000)
应用DNN分类器
classifier = tf.estimator.DNNClassifier(
feature_columns=[float]*X_train_sam.dense_shape[1],
hidden_units=[10, 10],
n_classes=len(y_train_sam.unique()))
classifier.train(input_fn=lambda:inp)
获取以下错误:
ValueError: features should be a dictionary of `Tensor`s. Given type: <class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>
请给出一些指示,我是ML和tensorflow的新手。
答案 0 :(得分:0)
如果在此行的代码中
classifier.train(input_fn=lambda:inp)
lambda:inp
应该是字典还是你的意思是匿名函数?
来自
https://www.tensorflow.org/api_docs/python/tf/estimator/DNNClassifier
input_fn:返回元组的输入函数:features - Tensor或 Tensor的字符串功能名称字典。标签 - 张量或 带有标签的Tensor字典。
所以你需要一个返回元组的函数,而不是单个值......