我正在嘗試在 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)
但我需要它在 Session 中,這是一個帶有錯誤示例的代碼:
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
uj5u.com熱心網友回復:
此代碼可以幫助您解決問題。
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 有一個配置選項來“急切”地運行函式,這將允許通過
.numpy()方法獲取張量值。3rd line of the code[沒有那行,由于裝飾器出于性能原因禁止執行功能,因此.numpy()將不起作用。@tf.functiontensor.numpy()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/468221.html
