neel
neel

Reputation: 9061

Capture exception in python

def makeFeatureVec(words, model, num_features):
    # Function to average all of the word vectors in a given
    # paragraph
    #
    # Pre-initialize an empty numpy array (for speed)
    featureVec = np.zeros((num_features,),dtype="float32")
    #
    nwords = 0.
    # 
    # Index2word is a list that contains the names of the words in 
    # the model's vocabulary. Convert it to a set, for speed 
    index2word_set = set(model.index2word)
    #
    # Loop over each word in the review and, if it is in the model's
    # vocaublary, add its feature vector to the total
    for word in words:
        if word in index2word_set :
            nwords = nwords + 1.
            featureVec = np.add(featureVec,model[word])
    # 
    # Divide the result by the number of words to get the average
    if nwords == 0 :
        return -1
    featureVec = np.divide(featureVec,nwords)
    return featureVec

Above function calculates the feature vector by just taking the average of feature vectors of words. But it will throw an error if number of words is equal to 0, and so I put the if condition to handle that thing. But now I am facing issues when I am calling this function in the following way :

feature = makeFeatureVec(words, model, int(num_features))  
if feature != -1 :
      docs_feature_vec.append(feature)

Following is the error traceback :

Traceback (most recent call last):
  File "classifier.py", line 161, in <module>
    if __name__ == "__main__": main()
  File "classifier.py", line 159, in main
    classify(train_file, model_file, flag, num_features)
  File "classifier.py", line 144, in classify
    data,label = create_feature_vector_docs(train_file, model_file, flag, num_features)
  File "classifier.py", line 94, in create_feature_vector_docs
    if feature != -1 :
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Upvotes: 0

Views: 170

Answers (1)

Dobz
Dobz

Reputation: 1213

To handle errors in python you must use try and except

try:
    if feature != -1:
        doSomething()
except Exception: 
    doSomethingElse()

I would not recommend this solution for what you are doing though.

In my opinion, you shouldn't return -1 instead of an array in the first place.

I'd return None, then use

if feature is not None:
    doSomething()
else:
    doSomethingElse()

In the try code, you would be basically expecting an Exception to occur.

This isn't good practice, and Exceptions should only really occur when you're not expecting them.

Upvotes: 2

Related Questions