更新时间:2023-12-02 19:45:40
很可能新的权重与第一个模型的权重相同.
Most likely that the new weights are identical to that of the first model.
示例:更改模型权重的简单示例
(async() => {
const model = tf.sequential({
layers: [tf.layers.dense({units: 1, inputShape: [10]})]
});
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
for (let i = 1; i < 5 ; ++i) {
const h = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), {
batchSize: 4,
epochs: 3
});
console.log("Loss after Epoch " + i + " : " + h.history.loss[0]);
}
const p = await model.predict(tf.zeros([1, 10]))
p.print()
const layers = model.layers
layers[0].setWeights([tf.zeros([10, 1]), tf.zeros([1])])
const q = await model.predict(tf.zeros([1, 10]))
q.print()
})()
<html>
<head>
<!-- Load TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"> </script>
</head>
<body>
</body>
</html>
代码问题
创建的 newWeights
未分配给 newWeights
.map
不是就地运算符.map
返回的数组应该分配回 newWeights
.
The newWeights
created is not assigned to newWeights
. map
is not an in-place operator. The array returned by map
should be assigned back to newWeights
.
newWeights[i][0] = newWeights[i][0].map(tensor => tensor.map(x => {
if (random(1) < 0.5) {
return x + offset();
}
return x;
})