markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Now we'll group everything by movieId and compute the mean rating for the movie.
import numpy as np mean_ratings = ratings[['movieId', 'rating']].groupby('movieId').agg({'rating': ['sum', 'mean']}) mean_ratings.columns = ['rating_count', 'mean_rating'] mean_ratings.sample(n=10)
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
There is likely a fair amount of variance in the sum of ratings, so we'll normalize that column.
mean_ratings['rating_count'] = ( (mean_ratings['rating_count'] - mean_ratings['rating_count'].min()) / (mean_ratings['rating_count'].max() - mean_ratings['rating_count'].min())) mean_ratings['rating_count'].describe()
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
Now let's get the genre information from the movies.csv file. In the genres column, we see the list of genres for each movie separated by a '|'. Note that a movie may have more than one genre. First we read the file into a DataFrame.
movies = pd.read_csv('./ml-latest-small/movies.csv') movies.sample(n=10) movies.describe()
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
Now we split the genres column on the '|' and create a new DataFrame called movies_split.
movies_split = movies.genres.str.split('|', expand=True) movies_split.head()
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
We now create a list of all the unique genres that appear in this DataFrame and remove values that indicate that a genre wasn't specified.
genres = list(pd.unique(movies_split.values.ravel())) genres.remove(None) genres.remove('(no genres listed)') genres = sorted(genres) genres
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
In the movies DataFrame, we want to recode the values of the genres column to be a list of 20 0s and 1s that correspond to the values in list (in the order that they appear in list). For example, if a movie has genres 'Adventure and Children', then we would like the element in the genres column to be: \ [1, 0, 0, 0, 0,...
genre_to_id = {v:i for i, v in enumerate(genres)} genre_to_id
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
The function defined below iterates through a list of genres and compares the values to the elements of genres_list. It then returns an appropriate array of 0s and 1s as described above.
# Create the array of 0s and 1s based on genres. def encode_genres(l): encoding = np.zeros(len(genres)).astype(int) for genre in l: if genre in genre_to_id: encoding[genre_to_id[genre]] = 1 return encoding # Test that f works as expected on an example list. encode_genres(['Adventure', 'Children'])
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
We split the genres column of the movies DataFrame to be a list. We do this in preparation for applying the function, encode_genres.
movies['genres'] = movies.genres.str.split('|') movies.sample(n=10)
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
We apply the function encode_genres to the genres column to change the elements to arrays of 0s and 1s representing the genres. We also set the index to be the movieId.
movies['genres'] = movies.genres.apply(encode_genres) movies = movies.set_index('movieId') movies.sample(n=10)
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
Now we can add the mean rating and the count of ratings to the movies. Let's first make sure that every index is accounted for.
np.setdiff1d(movies.index.to_numpy(), mean_ratings.index.to_numpy()) np.setdiff1d(mean_ratings.index.to_numpy(), movies.index.to_numpy())
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
It looks like we are missing some IDs from the ratings, so we need to be sure to do an inner join. We don't want to include movies with no ratings or ratings with no movies.
movies = movies.join(mean_ratings, how='inner') movies.sample(n=10)
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
Now let's define a function that computes the "distance" between two movies based on how similar their genres are and how similar their popularity is. To make sure it works, we'll compute the distance between movie IDs 2 and 2728:
from scipy import spatial def distance(a, b): genre_distance = spatial.distance.euclidean(a['genres'], b['genres']) popularity_distance = abs(a['rating_count'] - b['rating_count']) return genre_distance + popularity_distance distance(movies[movies.index == 2].iloc[0], movies[movies.index == 2728].iloc[0])
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
Remember, the higher the distance, the less similar the movies are. Let's check what movies 2 and 2728 actually are, and then let's confirm they're not all that similar:
print(movies[movies.index == 2].iloc[0]) print(movies[movies.index == 2728].iloc[0])
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
Now we just need a little code to compute the distance between some given test movie (Toy Story, in this example) and all of the movies in our dataset. We'll find the 10 nearest neighbors utilizing a heapq to keep our memory usage low. Note that heapq pops the smallest values first, so we need to take the negative of t...
import heapq def k_nearest_neighbors(movie_id, K): distances = [] central_movie = movies[movies.index == movie_id].iloc[0] for mid, movie in movies.iterrows(): if (mid != movie_id): dist = distance(central_movie, movie) if len(distances) < K: heapq.heappush(dis...
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
How does this compare to Toy Story's actual average rating?
movies[movies.index == 1].iloc[0]['mean_rating']
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
Exercise: KNeighborsRegressor Earlier in the lab, we built a KNN regressor from scratch. Scikit-learn offers the KNeighborsRegressor, which can perform the regression for us. In this exercise we'll again use the MovieLens dataset to predict rating. Instead of writing your own regressor, use the KNeighborsRegressor. You...
# Your code goes here.
content/06_other_models/04_knn/colab.ipynb
google/applied-machine-learning-intensive
apache-2.0
There is something I should mention here. python 2 can trip people up when trying to do something like the following:
2 / 3
data types.ipynb
epequeno/apl-jun2015
unlicense
This is because python defaults to returning an integer (rounded down) when you ask to divide two integers. Read more about this here: http://python-history.blogspot.com/2009/03/problem-with-integer-division.html To get the answer you'd expect you'll need at least one of the numbers to be a float:
2 / 3.0
data types.ipynb
epequeno/apl-jun2015
unlicense
Floating point numbers Floating point numbers can be a bit tricky. Let's take a look at some examples:
1.5 type(1.5)
data types.ipynb
epequeno/apl-jun2015
unlicense
So you might think that floats are simply numbers that have decimal parts but...
0.1 + 0.2
data types.ipynb
epequeno/apl-jun2015
unlicense
The python docs discuss this behavior: (https://docs.python.org/2/tutorial/floatingpoint.html#representation-error): Note that this is in the very nature of binary floating-point: this is not a bug in Python, and it is not a bug in your code either. You’ll see the same kind of thing in all languages that support your ...
from decimal import Decimal Decimal('0.1') + Decimal('0.2')
data types.ipynb
epequeno/apl-jun2015
unlicense
Strings Now we get to the fun stuff. I say we're getting into the fun stuff because there aren't a lot of methods for numerical types but the rest of the types we'll discuss have plenty of methods available to them which can be very useful. Strings are text, generally. A string is any collection of symbols surrounded b...
'Hello python learners'
data types.ipynb
epequeno/apl-jun2015
unlicense
Strings can use single, double, and triple quotes:
print 'Hello' print "there" print '''python''' print """learners!"""
data types.ipynb
epequeno/apl-jun2015
unlicense
It's useful that we can use all types of quotes as it allows us to have strings with quote's inside them.
print "This string contains single quotes but that's ok since it's surrounded by double quotes" print 'This string is surrounded by single quotes. The cow says: "mooo"' print '''This string want's to mix both "types" of quotes and that's ok since we surrounded it with triple quotes! ''' "We can " + "concatenate string...
data types.ipynb
epequeno/apl-jun2015
unlicense
One of the most common built-in functions you'll use is len(), as you might imagine it returns the length of the argument you pass it:
name = "Eve" len(name)
data types.ipynb
epequeno/apl-jun2015
unlicense
These methods on strings allow us to modify and ask questions about a string.
for i in dir('Hello'): if not i.startswith('_'): print i
data types.ipynb
epequeno/apl-jun2015
unlicense
Here are some examples of what we can do with these methods:
word = "hello" print "capitalize:", word.capitalize() # capitalize the first letter of the string print "count:", word.count('l') # count how many times the string we pass as an argument appear in 'word' print "endswith:", word.endswith('o') # T/F if it ends with the string we pass as an argument print "index:", word.i...
data types.ipynb
epequeno/apl-jun2015
unlicense
Lists So far we've talked about data types that exist as singular objects. Now we can move on to data types that act as collections of items. The first we'll discuss is lists. A list is an ordered series of things. A list can contain objects of any type, including other lists! We use square brackets [] around a comma s...
a = [1, 2, 3] print a print len(a) b = [1, 'one', 1.0] print b print len(b) c = [[1, 2, 3], ['one', 'two', 'three'], [1.0, 2.0, 3.0]] print c print len(c)
data types.ipynb
epequeno/apl-jun2015
unlicense
Just like strings there are methods available to us to work with lists
for i in dir([]): if not i.startswith('_'): print i
data types.ipynb
epequeno/apl-jun2015
unlicense
Let's take a look at how these work. We'll start off with a list of two names, alice and bob. From there we'll use each of the methods to modify the 'names' list.
names = ['alice', 'bob'] names
data types.ipynb
epequeno/apl-jun2015
unlicense
append() will add the argument to the end of the list
names.append('eve') names
data types.ipynb
epequeno/apl-jun2015
unlicense
We'll append again to show off the next method
names.append('bob') names
data types.ipynb
epequeno/apl-jun2015
unlicense
count() tells us how many times the argument occurs in the list
print "The word 'bob' is seen:", names.count('bob')
data types.ipynb
epequeno/apl-jun2015
unlicense
append() only adds a single item at a time, if we want to extend our original list by several items we can use the extend() method and pass in a list of things to add to the end.
names.extend(['bill', 'sally']) names
data types.ipynb
epequeno/apl-jun2015
unlicense
We can find the position of an item using index(), remember lists start counting at 0
print "'sally' is at index:", names.index('sally')
data types.ipynb
epequeno/apl-jun2015
unlicense
We can use insert() to put an item at a specific position in the list
names.insert(2, 'mike') names
data types.ipynb
epequeno/apl-jun2015
unlicense
pop() can be used for a couple of things, if we simply need to remove the last item from the list we can call it by itself
names.pop() names
data types.ipynb
epequeno/apl-jun2015
unlicense
But, we can also keep that last item in another variable:
last_person = names.pop() print names print last_person
data types.ipynb
epequeno/apl-jun2015
unlicense
remove() will remove the 1st occurance of the argument we give it. Notice that alice and mike are now next to each other and the last bob is still in the list
names.remove('bob') names
data types.ipynb
epequeno/apl-jun2015
unlicense
reverse() does pretty much what you'd expect it to
names.reverse() names
data types.ipynb
epequeno/apl-jun2015
unlicense
As does sort()
names.sort() names
data types.ipynb
epequeno/apl-jun2015
unlicense
Interlude: Index notation Before we move on to our discussion of tuples I'd like to discuss a common way to select items from objects. If we know the index of an item we can select it like this:
print names print names[0]
data types.ipynb
epequeno/apl-jun2015
unlicense
But this will work for other types as well
'alice'[3]
data types.ipynb
epequeno/apl-jun2015
unlicense
Tuples Tuples are a bit like lists but have some very important differences. First let's take a look at how they are similar: ordered series of things seperated by commas can be of any length can be a mix of any type of things It'll be easier to show thier differences through example. First, let's look at a typical t...
a = (1, 2, 3) print a print type(a)
data types.ipynb
epequeno/apl-jun2015
unlicense
We normally use parentheses to define a tuple but really any object followed by a comma becomes a tuple. Either way, python will add the parentheses for us anyway:
a = "example", print type(a) print a
data types.ipynb
epequeno/apl-jun2015
unlicense
Probably the most important difference between a list and a tuple has to do with 'immutability.' Let's take a look at an example:
names = ['alice', 'bob'] people = ('alice', 'bob') print names print people
data types.ipynb
epequeno/apl-jun2015
unlicense
So far, not much difference. But lets say that we wanted to get rid of bob and replace him with eve.
names[1] = 'eve' names people[1] = 'eve'
data types.ipynb
epequeno/apl-jun2015
unlicense
Uh-oh python has told us that the tuple does not allow us to 'mute' an item in the tuple the way we can with a list. In other words lists are mutable, tuples are immutable. Let's see what methods we have available to us for tuples:
for i in dir(()): if not i.startswith('_'): print i
data types.ipynb
epequeno/apl-jun2015
unlicense
As a result of the immutability of tuples we don't have many built in methods. Dictionaries So the data types we've seen so far are great for collections of things but there are times where we have pieces of information that are related in some way and we'd like to keep track of those relationships. Let's start off wit...
eng_to_spn = {'one': 'uno', 'two': 'dos', 'three': 'tres'} eng_to_spn
data types.ipynb
epequeno/apl-jun2015
unlicense
Here we have a relationship between pairs of strings, each pair is seperated by a ':' The object to the left of the ':' is called the key and that thing we will use to select a relationship from the dictionary. The object to the right of the ':' is the value. So we have a relationship that can be described as english ...
eng_to_spn['one']
data types.ipynb
epequeno/apl-jun2015
unlicense
Good, when I use a key to select from the dictionary I get the value associated with that key as a response. Let's try another way:
eng_to_spn[0]
data types.ipynb
epequeno/apl-jun2015
unlicense
An important thing to note about dictionaries is that while they are similar to lists and tuples they are unordered. This is where the similarity to a real-world dictionary breaks down. We call this data type a dictionary because it keeps track of the relationship between one thing (a word) and some other thing (it's d...
for key in eng_to_spn: print key
data types.ipynb
epequeno/apl-jun2015
unlicense
Dictionaries are mutable like a list so we can change the relationship of a pair like this:
eng_to_spn['one'] = 1 eng_to_spn['two'] = 2 eng_to_spn['three'] = 3 eng_to_spn
data types.ipynb
epequeno/apl-jun2015
unlicense
We can also add pairs:
eng_to_spn['four'] = 4 eng_to_spn
data types.ipynb
epequeno/apl-jun2015
unlicense
But for now let's keep the dictionary as a set of english words mapped to thier spanish translations:
eng_to_spn = {'one': 'uno', 'two': 'dos', 'three': 'tres'} eng_to_spn
data types.ipynb
epequeno/apl-jun2015
unlicense
Let's take a look at the methods available to us for dictionaries:
for i in dir({}): if not i.startswith('_'): print i
data types.ipynb
epequeno/apl-jun2015
unlicense
copy() will return a "shallow copy" of the dictionary. I won't get into detail here but if you'd like more information see: http://stackoverflow.com/a/3975388
eng_to_spn2 = eng_to_spn.copy() eng_to_spn2
data types.ipynb
epequeno/apl-jun2015
unlicense
fromkeys() will take the keys from one dict and make a new dict with the same keys but with the keys that we specify
eng_to_spn3 = eng_to_spn.fromkeys(eng_to_spn, 'english') eng_to_spn3
data types.ipynb
epequeno/apl-jun2015
unlicense
get() will pull the value from a dictionary:
eng_to_spn.get('one')
data types.ipynb
epequeno/apl-jun2015
unlicense
What's useful about the get() method is that we can specify a default value in the case that what we are asking for doesn't exist yet in the dictionary. This can avoid errors:
eng_to_spn['four'] print eng_to_spn.get('four', None)
data types.ipynb
epequeno/apl-jun2015
unlicense
We can also ask if a key exists using has_key():
eng_to_spn.has_key('four')
data types.ipynb
epequeno/apl-jun2015
unlicense
Although in this example we could have gotten the same result by doing the following:
'four' in eng_to_spn
data types.ipynb
epequeno/apl-jun2015
unlicense
Even though there are methods available to us (the ones we can see with dir()) there may be built-in tools of the language that may be a better choice. We can get the pairs as a list of tuples using the items() method:
eng_to_spn.items()
data types.ipynb
epequeno/apl-jun2015
unlicense
iteritems() gives an item that we can call .next() on. This is valuable in the case that don't want to load the entire dictionary into memory but still want to iterate through the items.
items = eng_to_spn.iteritems() print items.next() print items.next()
data types.ipynb
epequeno/apl-jun2015
unlicense
We can do the same with the keys using iterkeys():
keys = eng_to_spn.iterkeys() print keys.next() print keys.next()
data types.ipynb
epequeno/apl-jun2015
unlicense
We can remove a key and return the value using pop()
three = eng_to_spn.pop('three') print three eng_to_spn
data types.ipynb
epequeno/apl-jun2015
unlicense
popitem() will remove a associaton and return it as a tuple but you don't get to pick which item you'd like to pop out!
anything = eng_to_spn.popitem() print anything eng_to_spn
data types.ipynb
epequeno/apl-jun2015
unlicense
setdefault() works a bit like get() but will set the value for us if it doesn't exist in the dictionary:
eng_to_spn.setdefault('four', 'quatro') eng_to_spn
data types.ipynb
epequeno/apl-jun2015
unlicense
update() allows us to add values from another dictionary:
new_numbers = {'five': 'cinco', 'six': 'seis'} eng_to_spn.update(new_numbers) eng_to_spn
data types.ipynb
epequeno/apl-jun2015
unlicense
We can see all the values from a dictionary using values()
eng_to_spn.values()
data types.ipynb
epequeno/apl-jun2015
unlicense
These next methods, viewitems(), viewkeys() and viewvalues() each return a dictionary view object. The python docs discuss thier purpose: https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects The objects returned by dict.viewkeys(), dict.viewvalues() and dict.viewitems() are view objects. They provid...
eng_to_spn.viewitems() eng_to_spn.viewkeys() eng_to_spn.viewvalues()
data types.ipynb
epequeno/apl-jun2015
unlicense
We skipped over clear() but here's a good time to see what it does, clear the dictionary out!
eng_to_spn.clear() eng_to_spn
data types.ipynb
epequeno/apl-jun2015
unlicense
Make the ONCdb Here are step-by-step instructions on how to generate the ONCdb from VizieR catalogs. Step 1: Initialize the database and ingest the raw data
# Initialize a database onc = astrocat.Catalog() # Ingest a VizieR catalog by supplying a path, catalog name, and column name of a unique identifier onc.ingest_data(DIR_PATH+'/raw_data/viz_acs.tsv', 'ACS', 'ONCacs', count=10) # The raw dataset is stored as an attribute print(onc.ACS) # Add another one! (This is a t...
notebooks/generate_ONCdb.ipynb
ONCdb/ONCdb
mit
Step 2: Cross-match the sources
# Now let's group the sources by some critical distance in arcseconds # and assign IDs for our new custom database sources onc.group_sources() # Summary of what we've done onc.info # Take a look again onc.catalog # # Now let's correct the WFPC2 sources for some systematic offset # onc.correct_offsets('WFPC2', truth...
notebooks/generate_ONCdb.ipynb
ONCdb/ONCdb
mit
Step 3: Generate the SQL database
# Generate the ONCdb mo.generate_ONCdb(onc) # Check that it worked db = astrodb.Database(DIR_PATH+'/orion.sql') db.query("SELECT * FROM browse", fmt='table')
notebooks/generate_ONCdb.ipynb
ONCdb/ONCdb
mit
Hydropy-package Go to the hydropy website for more information on the package and the code on Github.
#Loading the hydropy package import hydropy as hp
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
We have a Dataframe with river discharge at different locations in the Maarkebeek basin (Belgium):
HTML('<iframe src=http://biomath.ugent.be/~stvhoey/maarkebeek_data/ width=700 height=350></iframe>')
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
Data downloaded from http://www.waterinfo.be/, made available by the Flemish Environmental Agency (VMM).
flowdata.head() flowdata.tail() print(len(flowdata), 'records', 'from', flowdata.index[0], 'till', flowdata.index[-1])
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
Converting the dataframe to a hydropy time series datatype, provides extra functionalities:
myflowserie = hp.HydroAnalysis(flowdata)
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
Select the summer of 2009:
myflowserie.get_year('2009').get_season('summer').plot(figsize=(12,6))
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
Select only the recession periods of the discharges (catchment drying) in June 2011:
myflowserie.get_year('2011').get_month("Jun").get_recess().plot(figsize=(12,6))
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
Peak values above the 90th percentile for the station LS06_347 in July 2010:
fig, ax = plt.subplots(figsize=(13, 6)) myflowserie['LS06_347'].get_year('2010').get_month("Jul").get_highpeaks(150, above_percentile=0.9).plot(style='o', ax=ax) myflowserie['LS06_347'].get_year('2010').get_month("Jul").plot(ax=ax)
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
Select storms and make plot
raindata.columns storms = myflowserie.derive_storms(raindata['P05_019'], 'LS06_347', number_of_storms=3, drywindow=50, makeplot=True) storms = myflowserie.derive_storms(raindata['P06_014'], 'LS06_347', number_of_s...
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
Season averages (Pandas!)
myflowserie.data.groupby('season').mean()
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
Goals Use the power of Python Pandas Provide domain specific (hydrological) functionalities Provide intuitive interface for hydrological time series (main focus on flow series) Combine different earlier written loose functionalities in package Independent, but useful in global Phd-developed framework: enables the user...
import hydropy as hp flowdata = pd.read_pickle("./data/FlowData") raindata = pd.read_pickle("./data/RainData") myflowserie = hp.HydroAnalysis(flowdata)
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
Forwarding Pandas functionalities
# Data inspection myflowserie.summary() #head(), tail(), # Resampling frequencies temp1 = myflowserie.frequency_resample('7D', 'mean') # 7 day means temp1.head() temp2 = myflowserie.frequency_resample("M", "max") # Monthly maxima temp2.head() temp3 = myflowserie.frequency_resample("A", 'sum') # Yearly sums temp3....
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
Easy period selection
# get_month, get_year, get_season, get_date_range myflowserie.get_date_range("01/01/2010","03/05/2010").plot(figsize=(13, 6)) # or combine different statements: myflowserie.get_year('2010').get_month(6).plot(figsize=(13, 6))
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
For the seasons some options are available: Meteorologic (first of the month) or astrologic (21st of the month)
myflowserie.current_season_dates() myflowserie.info_season_dates('north', 'astro')
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
'Hydrological' selections
# Peaks (high or low) myflowserie['LS06_348'].get_year('2012').get_highpeaks(60, above_percentile=0.8).data.dropna().head() # Recessions and climbing periods get_recess, get_climbing myflowserie.get_year("2012").get_month("april").get_climbing().plot(figsize=(13, 6)) # above/below certain percentile values myflowser...
hydropy_tutorial.ipynb
stijnvanhoey/hydropy
bsd-2-clause
Two candidate discretizations
n_bins=50
notebooks/CV issue.ipynb
maxentile/msm-learn
mit
Discretization_fast: finely resolving a fast DOF
offsets = np.linspace(-r,r,n_bins) plot_trajectories(trajs,alpha=0.3) for offset in offsets: plt.hlines(offset,-r,r,colors='grey') plt.xlim(-r,r) plt.ylim(-r,r) plt.xlabel(r'$x$') plt.ylabel(r'$y$') plt.title('Trajectories + discretization_fast')
notebooks/CV issue.ipynb
maxentile/msm-learn
mit
Discretization_slow: finely resolving a slow DOF
offsets = np.linspace(-r,r,n_bins) plot_trajectories(trajs,alpha=0.3) for offset in offsets: plt.vlines(offset,-r,r,colors='grey') plt.xlim(-r,r) plt.ylim(-r,r) plt.xlabel(r'$x$') plt.ylabel(r'$y$') plt.title('Trajectories + discretization_slow')
notebooks/CV issue.ipynb
maxentile/msm-learn
mit
Extract discrete trajectories
def axis_aligned_discretization(trajs,offsets,dim=0): dtrajs = [] for traj in trajs: ax = traj[:,dim] bins = np.zeros((len(offsets)+1)) bins[0] = -np.inf bins[1:] = offsets dtraj = np.digitize(ax,bins) dtrajs.append(dtraj) return dtrajs ...
notebooks/CV issue.ipynb
maxentile/msm-learn
mit
Cross-validation
def two_fold_cv(dtrajs,msm): train_scores = [] test_scores = [] split = len(dtrajs)/2 A = dtrajs[:split] B = dtrajs[split:] msm.fit(A) train_scores.append(msm.score_) try: test_scores.append(msm.score(B)) except: test_scores.append(np.nan) msm....
notebooks/CV issue.ipynb
maxentile/msm-learn
mit
Scale the Feature Data Use sklearn preprocessing to create a MinMaxScaler for the feature data. Fit this scaler only to the training data. Then use it to transform X_test and X_train. Then use the scaled X_test and X_train along with pd.Dataframe to re-create two dataframes of scaled data.
from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() scaler.fit(X_train) # Keeping Pandas DataFrame format after re-scaling X_train = pd.DataFrame(data = scaler.transform(X_train), columns = X_train.columns, index = X_train.index) X_test = pd.DataFram...
18-05-28-Complete-Guide-to-Tensorflow-for-Deep-Learning-with-Python/02-Tensorflow-Basics/06-Regression-Exercise.ipynb
arcyfelix/Courses
apache-2.0
Create Feature Columns Create the necessary tf.feature_column objects for the estimator. They should all be trated as continuous numeric_columns.
df.columns import tensorflow as tf age = tf.feature_column.numeric_column('housingMedianAge') rooms = tf.feature_column.numeric_column('totalRooms') bedrooms = tf.feature_column.numeric_column('totalBedrooms') pop = tf.feature_column.numeric_column('population') households = tf.feature_column.numeric_column('househol...
18-05-28-Complete-Guide-to-Tensorflow-for-Deep-Learning-with-Python/02-Tensorflow-Basics/06-Regression-Exercise.ipynb
arcyfelix/Courses
apache-2.0
Create the input function for the estimator object. (play around with batch_size and num_epochs)
input_feature_func = tf.estimator.inputs.pandas_input_fn(x = X_train, y = Y_train, batch_size = 10, num_epochs = 1000, ...
18-05-28-Complete-Guide-to-Tensorflow-for-Deep-Learning-with-Python/02-Tensorflow-Basics/06-Regression-Exercise.ipynb
arcyfelix/Courses
apache-2.0
Create the estimator model. Use a DNNRegressor. Play around with the hidden units!
dnn_model = tf.estimator.DNNRegressor(hidden_units = [6, 5, 5], feature_columns = feature_columns)
18-05-28-Complete-Guide-to-Tensorflow-for-Deep-Learning-with-Python/02-Tensorflow-Basics/06-Regression-Exercise.ipynb
arcyfelix/Courses
apache-2.0
Train the model for ~1,000 steps. (Later come back to this and train it for more and check for improvement)
dnn_model.train(input_fn = input_feature_func, steps = 5000)
18-05-28-Complete-Guide-to-Tensorflow-for-Deep-Learning-with-Python/02-Tensorflow-Basics/06-Regression-Exercise.ipynb
arcyfelix/Courses
apache-2.0
Create a prediction input function and then use the .predict method off your estimator model to create a list or predictions on your test data.
prediction_input_func = tf.estimator.inputs.pandas_input_fn(x = X_test, batch_size = 10, num_epochs = 1, shuffle = False) prediction_genera...
18-05-28-Complete-Guide-to-Tensorflow-for-Deep-Learning-with-Python/02-Tensorflow-Basics/06-Regression-Exercise.ipynb
arcyfelix/Courses
apache-2.0