In [1]:
%reload_ext autoreload
%autoreload 2
%matplotlib inline
import os
import numpy as np
import pandas as pd
pd.set_option('display.max_colwidth', -1)
In [2]:
import ktrain

STEP 1: Get Raw Document Data

In [3]:
# 20newsgroups
from sklearn.datasets import fetch_20newsgroups
remove = ('headers', 'footers', 'quotes')
newsgroups_train = fetch_20newsgroups(subset='train', remove=remove)
newsgroups_test = fetch_20newsgroups(subset='test', remove=remove)
texts = newsgroups_train.data +  newsgroups_test.data

STEP 2: Represent Documents as Semantically Meaningful Vectors With LDA

In [4]:
%%time
tm = ktrain.text.get_topic_model(texts, n_features=10000)
n_topics automatically set to 97
preprocessing texts...
fitting model...
iteration: 1 of max_iter: 5
iteration: 2 of max_iter: 5
iteration: 3 of max_iter: 5
iteration: 4 of max_iter: 5
iteration: 5 of max_iter: 5
done.
CPU times: user 16min 17s, sys: 41min 59s, total: 58min 17s
Wall time: 1min 56s
In [5]:
%%time
tm.build(texts, threshold=0.25)
done.
CPU times: user 1min 26s, sys: 3min 15s, total: 4min 41s
Wall time: 12.2 s

STEP 3: Train a Document Recommender

In [6]:
tm.train_recommender()

STEP 4: Generate Recommendations

Given some text, recommend documents that are semantically relevant to it.

In [8]:
rawtext = """
            Elon Musk leads Space Exploration Technologies (SpaceX), where he oversees
            the development and manufacturing of advanced rockets and spacecraft for missions
            to and beyond Earth orbit.
            """
In [9]:
for i, doc in enumerate(tm.recommend(text=rawtext, n=5)):
    print('RESULT #%s'% (i+1))
    print('TEXT:\n\t%s' % (" ".join(doc['text'].split()[:500])))
    print()
RESULT #1
TEXT:
	Archive-name: space/new_probes Last-modified: $Date: 93/04/01 14:39:17 $ UPCOMING PLANETARY PROBES - MISSIONS AND SCHEDULES Information on upcoming or currently active missions not mentioned below would be welcome. Sources: NASA fact sheets, Cassini Mission Design team, ISAS/NASDA launch schedules, press kits. ASUKA (ASTRO-D) - ISAS (Japan) X-ray astronomy satellite, launched into Earth orbit on 2/20/93. Equipped with large-area wide-wavelength (1-20 Angstrom) X-ray telescope, X-ray CCD cameras, and imaging gas scintillation proportional counters. CASSINI - Saturn orbiter and Titan atmosphere probe. Cassini is a joint NASA/ESA project designed to accomplish an exploration of the Saturnian system with its Cassini Saturn Orbiter and Huygens Titan Probe. Cassini is scheduled for launch aboard a Titan IV/Centaur in October of 1997. After gravity assists of Venus, Earth and Jupiter in a VVEJGA trajectory, the spacecraft will arrive at Saturn in June of 2004. Upon arrival, the Cassini spacecraft performs several maneuvers to achieve an orbit around Saturn. Near the end of this initial orbit, the Huygens Probe separates from the Orbiter and descends through the atmosphere of Titan. The Orbiter relays the Probe data to Earth for about 3 hours while the Probe enters and traverses the cloudy atmosphere to the surface. After the completion of the Probe mission, the Orbiter continues touring the Saturnian system for three and a half years. Titan synchronous orbit trajectories will allow about 35 flybys of Titan and targeted flybys of Iapetus, Dione and Enceladus. The objectives of the mission are threefold: conduct detailed studies of Saturn's atmosphere, rings and magnetosphere; conduct close-up studies of Saturn's satellites, and characterize Titan's atmosphere and surface. One of the most intriguing aspects of Titan is the possibility that its surface may be covered in part with lakes of liquid hydrocarbons that result from photochemical processes in its upper atmosphere. These hydrocarbons condense to form a global smog layer and eventually rain down onto the surface. The Cassini orbiter will use onboard radar to peer through Titan's clouds and determine if there is liquid on the surface. Experiments aboard both the orbiter and the entry probe will investigate the chemical processes that produce this unique atmosphere. The Cassini mission is named for Jean Dominique Cassini (1625-1712), the first director of the Paris Observatory, who discovered several of Saturn's satellites and the major division in its rings. The Titan atmospheric entry probe is named for the Dutch physicist Christiaan Huygens (1629-1695), who discovered Titan and first described the true nature of Saturn's rings. Key Scheduled Dates for the Cassini Mission (VVEJGA Trajectory) ------------------------------------------------------------- 10/06/97 - Titan IV/Centaur Launch 04/21/98 - Venus 1 Gravity Assist 06/20/99 - Venus 2 Gravity Assist 08/16/99 - Earth Gravity Assist 12/30/00 - Jupiter Gravity Assist 06/25/04 - Saturn Arrival 01/09/05 - Titan Probe Release 01/30/05 - Titan Probe Entry 06/25/08 - End of Primary Mission (Schedule last updated 7/22/92) GALILEO - Jupiter orbiter and atmosphere probe, in transit. Has returned the first resolved images of an asteroid, Gaspra, while in transit to Jupiter. Efforts to unfurl the stuck High-Gain

