【问题标题】:How to add Images in a tensorflow.js model and train the model for given images labels如何在 tensorflow.js 模型中添加图像并针对给定的图像标签训练模型
【发布时间】:2019-07-08 10:40:29
【问题描述】:

我们正在使用 TensorFlow.js 来创建和训练模型。我们使用 tf.fromPixels() 函数将图像转换为张量。 我们想创建一个具有以下属性的自定义模型:

AddImage(HTML_Image_Element, 'Label'):添加带有自定义标签的 imageElement Train() / fit() :使用相关标签训练此自定义模型 Predict():预测带有相关标签的图像,它将返回带有每个图像附加标签的预测响应。 为了更好地理解,让我们举个例子: 假设我们有三个用于预测的图像,即:img1、img2、img3,分别具有三个标签“A”、“B”和“C”。 所以我们想用这些图像和各自的标签来创建和训练我们的模型,如下所示: 当用户想要预测“img1”时,它会显示预测“A”,类似地,“img2”用“B”预测,“img3”用“C”预测

请向我建议我们如何创建和训练这个模型。

This is webpage we used to create a model with images and its associate labels:
 
<apex:page id="PageId" showheader="false">
    <head>
        <title>Image Classifier with TensorFlowJS</title> 
        <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.11.2"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
    <div id="output_field"></div>
    <img id="imgshow" src="{!$Resource.cat}" crossorigin="anonymous" width="400" height="300" />
    
    <script>
    async function learnlinear(){
        
        
        //img data set
        const imageHTML = document.getElementById('imgshow');           
        console.log('imageHTML::'+imageHTML.src);
        
        //convert to tensor 
        const tensorImg = tf.fromPixels(imageHTML);
        tensorImg.data().then(async function (stuffTensImg){
            console.log('stuffTensImg::'+stuffTensImg.toString());
            
        });
        const model = tf.sequential();
            
        model.add(tf.layers.conv2d({
            kernelSize: 5,
            filters: 20,
            strides: 1,
            activation: 'relu',
            inputShape: [imageHTML.height, imageHTML.width, 3],
        }));
        
        model.add(tf.layers.maxPooling2d({
            poolSize: [2, 2],
            strides: [2, 2],
        }));
        
        model.add(tf.layers.flatten());
        
        model.add(tf.layers.dropout(0.2));
        
        // Two output values x and y
        model.add(tf.layers.dense({
            units: 2,
            activation: 'tanh',
        }));
        
        // Use ADAM optimizer with learning rate of 0.0005 and MSE loss
        model.compile({
            optimizer: tf.train.adam(0.0005),
            loss: 'meanSquaredError',
        });
        await model.fit(tensorImg, {epochs: 500});
        model.predict(tensorImg).print();
    }
    learnlinear();
    </script>
   
</apex:page>

运行代码 sn-p 时出现以下错误: tfjs@0.11.2:1 Uncaught (in promise) 错误:检查输入时出错:预期 conv2d_Conv2D1_input 有 4 个维度。但得到了一个形状为 300,400,3 的数组 在新 t (tfjs@0.11.2:1) 在标准化输入数据 (tfjs@0.11.2:1) 在 t.standardizeUserData (tfjs@0.11.2:1) 在 t。 (tfjs@0.11.2:1) 在 n (tfjs@0.11.2:1) 在 Object.next (tfjs@0.11.2:1) 在 tfjs@0.11.2:1 在新的承诺 () 在 __awaiter$15 (tfjs@0.11.2:1) 在 t.fit (tfjs@0.11.2:1)

This error coming while passing this sample error

【问题讨论】:

  • 您的错误信息非常直接。预期的张量是4,但它收到了300,400,3 的输入。只需将数据重塑为 4 维,如 np.expand_dims(some-np-array, axis = 3)

标签: tensorflow keras image-recognition tensor tensorflow.js


【解决方案1】:

你只需要重塑你的张量数据。

您传入模型的数据应该比 inputShape 大一维。实际上predict 采用形状为InputShape 的元素数组。元素的数量是批量大小。因此,您的图像数据应具有以下形状[batchsize, ...inputShape](使用省略号作为剩余参数表示形状的后半部分等于inputShape

由于您只使用一个元素进行训练(这在实际情况中不会发生),因此只需使用 1 的批大小。

model.predict(tensorImg.expandDims(0)).print()

【讨论】:

  • 现在我使用图像对象进行了成功的训练。由于我的任务是基于图像标签/图像识别,所以我们想为每个图像关联一个“标签”。因此,当我们尝试使用图像和标签训练模型时,模型不会将标签存储在他的“model.json”文件中。那么您能否指导我们也训练带有标签的图像。
  • @Adarsh4sfdc 不清楚你在问什么。训练时总是有标签。所以我不明白你所说的“有标签的训练”和“没有标签的训练”有什么区别。考虑在包含更多详细信息的新帖子中单独提出您的新问题。如果上面的答案对您有所帮助,请不要忘记投票并将其标记为已接受:)
  • @edkeveked 你能帮我吗? stackoverflow.com/questions/67642621/…
  • @Greyfrog 我去看看
【解决方案2】:

TLDR:您只需使用np.expand_dims()np.reshape() 调整数据大小。

首先,让我们生成一些模拟当前张量输入的随机张量 -

# Some random numpy array
In [20]: x = np.random.random((2,2,4))

In [21]: x
Out[21]: 
array([[[0.8454901 , 0.75157647, 0.1511371 , 0.53809724],
        [0.50779498, 0.41321185, 0.45686143, 0.80532259]],

       [[0.93412402, 0.02820063, 0.5452628 , 0.8462806 ],
        [0.4315332 , 0.9528761 , 0.69604215, 0.538589  ]]])

# Currently your tensor is a similar 3D shape like x
In [22]: x.shape
Out[22]: (2, 2, 4)

现在您可以像这样将其转换为 4D 张量 -

[23]: y = np.expand_dims(x, axis = 3)

In [24]: y
Out[24]: 
array([[[[0.8454901 ],
         [0.75157647],
         [0.1511371 ],
         [0.53809724]],

        [[0.50779498],
         [0.41321185],
         [0.45686143],
         [0.80532259]]],


       [[[0.93412402],
         [0.02820063],
         [0.5452628 ],
         [0.8462806 ]],

        [[0.4315332 ],
         [0.9528761 ],
         [0.69604215],
         [0.538589  ]]]])

In [25]: y.shape
Out[25]: (2, 2, 4, 1)

您可以找到np.expand_dims 文档here


编辑:这是一个单行

np.reshape(np.ravel(x), (x.shape[0], x.shape[1], x.shape[2], 1)).shape 

您可以查看np.reshape 文档here

【讨论】:

  • 使用 resize_image = tf.reshape(tensorImg, [-1, 300, 300, 4]) 调整大小但仍然给出相同的错误错误:检查输入时出错:预期 conv2d_Conv2D1_input 具有 4 维(s)。但得到了形状为 300,400,3 的数组
  • 也许你在传递输入时没有使用resize_image。另外,不应该是resize_image = tf.reshape(tensorImg, [-1, 300, 400, 3])吗?
  • 现在我使用图像对象进行了成功的训练。由于我的任务是基于图像标签/图像识别,所以我们想为每个图像关联一个“标签”。因此,当我们尝试使用图像和标签训练模型时,模型不会将标签存储在他的“model.json”文件中。那么您能否指导我们也使用标签训练图像。
猜你喜欢
  • 2020-03-16
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多