嘿,我在本教程中尝试的这段代码有问题。我一直在尝试用数字预测创建一个简单的机器学习代码。
<div v-for="(item, index) in xValues" v-bind:key="index">
<div>
<div class="col-sm-1">
<input class="field field-x" v-model="xValues[index]" type="number">
<input class="field field-y" v-model="yValues[index]" type="number">
</div>
</div>
</div>
<button class="button-add-example button--green" v-on:click="addItem">Add Value</button>
<button class="button-train button--green" v-on:click="train">Train</button>
</div>
<div class="predict-controls">
<h2 class="section col-sm-1">Predicting</h2>
<input class="field element" v-model="valueToPredict" type="number" placeholder="Enter a number"><br>
<div class="element" {{predictedValue}}></div>
<button class="element button--green" v-on:click="predict" :disabled="!trained">Predict</button>
</div>
</div>
</template>
<script>
import * as tf from '@tensorflow/tfjs';
export default {
data() {
return {
trained: false,
xValues: [1,2,3,4,5,6],
yValues: [1,3,5,7,9,11],
predictedValue:'Click on train',
valueToPredict: ''
}
},
methods: {
addItem() {
this.xValues.push(0);
this.yValues.push(0);
},
train() {
// Define a model for linear regression.
const model = this.model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
// Prepare the model for training: Specify the loss and the optimizer.
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
const xs = tf.tensor2d(this.xValues, [this.xValues.length, 1]);
const ys = tf.tensor2d(this.yValues, [this.yValues.length, 1]);
// Train the model using the data.
model.fit(xs, ys, {epochs: 50}).then(() => {
this.trained = true;
this.predictedValue = 'Ready for making predictions';
});
},
predict() {
// Use the model to do inference on a data point the model hasn't seen before:
this.predictedValue = this.model.predict(tf.tensor2d([this.valueToPredict], [1, 1])).get(0, 0);
}
}
}
</script>
我收到此错误消息,但在Visual Studio中一切似乎都很好
传递给'slice2d'的参数'x'必须是数字张量,但具有字符串张量 呈现页面时发生错误。检查开发人员工具控制台以获取详细信息
答案 0 :(得分:0)
检查此行:
this.predictedValue = this.model.predict(tf.tensor2d([this.valueToPredict], [1, 1])).get(0, 0);
Tensorflow期望2d张量内的值为数字。当您从HTML输入字段中读取值时,this.valueToPredict
将是一个字符串,因此会出现错误消息。
只需将您的原始值转换为数字,例如使用parseInt(this.valueToPredict)
将其转换为整数即可。
答案 1 :(得分:0)
我只需使用parseInt就能解决此错误。
let val = parseInt(document.getElementById('inputValue').value);
console.log(tf.tensor2d([val],[1,1]));
document.getElementById('output').innerText = model.predict(tf.tensor2d([val],[1,1]));
});
Output for Console Log:
dataId: {}
dtype: "float32"
id: 35515
isDisposed: (...)
isDisposedInternal: false
kept: false
rank: (...)
rankType: "2"
shape: (2) [1, 1]
size: 1
strides: [1]
__proto__: Object