gpt4 book ai didi

javascript - 'info' 和 'history' 在 tensorflow.js 的模型中未定义

转载 作者:行者123 更新时间:2023-11-30 19:07:43 25 4
gpt4 key购买 nike

我正在尝试在我的 expo 项目中使用 tensorflow.js 库构建简单的机器学习模型。在代码沙箱中运行相同的代码不会出现任何错误。通过在 visual studio code 中运行,它也会给出未定义信息、历史记录和日志的错误。我的代码附在下面:

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,
},
})

错误信息是:

Can't find variable info

最佳答案

信息可以添加到应用程序的状态

.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>
)
}

关于javascript - 'info' 和 'history' 在 tensorflow.js 的模型中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58824466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com