Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8801035
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T00:44:17+00:00 2026-06-14T00:44:17+00:00

I am using the Python sklearn libraries. I have 150,000+ sentences. I need an

  • 0

I am using the Python sklearn libraries.
I have 150,000+ sentences.

I need an array-like object, where each row is for a sentences, each column corresponds to a word, and each element is the number of words in that sentence.

For example: If the two sentences were “The dog ran” and “The boy ran”, I need

[ [1, 1, 1, 0]
, [0, 1, 1, 1] ]

(the order of the columns is irrelevant, and depends on which column is assigned to which word)

My array will be sparse (each sentence will have a fraction of the possible words), and so I am using scipy.sparse.

def word_counts(texts, word_map):
    w_counts = sp.???_matrix((len(texts),len(word_map)))

    for n in range(0,len(texts)-1):
        for word in re.findall(r"[\w']+", texts[n]):
            index = word_map.get(word)
            if index != None:
                w_counts[n,index] += 1
    return w_counts

...
nb = MultinomialNB() #from sklearn
words = features.word_list(texts)
nb.fit(features.word_counts(texts,words), classes)

I want to know what sparse matrix would be best.

I tried using coo_matrix but got an error:

TypeError: ‘coo_matrix’ object has no attribute ‘__getitem__’

I looked at the documentation for COO but was very confused by the following:

Sparse matrices can be used in arithmetic operations …
Disadvantages of the COO format …
does not directly support:
arithmetic operations

I used dok_matrix, and that worked, but I don’t know if this performs best in this case.

Thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T00:44:18+00:00Added an answer on June 14, 2026 at 12:44 am

    Try either lil_matrix or dok_matrix; those are easy to construct and inspect (but in the case of lil_matrix, potentially very slow as each insertion takes linear time). Scikit-learn estimators that accept sparse matrices will accept any format and convert them to an efficient format internally (usually csr_matrix). You can also do the conversion yourself using the methods tocoo, todok, tocsr etc. on scipy.sparse matrices.

    Or, just use the CountVectorizer or DictVectorizer classes that scikit-learn provides for exactly this purpose. CountVectorizer takes entire documents as input:

    >>> from sklearn.feature_extraction.text import CountVectorizer
    >>> documents = ["The dog ran", "The boy ran"]
    >>> vectorizer = CountVectorizer(min_df=0)
    >>> vectorizer = CountVectorizer(min_df=0, stop_words=[])
    >>> X = CountVectorizer.fit_transform(documents)
    >>> X = vectorizer.fit_transform(documents)
    >>> X.toarray()
    array([[0, 1, 1, 1],
           [1, 0, 1, 1]])
    

    … while DictVectorizer assumes you’ve already done tokenization and counting, with the result of that in a dict per sample:

    >>> from sklearn.feature_extraction import DictVectorizer
    >>> documents = [{"the":1, "boy":1, "ran":1}, {"the":1, "dog":1, "ran":1}]
    >>> X = vectorizer.fit_transform(documents)
    >>> X.toarray()
    array([[ 1.,  0.,  1.,  1.],
           [ 0.,  1.,  1.,  1.]])
    >>> vectorizer.inverse_transform(X[0])
    [{'ran': 1.0, 'boy': 1.0, 'the': 1.0}]
    

    (The min_df argument to CountVectorizer was added a few releases ago. If you’re using an old version, omit it, or rather, upgrade.)

    EDIT According to the FAQ, I must disclose my affiliation, so here goes: I’m the author of DictVectorizer and I also wrote parts of CountVectorizer.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Using Python I would like to find the date object for last Wednesday. I
Using python 2.6: I have a dictionary where each key contains a list of
Using Python, how does one parse/access files with Linux-specific features, like ~/.mozilla/firefox/*.default ? I've
Using Python I need to insert a newline character into a string every 64
Using Python I need to delete all characters in a multiline string up to
Im using python to access a MySQL database and im getting a unknown column
I'm using sklearn.mixture.GMM in Python, and the results seem to depend on data scaling.
Using python's optparse module I would like to add extra example lines below the
When using Python is it possible that a dict can have a value that
(Using Python 3.2, though I doubt it matters.) I have class Data , class

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.