RESULT #2
TEXT:
	Archive-name: space/schedule Last-modified: $Date: 93/04/01 14:39:23 $ SPACE SHUTTLE ANSWERS, LAUNCH SCHEDULES, TV COVERAGE SHUTTLE LAUNCHINGS AND LANDINGS; SCHEDULES AND HOW TO SEE THEM Shuttle operations are discussed in the Usenet group sci.space.shuttle, and Ken Hollis ([email protected]) posts a compressed version of the shuttle manifest (launch dates and other information) periodically there. The manifest is also available from the Ames SPACE archive in SPACE/FAQ/manifest. The portion of his manifest formerly included in this FAQ has been removed; please refer to his posting or the archived copy. For the most up to date information on upcoming missions, call (407) 867-INFO (867-4636) at Kennedy Space Center. Official NASA shuttle status reports are posted to sci.space.news frequently. WHY DOES THE SHUTTLE ROLL JUST AFTER LIFTOFF? The following answer and translation are provided by Ken Jenks ([email protected]). The "Ascent Guidance and Flight Control Training Manual," ASC G&C 2102, "During the vertical rise phase, the launch pad attitude is commanded until an I-loaded V(rel) sufficient to assure launch tower clearance is achieved. Then, the tilt maneuver (roll program) orients the vehicle to a heads down attitude required to generate a negative q-alpha, which in turn alleviates structural loading. Other advantages with this attitude are performance gain, decreased abort maneuver complexity, improved S-band look angles, and crew view of the horizon. The tilt maneuver is also required to start gaining downrange velocity to achieve the main engine cutoff (MECO) target in second stage." This really is a good answer, but it's couched in NASA jargon. I'll try to interpret. 1) We wait until the Shuttle clears the tower before rolling. 2) Then, we roll the Shuttle around so that the angle of attack between the wind caused by passage through the atmosphere (the "relative wind") and the chord of the wings (the imaginary line between the leading edge and the trailing edge) is a slightly negative angle ("a negative q-alpha"). This causes a little bit of "downward" force (toward the belly of the Orbiter, or the +Z direction) and this force "alleviates structural loading." We have to be careful about those wings -- they're about the most "delicate" part of the vehicle. 3) The new attitude (after the roll) also allows us to carry more mass to orbit, or to achieve a higher orbit with the same mass, or to change the orbit to a higher or lower inclination than would be the case if we didn't roll ("performance gain"). 4) The new attitude allows the crew to fly a less complicated flight path if they had to execute one of the more dangerous abort maneuvers, the Return To Launch Site ("decreased abort maneuver complexity"). 5) The new attitude improves the ability for ground-based radio antennae to have a good line-of-sight signal with the S-band radio antennae on the Orbiter ("improved S-band look angles"). 6) The new attitude allows the crew to see the horizon, which is a helpful (but not mandatory) part of piloting any flying machine. 7) The new attitude orients the Shuttle so

