![](/img/trans.png)
[英]How to fix “model.predict is not a function” (tensorflow.js)?
[英]How to fix TensorFlow.js not responding?
我正在使用 TensorFlow.js 創建一個數字乘法站點,庫中的數據將被加載到 HTML 中。 但是,該站點不會加載 AI,並且似乎已被凍結。 如果我們剝離 HTML 元素,該庫將完美運行。
I have tried swapping the document.getElementByClassName function with the document.getElementById function and updated the HTML and CSS to make sure it still works. 我還嘗試重新加載頁面,並將其通過 chrome 調試器
JavaScript:
let model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}))
model.add(tf.layers.dense({units: 64, inputShape: [1]}))
model.add(tf.layers.dense({units: 1, inputShape: [64]}))
model.compile({loss: "meanSquaredError", optimizer: "sgd"})
let tInput = tf.tensor2d([1, 2, 3, 4, 5], [5, 1])
let tOutput = tf.tensor2d([2, 4, 6, 8, 10], [5, 1])
document.getElementById("status-light").style.backgroundColor = "lightyellow"
document.getElementById("status-text").innerHTML = "AI is training..."
model.fit(tInput, tOutput, {epochs: 500}).then(() => {
document.getElementById("ai-submit").onclick(() => {
document.getElementById("status-light").style.backgroundColor = "lightgreen"
document.getElementById("status-text").innerHTML = "AI is done training"
let aInput = document.getElementById(".ai-input").value
let aOutput = model.predict(tf.tensor2d([parseFloat(aInput)], [1, 1])).dataSync()[0])
document.getElementById("output-text").innerHTML = aOutput
})
})
HTML:
<div id="status">
<div id="status-light">
</div>
<label id="status-text">
AI is preparing to train...
</label>
</div>
<div id="ai">
<input id="ai-input" type="number" placeholder="Input Number Here">
<button id="ai-submit">
Submit Input
</button>
</div>
<div id="output">
<label>AI Output: <span id="output-text">calculating...</span></label>
</div>
CSS:
body {
height: 100vh;
width: 100vw;
background-color: lightblue;
color: white;
display: flex;
flex-direction: row;
justify-content: space-around;
}
#status-light {
height: 25px;
width: 25px;
border-radius: 50%;
background-color: lightpink;
border: 3px solid darkgray;
box-shadow: 1px 2px 5px darkgray;
}
#ai-submit {
background-color: lightgreen;
color: white;
box-shadow: 5px 5px 5px darkgray;
padding: 10px;
margin-left: 5px;
}
我的預期結果是燈泡在訓練過程中會變成淺黃色幾秒鍾,然后在准備好接收輸入時變成淺綠色。
實際結果是它只會在初始 state(淺紅色)中凍結,並且不執行任何操作。
我只是添加了一個額外的括號並忘記刪除一個句點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.