In [15]:
# Import all of the things you need to import!#
!pip install scipy
!pip install sklearn
!pip install nltk


Requirement already satisfied (use --upgrade to upgrade): scipy in /Users/gcg/.virtualenvs/ddj/lib/python3.5/site-packages
Requirement already satisfied (use --upgrade to upgrade): numpy>=1.6.2 in /Users/gcg/.virtualenvs/ddj/lib/python3.5/site-packages (from scipy)
Requirement already satisfied (use --upgrade to upgrade): sklearn in /Users/gcg/.virtualenvs/ddj/lib/python3.5/site-packages
Requirement already satisfied (use --upgrade to upgrade): scikit-learn in /Users/gcg/.virtualenvs/ddj/lib/python3.5/site-packages (from sklearn)
Requirement already satisfied (use --upgrade to upgrade): nltk in /Users/gcg/.virtualenvs/ddj/lib/python3.5/site-packages

In [16]:
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
import re
from nltk.stem.porter import PorterStemmer
from sklearn.cluster import KMeans
import numpy as np

pd.options.display.max_columns = 30
%matplotlib inline

Homework 14 (or so): TF-IDF text analysis and clustering

Hooray, we kind of figured out how text analysis works! Some of it is still magic, but at least the TF and IDF parts make a little sense. Kind of. Somewhat.

No, just kidding, we're professionals now.

Investigating the Congressional Record

The Congressional Record is more or less what happened in Congress every single day. Speeches and all that. A good large source of text data, maybe?

Let's pretend it's totally secret but we just got it leaked to us in a data dump, and we need to check it out. It was leaked from this page here.


In [17]:
# If you'd like to download it through the command line...
!curl -O http://www.cs.cornell.edu/home/llee/data/convote/convote_v1.1.tar.gz


  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 9607k  100 9607k    0     0  6409k      0  0:00:01  0:00:01 --:--:-- 6413k

In [18]:
# And then extract it through the command line...
!tar -zxf convote_v1.1.tar.gz

You can explore the files if you'd like, but we're going to get the ones from convote_v1.1/data_stage_one/development_set/. It's a bunch of text files.


In [19]:
# glob finds files matching a certain filename pattern
import glob

# Give me all the text files
paths = glob.glob('convote_v1.1/data_stage_one/development_set/*')
paths[:5]


Out[19]:
['convote_v1.1/data_stage_one/development_set/052_400011_0327014_DON.txt',
 'convote_v1.1/data_stage_one/development_set/052_400011_0327025_DON.txt',
 'convote_v1.1/data_stage_one/development_set/052_400011_0327044_DON.txt',
 'convote_v1.1/data_stage_one/development_set/052_400011_0327046_DON.txt',
 'convote_v1.1/data_stage_one/development_set/052_400011_1479036_DON.txt']

In [20]:
len(paths)


Out[20]:
702

So great, we have 702 of them. Now let's import them.


In [21]:
speeches = []
for path in paths:
    with open(path) as speech_file:
        speech = {
            'pathname': path,
            'filename': path.split('/')[-1],
            'content': speech_file.read()
        }
    speeches.append(speech)
speeches_df = pd.DataFrame(speeches)
speeches_df.head()


Out[21]:
content filename pathname
0 mr. chairman , i thank the gentlewoman for yie... 052_400011_0327014_DON.txt convote_v1.1/data_stage_one/development_set/05...
1 mr. chairman , i want to thank my good friend ... 052_400011_0327025_DON.txt convote_v1.1/data_stage_one/development_set/05...
2 mr. chairman , i rise to make two fundamental ... 052_400011_0327044_DON.txt convote_v1.1/data_stage_one/development_set/05...
3 mr. chairman , reclaiming my time , let me mak... 052_400011_0327046_DON.txt convote_v1.1/data_stage_one/development_set/05...
4 mr. chairman , i thank my distinguished collea... 052_400011_1479036_DON.txt convote_v1.1/data_stage_one/development_set/05...

In class we had the texts variable. For the homework can just do speeches_df['content'] to get the same sort of list of stuff.

