markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
In looking at the top 10 trips for each station, we see some very interesting results. For Capital bikeshare, the top most common trip and the 4th most common trip share the same stations. This could imply some sort of round trip behavior. For example, "Eastern Market Metro / Pennsylvania Ave & 7th St SE" is right besi...
def get_duration(path): #once again, the files are formatted slightly differently... if path=="citi": trip_duration = 'tripduration' start_station = 'start station id' end_station = 'end station id' if path=="capital": trip_duration = 'Duration' start_station = 'Start...
bikeshares.ipynb
bikeviz/bikeviz.github.io
apache-2.0
We'll define a round trip by looking at the start and end station to see if they are the same. One small issue, though--Capital bikeshare's data is formatted slightly differently, as shown below:
capital[1][0]
bikeshares.ipynb
bikeviz/bikeviz.github.io
apache-2.0
Since NYC's data comes in seconds, let's convert DC's data to seconds as well.
def parse_time(time): hms = re.sub("\s\s","",re.sub("[a-z]."," ",time)).split(" ") return int(hms[0])*60+60*int(hms[1])+int(hms[2]) nyc_round_trip = [int(entry[0]) for entry in citibike if entry[1]==entry[2]] nyc_one_way = [int(entry[0]) for entry in citibike if entry[1]!=entry[2]] dc_round_trip = [parse_time...
bikeshares.ipynb
bikeviz/bikeviz.github.io
apache-2.0
Something isn't quite right. Looking at the data, the shortest time for NYC we're looking at is 60 seconds, and a staggering 0 seconds for DC. At a first glance, this is way too short for a "round trip". One possible explanation is that someone realized a bike they rented was malfunctioning and returned it immediately ...
nyc_round_trip = [trip for trip in nyc_round_trip if trip>=300 and trip<20000] dc_round_trip = [trip for trip in dc_round_trip if trip>=300 and trip<20000] min(nyc_round_trip), min(dc_round_trip)
bikeshares.ipynb
bikeviz/bikeviz.github.io
apache-2.0
Let's look at this visually:
def plot_freq(trip_data,city,nbins=500): plt.xlim([0, 15500]) hist = plt.hist(trip_data,bins=np.arange(0,max(trip_data),len(trip_data)*1./nbins)) plt.ylim([0,22500]) plt.title(city + ' Round Trip Frequency') plt.xlabel('Trip Duration in Seconds') plt.ylabel('Counts') plt.show() plot_freq(...
bikeshares.ipynb
bikeviz/bikeviz.github.io
apache-2.0
Now that we have a better idea of how round trips work, let's take a look at one way trips. First things first, we need to check our data integrity and remove anything that doesn't make sense.
min(nyc_one_way),min(dc_one_way),max(nyc_one_way),max(dc_one_way)
bikeshares.ipynb
bikeviz/bikeviz.github.io
apache-2.0
Some of these numbers are unbelievable. In some other world, a 27 bike ride <i>might</i> be justifiable, but the max one way trip length for NYC is over 62 days, which is completely unreasonable. Let's filter those out.
nyc_one_way = [trip for trip in nyc_one_way if trip>=300 and trip<20000] dc_one_way = [trip for trip in dc_one_way if trip>=300 and trip<20000] min(nyc_one_way),min(dc_one_way),max(nyc_one_way),max(dc_one_way) def plot_freq_one_way(trip_data,city,nbins=500): plt.xlim([0, 15000]) hist = plt.hist(trip_data...
bikeshares.ipynb
bikeviz/bikeviz.github.io
apache-2.0
Looking at the frequencies for each of the locations, there seems to be a general bin for trip duration that has the highest frequency across all the categories. Aside from that, it is difficult to say that frequency alone, if at all, can indicate whether a one way trip or a round trip occurs. Part 3: A Look at Usage T...
from dateutil import parser ''' set param='depart' or param='arrive' ''' def count_trips(times,param,param2=None): trips = OrderedDict() for day in range(0,7): trips[str(day)] = OrderedDict() for hour in range(0,24): trips[str(day)][str(hour)] = 0 counter = 0 for time in ti...
bikeshares.ipynb
bikeviz/bikeviz.github.io
apache-2.0
To visualize the heatmap, we plan on using d3js, so we'll output the files to a .tsv format that our other code can read in.
def write_tsv(file_name, trips_dict): trips_array = list() for day in trips_dict: for hour in trips_dict[day]: trips_array.append({'day':day,'hour':hour,'count':trips_dict[day][hour]}) with open(file_name, 'w') as f: dict_writer = csv.DictWriter(f, delimiter='\t',fieldnames=['da...
bikeshares.ipynb
bikeviz/bikeviz.github.io
apache-2.0
Thanks to the "%%javascript" magic word, we can embed JavaScript right into the cells! First thing we want to do is import d3js into the notebook.
%%javascript require.config({ paths: { d3: "http://d3js.org/d3.v3.min" } }); require(["d3"], function(d3) { console.log(d3.version); });
bikeshares.ipynb
bikeviz/bikeviz.github.io
apache-2.0
The "%%html" magic word allows us to style our HTML and SVG that we are about to create. Running this cell after the HTML and SVG is created will change the styling to match any changes made to the cell. It can also be run before running the HTML and SVG to predefine styles.
%%html <style> rect.bordered { stroke: #E6E6E6; stroke-width:2px; } text.mono { font-size: 9pt; font-family: Consolas, courier; fill: #aaa; } text.axis-workweek { fill: #000; } text.axis-worktime { fill: #000; } body { font-size: 9pt; font-family: Consolas, couri...
bikeshares.ipynb
bikeviz/bikeviz.github.io
apache-2.0
With our styles in place, we have to define our div elements so that d3 can populate them. The code to do that is located below these images, as once again, running a cell in a notebook can apply changes retroactively. Unforutnately, due to security reasons, iPython does not allow arbitrary execution of JavaScript code...
%%html One-way trip in DC <div id="dccommuter"></div> Round trip in DC <div id="dcleisure"></div> One-way trip in NYC <div id="nyccommuter"></div> Round trip in NYC <div id="nycleisure"></div> %%javascript //$(document).ready(function(){ draw_heatmap("./data/dc_round_trips.tsv", "#dccommuter"); draw_heatmap("./data/...
bikeshares.ipynb
bikeviz/bikeviz.github.io
apache-2.0
The documentation page https://reboundx.readthedocs.io/en/latest/effects.html lists the various required and optional parameters that need to be set for each effect in REBOUNDx. Adding these parameters to particles, forces and operators is easy. We do it through the params attribute:
ps[1].params['primary'] = 1 gr.params['c'] = 3.e8
ipython_examples/GettingStartedParameters.ipynb
hannorein/reboundx
gpl-3.0
We would now sim.integrate as usual. If we want, we can access these values later (e.g., some effects could update these values as the simulation progresses). Here they don't:
sim.integrate(10.) gr.params['c']
ipython_examples/GettingStartedParameters.ipynb
hannorein/reboundx
gpl-3.0
Details For simples types (ints and floats), assigning variables to parameters makes a copy of the value. For example:
speed = 5 gr.params['c'] = speed
ipython_examples/GettingStartedParameters.ipynb
hannorein/reboundx
gpl-3.0
If we now update speed, this will not be reflected in our 'c' parameter:
speed = 10 gr.params['c']
ipython_examples/GettingStartedParameters.ipynb
hannorein/reboundx
gpl-3.0
More complicated objects are assigned as pointers. For example, adding REBOUNDx structures like forces works out of the box. As a simple example (with no meaning whatsoever):
ps[1].params['force'] = gr
ipython_examples/GettingStartedParameters.ipynb
hannorein/reboundx
gpl-3.0
Now if we update gr, the changes will be reflected in the 'force' parameter:
gr.params['c'] = 10 newgr = ps[1].params['force'] newgr.params['c']
ipython_examples/GettingStartedParameters.ipynb
hannorein/reboundx
gpl-3.0
If the parameter doesn't exist REBOUNDx will raise an exception, which we can catch and handle however we want
try: waterfrac = ps[1].params['waterfrac'] except: print('No water on this planet')
ipython_examples/GettingStartedParameters.ipynb
hannorein/reboundx
gpl-3.0
Adding Your Own Parameters In order to go back and forth between Python and C, REBOUNDx keeps a list of registered parameter names with their corresponding types. This list is compiled from all the parameters used by the various forces and operators in REBOUNDx listed here: https://reboundx.readthedocs.io/en/latest/eff...
try: gr.params['q'] = 7 except AttributeError as e: print(e)
ipython_examples/GettingStartedParameters.ipynb
hannorein/reboundx
gpl-3.0
You can register the name permanently on the C side, but can also do it from Python. You must pass a name along with one of the C types:
from reboundx.extras import REBX_C_PARAM_TYPES REBX_C_PARAM_TYPES
ipython_examples/GettingStartedParameters.ipynb
hannorein/reboundx
gpl-3.0
For example, say we want a double:
rebx.register_param("q", "REBX_TYPE_DOUBLE") gr.params['q'] = 7 gr.params['q']
ipython_examples/GettingStartedParameters.ipynb
hannorein/reboundx
gpl-3.0
Custom Parameters You can also add your own more complicated custom types (for example from another library) straightfowardly, with a couple caveats. First, the object must be wrapped as a ctypes object in order to communicate with the REBOUNDx C library, e.g.
from ctypes import * class SPH_sim(Structure): _fields_ = [("dt", c_double), ("Nparticles", c_int)] my_sph_sim = SPH_sim() my_sph_sim.dt = 0.1 my_sph_sim.Nparticles = 10000
ipython_examples/GettingStartedParameters.ipynb
hannorein/reboundx
gpl-3.0
We also have to register it as a generic POINTER:
rebx.register_param("sph", "REBX_TYPE_POINTER") gr.params['sph'] = my_sph_sim
ipython_examples/GettingStartedParameters.ipynb
hannorein/reboundx
gpl-3.0
Now when we get the parameter, REBOUNDx does not know how to cast it. You get a ctypes.c_void_p object back, which you have to manually cast to the Structure class we've created. See the ctypes library documentation for details:
mysph = gr.params['sph'] mysph = cast(mysph, POINTER(SPH_sim)).contents mysph.dt
ipython_examples/GettingStartedParameters.ipynb
hannorein/reboundx
gpl-3.0
Define a function that returns a slice as a Plotly Surface:
def get_the_slice(x,y,z, surfacecolor): return go.Surface(x=x, y=y, z=z, surfacecolor=surfacecolor, coloraxis='coloraxis') def get_lims_colors(surfacecolor):# color limits for a slice return np.min(surfacecolor), np.max(sur...
Plotly-Slice-in-volumetric-data.ipynb
empet/Plotly-plots
gpl-3.0
Let us plot the slices z=0 and y=-0.5 in the volume defined by:
scalar_f = lambda x,y,z: x*np.exp(-x**2-y**2-z**2) x = np.linspace(-2,2, 50) y = np.linspace(-2,2, 50) x, y = np.meshgrid(x,y) z = np.zeros(x.shape) surfcolor_z = scalar_f(x,y,z) sminz, smaxz = get_lims_colors(surfcolor_z) slice_z = get_the_slice(x, y, z, surfcolor_z) x = np.linspace(-2,2, 50) z = np.linspace(-2,2, ...
Plotly-Slice-in-volumetric-data.ipynb
empet/Plotly-plots
gpl-3.0
In order to be able to compare the two slices, we choose a unique interval of values to be mapped to the colorscale:
def colorax(vmin, vmax): return dict(cmin=vmin, cmax=vmax) fig1 = go.Figure(data=[slice_z, slice_y]) fig1.update_layout( title_text='Slices in volumetric data', title_x=0.5, width=700, height=700, scene_zaxis_range=[-2,2], coloraxis=dict(color...
Plotly-Slice-in-volumetric-data.ipynb
empet/Plotly-plots
gpl-3.0
Oblique slice in volumetric data As an example we plot comparatively two slices: a slice through $z=0$ and an oblique planar slice, that is defined by rotating the plane z=0 by $\alpha=\pi/4$, about Oy. Rotating the plane $z=c$ about Oy (from Oz towards Ox) with $\alpha$ radians we get the plane of equation $z=c/\cos(\...
alpha = np.pi/4 x = np.linspace(-2, 2, 50) y = np.linspace(-2, 2, 50) x, y = np.meshgrid(x,y) z = -x * np.tan(alpha) surfcolor_obl = scalar_f(x,y,z) smino, smaxo = get_lims_colors(surfcolor_obl) vmin = min([sminz, smino]) vmax = max([smaxz, smaxo]) slice_obl = get_the_slice(x,y,z, surfcolor_obl) fig2 = go.Figure(d...
Plotly-Slice-in-volumetric-data.ipynb
empet/Plotly-plots
gpl-3.0
Load Iris dataset The Iris Dataset here. This data sets consists of 3 different types of irises’ (Setosa, Versicolour, and Virginica) petal and sepal length, stored in a 150x4 numpy.ndarray. The rows being the samples and the columns being: Sepal Length, Sepal Width, Petal Length and Petal Width.
iris = datasets.load_iris() X = pd.DataFrame(iris.data, columns=iris.feature_names) y = pd.Series(iris.target, name='FlowerType') X.head() plt.figure(2, figsize=(8, 6)) plt.clf() # Plot the training points plt.scatter(X['sepal length (cm)'], X['sepal width (cm)'], s=35, c=y, cmap=plt.cm.brg) plt.xlabel('Sepal length'...
course/class1/pca/iris/PCA - Iris dataset.ipynb
hershaw/data-science-101
mit
PCA Can we reduce the dimensionality of our dataset withour losing much information? PCA will help us decide.
pca_iris = PCA(n_components=3).fit(iris.data) pca_iris.explained_variance_ratio_ pca_iris.transform(iris.data)
course/class1/pca/iris/PCA - Iris dataset.ipynb
hershaw/data-science-101
mit
The P.C. #0 explained variance is one order of magnitude higher than P.C. #1 and #2, and two orders of magnitude higher than P.C. #3. We can us use this knowledge to reduce our dataset from 4D to 3D. We could have done everything in one line by setting the number of components we want (3), fitting the PCA and transform...
iris_reduced = PCA(n_components=3).fit(iris.data) iris_reduced.components_ iris_reduced = PCA(n_components=3).fit_transform(iris.data) fig = plt.figure(1, figsize=(8, 6)) ax = Axes3D(fig, elev=-150, azim=110) X_reduced = PCA(n_components=3).fit_transform(iris.data) ax.scatter(iris_reduced[:, 0], iris_reduced[:, 1], ...
course/class1/pca/iris/PCA - Iris dataset.ipynb
hershaw/data-science-101
mit
Let's bring up our slippy map once again.
# Basemap Mosaic (v1 API) mosaicsSeries = 'global_quarterly_2017q1_mosaic' # Planet tile server base URL (Planet Explorer Mosaics Tiles) mosaicsTilesURL_base = 'https://tiles0.planet.com/experimental/mosaics/planet-tiles/' + mosaicsSeries + '/gmap/{z}/{x}/{y}.png' # Planet tile server url mosaicsTilesURL = mosaicsTiles...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Let's review from last time. We'll query the Planet API and get a list of scenes. We'll then use pandas and shapely to clean up and filter the results We'll then render the footprints of the good scenes over our AOI
print AOIs[1] myAOI = AOIs[1]["geometry"] # build a query using the AOI and # a cloud_cover filter that excludes 'cloud free' scenes old = datetime.datetime(year=2017,month=1,day=1) query = filters.and_filter( filters.geom_filter(myAOI), filters.range_filter('cloud_cover', lt=5), filters.date_range('acqu...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Now we'll add in our boiler plate activation code for reference.
def get_products(client, scene_id, asset_type='PSScene3Band'): """ Ask the client to return the available products for a given scene and asset type. Returns a list of product strings """ out = client.get_assets_by_id(asset_type,scene_id) temp = out.get() return temp.keys() def act...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Now we'll activate our scenes
to_get = scenes["id"][0:7].tolist() activated = [] # for each scene to get for scene in to_get: # get the product product_types = get_products(client,scene) for p in product_types: # if there is a visual product if p == "visual": # p == "basic_analytic_dn" print "Activating {0} ...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
And then download them.
tiff_files = [] asset_type = "_3B_Visual" # check if our scenes have been activated if True:#scenes_are_active(activated): for to_download,name in zip(activated,to_get): # create the product name name = name + asset_type + ".tif" # if the product exists locally if( os.path.isfile(nam...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Let's get going with Open Street Maps. Open Street Maps is a huge and open collection of data about the Earth. OSM is free to query. The interfaces are powerful, but hella cryptic. Let's say we had a pixel in an image and we wanted to know what in the world was at that pixel. We can use the Open Street Maps Nominat...
infile = tiff_files[0] # Open the file gtif = gdal.Open(infile) # Get the project reference object this knows the UTM zone reff = gtif.GetProjectionRef() # arr is the actual image data. arr = gtif.ReadAsArray() # Trans is our geo transfrom array. trans = gtif.GetGeoTransform() # print the ref object print reff # find ...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Now we are going to write a function to convert pixels to UTM Also a quick function to plot a point
def pixel2utm(ds, x, y): """ Returns utm coordinates from pixel x, y coords """ xoff, a, b, yoff, d, e = ds.GetGeoTransform() xp = a * x + b * y + xoff yp = d * x + e * y + yoff return(xp, yp) def draw_point(x,y,img): t = 20 # a cloud_cover filter that ex img[y-t:y+t,x-t:x+t,:] ...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Now let's query a point on our scene and see what OSM tells us. First we'll define a pixel position We'll use GDAL to open the scene and then map a pixel to UTM We'll then convert the UTM value to Lat / Lon using the UTM region we found before. Then we'll instantiate a Nominatim object and perform a revers lookup and...
pos = [3000,1400] # this is the pixel we want info abou ds = gdal.Open(infile) # take the GDAL info and make it into UTM my_utm = pixel2utm(ds,pos[0],pos[1]) # convert UTM into Lat Long # need to figure out how to get zone info my_lla = utm.to_latlon(my_utm[0],my_utm[1],10,"N") # do the lat long look up from OSM geoloc...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Now for completeness we'll plot our scene and add the annotation about the spot we found.
from matplotlib.patches import Circle fig,ax = plt.subplots(1) # create our plot plt.imshow(arr[:3,:,:].transpose((1, 2, 0)))#, extent=extent) fig = plt.gcf() # add our annotation plt.annotate(location.address, xy=pos, xycoords='data', xytext=(0.25, 0.5), textcoords='figure fraction',color="red", ...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Now, well, OSM is hard. This is I wanted to show where to programaticaly query OSM for all sorts of data. Turns out that it is a lot harder than it should be, especially if you want to work with GeoJson. Out of scope for this talk, but let's punt. OSM has a feature called Overpass. It is like the most convoluted Googl...
import geopandas as gpd fname = "./portland_parks_small.geojson" park_df = gpd.read_file(fname) portland_parks = json.load(open(fname,'r')) # raw geojson works better with GDAL geojson = [p for p in portland_parks["features"]] # no area out of the box p = [p.area for p in park_df["geometry"].tolist()] park_df["area"] =...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Now we'll update our slippy map. Just toss the aois in, just like our scene footprints.
for p in portland_parks["features"]: feat = {'geometry':p["geometry"],"properties":{ 'style':{'color': "#00FF00",'fillColor': "#00FF00",'fillOpacity': 0.0,'weight': 1}}, 'type':u"Feature"} # convert to geojson gjson = GeoJSON(data=feat) # add it our map m.add_layer(gjson) m
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Now let's find the big parks. The pandas dataframe can have multiple enteries per park. We can use the group by command to sum up these disparate areas. Finally we'll output the results
park_sz = park_df.groupby("name").sum() park_sz = park_sz.sort_values(by='area',ascending=[0]) display(park_sz)
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Now to the meat of the problem. Our goal is to get each park as a small image so we can analyze it. We'll write a function to create a geojson file from our big geojson file We'll also write a function that takes in our scene list, an input geojson file, and calls gdal warp to generate our small park image.
def write_geojson_by_name(df,name,outfile): """ Take in a dataframe, a park name, and an output file name Save the park's geojson to the specified file. """ temp = df[df["name"]==name] to_write = {"type": "FeatureCollection", "features": temp["geojson"].tolist()} with open(o...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Let's put it all together We're going to use the scenes we downloaded earlier as our input and build a little image for every park in Portland! We just have to make a few file names and call the functions above. If we really wanted to get fancy we could do this for every image that has our park and make a sick movie o...
geo_json_files = [] tif_file_names = [] unique_park_names = list(set(park_df["name"].tolist())) for name in list(unique_park_names): # Generate our file names geojson_name = "./parks/"+name.replace(" ","_")+".geojson" tif_name = "./parks/"+name.replace(" ","_")+".tif" # write geojson write_geojson_...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Let's take a look at the first few parks! matplotlib and tifs can be a bit heavy handed. imma teach you a protip use image magick and the built in image display. Use subprocess to tell imagemagick to convert tifs to jpg. Then load and display the images. WARNING: do not use imagemagick to modify geotiffs!
magic = ["mogrify","-format", "jpg", "./parks/*.tif"] subprocess.call(magic) for p in tif_file_names[0:20]: print p display(Image(p.replace('tif','jpg')))
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Not let's do some quick analytics -- your code goes here. For completeness let's do some basic image processing. For each of parks we are going to calculate the average "greeness" per pixel over the other two channels. We do this as it controls for white pixels, like clouds. Since there are black pixels we'll have to ...
def load_image3(filename): """Return a 3D (r, g, b) numpy array with the data in the specified TIFF filename.""" path = os.path.abspath(os.path.join('./', filename)) if os.path.exists(path): with rasterio.open(path) as src: b,g,r,mask = src.read() return np.dstack([b, g, r]) ...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Let's take a look at what this looks like in terms of images.
imgs = [p[0] for p in paired] for p in imgs[0:35]: print p[8:-4].replace("_"," ") display(Image(p.replace('tif','jpg')))
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Now let's plot over our slippy map. We'll calculate a non-linear opacity per park and then use that for plotting.
opacity_map = {} gmax = np.max(greens) gmin = np.min(greens) # this is a nonlinear mapping opacity = [np.clip((float(g**2)-gmin)/float(gmax-gmin),0,1) for g in greens] for op,name in zip(opacity,imgs): opacity_map[name]=op m = Map( center=center, zoom=zoom, default_tiles = planetMapTiles # Uncomment t...
OpenStreetMapsExample.ipynb
kscottz/PythonFromSpace
bsd-3-clause
Using constant number of data clusters (Ndata = 20) Cover all policy Load the data
# Data to use Ndata = 10000 Nside = 30 # First we load the file file_location = '../results_database/text_wall_street_columns_30_Ndata20.hdf5' # Now we need to get the letters and align them text_directory = '../data/wall_street_letters_30.npy' letters_sequence = np.load(text_directory) Nletters = len(letters_sequen...
presentations/2016-03-13(Nexa Wall Street Columns High Resolution - Next Letter Prediction).ipynb
h-mayorquin/time_series_basic
bsd-3-clause
Do the loop
# Calculate the predictions scores_mixed = [] scores_indp = [] max_lags = np.arange(2, 17, 2) # Nexa parameters Ntime_clusters = 20 Nembedding = 3 for max_lag in max_lags: print(max_lag) Nspatial_clusters = max_lag # Here calculate the scores for the mixes run_name = '/test' + str(max_lag)...
presentations/2016-03-13(Nexa Wall Street Columns High Resolution - Next Letter Prediction).ipynb
h-mayorquin/time_series_basic
bsd-3-clause
Cover Exclusively Policy Load data
# Data to use Ndata = 10000 Nside = 30 # Calculate the predictions scores_mixed = [] scores_indp = [] max_lags = np.arange(2, 17, 2) # Nexa parameters Nembedding = 3 Ntime_clusters = 20 # First we load the file file_location = '../results_database/text_wall_street_columns_30_Ndata20.hdf5' # Now we need to g...
presentations/2016-03-13(Nexa Wall Street Columns High Resolution - Next Letter Prediction).ipynb
h-mayorquin/time_series_basic
bsd-3-clause
Do the Loop and Calculate the Predictions
for max_lag in max_lags: targets = [] aux = Nside - max_lag for index in range(Ndata): letter_index = index // aux targets.append(letters_sequence[letter_index + 1]) # Transform to array targets = np.array(targets) print(max_lag) Nspatial_clusters =...
presentations/2016-03-13(Nexa Wall Street Columns High Resolution - Next Letter Prediction).ipynb
h-mayorquin/time_series_basic
bsd-3-clause
Using constant number of features Cover all policy Load the data
# Data to use Ndata = 10000 Nside = 30 # First we load the file file_location = '../results_database/text_wall_street_columns_30_semi_constantNdata.hdf5' # Now we need to get the letters and align them text_directory = '../data/wall_street_letters_30.npy' letters_sequence = np.load(text_directory) Nletters = len(let...
presentations/2016-03-13(Nexa Wall Street Columns High Resolution - Next Letter Prediction).ipynb
h-mayorquin/time_series_basic
bsd-3-clause
Do the loop
# Calculate the predictions scores_mixed = [] scores_indp = [] max_lags = np.arange(2, 17, 2) # Nexa parameters Ntime_clusters = 20 Nembedding = 3 for max_lag in max_lags: print(max_lag) Nspatial_clusters = max_lag Ntime_clusters = 60 // max_lag # Here calculate the scores for the mix...
presentations/2016-03-13(Nexa Wall Street Columns High Resolution - Next Letter Prediction).ipynb
h-mayorquin/time_series_basic
bsd-3-clause
Cover Exclusively Policy Load the Data
# Data to use Ndata = 10000 Nside = 30 # Calculate the predictions scores_mixed = [] scores_indp = [] max_lags = np.arange(2, 17, 2) # Nexa parameters Ntime_clusters = 20 Nembedding = 3 # First we load the file file_location = '../results_database/text_wall_street_columns_30_semi_constantNdata.hdf5' # Now w...
presentations/2016-03-13(Nexa Wall Street Columns High Resolution - Next Letter Prediction).ipynb
h-mayorquin/time_series_basic
bsd-3-clause
Do the Loop
for max_lag in max_lags: targets = [] aux = Nside - max_lag #Take the corresponding letters for index in range(Ndata): letter_index = index // aux targets.append(letters_sequence[letter_index + 1]) # Transform to array targets = np.array(targets) ...
presentations/2016-03-13(Nexa Wall Street Columns High Resolution - Next Letter Prediction).ipynb
h-mayorquin/time_series_basic
bsd-3-clause
Notebook arguments sigma (float): standard deviation of additive Gaussian noise to be simulated time_window (float): seconds, integration window duration time_step (float): seconds, time step for the moving integration window time_start (float): seconds, start of time axis (kinetics starts at t = t0). time_stop (float...
%matplotlib inline import numpy as np import lmfit import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import models # custom module
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
Fitting models Models used to fit the data. 1. Simple Exponential In this model, we define the model function as an exponential transient: $$ y = f(t) = A \cdot e^{-t/\tau} + K$$ The python function implementing it is: models.exp_func(). Next cell defines and initializes the fitting model (lmfit.model.Model) includin...
labels = ('tau', 'init_value', 'final_value') model = models.factory_model_exp(t0_vary=True)
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
2. Integrated Exponential A more realistic model needs to take into account that each data point is the result of an integration over a time window $w$: $$f(t) = A \cdot e^{-t/\tau} + K$$ $$y(t) = \int_{t}^{t+w} f(t')\;dt'$$ In other words, when we process a measurement in time chunks, we are integrating a non-station...
modelw = models.factory_model_expwin(t_window=time_window, decimation=decimation, t0_vary=t0_vary)
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
Generative model These are the models used to generate the simulates (noisy) data. 1. Simple Exponential + Noise In this simple model, we simulate random data $Y$ as an exponential decay plus additive Gaussian noise: $$ Y(t_k) = f(t_k) + N_k $$ $$ {N_k} \sim {\rm Normal}{\mu=0; \sigma}$$ $$ \Delta t = t_k - t_{k-1} = \...
t = np.arange(time_start, time_stop-time_window, time_step).astype(float) t.size
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
An ideal transient (no noise, no integration):
y = models.expwindec_func(t, t_window=time_window, **true_params) y.shape
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
A simulated transient (including noise + integration):
time_window, time_step yr = models.expwindec_func(t, t_window=time_window, sigma=sigma, **true_params) yr.shape
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
Plot the computed curves:
plt.plot(t, y, '-', label='model') plt.plot(t, yr, 'o', label='model + noise')
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
Fit data Fit the "Integrated Exponential" model:
#%%timeit resw = modelw.fit(yr, t=t, tau=10, init_value=0.1, final_value=0.9, verbose=False)
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
Fit the "Simple Exponential" model:
#%%timeit res = model.fit(yr, t=t + 0.5*time_window, tau=10, init_value=0.1, final_value=0.9, verbose=False)
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
Print and plot fit results:
fig = plt.figure(figsize=(14, 8)) res.plot(fig=fig) ci = lmfit.conf_interval(res, res) lmfit.report_fit(res) print(lmfit.ci_report(ci, with_offset=False)) #plt.xlim(-300, 300) fig = plt.figure(figsize=(14, 8)) resw.plot(fig=fig) ci = lmfit.conf_interval(resw, resw) lmfit.report_fit(resw) print(lmfit.ci_report(ci, with...
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
Monte-Carlo Simulation Here, fixed the model paramenters, we generate and fit several noisy datasets. Then, by plotting the distribution of the fitted parameters, we assess the stability and accuracy of the fit. Parameters The number simulation cycles is defined by num_sim_cycles. Current value is:
num_sim_cycles
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
The fixed kinetic curve parameters are:
{k: v for k, v in true_params.items() if k is not "tau"}
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
While tau is varied, taking the following values:
taus t0_vary
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
<div class="alert alert-info"> **NOTE**: All previous parameters are defined in the first notebook cell. </div> Functions Here we define two functions: draw_samples_and_fit() draws a set of data and fits it with both models monte_carlo_sim() run the Monte-Carlo simulation: calls draw_samples_and_fit() many times....
def draw_samples_and_fit(true_params): # Create the data t = np.arange(time_start, time_stop-time_window, time_step).astype(float) yr = models.expwindec_func(t, t_window=time_window, sigma=sigma, decimation=100, **true_params) # Fit the model tc = t + 0.5*time_window kws = dict(fit_kws=dict(nan...
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
Run Monte-Carlo simulation Run the Monte-Carlo fit for a set of different time-constants (taus) and save results in two DataFrames, one for each model.
mc_results1, mc_results2 = [], [] %%timeit -n1 -r1 # <-- prints execution time for tau in taus: true_params['tau'] = tau df1, df2 = monte_carlo_sim(true_params, num_sim_cycles) mc_results1.append(df1) mc_results2.append(df2)
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
<div class="alert alert-danger"> **WARNING**: The previous cell can take a long to execute. Execution time scales with **`num_sim_cycles * len(taus)`**. </div> Results1 - Simple Exponential
for tau, df in zip(taus, mc_results1): true_params['tau'] = tau fig, ax = plt.subplots(1, 3, figsize=(16, 4)) for i, var in enumerate(labels): std = df[var].std() df[var].hist(bins=30, ax=ax[i]) ax[i].set_title("%s = %.1f (%.3f)" % (var, true_params[var], std), fontsize=18) a...
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
Results2 - Integrated Exponential
for tau, df in zip(taus, mc_results2): true_params['tau'] = tau fig, ax = plt.subplots(1, 3, figsize=(16, 4)) for i, var in enumerate(labels): std = df[var].std() df[var].hist(bins=30, ax=ax[i]) ax[i].set_title("%s = %.1f (%.3f)" % (var, true_params[var], std), fontsize=18) a...
realtime kinetics/Simulated Kinetic Curve Fit - Template.ipynb
tritemio/multispot_paper
mit
Extracting features from the tweets 1) Tokenize the tweet in a list of words This part uses concepts from Naltural Langage Processing. We will use a tweet tokenizer I built based on TweetTokenizer from NLTK (http://www.nltk.org/). You can see how it works by opening the file TwSentiment.py. The goal is to process any t...
from TwSentiment import CustomTweetTokenizer tokenizer = CustomTweetTokenizer(preserve_case=False, # keep Upper cases reduce_len=True, # reduce repetition of letter to a maximum of three strip_handles=False, # remove usernames (@mentions) ...
04_Twitter_Sentiment_Analysis.ipynb
SchwaZhao/networkproject1
mit
2) Define the features that will represent the tweet We will use the occurrence of words and pair of words (bigrams) as features. This corresponds to a bag-of-words representation (https://en.wikipedia.org/wiki/Bag-of-words_model): we just count each words (or n-grams) without taking account their order. For document c...
from TwSentiment import bag_of_words_and_bigrams # this will return a dictionary of features, # we just list the features present in this tweet bag_of_words_and_bigrams(tokenizer.tokenize(tweet_df.text.iloc[0]))
04_Twitter_Sentiment_Analysis.ipynb
SchwaZhao/networkproject1
mit
Download the logistic regression classifier https://www.dropbox.com/s/09rw6a85f7ezk31/sklearn_SGDLogReg_.pickle.zip?dl=1 I trained this classifier on this dataset: http://help.sentiment140.com/for-students/, following the approach from this paper: http://cs.stanford.edu/people/alecmgo/papers/TwitterDistantSupervision09...
# the classifier is saved in a "pickle" file import pickle with open('sklearn_SGDLogReg_.pickle', 'rb') as fopen: classifier_dict = pickle.load(fopen) # classifier_dict contain the classifier and label mappers # that I added so that we remember how the classes are # encoded classifier_dict
04_Twitter_Sentiment_Analysis.ipynb
SchwaZhao/networkproject1
mit
The classifier is in fact contained in a pipeline. A sklearn pipeline allows to assemble several transformation of your data (http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html)
pipline = classifier_dict['sklearn_pipeline']
04_Twitter_Sentiment_Analysis.ipynb
SchwaZhao/networkproject1
mit
In our case we have two steps: Vectorize the textual features (using http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.DictVectorizer.html) Classify the vectorized features (using http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html)
pipline.steps # this the step that will transform a list of textual features to a vector of zeros and ones dict_vect = pipline.steps[0][1] dict_vect.feature_names_ # number of features len(dict_vect.feature_names_) # a little example text = 'Hi all, I am very happy today' # first tokenize tokens = tokenizer.tokeniz...
04_Twitter_Sentiment_Analysis.ipynb
SchwaZhao/networkproject1
mit
The mapping between the list of features and the vector of zeros and ones is done when you train the pipeline with its .fit method. Classifing the tweet Now that we have vector representing the presence of features in a tweet, we can apply our logistic regression classifier to compute the probability that a tweet belon...
classifier = pipline.steps[1][1] classifier # access the weights of the logistic regression classifier.coef_ # we have as many weights as features classifier.coef_.shape # plus the intrecept classifier.intercept_ # let's check the weight associated with a given feature x = dict_vect.transform({'bad': True}) _, in...
04_Twitter_Sentiment_Analysis.ipynb
SchwaZhao/networkproject1
mit
Using the sklearn pipeline to group the two last steps:
pipline.predict_proba(features)
04_Twitter_Sentiment_Analysis.ipynb
SchwaZhao/networkproject1
mit
We see to numbers, the first one is the probability of the tweet being sad, the second one is the probability of the tweet being happy.
# note that: pipline.predict_proba(features).sum()
04_Twitter_Sentiment_Analysis.ipynb
SchwaZhao/networkproject1
mit
Putting it all together: We will use the class TweetClassifier from TwSentiment.py that puts together this process for us:
from TwSentiment import TweetClassifier twClassifier = TweetClassifier(pipline, tokenizer=tokenizer, feature_extractor=bag_of_words_and_bigrams) # example text = 'Hi all, I am very happy today' twClassifier.classify_text(text) # the classify text method als...
04_Twitter_Sentiment_Analysis.ipynb
SchwaZhao/networkproject1
mit
We can now classify our tweets:
emo_clas, prob = twClassifier.classify_text(tweet_df.text.tolist()) # add the result to the dataframe tweet_df['pos_class'] = (emo_clas == 'pos') tweet_df['pos_prob'] = prob[:,1] tweet_df.head() # plot the distribution of probability import matplotlib.pyplot as plt %matplotlib inline h = plt.hist(tweet_df.pos_prob...
04_Twitter_Sentiment_Analysis.ipynb
SchwaZhao/networkproject1
mit
We want to classify users based on the class of their tweets. Pandas allows to easily group tweets per users using the groupy method of DataFrames:
user_group = tweet_df.groupby('user_id') print(type(user_group)) # let's look at one of the group groups = user_group.groups uid = list(groups.keys())[5] user_group.get_group(uid) # we need to make a function that takes the dataframe of tweets grouped by users and return the class of the users def get_user_emo(group...
04_Twitter_Sentiment_Analysis.ipynb
SchwaZhao/networkproject1
mit
Let's add this information to the graph we created earlier
import networkx as nx G = nx.read_graphml('twitter_lcc_AI2.graphml', node_type=int) for n in G.nodes_iter(): if n in user_df.index: # here we look at the value of the user_df series at the position where the index # is equal to the user_id of the node G.node[n]['emotion'] = user_df.loc[us...
04_Twitter_Sentiment_Analysis.ipynb
SchwaZhao/networkproject1
mit
Creating a training dataset The training dataset simply consists of a bunch of words separated by spaces extracted from your documents. The words are simply in the order that they appear in the documents and words from successive documents are simply appended together. In other words, there is not "document separator"....
import google.datalab.bigquery as bq query=""" SELECT CONCAT( LOWER(REGEXP_REPLACE(title, '[^a-zA-Z $-]', ' ')), " ", LOWER(REGEXP_REPLACE(text, '[^a-zA-Z $-]', ' '))) AS text FROM `bigquery-public-data.hacker_news.stories` WHERE LENGTH(title) > 100 AND LENGTH(text) > 100 """ df = bq.Query(query).execut...
courses/machine_learning/deepdive/09_sequence_keras/word2vec.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
This is what the resulting file looks like:
!cut -c-1000 word2vec/words.txt
courses/machine_learning/deepdive/09_sequence_keras/word2vec.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Running word2vec We can run the existing tutorial code as-is.
%%bash cd word2vec TF_CFLAGS=( $(python -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_compile_flags()))') ) TF_LFLAGS=( $(python -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_link_flags()))') ) g++ -std=c++11 \ -shared word2vec_ops.cc word2vec_kernels.cc \ -o word2vec_ops.so -fPIC ${TF...
courses/machine_learning/deepdive/09_sequence_keras/word2vec.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
The actual evaluation dataset doesn't matter. Let's just make sure to have some words in the input also in the eval. The analogy dataset is of the form <pre> Athens Greece Cairo Egypt Baghdad Iraq Beijing China </pre> i.e. four words per line where the model is supposed to predict the fourth given the first three. Bu...
%%writefile word2vec/junk.txt : analogy-questions-ignored the user plays several levels of the game puzzle vote down the negative %%bash cd word2vec rm -rf trained python word2vec.py \ --train_data=./words.txt --eval_data=./junk.txt --save_path=./trained \ --min_count=1 --embedding_size=10 --window_size=2
courses/machine_learning/deepdive/09_sequence_keras/word2vec.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Examine the created embedding Let's load up the embedding file in TensorBoard. Start up TensorBoard, switch to the "Projector" tab and then click on the button to "Load data". Load the vocab.txt that is in the output directory of the model.
from google.datalab.ml import TensorBoard TensorBoard().start('word2vec/trained')
courses/machine_learning/deepdive/09_sequence_keras/word2vec.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Here, for example, is the word "founders" in context -- it's near doing, creative, difficult, and fight, which sounds about right ... The numbers next to the words reflect the count -- we should try to get a large enough vocabulary that we can use --min_count=10 when training word2vec, but that would also take too lon...
for pid in TensorBoard.list()['pid']: TensorBoard().stop(pid) print('Stopped TensorBoard with pid {}'.format(pid))
courses/machine_learning/deepdive/09_sequence_keras/word2vec.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Export the embedding vectors into a text file Let's export the embedding into a text file, so that we can use it the way we used the Glove embeddings in txtcls2.ipynb. Notice that we have written out our vocabulary and vectors into two files. We just have to merge them now.
!wc word2vec/trained/*.txt !head -3 word2vec/trained/*.txt import pandas as pd vocab = pd.read_csv("word2vec/trained/vocab.txt", sep="\s+", header=None, names=('word', 'count')) vectors = pd.read_csv("word2vec/trained/vectors.txt", sep="\s+", header=None) vectors = pd.concat([vocab, vectors], axis=1) del vectors['cou...
courses/machine_learning/deepdive/09_sequence_keras/word2vec.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Training model with custom embedding Now, you can use this embedding file instead of the Glove embedding used in txtcls2.ipynb
%%bash gsutil cp word2vec/trained/embedding.txt.gz gs://${BUCKET}/txtcls2/custom_embedding.txt.gz %%bash OUTDIR=gs://${BUCKET}/txtcls2/trained_model JOBNAME=txtcls_$(date -u +%y%m%d_%H%M%S) echo $OUTDIR $REGION $JOBNAME gsutil -m rm -rf $OUTDIR gsutil cp txtcls1/trainer/*.py $OUTDIR gcloud ml-engine jobs submit traini...
courses/machine_learning/deepdive/09_sequence_keras/word2vec.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
I will define fredbuns to be a lock with four tumblers. For now, each tumbler will consist of not all ten letters, but only the two letters that spell "FRED BUNS":
fredbuns = ['FB', 'RU', 'EN', 'DS'] # A lock with two letters on each of four tumblers
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
We need a way to get the combinations that can be made from this lock. It turns out that the built-in function itertools.product does the job; it generates the product of all 2 &times; 2 &times; 2 &times; 2 = 16 combinations of letters:
list(itertools.product(*fredbuns))
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Note: product(*fredbuns) means to apply the function product to the list fredbuns; this is equivalent to itertools.product('FB', 'RU', 'EN', 'DS'). I would prefer to deal with the string 'BUNS' rather than the tuple ('B', 'U', 'N', 'S'), so I will define a function, combinations, that takes a lock as input and returns...
def combinations(lock): "Return a list of all combinations that can be made by this lock." return [cat(c) for c in itertools.product(*lock)] cat = ''.join # Function to concatenate strings together. combinations(fredbuns)
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Dictionary Words I happen to have handy a file of four-letter words (no, not that kind of four-letter word). It is the union of an official Scrabble&reg; word list and a list of proper names. The following shell command tests if the file has already been downloaded to our local directory and if not, fetches it from the...
! [ -e words4.txt ] || curl -O http://norvig.com/ngrams/words4.txt
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Here are the first few lines of the file:
! head words4.txt
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0