RESULT #3
TEXT:
	All of this talk about a COMMERCIAL space race (i.e. $1G to the first 1-year moon base) is intriguing. Similar prizes have influenced aerospace development before. The $25k Orteig prize helped Lindbergh sell his Spirit of Saint Louis venture to his financial backers. If memory serves, the $25k prize would not have been enough to totally reimburse some of the more expensive transatlantic projects (such as Fokker's, Nungesser and other multi-engine projects). However Lindbergh ultimately kept his total costs below that amount. But I strongly suspect that his Saint Louis backers had the foresight to realize that much more was at stake than $25,000. Could it work with the moon? Who are the far-sighted financial backers of today?

RESULT #4
TEXT:
	From the article "What's New" Apr-16-93 in sci.physics.research: ........ WHAT'S NEW (in my opinion), Friday, 16 April 1993 Washington, DC 1. SPACE BILLBOARDS! IS THIS ONE THE "SPINOFFS" WE WERE PROMISED? In 1950, science fiction writer Robert Heinlein published "The Man Who Sold the Moon," which involved a dispute over the sale of rights to the Moon for use as billboard. NASA has taken the firsteps toward this hideous vision of the future. Observers were startled this spring when a NASA launch vehicle arrived at the pad with "SCHWARZENEGGER" painted in huge block letters on the side of the booster rockets. Space Marketing Inc. had arranged for the ad to promote Arnold's latest movie. Now, Space Marketing is working with University of Colorado and Livermore engineers on a plan to place a mile-long inflatable billboard in low-earth orbit. NASA would provide contractual launch services. However, since NASA bases its charge on seriously flawed cost estimates (WN 26 Mar 93) the taxpayers would bear most of the expense. This may look like environmental vandalism, but Mike Lawson, CEO of Space Marketing, told us yesterday that the real purpose of the project is to help the environment! The platform will carry ozone monitors he explained--advertising is just to help defray costs. .......... What do you think of this revolting and hideous attempt to vandalize the night sky? It is not even April 1 anymore. What about light pollution in observations? (I read somewhere else that it might even be visible during the day, leave alone at night). Is NASA really supporting this junk? Are protesting groups being organized in the States? Really, really depressed. Enzo

RESULT #5
TEXT:
	What evidence indicates that Gamma Ray bursters are very far away? Their distribution is very isotropic and the intensity distribution, crudely speaking, indicates we're seeing an edge to the distribution. Given the enormous power, i was just wondering, what if they are quantum black holes or something like that fairly close by? Why would they have to be at galactic ranges? Now, in the good old days before GRO data, it was thought the gamma bursters were neutron stars in the galaxy, it was expected that GRO would confirm this by either showing they were a local population (within a few hundred light years) or that they were in the galactic halo. (Mechanism was not known but several plausible ones existed) (also to be fair it was noted that the _brightest_ burster was probably in the LMC, suggesting theorists might be wrong back then...) As the Sun is not at the center of the galaxy a halo population should show anisotropy (a local disk population is ruled out completely at this stage) - to avoid the anisotropy you have to push the halo out, the energy then gets large, the mechanism of getting NS out that far becomes questionable, and we should start to see for example the Andromeda's bursters. The data is consistent with either a Oort cloud distribution (but only just) - but no one can think of a plausible source with the right spectrum. Or, it can be a cosmological distances (hence isotropy) and the edge is "the edge of the Universe" ;-) If at cosmological distances you need very high energy (to detect) and a very compact source (for spectrum), ergo a neutron star colliding with another neutron star or black hole. Even then getting the spectrum is very hard, but conceivable. If we know anything about physics at that level, the bursters are not due to quantum black holes or cosmic strings, wrong spectrum for one thing. The situation is further complicated by recent claims that there are two classes of sources ;-) [in the colliding NS they'd actually probably fit relatively easily into the NS-NS and NS-BH collision scenarios respectively] my own pet theory is that it's Flying saucers entering hyperspace :-) but the reason i am asking is that most everyone assumes that they are colliding nuetron stars or spinning black holes, i just wondered if any mechanism could exist and place them closer in. If you can think of one, remember to invite me to Stockholm...

