xxx
xxx

Reputation: 35

How to fix : Exception has occurred: ZeroDivisionError division by zero

Currently working on ML project for testing and training models and I got this zero division error on this line.

p_bar.set_description('{}. Testing Data of phoneme "{}" against all models \nResult: {}/{} 
correct prediction;\n accuracy: {:.2f}%'.format(
i+1,fc.get39Phon(i),count,len(test_lengths[i]),(count/len(test_lengths[i]))*100) #LINE ERROR

I couldn't figure it out why it generates the exception zero. How can i solve this?

Training the models:

try:
    for i in range(39):
        p_bar.set_description('{}. Training "{}" Phoneme Model'.format(i,fc.get39Phon(i)))
        models[i].fit(features[i].reshape(-1,1),lengths[i] )#Expected 2D array, got 1D array instead, I reshaped the data as suggested

        traceback.print_stack()
        p_bar.update()

except Exception:
    print(traceback.format_exc())

Testing the models

for i in range(39):
    # --- adding missing length at end
    tfeat_len = test_features[i].shape[0]
    tlen_len = np.sum(test_lengths[i])
    if tfeat_len != tlen_len:
        test_lengths[i].append(tfeat_len-tlen_len)

predictions = []
for i in range(39):
    #for each phon data
    count = 0
    s = 0
    p_bar = tqdm(range(len(test_lengths[i])))
    p_bar.set_description('{}. Testing Data of phoneme "{}" against all models'.format(i,fc.get39Phon(i)))
    for j in test_lengths[i]:
        # test in each phon model
        max_prediction = -999999999999
        max_index = 0
        t_feat = test_features[i][s:j+s]
        for k in range(39):
            try:
                score = math.floor(models[k].score(t_feat)*1000)
                if(score > max_prediction):
                    max_prediction = score
                    max_index = k
                if max_index > i:
                    break
            except:
                continue
                
        p_bar.update() 
        count+= 1 if max_index == i else 0      
        s=j
        
    predictions.append((count,len(test_lengths[i])))

TRACEBACK

traceback (most recent call last):
  File "d:\github-space\Phoneme-Recognizer-\r.py", line 392, in <module>
    models[i].fit(features[i].reshape(-1,1),lengths[i])
  File "C:\Python\Python39\lib\site-packages\hmmlearn\base.py", line 496, in fit
    X = check_array(X)
  File "C:\Users\Acer\AppData\Roaming\Python\Python39\site-packages\sklearn\utils\validation.py", line 909, in check_array
    raise ValueError(
ValueError: Found array with 0 sample(s) (shape=(0, 1)) while a minimum of 1 is required.

Upvotes: 0

Views: 769

Answers (1)

Cyao
Cyao

Reputation: 774

It is giving you a division by zero error because len(test_lengths[i]) in count/len(test_lengths[i])*100 is 0, and you know that a number divided by zero is undefined, so it's giving you the error.

Upvotes: 1

Related Questions