是否可以在tensorflow会话中使用sklearn.neighbors.KNeighbors分类器,即使用Tenso



我正试图在Tensorflow会话中使用KNN分类器。

但我得到了以下错误:

NotImplementedError: Cannot convert a symbolic Tensor (Const:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported

在会话之外,代码运行良好:

import tensorflow as tf
from sklearn.neighbors import KNeighborsClassifier
features= tf.constant([[1., 1.], [2., 2.],[2., 2.],[2., 2.],[2., 2.],[2., 2.]])
label= tf.constant([[1], [2], [2], [2], [2], [2]])
model = KNeighborsClassifier(n_neighbors=3)
# Train the model using the training sets
model.fit(features,label)
teste = tf.constant([[1., 1.], [2., 2.]])
#Predict Output
predicted= model.predict(teste) # 0:Overcast, 2:Mild
print(predicted)

但我需要它在会话中,这里有一个错误示例代码:

import tensorflow as tf
from sklearn.neighbors import KNeighborsClassifier
@tf.function
def add():
model = KNeighborsClassifier(n_neighbors=3)

features= tf.constant([[1., 1.], [2., 2.],[2., 2.],[2., 2.],[2., 2.],[2., 2.]])
label= tf.constant([[1], [2], [2], [2], [2], [2]])
# Train the model using the training sets
model.fit(features,label)

return model
add()

版本:

tf.version.VERSION
'2.6.0'
sklearn.__version__
1.0.1

此代码可以帮助您解决问题。

import tensorflow as tf
from sklearn.neighbors import KNeighborsClassifier
tf.config.run_functions_eagerly(True)
@tf.function
def add():

model = KNeighborsClassifier(n_neighbors=3)

features= tf.constant([[1., 1.], [2., 2.],[2., 2.],[2., 2.],[2., 2.],[2., 2.]])
label= tf.constant([[1], [2], [2], [2], [2], [2]])
features = features.numpy()
label = label.numpy()
# Train the model using the training sets
model.fit(features,label)

return model
add()

我已经在Google Colab中运行了代码。将NumPy降级为1.19.5

注:

  • .numpy()将张量更改为numpy数组
  • Tensorflow 2有一个配置选项;急切地";这将使得能够通过CCD_ 4方法获得张量值。3rd line of the code[如果没有这一行,.numpy()将无法工作,因为@tf.function装饰器出于性能原因禁止执行类似tensor.numpy()的函数

相关内容

  • 没有找到相关文章

最新更新