我在使用一个简单的@tensorflow/tfjs
模型,它仅显示准确率。相同的代码在代码沙箱中运行时没有错误,但在Visual Studio Code中运行时会出现一个不变类型错误。我的代码附在下面。另外,请指导关于代码中使用的输入形状和单位术语,以及如何在React Native中实现此代码。
import '@tensorflow/tfjs-react-native'import * as tf from "@tensorflow/tfjs";import * as ft from '@tensorflow/tfjs-backend-webgpu';//import { writeFileSync, readFileSync } from 'fs';(async() => { await ft.ready // then do all operations on the backend})()const model = tf.sequential({ layers: [ tf.layers.dense({ inputShape: [784], units: 32, activation: "relu" }), tf.layers.dense({ units: 10, activation: "softmax" }) ]});model.weights.forEach(w => { console.log(w.name, w.shape);});model.weights.forEach(w => { const newVals = tf.randomNormal(w.shape); // w.val is an instance of tf.Variable w.val.assign(newVals);});model.compile({ optimizer: "sgd", loss: "categoricalCrossentropy", metrics: ["accuracy"]});const data = tf.randomNormal([100, 784]);const labels = tf.randomUniform([100, 10]);function onBatchEnd(batch, logs) { console.log("Accuracy", logs.acc);}// Train for 5 epochs with batch size of 32.model .fit(data, labels, { epochs: 5, batchSize: 32, callbacks: { onBatchEnd } }) .then(info => { console.log("Final accuracy", info.history.acc); });
以及错误
回答:
你需要导入@tensorflow/tfjs-react-native
包。此外,如果后端是异步的,应该使用tf.ready()
。这里是一个你的React应用应该如何编写的示例
import * as tf from '@tensorflow/tfjs';import '@tensorflow/tfjs-react-native';export class App extends React.Component { constructor(props) { super(props); this.state = { isTfReady: false, }; } init() { const model = tf.sequential({ layers: [ tf.layers.dense({ inputShape: [784], units: 32, activation: "relu" }), tf.layers.dense({ units: 10, activation: "softmax" }) ] }); model.weights.forEach(w => { console.log(w.name, w.shape); }); model.weights.forEach(w => { const newVals = tf.randomNormal(w.shape); // w.val is an instance of tf.Variable w.val.assign(newVals); }); model.compile({ optimizer: "sgd", loss: "categoricalCrossentropy", metrics: ["accuracy"] }); const data = tf.randomNormal([100, 784]); const labels = tf.randomUniform([100, 10]); function onBatchEnd(batch, logs) { console.log("Accuracy", logs.acc); } // Train for 5 epochs with batch size of 32. model .fit(data, labels, { epochs: 5, batchSize: 32, callbacks: { onBatchEnd } }) .then(info => { console.log("Final accuracy", info.history.acc); }); } async componentDidMount() { // Wait for tf to be ready. await tf.ready(); // Signal to the app that tensorflow.js can now be used. this.setState({ isTfReady: true, }); } render() { init() // }}