python - TensorFlow 机器学习 - 对用户输入进行预测

标签 python tensorflow machine-learning keras data-science

我正在研究涉及两个类的分类问题。我需要在数据集上训练模型,并在将一个值作为每个属性的输入后预测正确的类别。这是数据集的片段。这些类是 01enter image description here

这是我用来训练和测试模型的代码:

X = df.drop(["classification"], axis=1)
y = df["classification"]

x_scaler = MinMaxScaler()
x_scaler.fit(X)
column_names = X.columns
X[column_names] = x_scaler.transform(X)

X_train,  X_test, y_train, y_test = train_test_split(
        X, y, test_size= 0.2, shuffle=True)

我尝试从用户那里获取输入,如下所示:

userInput=input("Enter 14 attributes separated by commas")
#userInput=userInput.split(",")
#userInput=[np.float32(c) for c in userInput]

并预测:

pred=model.predict(userInput)

但我收到错误:

AttributeError: 'str' object has no attribute 'ndim'

我还尝试手动输入属性:

prediction=np.array([40,8,1,2,0,2,6,10,34,40,16,23,67,25])
print(prediction.shape) # Shape is (14,)
print(prediction[0].shape) # Shape is ()
print(prediction[0:1].shape) #Shape is (1,)
print(X_test[0:1].shape) #Shape is (1, 14)

并通过以下方式进行预测:

  (1) pred = model.predict(x=np.array(prediction[0:1].shape))
  (2) pred = model.predict(x=np.array(prediction[0].shape))
  (3) pred = model.predict(prediction)
  (4) pred = model.predict([40,8,1,2,0,2,6,10,34,40,16,23,67,25])
  (5) pred = model.predict(prediction.shape)
  (6) pred = model.predict([40],[8],[1],[2],[0],[2],[6],[10],[34],[40],[16],[23],[67],[25])

但是在 14 的情况下我收到此错误

ValueError: Error when checking input: expected dense_1_input to have shape (14,) but got array with shape (1,)

这分别是 56 的情况

AttributeError: 'tuple' object has no attribute 'ndim'
TypeError: predict() takes from 2 to 9 positional arguments but 15 were given

另外,我尝试运行这个'并且它有效:

pred=model.predict(X_test)

但预测却并非如此。我尝试过:

(1) print(np.argmax(pred(userInput)))
(2) print(np.argmax(pred(prediction)))

使用 .shape 也不起作用,并给出错误:

TypeError: 'list' object is not callable

训练数据的形状:(320, 14) 测试数据形状:(80, 14)

有什么方法可以获取用户的输入并将其用于预测吗?

最佳答案

当你预测时 pred=model.predict(userInput) 您收到错误 AttributeError: 'str' object has no attribute 'ndim' 因为您将字符串传递给函数。您必须拆分从终端读取的字符串并将字符串转换为整数。

inputString = "1, 2, 3,4"
sample = inputString.replace(" ", "").split(",")
sample = [int(x) for x in sample]
print(sample)
[1, 2, 3, 4]

对于预测,请尝试将样本传递给预测方法,如下所示:

pred = model.predict([[40,8,1,2,0,2,6,10,34,40,16,23,67,25]])

关于python - TensorFlow 机器学习 - 对用户输入进行预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59827963/

相关文章:

python - tensorflow einsum vs. matmul vs. tensordot

python - 从 sklearn 的 MLPClassifier 中检索最终的隐藏激活层输出

python - 当输入是特定字符串时如何中断 while 循环?

python - 区分覆盖和重载

python - 有没有办法测试数据 X 和二进制输出 Y 之间的相关性?

python - 在 LinearSVC 的 scikit 中计算每个样本 x 的概率估计 P(y|x)

python - 如何使用协同过滤通过用户行为来预测用户?

python - 在条形图上添加条形高度值和缺失值

python - 为什么 conv2d 层需要 ndim=4 输入?

python - 恢复keras seq2seq模型