【问题标题】:How to apply tf.layers.add on different models' weights?如何将 tf.layers.add 应用于不同模型的权重?
【发布时间】:2020-03-16 18:44:06
【问题描述】:

我正在尝试对两个不同模型的权重进行元素相加

我开发了以下算法:

async function getWeights(url){
  return new Promise(async function(resolve, reject){
  const model  =  await tf.loadLayersModel(url);
  resolve(model.layers[0].getWeights);
});
}

async function aggregate(){
  return new Promise(function (resolve, reject){
    weights.push(getWeights('file://./mymodel/modelReceived.json'));
    weights.push(getWeights('file://./mymodel/model.json'));
    let averageLayer = tf.layers.average();
    console.log(weights.length);
    const average = averageLayer.apply([weights[0], weights[1]]);
    model.layers[0].setWeights[average];
    resolve(model);
  });

}

async function returnValue(){
  var model = await aggregate();
  console.log(model);
}

returnValue();

但是,我收到此错误:

(node:20468) UnhandledPromiseRejectionWarning: Error: A merge layer should be called on an Array of at least 2 inputs. Got 1 input(s).

我使用以下代码创建了模型:

const modelOne = tf.sequential();
modelOne.add(tf.layers.dense({units: 100, activation: 'relu', inputShape: [50]}));
modelOne.compile({optimizer: 'sgd', loss: 'meanSquaredError', metrics: ['accuracy']});

谁能向我解释这个错误?有没有其他方法可以进行添加?

【问题讨论】:

    标签: node.js tensorflow machine-learning tensorflow.js


    【解决方案1】:

    getWeights() 函数返回一个 Promise,因此当您调用 weights.push(getWeights('...')) 时,您传入的是 Promise 而不是张量。它可以像这样更新:

    weights.push(await getWeights('...'))
    

    getWeights() 中的 Promise 解析为一个函数(即model.layers[0].getWeights),而不是解析为权重:

    resolve(model.layers[0].getWeights())
    

    您不需要同时执行 Promise 和 async/await。您可以像这样简化getWeights() 函数:

    async function getWeights(url){
      const model  =  await tf.loadLayersModel(url);
      return model.layers[0].getWeights();
    }
    

    aggregate() 也可以使用类似的更新。

    您可以在此处找到有关 Promises 和 async/await 的更多详细信息:https://stackoverflow.com/a/14220323

    【讨论】:

      猜你喜欢
      • 2020-02-12
      • 1970-01-01
      • 2016-02-03
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多