Take a look at the contents of the first 5 speeches


In [22]:
for item in speeches_df['content'].head(5):
    print("++++++++++++++++++++NEW SPEECH+++++++++++++++++++++")
    print(item)
    print("     ")


++++++++++++++++++++NEW SPEECH+++++++++++++++++++++
mr. chairman , i thank the gentlewoman for yielding me this time . 
my good colleague from california raised the exact and critical point . 
the question is , what happens during those 45 days ? 
we will need to support elections . 
there is not a single member of this house who has not supported some form of general election , a special election , to replace the members at some point . 
but during that 45 days , what happens ? 
the chair of the constitution subcommittee says this is what happens : martial law . 
we do not know who would fill the vacancy of the presidency , but we do know that the succession act most likely suggests it would be an unelected person . 
the sponsors of the bill before us today insist , and i think rightfully so , on the importance of elections . 
but to then say that during a 45-day period we would have none of the checks and balances so fundamental to our constitution , none of the separation of powers , and that the presidency would be filled by an unelected member of the cabinet who not a single member of this country , not a single citizen , voted to fill that position , and that that person would have no checks and balances from congress for a period of 45 days i find extraordinary . 
i find it inconsistent . 
i find it illogical , and , frankly , i find it dangerous . 
the gentleman from wisconsin refused earlier to yield time , but i was going to ask him , if virginia has those elections in a shorter time period , they should be commended for that . 
so now we have a situation in the congress where the virginia delegation has sent their members here , but many other states do not have members here . 
do they at that point elect a speaker of the house in the absence of other members ? 
and then three more states elect their representatives , temporary replacements , or full replacements at that point . 
they come in . 
do they elect a new speaker ? 
and if that happens , who becomes the president under the succession act ? 
this bill does not address that question . 
this bill responds to real threats with fantasies . 
it responds with the fantasy , first of all , that a lot of people will still survive ; but we have no guarantee of that . 
it responds with the fantasy that those who do survive will do the right thing . 
we are here having this debate , we have debates every day , because people differ on what the right thing is to do . 
i have been in very traumatic situations with people in severe car wrecks and mountain climbing accidents . 
my experience has not been that crisis imbues universal sagacity and fairness . 
it has not been that . 
people respond in extraordinary ways , and we must preserve an institution that has the deliberative body and the checks and balances to meet those challenges . 
many of our states are going increasingly to mail-in ballots . 
we in this body were effectively disabled by an anthrax attack not long after september 11 . 
i would ask my dear friends , will you conduct this election in 45 days if there is anthrax in the mail and still preserve the franchise of the american people ? 
how will you do that ? 
you have no answer to that question . 
i find it extraordinary , frankly , that while saying you do not want to amend the constitution , we began this very congress by amending the constitution through the rule , by undermining the principle that a quorum is 50 percent of the body and instead saying it is however many people survive . 
and if that rule applies , who will designate it , who will implement it ? 
the speaker , or the speaker 's designee ? 
again , not an elected person , as you say is so critical and i believe is critical , but a temporary appointee , frankly , who not a single other member of this body knows who they are . 
so we not only have an unelected person , we have an unknown person who will convene this body , and who , by the way , could conceivably convene it for their own election to then become the president of the united states under the succession act . 
you have refused steadfastly to debate this real issue broadly . 
you had a mock debate in the committee on the judiciary in which the distinguished chairman presented my bill without allowing me the courtesy or dignity to defend it myself . 
and on that , you proudly say you defend democracy . 
sir , i think you dissemble in that regard . 
here is the fundamental question for us , my friends , and it is this : the american people are watching television and an announcement comes on and says the congress has been destroyed in a nuclear attack , the president and vice president are killed and the supreme court is dead and thousands of our citizens in this town are . 
what happens next ? 
under your bill , 45 days of chaos . 
apparently , according to the committee on the judiciary subcommittee on the constitution chairman , 45 days of marshal law , rule of this country by an unelected president with no checks and balances . 
or an alternative , an alternative which says quite simply that the people have entrusted the representatives they send here to make profound decisions , war , taxation , a host of other things , and those representatives would have the power under the bill of the gentleman from california ( mr. rohrabacher ) xz4003430 bill or mine to designate temporary successors , temporary , only until we can have a real election . 
the american people , in one scenario , are told we do not know who is going to run the country , we have no representatives ; where in another you will have temporary representatives carrying your interests to this great body while we deliberate and have real elections . 
that is the choice . 
you are making the wrong choice today if you think you have solved this problem . 

     
++++++++++++++++++++NEW SPEECH+++++++++++++++++++++
mr. chairman , i want to thank my good friend from california ( mr. rohrabacher ) xz4003430 . 
i will always remember that day , as we all will . 
his point is well taken . 
i understand there is good intent behind the bill before us today and the amendment , but it is not enough . 
it simply is not . 
it leaves our country vulnerable for 45 days and that is too long . 
the distinguished chairman of the committee on the judiciary made some comments recently that suggested that somehow terrorists would oppose this bill and by some implication would favor the bill the gentleman from california ( mr. rohrabacher ) xz4003430 and i have put forward because it seems to support their autocratic views of government . 
nothing could be further from the truth . 
in fact , what our bill would do is tell the terrorists , you could come on a single day and set off a nuclear weapon in this town and kill every single member of us ; and though we would be missed , the very next day the congress would be up and functioning with every single state , every single district having full representation by statesmen and stateswomen at a time of national crisis . 
that is what the gentleman from california ( mr. rohrabacher ) xz4003430 and i are trying to do . 
we are trying to tell the terrorists , you can kill all of us as individuals , but you will not defeat this institution . 
you will not defeat the principle of representation . 
you will not defeat the principles of checks and balances . 
you will not impose martial law . 
here is the irony . 
if terrorists hit us today when we finally vote on this , let us suppose a few democrats do not make it over here . 
you are leaving this country vulnerable to change in power . 
if the terrorists were to strike your conference retreat where the president speaks to the republican house and senate members and kill hundreds of house and senate members on the republican side , the democrats at that point claim the majority . 
the democrats at that point elect a speaker of the house . 
i am a democrat , for goodness sakes ; but that is not the way to leave our country vulnerable . 
you are leaving your own party , you are leaving the will of the people through their elections vulnerable . 
if we have temporary replacements , you immediately reconstitute the house ; you immediately ensure representation ; you assure that you maintain the balance of political power ; and you do it in an orderly , structured way with no chaos , in a way that is constitutionally valid by definition . 
what you have proposed is not necessarily constitutionally valid . 
it leaves the terrorists able to change our system of government . 
it depends on a fantasy immediate or quick election . 
it does not allow really qualified people necessarily to get here and act in time . 
there are so many things you have left undone . 
you are going to try to say that at the start of this year we have solved this problem ; let us go home . 
you have not solved the problem , and it is a doggone disgrace , and it is a danger to this country . 
the other day a gentleman testified before the committee on the budget and said this : `` the lack of preparation for continuity , for true continuity invites attack. '' you are inviting attack . 
not preventing attack . 

     
++++++++++++++++++++NEW SPEECH+++++++++++++++++++++
mr. chairman , i rise to make two fundamental points before we proceed to vote on this . 
the two points are these : this resolution does not solve the real problem and it may create more problems than it purports to solve , and we have to understand that . 
it does not solve the problem for this reason : by leaving us without a congress for 45 days , we essentially impose the opportunity for the executive branch to exert marshal law , and that is not what the framers of this country had in mind . 
this bill , if we do not provide some mechanism for prompt replacement other than this bill , will leave this country governed by an unelected executive , a cabinet member most likely who not a single american elected to that office . 
furthermore , it has a host of problems . 
it does not address the possibility that one delegation will elect its representatives more promptly than another . 
they will come to this body , choose one of its members as speaker . 
that person could move on to become the president . 
then another delegation comes in , et cetera . 
you are essentially leaving this country without a house of representatives , without checks and balances , without separation of powers , for at least 45 days , assuming an election can be held in 45 days and assuming that the terrorists through an anthrax attack , like they subjected this very capitol to , will not somehow undermine that ability . 
this is reality . 
we have seen the reality here . 
we saw those airplanes hit the buildings , we saw the anthrax , and yet we are not truly acting to solve this . 
mr. chairman , i yield to my distinguished friend , the gentleman from california ( mr. rohrabacher ) xz4003430 . 

     
++++++++++++++++++++NEW SPEECH+++++++++++++++++++++
mr. chairman , reclaiming my time , let me make two final points : one , the majority party must understand this : if you are at a republican conference retreat and terrorists should strike you and kill the president and vice president and significant numbers of your side of the aisle , the democrats under your proposed law will obtain the majority , will elect a speaker of the house , and that person will then become the president of the united states of america . 
you are leaving this country vulnerable to that . 
you must not do it . 
you must not . 
this matter must be taken seriously . 
it deserves full debate . 
whether it is the proposal of the gentleman from california ( mr. rohrabacher ) xz4003430 and mine or others , we should commit to having this full house seriously consider this . 
if we do not and we are not fortunate , history will not look kindly upon the jeopardy in which we have left this great nation . 
vote no on this bill and insist on true debate on true continuity of congress in a responsible way that protects the balance of power , assures real succession to the presidency , and , most importantly , assures that your constituents will have representation at a time when our nation may well go to nuclear war , institute a draft , appropriate trillions of dollars , suspend habeas corpus and impose marshal law . 
you do not want that . 
but if you stop at this bill , you leave this nation vulnerable . 
mr. chairman , if there is no one to speak in opposition , i ask unanimous consent to withdraw my preferential motion . 

     
++++++++++++++++++++NEW SPEECH+++++++++++++++++++++
mr. chairman , i thank my distinguished colleague , and i appreciate his leadership on this issue . 
the gentleman from california ( mr. rohrabacher ) xz4003430 spoke eloquently about the need for the rohrabacher/baird amendment ; and i would like to address it briefly , if i may . 
madison is quoted on this topic , but let me quote madison from federalist 47 . 
he said : `` the accumulation of all powers , legislative , executive , and judiciary in the same hands , whether of one , a few , or many , and whether hereditary , self-appointed , or elected , may justly be pronounced the very definition of tyranny. '' now , i would like , if i may , to ask my colleagues , before we pass this appropriations bill with legislative language in it alleging to maintain continuity , to maybe address a couple of questions , before my colleagues vote on this , and i will yield time . 
not for a filibuster , but just to address some questions . 
how will we , given madison 's concern , maintain checks and balances during the 49-day period until we have the special elections ? 
i would be happy to yield 30 seconds to anyone who plans to vote for this bill to address that question . 

     