Saving and Restoring the Topic Model

The topic model can be saved and restored as follows.

Save the Topic Model:

In [10]:
tm.save('/tmp/tm')

Restore the Topic Model and Rebuild the Document-Topic Matrix

In [11]:
tm = ktrain.text.load_topic_model('/tmp/tm')
done.
In [12]:
tm.build(texts, threshold=0.25)
done.

Note that the scorer and recommender are not saved, only the LDA topic model is saved. So, the scorer and recommender should be retrained prior to use as follows:

In [13]:
tm.train_recommender()
In [14]:
rawtext = """
            Elon Musk leads Space Exploration Technologies (SpaceX), where he oversees
            the development and manufacturing of advanced rockets and spacecraft for missions
            to and beyond Earth orbit.
            """
In [15]:
print(tm.recommend(text=rawtext, n=1)[0]['text'])
Archive-name: space/new_probes
Last-modified: $Date: 93/04/01 14:39:17 $

UPCOMING PLANETARY PROBES - MISSIONS AND SCHEDULES

    Information on upcoming or currently active missions not mentioned below
    would be welcome. Sources: NASA fact sheets, Cassini Mission Design
    team, ISAS/NASDA launch schedules, press kits.


    ASUKA (ASTRO-D) - ISAS (Japan) X-ray astronomy satellite, launched into
    Earth orbit on 2/20/93. Equipped with large-area wide-wavelength (1-20
    Angstrom) X-ray telescope, X-ray CCD cameras, and imaging gas
    scintillation proportional counters.


    CASSINI - Saturn orbiter and Titan atmosphere probe. Cassini is a joint
    NASA/ESA project designed to accomplish an exploration of the Saturnian
    system with its Cassini Saturn Orbiter and Huygens Titan Probe. Cassini
    is scheduled for launch aboard a Titan IV/Centaur in October of 1997.
    After gravity assists of Venus, Earth and Jupiter in a VVEJGA
    trajectory, the spacecraft will arrive at Saturn in June of 2004. Upon
    arrival, the Cassini spacecraft performs several maneuvers to achieve an
    orbit around Saturn. Near the end of this initial orbit, the Huygens
    Probe separates from the Orbiter and descends through the atmosphere of
    Titan. The Orbiter relays the Probe data to Earth for about 3 hours
    while the Probe enters and traverses the cloudy atmosphere to the
    surface. After the completion of the Probe mission, the Orbiter
    continues touring the Saturnian system for three and a half years. Titan
    synchronous orbit trajectories will allow about 35 flybys of Titan and
    targeted flybys of Iapetus, Dione and Enceladus. The objectives of the
    mission are threefold: conduct detailed studies of Saturn's atmosphere,
    rings and magnetosphere; conduct close-up studies of Saturn's
    satellites, and characterize Titan's atmosphere and surface.

    One of the most intriguing aspects of Titan is the possibility that its
    surface may be covered in part with lakes of liquid hydrocarbons that
    result from photochemical processes in its upper atmosphere. These
    hydrocarbons condense to form a global smog layer and eventually rain
    down onto the surface. The Cassini orbiter will use onboard radar to
    peer through Titan's clouds and determine if there is liquid on the
    surface. Experiments aboard both the orbiter and the entry probe will
    investigate the chemical processes that produce this unique atmosphere.

    The Cassini mission is named for Jean Dominique Cassini (1625-1712), the
    first director of the Paris Observatory, who discovered several of
    Saturn's satellites and the major division in its rings. The Titan
    atmospheric entry probe is named for the Dutch physicist Christiaan
    Huygens (1629-1695), who discovered Titan and first described the true
    nature of Saturn's rings.

	 Key Scheduled Dates for the Cassini Mission (VVEJGA Trajectory)
	 -------------------------------------------------------------
	   10/06/97 - Titan IV/Centaur Launch
	   04/21/98 - Venus 1 Gravity Assist
	   06/20/99 - Venus 2 Gravity Assist
	   08/16/99 - Earth Gravity Assist
	   12/30/00 - Jupiter Gravity Assist
	   06/25/04 - Saturn Arrival
	   01/09/05 - Titan Probe Release
	   01/30/05 - Titan Probe Entry
	   06/25/08 - End of Primary Mission
	    (Schedule last updated 7/22/92)


    GALILEO - Jupiter orbiter and atmosphere probe, in transit. Has returned
    the first resolved images of an asteroid, Gaspra, while in transit to
    Jupiter. Efforts to unfurl the stuck High-Gain Antenna (HGA) have
    essentially been abandoned. JPL has developed a backup plan using data
    compression (JPEG-like for images, lossless compression for data from
    the other instruments) which should allow the mission to achieve
    approximately 70% of its original objectives.

	   Galileo Schedule
	   ----------------
	   10/18/89 - Launch from Space Shuttle
	   02/09/90 - Venus Flyby
	   10/**/90 - Venus Data Playback
	   12/08/90 - 1st Earth Flyby
	   05/01/91 - High Gain Antenna Unfurled
	   07/91 - 06/92 - 1st Asteroid Belt Passage
	   10/29/91 - Asteroid Gaspra Flyby
	   12/08/92 - 2nd Earth Flyby
	   05/93 - 11/93 - 2nd Asteroid Belt Passage
	   08/28/93 - Asteroid Ida Flyby
	   07/02/95 - Probe Separation
	   07/09/95 - Orbiter Deflection Maneuver
	   12/95 - 10/97 - Orbital Tour of Jovian Moons
	   12/07/95 - Jupiter/Io Encounter
	   07/18/96 - Ganymede
	   09/28/96 - Ganymede
	   12/12/96 - Callisto
	   01/23/97 - Europa
	   02/28/97 - Ganymede
	   04/22/97 - Europa
	   05/31/97 - Europa
	   10/05/97 - Jupiter Magnetotail Exploration


    HITEN - Japanese (ISAS) lunar probe launched 1/24/90. Has made
    multiple lunar flybys. Released Hagoromo, a smaller satellite,
    into lunar orbit. This mission made Japan the third nation to
    orbit a satellite around the Moon.


    MAGELLAN - Venus radar mapping mission. Has mapped almost the entire
    surface at high resolution. Currently (4/93) collecting a global gravity
    map.


    MARS OBSERVER - Mars orbiter including 1.5 m/pixel resolution camera.
    Launched 9/25/92 on a Titan III/TOS booster. MO is currently (4/93) in
    transit to Mars, arriving on 8/24/93. Operations will start 11/93 for
    one martian year (687 days).


    TOPEX/Poseidon - Joint US/French Earth observing satellite, launched
    8/10/92 on an Ariane 4 booster. The primary objective of the
    TOPEX/POSEIDON project is to make precise and accurate global
    observations of the sea level for several years, substantially
    increasing understanding of global ocean dynamics. The satellite also
    will increase understanding of how heat is transported in the ocean.


    ULYSSES- European Space Agency probe to study the Sun from an orbit over
    its poles. Launched in late 1990, it carries particles-and-fields
    experiments (such as magnetometer, ion and electron collectors for
    various energy ranges, plasma wave radio receivers, etc.) but no camera.

    Since no human-built rocket is hefty enough to send Ulysses far out of
    the ecliptic plane, it went to Jupiter instead, and stole energy from
    that planet by sliding over Jupiter's north pole in a gravity-assist
    manuver in February 1992. This bent its path into a solar orbit tilted
    about 85 degrees to the ecliptic. It will pass over the Sun's south pole
    in the summer of 1993. Its aphelion is 5.2 AU, and, surprisingly, its
    perihelion is about 1.5 AU-- that's right, a solar-studies spacecraft
    that's always further from the Sun than the Earth is!

    While in Jupiter's neigborhood, Ulysses studied the magnetic and
    radiation environment. For a short summary of these results, see
    *Science*, V. 257, p. 1487-1489 (11 September 1992). For gory technical
    detail, see the many articles in the same issue.


    OTHER SPACE SCIENCE MISSIONS (note: this is based on a posting by Ron
    Baalke in 11/89, with ISAS/NASDA information contributed by Yoshiro
    Yamada ([email protected]). I'm attempting to track changes based
    on updated shuttle manifests; corrections and updates are welcome.

    1993 Missions
	o ALEXIS [spring, Pegasus]
	    ALEXIS (Array of Low-Energy X-ray Imaging Sensors) is to perform
	    a wide-field sky survey in the "soft" (low-energy) X-ray
	    spectrum. It will scan the entire sky every six months to search
	    for variations in soft-X-ray emission from sources such as white
	    dwarfs, cataclysmic variable stars and flare stars. It will also
	    search nearby space for such exotic objects as isolated neutron
	    stars and gamma-ray bursters. ALEXIS is a project of Los Alamos
	    National Laboratory and is primarily a technology development
	    mission that uses astrophysical sources to demonstrate the
	    technology. Contact project investigator Jeffrey J Bloch
	    ([email protected]) for more information.

	o Wind [Aug, Delta II rocket]
	    Satellite to measure solar wind input to magnetosphere.

	o Space Radar Lab [Sep, STS-60 SRL-01]
	    Gather radar images of Earth's surface.

	o Total Ozone Mapping Spectrometer [Dec, Pegasus rocket]
	    Study of Stratospheric ozone.

	o SFU (Space Flyer Unit) [ISAS]
	    Conducting space experiments and observations and this can be
	    recovered after it conducts the various scientific and
	    engineering experiments. SFU is to be launched by ISAS and
	    retrieved by the U.S. Space Shuttle on STS-68 in 1994.

    1994
	o Polar Auroral Plasma Physics [May, Delta II rocket]
	    June, measure solar wind and ions and gases surrounding the
	    Earth.

	o IML-2 (STS) [NASDA, Jul 1994 IML-02]
	    International Microgravity Laboratory.

	o ADEOS [NASDA]
	    Advanced Earth Observing Satellite.

	o MUSES-B (Mu Space Engineering Satellite-B) [ISAS]
	    Conducting research on the precise mechanism of space structure
	    and in-space astronomical observations of electromagnetic waves.

    1995
	LUNAR-A [ISAS]
	    Elucidating the crust structure and thermal construction of the
	    moon's interior.


    Proposed Missions:
	o Advanced X-ray Astronomy Facility (AXAF)
	    Possible launch from shuttle in 1995, AXAF is a space
	    observatory with a high resolution telescope. It would orbit for
	    15 years and study the mysteries and fate of the universe.

	o Earth Observing System (EOS)
	    Possible launch in 1997, 1 of 6 US orbiting space platforms to
	    provide long-term data (15 years) of Earth systems science
	    including planetary evolution.

	o Mercury Observer
	    Possible 1997 launch.

	o Lunar Observer
	    Possible 1997 launch, would be sent into a long-term lunar
	    orbit. The Observer, from 60 miles above the moon's poles, would
	    survey characteristics to provide a global context for the
	    results from the Apollo program.

	o Space Infrared Telescope Facility
	    Possible launch by shuttle in 1999, this is the 4th element of
	    the Great Observatories program. A free-flying observatory with
	    a lifetime of 5 to 10 years, it would observe new comets and
	    other primitive bodies in the outer solar system, study cosmic
	    birth formation of galaxies, stars and planets and distant
	    infrared-emitting galaxies

	o Mars Rover Sample Return (MRSR)
	    Robotics rover would return samples of Mars' atmosphere and
	    surface to Earch for analysis. Possible launch dates: 1996 for
	    imaging orbiter, 2001 for rover.

	o Fire and Ice
	    Possible launch in 2001, will use a gravity assist flyby of
	    Earth in 2003, and use a final gravity assist from Jupiter in
	    2005, where the probe will split into its Fire and Ice
	    components: The Fire probe will journey into the Sun, taking
	    measurements of our star's upper atmosphere until it is
	    vaporized by the intense heat. The Ice probe will head out
	    towards Pluto, reaching the tiny world for study by 2016.

In [ ]: