我正在寻找将一些原始tf.js转换为react组件的最简单方法。
这里是一个React组件:
class KMeans extends Component {
render() {
return (
<div className="KMeansMonitor">
</div>
)
}
}
export default KMeans;
而且我有一个异步函数来计算MSE:
async function learnLinear(){
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({
loss: 'meanSquaredError',
optimizer: 'sgd'
});
const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);
await model.fit(xs, ys, {epochs: 500});
document.getElementById('output_field').innerText =
model.predict(tf.tensor2d([10], [1, 1]));
}
learnLinear();
我只想让这个普通的js在React组件中运行。一如既往,我们将为您提供任何帮助。
很简单。更改learnLinear
函数,使其仅返回带有值的Promise,并使用必要的挂钩来等待数据和更新状态
示例
const { useState, useEffect } = React;
async function learnLinear() {
const model = tf.sequential();
const layer = tf.layers.dense({units: 1, inputShape: [1]});
model.add(layer);
model.compile({
loss: 'meanSquaredError',
optimizer: 'sgd'
});
const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);
await model.fit(xs, ys, {epochs: 500});
const prediction = await model.predict(tf.tensor2d([10], [1, 1]));
return prediction.toString();
}
const App = () => {
const [value, setValue] = useState(null);
useEffect(() => {
let isUnmounted = false;
learnLinear()
.then(result => {
if(isUnmounted) {
return;
}
console.log(result);
setValue(result);
});
return () => {
isUnmounted = true;
}
}, [])
return <div>
{value ? value : 'Predicting value...'}
</div>
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/@tensorflow/[email protected]/dist/tf.min.js"></script>
<div id="root"></div>