Doing our analysis

Use the sklearn package and a plain boring CountVectorizer to get a list of all of the tokens used in the speeches. If it won't list them all, that's ok! Make a dataframe with those terms as columns.

Be sure to include English-language stopwords


In [23]:
c_vectorizer = CountVectorizer(stop_words='english')
x = c_vectorizer.fit_transform(speeches_df['content'])
x


Out[23]:
<702x9106 sparse matrix of type '<class 'numpy.int64'>'
	with 56106 stored elements in Compressed Sparse Row format>

In [24]:
df = pd.DataFrame(x.toarray(), columns=c_vectorizer.get_feature_names())

In [25]:
df


Out[25]:
000 00007 018 050 092 10 100 106 107 108 108th 109th 10th 11 110 ... yields york yorkers young younger youngsters youth yuan zero zeroing zeros zigler zirkin zoe zoellick
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
12 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 ... 0 0 0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0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
29 2 0 0 0 0 1 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
672 0 0 0 0 0 0 0 0 0 0 0 0 0 5 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
673 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
674 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
675 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
676 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
677 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
678 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
679 0 0 0 0 0 0 0 0 0 0 1 0 0 4 0 ... 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
680 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
681 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
682 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
683 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
684 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
685 0 0 0 0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 0 0 0
701 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

