【问题标题】:Feeding images to Theano throws ShapeMismatch error将图像馈送到 Theano 会引发 ShapeMismatch 错误
【发布时间】:2016-02-22 01:37:37
【问题描述】:

我正在尝试一个非常基本的 Theano Logistic 回归模型示例,在训练网络之后,我想测试一些图像以了解它们是如何分类的。训练和测试的代码可以在http://deeplearning.net/tutorial/code/logistic_sgd.py找到。事实上,我尝试修改的唯一部分是 predict() 函数,如下所示:

def predict():
    """
    An example of how to load a trained model and use it
    to predict labels.
    """

    # load the saved model
    classifier = cPickle.load(open('best_model.pkl'))

    # compile a predictor function
    predict_model = theano.function(
        inputs=[classifier.input],
        outputs=classifier.y_pred)

    # We can test it on some examples from test test
    #dataset='mnist.pkl.gz'
    #datasets = load_data(dataset)
    #test_set_x, test_set_y = datasets[2]
    #test_set_x = test_set_x.get_value()

    img = Image.open('index.png','r')
    shared_x = theano.shared(numpy.asarray(img,dtype=theano.config.floatX))


    predicted_values = predict_model(shared_x.get_value())
    print ("Predicted values for the first 10 examples in test set:")
    print predicted_values

我遵循了在这里找到的一些提示http://blog.eduardovalle.com/2015/08/25/input-images-theano/,但显然我遇到了问题,因为我得到的是:

ValueError:形状不匹配:x 有 28 列(和 28 行)但 y 有 784 行(和 10 列)应用导致错误的节点:Dot22(x, W) 输入类型:[TensorType(float64, matrix), TensorType(float64, matrix)] 输入形状:[(28, 28), (784, 10)] 输入步幅:[(224, 8), (80, 8)] 输入值:['未显示', '未显示']

那么,将图像(在我的情况下为 28x28)提供给 Theano 进行预测的正确方法是什么?

【问题讨论】:

    标签: image theano predict


    【解决方案1】:

    模型需要 批次 扁平化图像作为输入。

    输入需要是一个矩阵,每个图像有一行。有 784 列是 28x28 像素图像的展平(或重塑)版本(请注意,28*28=784)。

    而不是

    img = Image.open('index.png','r')
    shared_x = theano.shared(numpy.asarray(img,dtype=theano.config.floatX))
    predicted_values = predict_model(shared_x.get_value())
    

    使用

    img = Image.open('index.png','r')
    img = numpy.asarray(img, dtype=theano.config.floatX)
    img = img.flatten()
    x_batch = numpy.expand_dims(img, 0)
    predicted_values = predict_model(x_batch)
    

    没有必要使用共享变量,因为您只是将它包含的 numpy 数组传递给 Theano 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2020-12-25
      • 1970-01-01
      相关资源
      最近更新 更多