Skip to main content
 首页 » 编程设计

python之将用户输入实现到神经网络中

2024年12月31日10zhenyulu

我有一些理论问题以及我的原始问题。

我是 Keras 的新手,有一些逻辑问题。第一个问题是关于火车、考试等。 我来自使用 Sci-kit learn,通常使用 test_train_split 库来执行此操作(我假设我可以在这里做同样的事情?)

我的下一个问题是特征和标签的转换。据我目前的理解,我们不能提供字符串 进入神经网络,因此必须进行某种归一化。

我学习了分类变量的标记化或虚拟变量,应该对数值进行归一化。我的问题是:特征向量中有 5 列(2 列和 3 列)。我可以为 2 分类创建虚拟变量,然后标准化整个特征向量吗?

在此之后,我的问题将出现在下面关于 input_shape(x, y) 的代码中。下面的示例代码来自图像识别。假设我想使用我自己的数据集,我是否必须事先知道 input_shape 并以这种方式定义它?还是模型可以自行学习?

我的最后一个问题是:假设特征向量由变量 a、b、c 和 d 组成。如何让用户输入 a、b、c 和 d 的值并让模型给出输出?在示例中,模型从 CSV 加载到数据框中,然后我将该数据放入特征和标签的测试和训练中。在这种情况下,我是否需要将用户变量存储到数据框中以便模型预测输出?

我指的是图像代码,但我的用例不是图像而是整数。代码:

from keras.datasets import mnist 
from keras import models 
from keras import layers 
 
(train_images, train_labels), (test_images, test_labels) = mnist.load_data() 
 
model = model.Sequential() 
model.add(layers.Dense(16, activation = 'relu', input_shape = (10000,))) 
model.add(layers.Dense(16, activation = 'relu')) 
model.add(layers.Dense(1, activation = 'sigmoid')) 
 
model.compile(optimizer= 'rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) 
model.fit(train_images, train_labels, epochs=5, batch_size=64) 
 
test_loss, test_acc = model.evaluate(test_images, test_labels) 

任何帮助都会很棒,因为我对此很陌生!

请您参考如下方法:

I come from using Sci-kit learn and usually use the test_train_split library to do this (I am assuming I can do the same here?)

是的!应该没关系

From my understanding so far, we cannot feed strings into the neural network, so some sort of nomalization would have to be done.

正确。神经网络只是对数字进行的大量数学运算。也就是说,您可以将字符串表示为数字(有关更多信息,请使用 Google word2vec)

[T]here are 5 columns (2 categorical and 3 numerical) in a feature vector. Can I create dummy variables for the 2 categorical and then normalize the ENTIRE feature vector?

我假设您所说的分类是指类别?这些类永远不会作为特征进入网络。那么分类就毫无意义了。如果你只想做预测,你可以看看 model.predict .

The example code below is from image recognization. Say that I want to use my own data set, will I have to know the input_shape beforehand and define it that way? Or is that something that the model can learn itself?

神经网络是一串矩阵乘法。您需要提供一些 尺寸。它不需要 batch_size 的先验知识(不过你可以给它),但其他维度很重要:即输入层中的特征数量。代码中的 input_shape = (10000,) 只是 input_shape = (10000,None) 的简写,其中 None 将是您的位置可以放批量大小(数据点数)。在本例中,10000 是特征数。

How can I have the user enter their value for a, b, c, and d and have the model give an output?

请注意,关键是您事先不知道输出。

oneToFive=input("Enter 5 numbers separated by commas") 
oneToFive=oneToFive.split(",") 
oneToFive=[np.float32(c) for c in oneToFive] 
model.predict(x=np.array(oneToFive)) 

我建议您研究一下这背后的理论。只是盲目地跑来跑去可能会很烦人,因为你很难获得好的结果。而且,即使您取得了不错的成绩,它们通常也可能不如您想象的那么好。一个阅读的地方是 Ian Goodfellow's book on deep learning .