702 rows × 9106 columns

Okay, it's far too big to even look at. Let's try to get a list of features from a new CountVectorizer that only takes the top 100 words.


In [26]:
#http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html
c2_vectorizer = CountVectorizer(stop_words='english', max_features=100)
y = c2_vectorizer.fit_transform(speeches_df['content'])
y


Out[26]:
<702x100 sparse matrix of type '<class 'numpy.int64'>'
	with 11088 stored elements in Compressed Sparse Row format>

Now let's push all of that into a dataframe with nicely named columns.


In [27]:
new_df = pd.DataFrame(y.toarray(), columns=c2_vectorizer.get_feature_names())
#new_df

Everyone seems to start their speeches with "mr chairman" - how many speeches are there total, and how many don't mention "chairman" and how many mention neither "mr" nor "chairman"?


In [28]:
#http://stackoverflow.com/questions/15943769/how-to-get-row-count-of-pandas-dataframe
total_speeches = len(new_df.index)
print("In total there are", total_speeches, "speeches.")


In total there are 702 speeches.

In [29]:
wo_chairman = new_df[new_df['chairman']==0]['chairman'].count()
print(wo_chairman, "speeches don't mention 'chairman'")


250 speeches don't mention 'chairman'

In [30]:
wo_mr_chairman = new_df[(new_df['chairman']==0) & (new_df['mr']==0)]['chairman'].count()
print(wo_mr_chairman, "speeches don't mention neither 'chairman' nor 'mr'")


