未捕获(在承诺中)TypeError:无法读取 null 的属性“length”
2020-11-19
1725
我当时正在学习 TensorFlow.js - 使用迁移学习进行音频识别 教程。当我按下“train”按钮调用 train() 函数时,出现了如上错误。是我问题还是教程中有错误?
(我确实一步一步按照指南操作...并在最新版本的 chrome 中使用本地主机进行了测试)
第一个代码片段来自 index.js,第二个代码片段来自 index.html。
let recognizer;
function predictWord() {
// Array of words that the recognizer is trained to recognize.
const words = recognizer.wordLabels();
recognizer.listen(({scores}) => {
// Turn scores into a list of (score,word) pairs.
scores = Array.from(scores).map((s, i) => ({score: s, word: words[i]}));
// Find the most probable word.
scores.sort((s1, s2) => s2.score - s1.score);
document.querySelector('#console').textContent = scores[0].word;
}, {probabilityThreshold: 0.75});
}
async function app() {
recognizer = speechCommands.create('BROWSER_FFT');
await recognizer.ensureModelLoaded();
console.log("The pre-trained model is loaded.");
//predictWord();
buildModel();
console.log("The model is built.");
}
app();
// One frame is ~23ms of audio.
const NUM_FRAMES = 3;
let examples = [];
function collect(label) {
if (recognizer.isListening()) {
return recognizer.stopListening();
}
if (label == null) {
return;
}
recognizer.listen(async ({spectrogram: {frameSize, data}}) => {
let vals = normalize(data.subarray(-frameSize * NUM_FRAMES));
examples.push({vals, label});
document.querySelector('#console').textContent =
`${examples.length} examples collected`;
}, {
overlapFactor: 0.999,
includeSpectrogram: true,
invokeCallbackOnNoiseAndUnknown: true
});
}
function normalize(x) {
const mean = -100;
const std = 10;
return x.map(x => (x - mean) / std);
}
const INPUT_SHAPE = [NUM_FRAMES, 232, 1];
let model;
async function train() {
toggleButtons(false);
const ys = tf.oneHot(examples.map(e => e.label), 3);
console.log("line one in train() is executed successfully.");
const xsShape = [examples.length, ...INPUT_SHAPE];
console.log("line two in train() is executed successfully.");
const xs = tf.tensor(flatten(examples.map(e => e.vals)), xsShape);
console.log("line three in train() is executed sucessfully.");
console.log(examples);
await model.fit(xs, ys, {
batchSize: 16,
epochs: 10,
callbacks: {
onEpochEnd: (epoch, logs) => {
document.querySelector('#console').textContent =
`Accuracy: ${(logs.acc * 100).toFixed(1)}% Epoch: ${epoch + 1}`;
}
}
});
console.log("The training is done !");
tf.dispose([xs, ys]);
toggleButtons(true);
}
function buildModel() {
model = tf.sequential();
model.add(tf.layers.depthwiseConv2d({
depthMultiplier: 8,
kernelSize: [NUM_FRAMES, 3],
activation: 'relu',
inputShape: INPUT_SHAPE
}));
model.add(tf.layers.maxPooling2d({poolSize: [1, 2], strides: [2, 2]}));
model.add(tf.layers.flatten());
model.add(tf.layers.dense({units: 3, activation: 'softmax'}));
const optimizer = tf.train.adam(0.01);
model.compile({
optimizer,
loss: 'categoricalCrossentropy',
metrics: ['accuracy']
});
}
function toggleButtons(enable) {
document.querySelectorAll('button').forEach(b => b.disabled = !enable);
}
function flatten(tensors) {
const size = tensors[0].length;
const result = new Float32Array(tensors.length * size);
tensors.forEach((arr, i) => result.set(arr, i * size));
return result;
}
//Call buildModel() when the app loads:
async function moveSlider(labelTensor) {
const label = (await labelTensor.data())[0];
document.getElementById('console').textContent = label;
if (label == 2) {
return;
}
let delta = 0.1;
const prevValue = +document.getElementById('output').value;
document.getElementById('output').value =
prevValue + (label === 0 ? -delta : delta);
}
function listen() {
if (recognizer.isListening()) {
recognizer.stopListening();
toggleButtons(true);
document.getElementById('listen').textContent = 'Listen';
return;
}
toggleButtons(false);
document.getElementById('listen').textContent = 'Stop';
document.getElementById('listen').disabled = false;
recognizer.listen(async ({spectrogram: {frameSize, data}}) => {
const vals = normalize(data.subarray(-frameSize * NUM_FRAMES));
const input = tf.tensor(vals, [1, ...INPUT_SHAPE]);
const probs = model.predict(input);
const predLabel = probs.argMax(1);
await moveSlider(predLabel);
tf.dispose([input, probs, predLabel]);
}, {
overlapFactor: 0.999,
includeSpectrogram: true,
invokeCallbackOnNoiseAndUnknown: true
});
}
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/speech-commands"> </script>
</head>
<body>
<button id="left" onmousedown="collect(0)" onmouseup="collect(null)">a</button>
<button id="right" onmousedown="collect(1)" onmouseup="collect(null)">o</button>
<button id="noise" onmousedown="collect(2)" onmouseup="collect(null)">Noise</button>
<br/><br/>
<button id="train" onclick="train()">Train</button>
<br/><br/>
<button id="listen" onclick="listen()">Listen</button>
<input type="range" id="output" min="0" max="10" step="0.1">
<div id="console"></div>
<script src="index.js"></script>
</body>
</html>
2个回答
该教程似乎是在 TensorFlow.js 2.0 发布之前编写的,但由于 jsDelivr 链接中未指定版本,因此它正在加载最新的 2.x 版本。
如果您指定 1.x 版本,它似乎可以工作,例如,您可以将:
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
替换为:
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"></script>
bruz
2020-11-20
控制台上打印的错误应该会指出您运行了哪些代码行,但如果没有,则没有太多信息可供参考。
首先猜测,您似乎需要先运行
buildModel()
来初始化
model
变量。目前它被初始化为
undefined
。
Andy K
2020-11-20