Wednesday, 21 April 2021

value becomes undefined because of setState

I am using p5 and ml5.js to train an ML model by adding some images via my webcam. The train function works fine like this. However, if I uncomment the if statement within the train function:

if (lossValue == null)

the value of classifier because undefined after that and it would throw an error in the next step. Why is this happening and how can I fix this? If I just use a console.log inside the if statement, it doesn't create a problem. However, if I use the setState inside it, it sets the classifier to undefined.

export const Component: React.FC<ComponentProps> = (props: ComponentProps) => {
    const [prediction, setPrediction] = useState<string>();
    const [confidence, setConfidence] = useState<string>();
    const [trainingComplete, setTrainingComplete] = useState<boolean>();
    //const [lossValue, setLoss] = useState<any>();

    let capture: p5Types.Element;
    let classifier: any;
    const setup = (p5: p5Types, canvasParentRef: Element) => {
        capture = p5.createCapture(p5.VIDEO).parent(canvasParentRef);
        const featureExtractor = ml5.featureExtractor('MobileNet', modelReady);
         classifier = featureExtractor.classification(capture, videoReady);
    }

    const draw = (p5: p5Types) => {
    }

    function modelReady() {
        console.log('Model Ready');
    }

    function videoReady() {
        console.log('Video Ready');
    }


    function gotResult() {
        console.log('classifier in results', classifier);
        classifier.classify(capture, (err: any, result: any) => {
            setPrediction(result[0].label);
            
        });
    }

    function train() {
        console.log('classifier in train', classifier);
        classifier.train((lossValue: any) => {
            console.log('Loss is', lossValue);
            // if (lossValue == null){
            //  setTrainingComplete(true);
            // }
        });
        console.log('classifier in train', classifier);
    }



    return (<div><Sketch setup={setup} draw={draw} className="sketch" />
        <div className="button">
            <Button variant="contained" color="primary" onClick={() => {classifier.addImage('first');console.log('image added')}}>First</Button>
            <Button variant="contained" color="primary" onClick={() => {classifier.addImage('second');console.log('image added')}}>Second</Button>
        </div>
        <div className="secondbutton">
            <Button variant="contained" color="primary" onClick={() => train()}>Train!</Button>
            <Button variant="contained" color="primary" onClick={() => gotResult()}>Test!</Button>
            <br />
            {trainingComplete && (<span>Training Complete!</span>)}<br />
        </div>
    </div>)
        ;
};

Codesandbox:

https://codesandbox.io/s/hardcore-solomon-zb34l?file=/src/Component.tsx



from value becomes undefined because of setState

No comments:

Post a Comment