76 speeches don't mention neither 'chairman' nor 'mr'

What is the index of the speech thank is the most thankful, a.k.a. includes the word 'thank' the most times?


In [31]:
#http://stackoverflow.com/questions/18199288/getting-the-integer-index-of-a-pandas-dataframe-row-fulfilling-a-condition
print("The speech with the most 'thank's has the index", np.where(new_df['thank']==new_df['thank'].max()))


The speech with the most 'thank's has the index (array([577]),)

If I'm searching for China and trade, what are the top 3 speeches to read according to the CountVectoriser?


In [32]:
china_trade_speeches = (new_df['china'] + new_df['trade']).sort_values(ascending = False).head(3)
china_trade_speeches


Out[32]:
379    92
399    36
345    27
dtype: int64

Now what if I'm using a TfidfVectorizer?


In [33]:
porter_stemmer = PorterStemmer()

def stem_tokenizer(str_input):
    words = re.sub(r"[^A-Za-z0-9\-]", " ", str_input).lower().split()
    words = [porter_stemmer.stem(word) for word in words]
    return words

tfidf_vectorizer = TfidfVectorizer(stop_words='english', tokenizer=stem_tokenizer, use_idf=False, norm='l1', max_features=100)
X = tfidf_vectorizer.fit_transform(speeches_df['content'])
t_df = pd.DataFrame(X.toarray(), columns=tfidf_vectorizer.get_feature_names())

In [34]:
china_trade_speeches_v2 = (t_df['china'] + t_df['trade']).sort_values(ascending = False).head(3)
china_trade_speeches_v2


Out[34]:
345    0.397059
336    0.281250
402    0.250000
dtype: float64

What's the content of the speeches? Here's a way to get them:


In [35]:
# index 0 is the first speech, which was the first one imported.
paths[0]


Out[35]:
'convote_v1.1/data_stage_one/development_set/052_400011_0327014_DON.txt'

In [36]:
# Pass that into 'cat' using { } which lets you put variables in shell commands
# that way you can pass the path to cat
print("++++++++++NEW SPEECH+++++++++")
!cat {paths[345]}

print("++++++++++NEW SPEECH+++++++++")
!cat {paths[336]}

print("++++++++++NEW SPEECH+++++++++")
!cat {paths[402]}


