LaVOZs

The World’s Largest Online Community for Developers

'; python - Error: "ValueError: cannot use sparse input in 'SVR' trained on dense data"? - LavOzs.Com

from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
vector = vectorizer.fit_transform(X_train).toarray()
print(vector.shape)
print(type(vector))
print(vector)    
vector

This gives class 'numpy.ndarray' with shape (97, 370)

from sklearn.svm import SVR
from sklearn.model_selection import cross_val_score
clf = SVR(gamma='auto',cache_size=12000,max_iter=-1)
print("Training the data set...")
clf = clf.fit(vector, y_train)
print("Training Completed")
test_vectors = vectorizer.transform(X_test)
test_vectors

This gives <108x370 sparse matrix of type '' with 1212 stored elements in Compressed Sparse Row format>

clf.predict(test_vectors)

This gives the error "ValueError: cannot use sparse input in 'SVR' trained on dense data"

What is the problem here? How can I fix it? Thanks!

You should call .toarray() as you have done for train data:

test_vectors = vectorizer.transform(X_test).toarray()

Related
Sparse-Dense multiplication in Python
AttributeError: 'numpy.ndarray' object has no attribute 'toarray'
Dense-to-sparse and sparse-to-dense conversions using cuSPARSE
Pandas mul with dense with sparse
sckit-learn fit() leads to error after normalising the data
quadratic featurizer: preprocessing with fit_transform
ExtraTreesClassifier with sparse training data?
SKLearn Perceptron behaving differently for sparse and dense
Error after upgrading pip: cannot import name 'main'
ValueError: cannot use sparse input in 'SVC' trained on dense data