我正在尝试使用expo项目中的tensorflow.js
库构建简单的机器学习模型。在代码沙箱中运行相同的代码不会产生任何错误。通过在Visual Studio代码中运行,它也会给出未定义的信息,历史和日志错误。我的代码附在下面:
import React from 'react';
import {View, Text, StyleSheet} from 'react-native';
import * as tf from '@tensorflow/tfjs';
import '@tensorflow/tfjs-react-native';
export default 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) {
logs.acc = parseFloat((logs.acc * 100).toFixed(2));
logs.loss = parseFloat((logs.loss * 100).toFixed(3));
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() {
//this.init()
// //
return (
<View style={styles.buttonContainer}>
<Text>{'Final accuracy', info.history.acc}</Text>
</View>
)
}
}
const styles = StyleSheet.create({
// container: {
// flex: 1,
// },
buttonContainer: {
// flexDirection: 'row',
alignItems: 'center',
marginTop: 50,
},
})
错误消息是:
找不到变量信息
答案 0 :(得分:1)
信息可以添加到应用程序的状态
.then(info => {
this.state = {...this.state, info}
console.log("Final accuracy", info.history.acc);
});
仅在模型使用条件渲染完成训练后才显示信息
render() {
const {info} = this.state;
return (
<View style={styles.buttonContainer}>
{info && <Text>{'Final accuracy', info.history.acc}</Text>}
</View>
)
}