++++++++++NEW SPEECH+++++++++
i thank the gentleman from new york for yielding me this time . 
madam speaker , we have been here before . 
congress has often resorted to bills and memoranda of understanding concerning china . 
but the u.s. trade deficit with china has continued to increase . 
so i am not going to stand here and argue process . 
we can look at the history and the fact of the whole architecture of agreements that we have had with china , memoranda of understanding , concerns that members of congress from both sides of the aisle brought to this floor in order to try to manage united states trade with china . 
remember we were told that a memorandum of understanding on prison labor with china would remove their competitive advantage and restore balanced trade . 
but the u.s. trade deficit with china worsened . 
remember the agreement to reaffirm the 1992 market access memorandum of understanding . 
we passed that , but the u.s. trade deficit with china grew worse . 
remember china 's agreement to lower tariffs on imports . 
they cut the tariffs from 42 percent to 23 percent , then to 17 percent , then to 12 percent . 
but the u.s. trade deficit with china got worse . 
remember china stopped arbitrary limits on maintaining agricultural imports . 
that was supposed to be a boon for the united states . 
but the u.s. trade deficit with china got worse . 
that is exactly the story that we see with nafta and the wto and , this week , cafta . 
why does the u.s. trade deficit with china keep getting worse no matter what we do ? 
no matter what our best intentions are ? 
the u.s. trade deficit with china keeps getting worse because labor costs in china are so much cheaper . 
hello ? 
wake up , america . 
we are giving away our jobs here , and the central issue is the cheap labor in china . 
you can pass all of these agreements you want . 
they are not going to amount to a hill of beans , because the fact of the matter is that the u.s. trade deficit in china will continue to grow , it will approach $ 200 billion , as long as the labor costs are cheaper . 
that is why we are losing jobs . 
that is why the trade deficit is growing . 
that is why we are losing market share . 
with all due respect to my good friend from pennsylvania , i do not see this bill amounting to anything . 
vote against it . 
++++++++++NEW SPEECH+++++++++
madam speaker , i yield myself the balance of my time . 
madam speaker , i would like , in this closing minute , to cut through the fog of process arguments and weird alice in wonderland illusions to linkage to other trade agreements . 
this is important legislation , and it is important in itself , and it deals directly with key problems that we are having in our trade relations , particularly with china . 
this legislation closes loopholes , not creates loopholes . 
it allows us , for the first time , to apply countervailing duties to nonmarket economies . 
that is a good thing . 
i realize our friends on the other side of the aisle never engaged on the sos bill , the underlying core of this bill , nor cosponsored it . 
i realize that they have been behind the curve on this . 
we have to move today and put this on the calendar today so that we can move quickly to send a message to china that we are going to close the loopholes , that we are going to audit their compliance with their trade obligations , that we are going to oppose the wto watering down our domestic trade relations ; and we are determined to put more money into trade so that we can enforce these agreements . 
if you care about china , if you care about trade , vote for this bill and avoid the petty partisan politics . 
++++++++++NEW SPEECH+++++++++
madam speaker , i rise today in opposition to h.r. 3283 , the so-called united states trade rights enforcement act . 
this bill purports to address china 's lax enforcement of its international trade obligations . 
in fact , this bill does little to address serious trade issues with china , and it is on the house floor for only one reason : to garner votes for cafta later this week . 
there is no question that congress should do everything in its power to enforce trade rights worldwide . 
however , giving lip service to an issue that deserves our careful consideration and strong action is a grave disservice to the american people . 
what we should be talking about today is the bush administration 's continued failure to decrease our trade deficits and promote labor rights , environmental standards and public health protections with our trading partners . 
let 's look at the facts : in 2004 , the u.s. trade deficit with china grew to a record $ 162 billion . 
this despite the fact that china joined the world trade organization , wto , in 2001 and should be well on its way to reducing trade barriers and opening up their markets to u.s. goods and services . 
even the united states trade representative has said that china 's wto compliance efforts are `` far from complete and have not always been satisfactory. '' given these facts , i support strong trade enforcement against china . 
i am a cosponsor of h.r. 1498 , the chinese currency act , which would allow the administration to impose countervailing duties due to china 's continued currency manipulation . 
the bill has 110 bipartisan cosponsors and provides real enforcement mechanisms , instead of the studies and redefinitions offered by h.r. 3283 . 
if the leadership were serious about china we would be voting on this meaningful legislation today . 
but , that is not the case . 
madam speaker , we have known about trade enforcement issues in china for years . 
but china legislation magically appears only now that cafta is in trouble . 
i urge my colleagues to vote against this sham bill . 

Now search for something else! Another two terms that might show up. elections and chaos? Whatever you thnik might be interesting.


In [37]:
new_df.columns


Out[37]:
Index(['000', '11', 'act', 'allow', 'amendment', 'america', 'american', 'amp',
       'association', 'balance', 'based', 'believe', 'bipartisan', 'chairman',
       'children', 'china', 'civil', 'colleagues', 'committee', 'congress',
       'country', 'days', 'debate', 'discrimination', 'does', 'education',
       'election', 'elections', 'fact', 'faith', 'federal', 'frivolous',
       'funding', 'gentleman', 'going', 'good', 'government', 'gt', 'head',
       'health', 'help', 'house', 'important', 'issue', 'just', 'know', 'law',
       'legislation', 'let', 'like', 'lt', 'make', 'member', 'members',
       'million', 'money', 'mr', 'nation', 'national', 'nbsp', 'need', 'new',
       'order', 'organizations', 'people', 'percent', 'policy', 'president',
       'process', 'program', 'programs', 'provide', 'religious', 'right',
       'rights', 'rule', 'rules', 'say', 'school', 'services', 'speaker',
       'start', 'state', 'states', 'support', 'teachers', 'thank', 'think',
       'time', 'today', 'trade', 'united', 'urge', 'vote', 'want', 'way',
       'work', 'year', 'years', 'yield'],
      dtype='object')

In [38]:
election_speeches = (new_df['discrimination'] + new_df['rights']).sort_values(ascending = False).head(3)
election_speeches


Out[38]:
577    243
348     14
672     13
dtype: int64

Enough of this garbage, let's cluster

Using a simple counting vectorizer, cluster the documents into eight categories, telling me what the top terms are per category.

Using a term frequency vectorizer, cluster the documents into eight categories, telling me what the top terms are per category.

Using a term frequency inverse document frequency vectorizer, cluster the documents into eight categories, telling me what the top terms are per category.


In [39]:
def new_stem_tokenizer(str_input):
    words = re.sub(r"[^A-Za-z0-9\-]", " ", str_input).lower().split()
    #With PorterStemmer implemented as above, the text was pretty crippled and hard to judge which made more sense.
    #that's why I have commented that line out for now
    
    #words = [porter_stemmer.stem(word) for word in words]
    return words

vectorizer_types = [
    {'name': 'CVectorizer', 'definition': CountVectorizer(stop_words='english', tokenizer=new_stem_tokenizer,  max_features=100)},
    {'name': 'TFVectorizer', 'definition': TfidfVectorizer(stop_words='english', tokenizer=new_stem_tokenizer,  max_features=100, use_idf=False)},
    {'name': 'TFVIDFVectorizer', 'definition': TfidfVectorizer(stop_words='english', tokenizer=new_stem_tokenizer,  max_features=100, use_idf=True)}
]

In [40]:
for vectorizer in vectorizer_types:
    X = vectorizer['definition'].fit_transform(speeches_df['content'])

    number_of_clusters = 8
    km = KMeans(n_clusters=number_of_clusters)
    km.fit(X)

    print("++++++++ Top terms per cluster -- using a", vectorizer['name'])
    order_centroids = km.cluster_centers_.argsort()[:, ::-1]
    terms = vectorizer['definition'].get_feature_names()
    for i in range(number_of_clusters):
        top_ten_words = [terms[ind] for ind in order_centroids[i, :7]]
        print("Cluster {}: {}".format(i, ' '.join(top_ten_words)))


++++++++ Top terms per cluster -- using a CVectorizer
Cluster 0: trade china s american mr vote speaker
Cluster 1: start head religious rights civil program discrimination
Cluster 2: nbsp amp lt gt trade -- s
Cluster 3: mr chairman gentleman amendment time yield speaker
Cluster 4: association national amp american new america --
Cluster 5: start head children program mr amendment programs
Cluster 6: mr time house s chairman amendment people
Cluster 7: rule 11 rules federal h r civil
++++++++ Top terms per cluster -- using a TFVectorizer
Cluster 0: china trade s speaker mr legislation american
Cluster 1: mr chairman yield gentleman 2 1 vote
Cluster 2: time mr chairman balance yield amendment gentleman
Cluster 3: amendment mr chairman gentleman s time order
Cluster 4: yield gentleman time legislation law education elections
Cluster 5: mr gentleman time chairman s house people
Cluster 6: mr speaker yield gentleman time committee balance
Cluster 7: start head children program amendment mr chairman
++++++++ Top terms per cluster -- using a TFVIDFVectorizer
Cluster 0: yield gentleman mr chairman 2 1 member
Cluster 1: balance time chairman mr yield speaker gentleman
Cluster 2: start head children program amendment religious programs
Cluster 3: house frivolous state legislation elections people rule
Cluster 4: speaker mr yield gentleman committee time 2
Cluster 5: china trade s speaker u legislation american
Cluster 6: amendment chairman mr vote time order gentleman
Cluster 7: gentleman mr s chairman amendment time think

Which one do you think works the best?

The last two seem to make more sense than the first one, telling from its cluster three. The last two are more human-readable. However human-readability ends with that distinction -- I can't tell which from the last two would be better, based on the top terms per cluster.

Harry Potter time

I have a scraped collection of Harry Potter fanfiction at https://github.com/ledeprogram/courses/raw/master/algorithms/data/hp.zip.

I want you to read them in, vectorize them and cluster them. Use this process to find out the two types of Harry Potter fanfiction. What is your hypothesis?


In [41]:
!curl -O https://github.com/ledeprogram/courses/raw/master/algorithms/data/hp.zip


  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   149  100   149    0     0    192      0 --:--:-- --:--:-- --:--:--   193

In [42]:
import zipfile

In [43]:
import glob
potter_paths = glob.glob('hp/*')
potter_paths[:5]


Out[43]:
['hp/10001898.txt',
 'hp/10004131.txt',
 'hp/10004927.txt',
 'hp/10007980.txt',
 'hp/10010343.txt']

In [44]:
potter = []
for path in potter_paths:
    with open(path) as potter_file:
        potter_text = {
            'pathname': path,
            'filename': path.split('/')[-1],
            'content': potter_file.read()
        }
    potter.append(potter_text)
potter_df = pd.DataFrame(potter)
potter_df.head()


Out[44]:
content filename pathname
0 Prologue: The MissionDisclaimer: All character... 10001898.txt hp/10001898.txt
1 BlackDisclaimer: I do not own Harry PotterAuth... 10004131.txt hp/10004131.txt
2 Chapter 1"I'm pregnant.""""Mum please say some... 10004927.txt hp/10004927.txt
3 Author's Note: Hey, just so you know, this is ... 10007980.txt hp/10007980.txt
4 Disclaimer: I do not own Harry Potter and frie... 10010343.txt hp/10010343.txt

In [47]:
vectorizer = TfidfVectorizer(stop_words='english', tokenizer=new_stem_tokenizer, use_idf=True)
X = vectorizer.fit_transform(potter_df['content'])

number_of_clusters = 2
km = KMeans(n_clusters=number_of_clusters)
km.fit(X)

print("Top terms per cluster")
order_centroids = km.cluster_centers_.argsort()[:, ::-1]
terms = vectorizer.get_feature_names()
for i in range(number_of_clusters):
    top_ten_words = [terms[ind] for ind in order_centroids[i, :7]]
    print("Cluster {}: {}".format(i, ' '.join(top_ten_words)))


Top terms per cluster
Cluster 0: harry hermione t s draco ron said
Cluster 1: t s lily james sirius said remus

The first cluster evolves around Harry and his friends Hermoine and Ron as well as his enemy Draco.

The second cluster evolves around Harry's family as well as his godfather Sirius and his mentor Lupin.


In [ ]: