markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
We can use these to make vp and rho earth models. We can use NumPy’s fancy indexing by passing our array of indicies to access the rock properties (in this case acoustic impedance) for every element at once. | vp = vps[w]
rho = rhos[w] | docs/_userguide/_A_quick_wedge_model.ipynb | agile-geoscience/bruges | apache-2.0 |
Each of these new arrays is the shape of the model, but is filled with a rock property: | vp.shape
vp[:5, :5] | docs/_userguide/_A_quick_wedge_model.ipynb | agile-geoscience/bruges | apache-2.0 |
Now we can create the reflectivity profile: | rc = bg.reflection.acoustic_reflectivity(vp, rho) | docs/_userguide/_A_quick_wedge_model.ipynb | agile-geoscience/bruges | apache-2.0 |
Then make a wavelet and convolve it with the reflectivities: | ricker, _ = bg.filters.ricker(duration=0.064, dt=0.001, f=40)
syn = bg.filters.convolve(rc, ricker)
syn.shape | docs/_userguide/_A_quick_wedge_model.ipynb | agile-geoscience/bruges | apache-2.0 |
The easiest way to check everything worked is probably to plot it. | fig, axs = plt.subplots(figsize=(17, 4), ncols=5,
gridspec_kw={'width_ratios': (4, 4, 4, 1, 4)})
axs[0].imshow(w)
axs[0].set_title('Wedge model')
axs[1].imshow(vp * rho)
axs[1].set_title('Impedance')
axs[2].imshow(rc)
axs[2].set_title('Reflectivity')
axs[3].plot(ricker, np.arange(ricker.size))... | docs/_userguide/_A_quick_wedge_model.ipynb | agile-geoscience/bruges | apache-2.0 |
Alternative workflow
In the last example, we made an array of integers, then used indexing to place rock properties in the array, using the index as a sort of look-up.
But we could make the impedance model directly, passing rock properties in to the wedge() function via teh strat argument. It just depends how you want ... | vps = np.array([2320, 2350, 2350])
rhos = np.array([2650, 2600, 2620])
impedances = vps * rhos
w, top, base, ref = bg.models.wedge(strat=impedances) | docs/_userguide/_A_quick_wedge_model.ipynb | agile-geoscience/bruges | apache-2.0 |
Now the wedge contains rock properties, not integer labels.
Offset reflectivity
Let's make things more realistic by computing offset reflectivities, not just normal incidence (acoustic) reflectivity. We'll need Vs as well: | vps = np.array([2320, 2350, 2350])
vss = np.array([1150, 1250, 1200])
rhos = np.array([2650, 2600, 2620]) | docs/_userguide/_A_quick_wedge_model.ipynb | agile-geoscience/bruges | apache-2.0 |
We need the model with integers like 0, 1, 2 again: | w, top, base, ref = bg.models.wedge() | docs/_userguide/_A_quick_wedge_model.ipynb | agile-geoscience/bruges | apache-2.0 |
Index to get the property models: | vp = vps[w]
vs = vss[w]
rho = rhos[w] | docs/_userguide/_A_quick_wedge_model.ipynb | agile-geoscience/bruges | apache-2.0 |
Compute the reflectivity for angles up to 45 degrees: | rc = bg.reflection.reflectivity(vp, vs, rho, theta=range(46))
rc.shape | docs/_userguide/_A_quick_wedge_model.ipynb | agile-geoscience/bruges | apache-2.0 |
The result is three-dimensional: the angles are in the first dimension. So the zero-offset reflectivities are in w[0] and 30 degrees is at w[30].
Or, you can slice this cube in another orientation and see how reflectivity varies with angle: | plt.imshow(rc.real[:, :, 50].T) | docs/_userguide/_A_quick_wedge_model.ipynb | agile-geoscience/bruges | apache-2.0 |
init from dict and xrange index vs from somethign else
Timings | %%timeit
d = pd.DataFrame(columns=['A'], index=xrange(1000))
%%timeit
d = pd.DataFrame(columns=['A'], index=xrange(1000), dtype='float')
%%timeit
d = pd.DataFrame({'A': np.zeros(1000)}) | notebooks/#32-address-testing-findings/#32-isolated-profiling-2.ipynb | tesera/pygypsy | mit |
The problem here is that dataframe init being called 7000 times because of the aw ba factor finder
Maybe it's not worth using a data frame here. use a list or numpy and then convert to dataframe when the factor is found, e.g.: | %%timeit
for _ in xrange(5000):
d = pd.DataFrame(columns=['A'], index=xrange(1000))
%%timeit
for _ in xrange(5000):
d = np.zeros(1000) | notebooks/#32-address-testing-findings/#32-isolated-profiling-2.ipynb | tesera/pygypsy | mit |
Review the code to see how this can be applied
The numpy/purepython approach as potential
But there's a couple issues for which the code must be examined
The problem comes from the following call chain
simulate_forwards_df (called 1x) ->
get_factors_for_all_species (called 10x, 1x per plot) ->
BAfactorFinder_Aw (called... | d = pd.Series(np.random.randint(0,100, size=(100)), index=['%d' %d for d in xrange(100)])
%%timeit
d['1']
%%timeit
d.at('1')
%%timeit
d.loc('1') | notebooks/#32-address-testing-findings/#32-isolated-profiling-2.ipynb | tesera/pygypsy | mit |
loc or at are faster than [] indexing.
Revise the code
Go on. Do it.
Review code changes | %%bash
git log --since 2016-11-09 --oneline
! git diff HEAD~23 ../gypsy | notebooks/#32-address-testing-findings/#32-isolated-profiling-2.ipynb | tesera/pygypsy | mit |
Tests
Do tests still pass?
Run timings | %%bash
# git checkout dev
# time gypsy simulate ../private-data/prepped_random_sample_300.csv --output-dir tmp
# rm -rfd tmp
# real 8m18.753s
# user 8m8.980s
# sys 0m1.620s
%%bash
# after factoring dataframe out of zerotodata functions
# git checkout -b da080a79200f50d2dda7942c838b7f3cad845280 df-factored-out-zerotod... | notebooks/#32-address-testing-findings/#32-isolated-profiling-2.ipynb | tesera/pygypsy | mit |
Removing the data frame init gets a 25% time reduction | %%bash
# after using a faster indexing method for the arguments put into the apply functions
# git checkout 6b541d5fb8534d6fb055961a9d5b09e1946f0b46 -b applys-use-faster-getitem
# time gypsy simulate ../private-data/prepped_random_sample_300.csv --output-dir tmp
# rm -rfd tmp
# real 6m16.021s
# user 5m59.620s
# sys 0m... | notebooks/#32-address-testing-findings/#32-isolated-profiling-2.ipynb | tesera/pygypsy | mit |
Hm, this actually got worse, although it is a small sample......... if anything i suspect its because we're calling row.at[] instead of assigning the variable outside the loop. It's ok as the code has less reptition, it's a good tradeoff. | %%bash
# after fixing `.at` redundancy - calling it in each apply call
# git checkout 4c978aff110001efdc917ed60cb611139e1b54c9 -b remove-getitem-redundancy
# time gypsy simulate ../private-data/prepped_random_sample_300.csv --output-dir tmp
# rm -rfd tmp
# real 5m36.407s
# user 5m25.740s
# sys 0m2.140s | notebooks/#32-address-testing-findings/#32-isolated-profiling-2.ipynb | tesera/pygypsy | mit |
It doesn't totrally remove redundancy, we still get an attr/value of an object, but now its a dict instead of a pandas series. Hopefully it's faster. Should have tested first using MWE.
It is moderately faster. Not much.
Leave cython optimization for next iteration
Run profiling | from gypsy.forward_simulation import simulate_forwards_df
data = pd.read_csv('../private-data/prepped_random_sample_300.csv', index_col=0, nrows=10)
%%prun -D forward-sim-2.prof -T forward-sim-2.txt -q
result = simulate_forwards_df(data)
!head forward-sim-2.txt | notebooks/#32-address-testing-findings/#32-isolated-profiling-2.ipynb | tesera/pygypsy | mit |
Compare performance visualizations
Now use either of these commands to visualize the profiling
```
pyprof2calltree -k -i forward-sim-1.prof forward-sim-1.txt
or
dc run --service-ports snakeviz notebooks/forward-sim-1.prof
```
Old
New
Summary of performance improvements
forward_simulation is now 2x faster than last it... | ! rm -rfd gypsy-output
output_dir = 'gypsy-output'
%%prun -D forward-sim-2.prof -T forward-sim-2.txt -q
# restart the kernel first
data = pd.read_csv('../private-data/prepped_random_sample_300.csv', index_col=0, nrows=10)
result = simulate_forwards_df(data)
os.makedirs(output_dir)
for plot_id, df in result.items():
... | notebooks/#32-address-testing-findings/#32-isolated-profiling-2.ipynb | tesera/pygypsy | mit |
Plot this function over the range $x\in\left[-3,3\right]$ with $b=1.0$ and $a=5.0$: | a = 5.0
b = 1.0
v = []
x = np.linspace(-3,3,50)
for i in x:
v.append(hat(i,5.0,1.0))
plt.figure(figsize=(7,5))
plt.plot(x,v)
plt.tick_params(top=False,right=False,direction='out')
plt.xlabel('x')
plt.ylabel('V(x)')
plt.title('V(x) vs. x');
assert True # leave this to grade the plot | assignments/assignment11/OptimizationEx01.ipynb | bjshaw/phys202-2015-work | mit |
Write code that finds the two local minima of this function for $b=1.0$ and $a=5.0$.
Use scipy.optimize.minimize to find the minima. You will have to think carefully about how to get this function to find both minima.
Print the x values of the minima.
Plot the function as a blue line.
On the same axes, show the minima... | x1=opt.minimize(hat,-1.8,args=(5.0,1.0))['x']
x2=opt.minimize(hat,1.8,args=(5.0,1.0))['x']
print(x1,x2)
v = []
x = np.linspace(-3,3,50)
for i in x:
v.append(hat(i,5.0,1.0))
plt.figure(figsize=(7,5))
plt.plot(x,v)
plt.scatter(x1,hat(x1,5.0,1.0),color='r',label='Local Minima')
plt.scatter(x2,hat(x2,5.0,1.0),color='... | assignments/assignment11/OptimizationEx01.ipynb | bjshaw/phys202-2015-work | mit |
To check your numerical results, find the locations of the minima analytically. Show and describe the steps in your derivation using LaTeX equations. Evaluate the location of the minima using the above parameters.
To find the minima of the equation $V(x) = -a x^2 + b x^4$, we first have to find the $x$ values where the... | x_1 = np.sqrt(10/4)
x_2 = -np.sqrt(10/4)
print(x_1,x_2) | assignments/assignment11/OptimizationEx01.ipynb | bjshaw/phys202-2015-work | mit |
Extracting Data of Southwest states of the United states from 1992 - 2016.
The following query will extract data from the mongoDB instance and project only selected attributes such as structure number, yearBuilt, deck, year, superstructure, owner, countryCode, structure type, type of wearing surface, and subtructure. | def getData(state):
pipeline = [{"$match":{"$and":[{"year":{"$gt":1991, "$lt":2017}},{"stateCode":state}]}},
{"$project":{"_id":0,
"structureNumber":1,
"yearBuilt":1,
"yearReconstructed":1,
"deck":1, ## R... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Particularly in the area of determining a deterioration model of bridges, There is an observed sudden increase in condition ratings of bridges over the period of time, This sudden increase in the condition rating is attributed to the reconstruction of the bridges. NBI dataset contains an attribute to record this recons... |
def findSurvivalProbablities(conditionRatings):
i = 1
j = 2
probabilities = []
while j < 121:
v = list(conditionRatings.loc[conditionRatings['Age'] == i]['deck'])
k = list(conditionRatings.loc[conditionRatings['Age'] == i]['structureNumber'])
Age1 = {key:int(value) for key,... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
The following script will select all the bridges in the Southwest United States, filter missing and not required data. The script also provides information of how much of the data is being filtered. | states = ['48','40','35','04']
# Mapping state code to state abbreviation
stateNameDict = {'25':'MA',
'04':'AZ',
'08':'CO',
'38':'ND',
'09':'CT',
'19':'IA',
'26':'MI',
'48':'TX',
'35':'NM',
... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
In following figures, shows the cumulative distribution function of the probability of reconstruction over the bridges' lifespan, of bridges in the Southwest United States, as the bridges grow older the probability of reconstruction increases. | plt.figure(figsize=(12,8))
plt.title("CDF Probability of Reconstruction vs Age")
palette = [
'blue', 'green', 'magenta', 'cyan', 'brown', 'grey', 'red', 'silver', 'purple', 'gold', 'black','olive'
]
linestyles =[':','-.','--','-',':','-.','--','-',':','-.','--','-']
for num, state in enumerate(df_cumsum_prob_recon... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
The below figure presents CDF Probability of reconstruction, of bridge in the Southwest United States. | plt.figure(figsize = (16,12))
plt.xlabel('Age')
plt.ylabel('Mean')
# Initialize the figure
plt.style.use('seaborn-darkgrid')
# create a color palette
palette = [
'blue', 'blue', 'green', 'magenta', 'cyan', 'brown', 'grey', 'red', 'silver', 'purple', 'gold', 'black','olive'
]
# multiple line plot
num = 1
linestyl... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
A key observation in this investigation of several state reveals a constant number of bridges are reconstructed every year, this could be an effect of fixed budget allocated for reconstruction by the state. This also highlights the fact that not all bridges that might require reconstruction are reconstructed.
To Unders... | plt.figure(figsize = (16,12))
plt.xlabel('Age')
plt.ylabel('Mean')
# Initialize the figure
plt.style.use('seaborn-darkgrid')
# create a color palette
palette = [
'blue', 'blue', 'green', 'magenta', 'cyan', 'brown', 'grey', 'red', 'silver', 'purple', 'gold', 'black','olive'
]
# multiple line plot
num = 1
linesty... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Set the workspace loglevel to not print anything | wrk = op.Workspace()
wrk.loglevel=50 | PaperRecreations/Wu2010_part_a.ipynb | PMEAL/OpenPNM-Examples | mit |
Convert a grid from one format to another
We will start with a common simple task, converting a grid from one format to another. Geosoft supports many common geospatial grid formats which can all be openned as a geosoft.gxpy.grid.Grid instance. Different formats and characteristics are specified using grid decorations... | # open surfer grid
with gxgrid.Grid.open('elevation_surfer.grd(SRF;VER=V7)') as grid_surfer:
# copy the grid to an ER Mapper format grid file
with gxgrid.Grid.copy(grid_surfer, 'elevation.ers(ERM)', overwrite=True) as grid_erm:
print('file:', grid_erm.file_name,
'\ndecorated:', grid_erm.... | examples/jupyter_notebooks/Tutorials/Grids and Images.ipynb | GeosoftInc/gxpy | bsd-2-clause |
Working with Grid instances
You work with a grid using a geosoft.gxpy.grid.Grid instance, which is a spatial dataset sub-class of a geosoft.gxpy.geometry.Geometry. In Geosoft, all spatial objects are sub-classed from the Geometry class, and all Geometry instances have a coordinate system and spatial extents. Other spat... | # open surfer grid, then set to None to free resources
grid_surfer = gxgrid.Grid.open('elevation_surfer.grd(SRF;VER=V7)')
print(grid_surfer.name)
grid_surfer = None
# open surfer grid using with
with gxgrid.Grid.open('elevation_surfer.grd(SRF;VER=V7)') as grid_surfer:
print(grid_surfer.name) | examples/jupyter_notebooks/Tutorials/Grids and Images.ipynb | GeosoftInc/gxpy | bsd-2-clause |
Displaying a grid
One often needs to see what a grid looks like, and this is accomplished by displaying the grid as an image in which the colours represent data ranges. A simple way to do this is to create a grid image file as a png file ising the image_file() method.
In this example we create a shaded image with defau... | image_file = gxgrid.Grid.open('elevation_surfer.grd(SRF;VER=V7)').image_file(shade=True, pix_width=500)
Image(image_file) | examples/jupyter_notebooks/Tutorials/Grids and Images.ipynb | GeosoftInc/gxpy | bsd-2-clause |
A nicer image might include a neat-line outline, colour legend, scale bar and title. The gxgrid.figure_map() function will create a figure-style map, which can be saved to an image file using the image_file() method of the map instance. | image_file = gxgrid.figure_map('elevation_surfer.grd(SRF;VER=V7)', title='Elevation').image_file(pix_width=800)
Image(image_file) | examples/jupyter_notebooks/Tutorials/Grids and Images.ipynb | GeosoftInc/gxpy | bsd-2-clause |
Grid Coordinate System
In Geosoft all spatial data should have a defined coordinate system which allows data to be located on the Earth. This also takes advantage of Geosoft's ability to reproject data as required. However, in this example the Surfer grid does not store the coordinate system information, but we know ... | # define the coordinate system of the Surfer grid
with gxgrid.Grid.open('elevation_surfer.grd(SRF;VER=V7)') as grid_surfer:
grid_surfer.coordinate_system = 'GDA94 / UTM zone 54S'
# copy the grid to an ER Mapper format grid file and the coordinate system is transferred
with gxgrid.Grid.copy(grid_surfer, '... | examples/jupyter_notebooks/Tutorials/Grids and Images.ipynb | GeosoftInc/gxpy | bsd-2-clause |
Coordinate systems also contain the full coordinate system parameter information, from which you can construct coordinate systems in other applications. | with gxgrid.Grid.open('elevation.ers(ERM)') as grid_erm:
print('Grid Exchange Format coordinate system:\n', grid_erm.coordinate_system.gxf)
with gxgrid.Grid.open('elevation.ers(ERM)') as grid_erm:
print('ESRI WKT format:\n', grid_erm.coordinate_system.esri_wkt)
with gxgrid.Grid.open('elevation.ers(ERM)') as g... | examples/jupyter_notebooks/Tutorials/Grids and Images.ipynb | GeosoftInc/gxpy | bsd-2-clause |
Display with coordinate systems
The grids now have known coordinate systems and displaying the grid will show the coordinate system on the scale bar. We can also annotate geographic coordinates. This requires a Geosoft Desktop License. | # show the grid as an image
Image(gxgrid.figure_map('elevation.ers(ERM)', features=('NEATLINE', 'SCALE', 'LEGEND', 'ANNOT_LL')).image_file(pix_width=800)) | examples/jupyter_notebooks/Tutorials/Grids and Images.ipynb | GeosoftInc/gxpy | bsd-2-clause |
Basic Grid Statistics
In this exercise we will work with the data stored in a grid. One common need is to determine some basic statistical information about the grid data, such as the minimum, maximum, mean and standard deviation. This exercise will work with the grid data a number of ways that demonstrate some usefu... | import numpy as np
# open the grid, using the with construct ensures resources are released
with gxgrid.Grid.open('elevation_surfer.grd(SRF;VER=V7)') as grid:
# get the data in a numpy array
data_values = grid.xyzv()[:, :, 3]
# print statistical properties
print('minimum: ', np.nanmin(data_values))
prin... | examples/jupyter_notebooks/Tutorials/Grids and Images.ipynb | GeosoftInc/gxpy | bsd-2-clause |
Statistics using Geosoft VVs
Many Geosoft methods will work with a geosoft.gxpy.vv.GXvv, which wraps the geosoft.gxapi.GXVV class that deals with very long single-value vectors. The Geosoft GXVV methods works with Geosoft data types and, like numpy, is optimized to take advantage of multi-core processors to improve pe... | import geosoft.gxapi as gxapi
# the GXST class requires a desktop license
if gxc.entitled:
# create a gxapi.GXST instance to accumulate statistics
stats = gxapi.GXST.create()
# open the grid
with gxgrid.Grid.open('elevation_surfer.grd(SRF;VER=V7)') as grid:
# add data from each row to the st... | examples/jupyter_notebooks/Tutorials/Grids and Images.ipynb | GeosoftInc/gxpy | bsd-2-clause |
Grid Iterator
A grid instance also behaves as an iterator that works through the grid data points by row, then by column, each iteration returning the (x, y, z, grid_value). In this example we will iterate through all points in the grid and accumulate the statistics a point at a time. This is the least-efficient way ... | # the GXST class requires a desktop license
if gxc.entitled:
# create a gxapi.GXST instance to accumulate statistics
stats = gxapi.GXST.create()
# add each data to stats point-by-point (slow, better to use numpy or vector approach)
number_of_dummies = 0
with gxgrid.Grid.open('elevation_surfer.grd(... | examples/jupyter_notebooks/Tutorials/Grids and Images.ipynb | GeosoftInc/gxpy | bsd-2-clause |
AGB and massive star tables used | table='yield_tables/agb_and_massive_stars_nugrid_MESAonly_fryer12delay.txt' | DOC/Teaching/ExtraSources.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Setup | # OMEGA parameters for MW
mass_loading = 0.0
nb_1a_per_m = 3.0e-3
sfe=0.04
SF_law=True
DM_evolution=False
imf_yields_range=[1.0,30.0]
special_timesteps=30
Z_trans=0.0
iniZ=0.0001 | DOC/Teaching/ExtraSources.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Default setup | o0=o.omega(iniZ=iniZ,galaxy='milky_way',Z_trans=Z_trans, table=table,sfe=sfe, DM_evolution=DM_evolution,\
mass_loading=mass_loading, nb_1a_per_m=nb_1a_per_m, special_timesteps=special_timesteps,
imf_yields_range=imf_yields_range,
SF_law=SF_law) | DOC/Teaching/ExtraSources.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Setup with different extra sources
Here we use yields in two (extra source) yield tables which we apply in the mass range from 8Msun to 12Msun and from 12Msun to 30Msun respectively. We apply a factor of 0.5 to the extra yields of the first yield table and 1. to the second yield table. | extra_source_table=['yield_tables/r_process_arnould_2007.txt',
'yield_tables/r_process_arnould_2007.txt']
#Apply yields only in specific mass ranges;
extra_source_mass_range = [[8,12],[12,30]]
#percentage of stars to which the yields are added. First entry for first yield table etc.
f_extra_source =... | DOC/Teaching/ExtraSources.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
SYGMA | s0 = s.sygma(iniZ=0.0001,extra_source_on=False) #default False
s0p1 = s.sygma(iniZ=0.0001,extra_source_on=True,
extra_source_table=extra_source_table,extra_source_mass_range=extra_source_mass_range,
f_extra_source=f_extra_source, extra_source_exclude_Z=extra_source_exclude_Z) | DOC/Teaching/ExtraSources.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
OMEGA | o0p1=o.omega(iniZ=iniZ,galaxy='milky_way',Z_trans=Z_trans, table=table,sfe=sfe, DM_evolution=DM_evolution,\
mass_loading=mass_loading, nb_1a_per_m=nb_1a_per_m, special_timesteps=special_timesteps,
imf_yields_range=imf_yields_range,SF_law=SF_law,extra_source_on=True,
extra_... | DOC/Teaching/ExtraSources.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Now we do some data cleaning and remove all rows where Longitude and Latitude are 'null'. | df = df[df['Longitude'].notnull()]
df = df[df['Latitude'].notnull()]
# will display all rows that have null values
#df[df.isnull().any(axis=1)] | geojson/geojson_stations.ipynb | rueedlinger/python-snippets | mit |
Convert pandas data frame to GeoJSON
Next we convert the panda data frame to geosjon objects (FeatureCollection/Feature/Point). | import geojson as geojson
values = zip(df['Longitude'], df['Latitude'], df['Remark'])
points = [geojson.Feature(geometry=geojson.Point((v[0], v[1])), properties={'name': v[2]}) for v in values]
geo_collection = geojson.FeatureCollection(points)
print(points[0]) | geojson/geojson_stations.ipynb | rueedlinger/python-snippets | mit |
Save the GeoJSON (FeatureCollection) to a file
Finally we dump the GeoJSON objects to a file. | dump = geojson.dumps(geo_collection, sort_keys=True)
'''
with open('stations.geojson', 'w') as file:
file.write(dump)
''' | geojson/geojson_stations.ipynb | rueedlinger/python-snippets | mit |
Explore the Data
Play around with view_sentence_range to view different parts of the data. | view_sentence_range = (8, 100)
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
print('Dataset Stats')
print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))
scenes = text.split('\n\n')
print('Number of scenes: {}'.format(len(scenes)))
sentence_count_scene = [s... | tv-script-generation/dlnd_tv_script_generation.ipynb | rally12/deep-learning | mit |
Implement Preprocessing Functions
The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:
- Lookup Table
- Tokenize Punctuation
Lookup Table
To create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:
- Dict... | import numpy as np
import problem_unittests as tests
def create_lookup_tables(text):
"""
Create lookup tables for vocabulary
:param text: The text of tv scripts split into words
:return: A tuple of dicts (vocab_to_int, int_to_vocab)
"""
# TODO: Implement Function
words = set()
index_to_... | tv-script-generation/dlnd_tv_script_generation.ipynb | rally12/deep-learning | mit |
Tokenize Punctuation
We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!".
Implement the function token_lookup to return a dict that will be used to token... | def token_lookup():
"""
Generate a dict to turn punctuation into a token.
:return: Tokenize dictionary where the key is the punctuation and the value is the token
"""
# TODO: Implement Function
ret = {}
ret['.'] = "||Period||" #( . )
ret[','] = "||Comma||" #( , )
ret['"'] = "||Quotat... | tv-script-generation/dlnd_tv_script_generation.ipynb | rally12/deep-learning | mit |
Input
Implement the get_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders:
- Input text placeholder named "input" using the TF Placeholder name parameter.
- Targets placeholder
- Learning Rate placeholder
Return the placeholders in the following tuple (Inpu... | def get_inputs():
"""
Create TF Placeholders for input, targets, and learning rate.
:return: Tuple (input, targets, learning rate)
"""
# TODO: Implement Function
inputs = tf.placeholder(tf.int32, [None, None ], name="input")
targets = tf.placeholder(tf.int32, [None, None ], name... | tv-script-generation/dlnd_tv_script_generation.ipynb | rally12/deep-learning | mit |
Build RNN Cell and Initialize
Stack one or more BasicLSTMCells in a MultiRNNCell.
- The Rnn size should be set using rnn_size
- Initalize Cell State using the MultiRNNCell's zero_state() function
- Apply the name "initial_state" to the initial state using tf.identity()
Return the cell and initial state in the follo... | def get_init_cell(batch_size, rnn_size):
"""
Create an RNN Cell and initialize it.
:param batch_size: Size of batches
:param rnn_size: Size of RNNs
:return: Tuple (cell, initialize state)
"""
# TODO: Implement Function
layer_count = 2
keep_prob = tf.constant(0.7,tf.float32, name="kee... | tv-script-generation/dlnd_tv_script_generation.ipynb | rally12/deep-learning | mit |
Word Embedding
Apply embedding to input_data using TensorFlow. Return the embedded sequence. | import random
import math
def get_embed(input_data, vocab_size, embed_dim):
"""
Create embedding for <input_data>.
:param input_data: TF placeholder for text input.
:param vocab_size: Number of words in vocabulary.
:param embed_dim: Number of embedding dimensions
:return: Embedded input.
"""... | tv-script-generation/dlnd_tv_script_generation.ipynb | rally12/deep-learning | mit |
Build RNN
You created a RNN Cell in the get_init_cell() function. Time to use the cell to create a RNN.
- Build the RNN using the tf.nn.dynamic_rnn()
- Apply the name "final_state" to the final state using tf.identity()
Return the outputs and final_state state in the following tuple (Outputs, FinalState) | def build_rnn(cell, inputs):
"""
Create a RNN using a RNN Cell
:param cell: RNN Cell
:param inputs: Input text data
:return: Tuple (Outputs, Final State)
"""
# TODO: Implement Function
output, final_state = tf.nn.dynamic_rnn(cell, inputs, dtype = tf.float32)
final_state = tf.identity... | tv-script-generation/dlnd_tv_script_generation.ipynb | rally12/deep-learning | mit |
Build the Neural Network
Apply the functions you implemented above to:
- Apply embedding to input_data using your get_embed(input_data, vocab_size, embed_dim) function.
- Build RNN using cell and your build_rnn(cell, inputs) function.
- Apply a fully connected layer with a linear activation and vocab_size as the number... | def build_nn(cell, rnn_size, input_data, vocab_size, embed_dim):
"""
Build part of the neural network
:param cell: RNN cell
:param rnn_size: Size of rnns
:param input_data: Input data
:param vocab_size: Vocabulary size
:param embed_dim: Number of embedding dimensions
:return: Tuple (Logi... | tv-script-generation/dlnd_tv_script_generation.ipynb | rally12/deep-learning | mit |
Batches
Implement get_batches to create batches of input and targets using int_text. The batches should be a Numpy array with the shape (number of batches, 2, batch size, sequence length). Each batch contains two elements:
- The first element is a single batch of input with the shape [batch size, sequence length]
- Th... | def get_batches(int_text, batch_size, seq_length):
"""
Return batches of input and target
:param int_text: Text with the words replaced by their ids
:param batch_size: The size of batch
:param seq_length: The length of sequence
:return: Batches as a Numpy array
"""
# TODO: Implement Func... | tv-script-generation/dlnd_tv_script_generation.ipynb | rally12/deep-learning | mit |
Neural Network Training
Hyperparameters
Tune the following parameters:
Set num_epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set embed_dim to the size of the embedding.
Set seq_length to the length of sequence.
Set learning_rate to the learning rate.
Set show_e... | # Number of Epochs
num_epochs = 300 # previously 150, but want to get lower loss.
# Batch Size
batch_size = 128
# RNN Size
rnn_size = 1024
# Embedding Dimension Size
embed_dim = None
# Sequence Length
seq_length = 12 # already discouraged from using 6 and 16, avg sentence length being 10-12
# I'm favoring this formu... | tv-script-generation/dlnd_tv_script_generation.ipynb | rally12/deep-learning | mit |
Implement Generate Functions
Get Tensors
Get tensors from loaded_graph using the function get_tensor_by_name(). Get the tensors using the following names:
- "input:0"
- "initial_state:0"
- "final_state:0"
- "probs:0"
Return the tensors in the following tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTen... | def get_tensors(loaded_graph):
"""
Get input, initial state, final state, and probabilities tensor from <loaded_graph>
:param loaded_graph: TensorFlow graph loaded from file
:return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)
"""
# TODO: Implement Function
in... | tv-script-generation/dlnd_tv_script_generation.ipynb | rally12/deep-learning | mit |
Choose Word
Implement the pick_word() function to select the next word using probabilities. | def pick_word(probabilities, int_to_vocab):
"""
Pick the next word in the generated text
:param probabilities: Probabilites of the next word
:param int_to_vocab: Dictionary of word ids as the keys and words as the values
:return: String of the predicted word
"""
# TODO: Implement Function
... | tv-script-generation/dlnd_tv_script_generation.ipynb | rally12/deep-learning | mit |
Exercise
Compute some basic descriptive statistics about the graph, namely:
the number of nodes,
the number of edges,
the graph density,
the distribution of degree centralities in the graph, | # Number of nodes:
len(G.nodes())
# Number of edges:
len(G.edges())
# Graph density:
nx.density(G)
# Degree centrality distribution:
list(nx.degree_centrality(G).values())[0:5] | archive/bonus-1-network-statistical-inference-instructor.ipynb | ericmjl/Network-Analysis-Made-Simple | mit |
How are protein-protein networks formed? Are they formed by an Erdos-Renyi process, or something else?
In the G(n, p) model, a graph is constructed by connecting nodes randomly. Each edge is included in the graph with probability p independent from every other edge.
If protein-protein networks are formed by an E-R pr... | ppG_deg_centralities = list(nx.degree_centrality(G).values())
plt.plot(*ecdf(ppG_deg_centralities))
erG = nx.erdos_renyi_graph(n=len(G.nodes()), p=nx.density(G))
erG_deg_centralities = list(nx.degree_centrality(erG).values())
plt.plot(*ecdf(erG_deg_centralities))
plt.show() | archive/bonus-1-network-statistical-inference-instructor.ipynb | ericmjl/Network-Analysis-Made-Simple | mit |
One of the most effective use of pandas is the ease at which we can select rows and coloumns in different ways, here's how we do it:
To access the coloumns, there are three different ways we can do it, these are:
data_set_var[ "coloumn-name" ]
< data_set_var >.< coloumn-name >
We can add coloumns too,... | # Add a new coloumn
brics["on_earth"] = [ True, True, True, True, True ]
# Print them
brics
# Manupalating Coloumns
"""Coloumns can be manipulated using arithematic operations
on other coloumns""" | Courses/DAT-208x/DAT208x - Week 6 - Pandas.ipynb | dataDogma/Computer-Science | gpl-3.0 |
Accessing Rows:
Syntax: dataframe.loc[ <"row name"> ]
Go to top:TOC
Element access
To get just one element in the table, we can specify both coloumn and row label in the loc().
Syntax:
dataframe.loc[ <"row-name, coloumn name"> ]
dataframe[ <"row-name"> ].loc[ <"coloumn-name"> ]
datafram... | """
# Import pandas as pd
import pandas as pd
# Import the cars.csv data: cars
cars = pd.read_csv("cars.csv")
# Print out cars
print(cars)
""" | Courses/DAT-208x/DAT208x - Week 6 - Pandas.ipynb | dataDogma/Computer-Science | gpl-3.0 |
CSV to DataFrame2
Preface:
We have a slight of a problem, the row labels are imported as another coloumn, that has no name.
To fix this issue, we are goint to pass an argument index_col = 0 to read_csv(). This is used to specify which coloumn in the CSV file should be used as row label?
Instructions:
Run the code wi... | """
# Import pandas as pd
import pandas as pd
# Import the cars.csv data: cars
cars = pd.read_csv("cars.csv", index_col=0)
# Print out cars
print(cars)
""" | Courses/DAT-208x/DAT208x - Week 6 - Pandas.ipynb | dataDogma/Computer-Science | gpl-3.0 |
Square Brackets
Preface
Selecting coloumns can be done in two way.
variable_containing_CSV_file['coloumn-name']
variable_containing_CSV_file[['coloumn-name']]
The former gives a pandas series, whereas the latter gives a pandas dataframe.
Instructions:
Use single square brackets to print out the country column ... | """
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
# Print out country column as Pandas Series
print( cars['country'])
# Print out country column as Pandas DataFrame
print( cars[['country']])
""" | Courses/DAT-208x/DAT208x - Week 6 - Pandas.ipynb | dataDogma/Computer-Science | gpl-3.0 |
Loc1
With loc we can do practically any data selection operation on DataFrames you can think of.
loc is label-based, which means that you have to specify rows and coloumns based on their row and coloumn labels.
Instructions:
Use loc to select the observation corresponding to Japan as a Series. The label of this row ... | """
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
# Print out observation for Japan
print( cars.loc['JAP'] )
# Print out observations for Australia and Egypt
print( cars.loc[ ['AUS', 'EG'] ])
""" | Courses/DAT-208x/DAT208x - Week 6 - Pandas.ipynb | dataDogma/Computer-Science | gpl-3.0 |
Данные
Возьмите данные с https://www.kaggle.com/c/shelter-animal-outcomes .
Обратите внимание, что в этот раз у нас много классов, почитайте в разделе Evaluation то, как вычисляется итоговый счет (score).
Визуализация
<div class="panel panel-info" style="margin: 50px 0 0 0">
<div class="panel-heading">
<h3 ... | visual = pd.read_csv('data/CatsAndDogs/TRAIN2.csv')
#Сделаем числовой столбец Outcome, показывающий, взяли животное из приюта или нет
#Сначала заполним единицами, типа во всех случах хорошо
visual['Outcome'] = 'true'
#Неудачные случаи занулим
visual.loc[visual.OutcomeType == 'Euthanasia', 'Outcome'] = 'false'
visual.l... | 3. Котики и собачки.ipynb | lithiumdenis/MLSchool | mit |
<b>Вывод по возрасту:</b> лучше берут не самых старых, но и не самых молодых
<br>
<b>Вывод по полу:</b> по большому счёту не имеет значения
<br>
<b>Вывод по фертильности:</b> лучше берут животных с ненарушенными репродуктивными способностями. Однако две следующие группы не сильно различаются по сути и, если их сложить,... | train, test = pd.read_csv(
'data/CatsAndDogs/TRAIN2.csv' #наши данные
#'data/CatsAndDogs/train.csv' #исходные данные
), pd.read_csv(
'data/CatsAndDogs/TEST2.csv' #наши данные
#'data/CatsAndDogs/test.csv' #исходные данные
)
train.head()
test.shape | 3. Котики и собачки.ipynb | lithiumdenis/MLSchool | mit |
<b>Добавим новые признаки в train</b> | #Сначала по-аналогии с визуализацией
#Заменим строки, где в SexuponOutcome, Breed, Color NaN
train.loc[train.SexuponOutcome.isnull(), 'SexuponOutcome'] = 'Unknown Unknown'
train.loc[train.AgeuponOutcome.isnull(), 'AgeuponOutcome'] = '0 0'
train.loc[train.Breed.isnull(), 'Breed'] = 'Unknown'
train.loc[train.Color.isnul... | 3. Котики и собачки.ipynb | lithiumdenis/MLSchool | mit |
<div class="panel panel-info" style="margin: 50px 0 0 0">
<div class="panel-heading">
<h3 class="panel-title">Задание 3.</h3>
</div>
</div>
Выполните отбор признаков, попробуйте различные методы. Проверьте качество на кросс-валидации.
Выведите топ самых важных и самых незначащих признаков.
Предобрабо... | np.random.seed = 1234
from sklearn.preprocessing import LabelEncoder
from sklearn import preprocessing
#####################Заменим NaN значения на слово Unknown##################
#Уберем Nan значения из train
train.loc[train.AnimalID.isnull(), 'AnimalID'] = 'Unknown'
train.loc[train.Name.isnull(), 'Name'] = 'Unknown'... | 3. Котики и собачки.ipynb | lithiumdenis/MLSchool | mit |
<b>Вывод по признакам:</b>
<br>
<b>Не нужны:</b> Name, DateTime, month, day, Breed, breedColor. Всё остальное менее однозначно, можно и оставить.
<div class="panel panel-info" style="margin: 50px 0 0 0">
<div class="panel-heading">
<h3 class="panel-title">Задание 4.</h3>
</div>
</div>
Попробуйте смеша... | #Для начала выкинем ненужные признаки, выявленные на прошлом этапе
X_tr = X_tr.drop(['Name', 'DateTime', 'month', 'day', 'Breed', 'breedColor'], axis=1)
test = test.drop(['Name', 'DateTime', 'month', 'day', 'Breed', 'breedColor'], axis=1)
X_tr.head()
from sklearn.ensemble import VotingClassifier
from sklearn.linear_m... | 3. Котики и собачки.ipynb | lithiumdenis/MLSchool | mit |
Проверим, что никакие строчки при манипуляции с NaN не потерялись | test.shape[0] == ans_nn.shape[0]
#Сделаем нумерацию индексов не с 0, а с 1
ans_nn.index += 1
#Воткнем столбец с индексами как столбец в конкретное место
ans_nn.insert(0, 'ID', ans_nn.index)
#delete AnimalID from test
ans_nn = ans_nn.drop(['AnimalID'], axis=1)
ans_nn.head()
#Сохраним
ans_nn.to_csv('ans_catdog.csv', i... | 3. Котики и собачки.ipynb | lithiumdenis/MLSchool | mit |
Motor imagery decoding from EEG data using the Common Spatial Pattern (CSP)
Decoding of motor imagery applied to EEG data decomposed using CSP.
Here the classifier is applied to features extracted on CSP filtered signals.
See https://en.wikipedia.org/wiki/Common_spatial_pattern and [1]. The EEGBCI
dataset is documented... | # Authors: Martin Billinger <martin.billinger@tugraz.at>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import ShuffleSplit, cross_val_score
from mn... | 0.20/_downloads/a4d4c1a667c2374c09eed24ac047d840/plot_decoding_csp_eeg.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Solución:
Inicialmente encontremos los valores principales $(\lambda)$ a partir de la solución del polinomio característico:
${\lambda ^3} - {I_\sigma}{\lambda ^2} + {II_\sigma}\lambda - {III_\sigma} = 0$
Donde ${I_\sigma}$, ${II_\sigma}$ y ${III_\sigma}$ son los invariantes 1, 2 y 3 respectivamente que están dados p... | import numpy as np
from scipy import linalg
S = np.array([
[200,100,300.],
[100,0,0],
[300,0,0]])
IS = S[0,0]+S[1,1]+S[2,2]
IIS = S[0,0]*S[1,1]+S[1,1]*S[2,2]+S[0,0]*S[2,2]-(S[0,1]**2)-(S[0,2]**2)-(S[1,2]**2)
IIIS = S[0,0]*S[1,1]*S[2,2]-S[0,0]*(S[1,2]**2)-S[1,1]*(S[0,2]**2)-S[2,2]*(S[0,1]**2)+2*S[1,2]*S... | NOTEBOOKS/Ej4_Eingen.ipynb | jgomezc1/medios | mit |
Resolviendo vía polinomio característico: | coeff=[1.0,-IS,IIS,-IIIS]
ps=np.roots(coeff)
print
print "Esfuerzos principales:", np.sort(np.round(ps,1))
print | NOTEBOOKS/Ej4_Eingen.ipynb | jgomezc1/medios | mit |
Resolviendo vía librerías python con linalg.eig podemos encontrar valores (la) y direcciones principales (n) simultaneamente | la, n= linalg.eigh(S)
la = la.real
print
print "Esfuerzos principales:", np.round(la,1)
print
#print S
print
print 'n=', np.round(n,2)
print | NOTEBOOKS/Ej4_Eingen.ipynb | jgomezc1/medios | mit |
De esta manera escribamos en tensor asociado a las direcciones principales: | print
Sp = np.array([
[la[0],0,0],
[0,la[1],0],
[0,0,la[2]]])
print 'Sp =',np.round(Sp,1)
print
Image(filename='FIGURES/Sprinc.png',width=400) | NOTEBOOKS/Ej4_Eingen.ipynb | jgomezc1/medios | mit |
Los vectores $i'$, $j'$ y $k'$ están dados por: | print "i'=", np.round(n[:,0],2)
print "j'=", np.round(n[:,1],2)
print "k'=", np.round(n[:,2],2)
print | NOTEBOOKS/Ej4_Eingen.ipynb | jgomezc1/medios | mit |
Verifiquemos que se cumplen los invariantes en el tensor asociado a direcciones principales: | IS = Sp[0,0]+Sp[1,1]+Sp[2,2]
IIS =Sp[0,0]*Sp[1,1]+Sp[1,1]*Sp[2,2]+Sp[0,0]*Sp[2,2]-(Sp[0,1]**2)-(Sp[0,2]**2)-(Sp[1,2]**2)
IIIS =Sp[0,0]*Sp[1,1]*Sp[2,2]-Sp[0,0]*(Sp[1,2]**2)-Sp[1,1]*(Sp[0,2]**2)-Sp[2,2]*(Sp[0,1]**2)+2*Sp[1,2]*Sp[0,2]*Sp[0,1]
print
print 'Invariantes:', IS,IIS,IIIS
print | NOTEBOOKS/Ej4_Eingen.ipynb | jgomezc1/medios | mit |
Para terminar se debe de tener en cuenta que las direcciones principales no son otra cosa que la matriz de cosenos directores que transformaría el tensor original al tensor en direcciones principales mediante la ecuación de transformación:
\begin{align}
&[\sigma']=[C][\sigma][C]^T\
\end{align}
Teniendo en cuenta que n... | C = n.T
Sp2 = np.dot(np.dot(C,S),C.T)
print
print 'Sp =', np.round(Sp2,1)
from IPython.core.display import HTML
def css_styling():
styles = open('./custom_barba.css', 'r').read()
return HTML(styles)
css_styling() | NOTEBOOKS/Ej4_Eingen.ipynb | jgomezc1/medios | mit |
Tracking a CO$_2$ Plume
CO$_2$ from an industrial site can be compressed and injected into a deep saline aquifer for storage. This technology is called CO$_2$ capture and storage or CCS, proposed in (TODO) to combat global warming. As CO$_2$ is lighter than the saline water, it may leak through a natural fracture and c... | CO2 = CO2simulation('low')
data = []
x = []
for i in range(10):
data.append(CO2.move_and_sense())
x.append(CO2.x)
param = vco2.getImgParam('low')
vco2.plotCO2map(x,param)
plt.show() | .ipynb_checkpoints/FristExample-checkpoint.ipynb | judithyueli/pyFKF | mit |
Simulating the Sensor Measurement
The sensor measures the travel time of a seismic signal from a source to a receiver.
$$ y = Hx + v $$
$x$ is the grid block value of CO$_2$ slowness, an idicator of how much CO$_2$ in a block. The product $Hx$ simulate the travel time measurements by integrating $x$ along a raypath. $v... | reload(visualizeCO2)
vco2.plotCO2data(data,0,47) | .ipynb_checkpoints/FristExample-checkpoint.ipynb | judithyueli/pyFKF | mit |
TODO:
Fig: Run animation/image of the ray path (shooting from one source and receiver) on top of a CO$_2$ plume and display the travel time changes over time.
Fig: Show the time-series data (Path 1 and Path 2) at a receiver with and without noise.
optional: run getraypath will give me all the index of the cells and... | np.dot(1,5)
run runCO2simulation | .ipynb_checkpoints/FristExample-checkpoint.ipynb | judithyueli/pyFKF | mit |
Implementing the Prediction Step
$$ x_{k+1} = x_{k} + w_k $$
Note here a simplified Random Walk forecast model is used to substitute $f(x)$. The advantage of using a random walk forecast model is that now we are dealing with a linear instead of nonlinear filtering problem, and the computational cost is much lower as we... | from filterpy.common import Q_discrete_white_noise
kf.F = np.diag(np.ones(dim_x))
# kf.Q = Q_discrete_white_noise(dim = dim_x, dt = 0.1, var = 2.35)
kf.Q = 2.5
kf.predict()
print kf.x[:10] | .ipynb_checkpoints/FristExample-checkpoint.ipynb | judithyueli/pyFKF | mit |
Implementing the Update Step | kf.H = CO2.H_mtx
kf.R *= 0.5
z = data[0]
kf.update(z) | .ipynb_checkpoints/FristExample-checkpoint.ipynb | judithyueli/pyFKF | mit |
TODO
- Fig: Estimate at k, Forecast at k+1, Estimate at k+1, True at k+1
- A table showing:
x: the time CO2 reaches the monitoring well
y: the time CO2 reaches the ray path
PREDICT: x var y UPDATE: x var y
- Fig: MSE vs time
- Fig: Data fitting, slope 45 degree indicates a pe... | from HiKF import HiKF
hikf = HiKF(dim_x, dim_z)
hikf.x | .ipynb_checkpoints/FristExample-checkpoint.ipynb | judithyueli/pyFKF | mit |
Coefficients to find | w_true = [3,3,3]
w_true = w_true / np.sum(w_true)
mu_true = [3,10,20]
sigma_true = [2,4,1] | tensorflow_fit_gaussian_mixture_model.ipynb | pierresendorek/tensorflow_crescendo | lgpl-3.0 |
Sampling the distribution | def draw_from_gaussian_mixture(w, mu, sigma, n_samples):
samples = []
for i in range(n_samples):
idx_comp = np.random.multinomial(1,w).argmax()
samples.append( np.random.randn()*sigma[idx_comp] + mu[idx_comp] )
return samples
samples = np.array(draw_from_gaussian_mixture(w_true, mu_true, si... | tensorflow_fit_gaussian_mixture_model.ipynb | pierresendorek/tensorflow_crescendo | lgpl-3.0 |
Finding coefficients with Tensorflow | import tensorflow as tf | tensorflow_fit_gaussian_mixture_model.ipynb | pierresendorek/tensorflow_crescendo | lgpl-3.0 |
Loss function | import math
oneDivSqrtTwoPI = tf.constant(1 / math.sqrt(2*math.pi)) # normalisation factor for gaussian, not needed.
my_epsilon = tf.constant(1e-14)
def tf_normal(y, mu, sigma):
result = tf.subtract(y, mu)
result = tf.divide(result,sigma)
result = -tf.square(result)/2
return tf.divide(tf.exp(result),si... | tensorflow_fit_gaussian_mixture_model.ipynb | pierresendorek/tensorflow_crescendo | lgpl-3.0 |
Optimizer | train_op = tf.train.AdamOptimizer(learning_rate=0.05, epsilon=1E-12).minimize(loss) | tensorflow_fit_gaussian_mixture_model.ipynb | pierresendorek/tensorflow_crescendo | lgpl-3.0 |
Init Session | sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
def do(x):
return sess.run(x, feed_dict={samples_tf: samples.reshape(-1,1)})
loss_list = []
sess.run(get_density(out_pi, out_sigma, out_mu, samples_tf), feed_dict={samples_tf: samples.reshape(-1,1)})
for i in range(2000):
sess.run(tr... | tensorflow_fit_gaussian_mixture_model.ipynb | pierresendorek/tensorflow_crescendo | lgpl-3.0 |
$$
\log \exp(a) = a
$$
$$
\log (\exp(a) \exp(b))
= \log(\exp(a)) + \log(\exp(b))
= a + b
$$ | print(math.log(math.exp(0.2) * math.exp(0.7)))
print(0.2 + 0.7) | maths/logs.ipynb | hughperkins/pub-prototyping | apache-2.0 |
NLP Lab, Part I
Welcome to the first lab of 6.S191!
Administrivia
Things to install:
- tensorflow
- word2vec
Lab Objectives:
Learn Machine Learning methodology basics (train/dev/test sets)
Learn some Natural Language Processing basics (word embeddings with word2vec)
Learn the basics of tensorflow, build your first de... | trainSet = p.load( open('data/train.p','rb'))
devSet = p.load( open('data/dev.p','rb'))
testSet = p.load( open('data/test.p','rb'))
## Let's look at the size of what we have here. Note, we could use a much larger train set,
## but we keep it mid-size so you can run this whole thing off your laptop
len(trainSet), len(... | draft/part1.ipynb | yala/introdeeplearning | mit |
NLP Basics
The first question we need to address is how do we represent a tweet? how do we represent a word?
One way to do this is with one_hot vectors for each word. Where a given word $w_i= [0,0,...,1,..0]$.
However, in this representation, words like "love" and "adore" are as similar as "love" and "hate", because th... | ## Note, these tweets were preprocessings to remove non alphanumeric chars, replace unfrequent words, and padded to same length.
## Note, we're going to train our embeddings on only our train set in order to keep our dev/test tests fair
trainSentences = [" ".join(tweetPair[0]) for tweetPair in trainSet]
print trainSen... | draft/part1.ipynb | yala/introdeeplearning | mit |
Now lets look at the words most similar to the word "fun" | indices, cosineSim = w2vModel.cosine('fun')
print w2vModel.vocab[indices]
word_embeddings = w2vModel.vectors
vocab_size = len(w2vModel.vocab) | draft/part1.ipynb | yala/introdeeplearning | mit |
Feel free to play around here test the properties of your embeddings, how they cluster etc. In the interest of time, we're going to move on straight to models.
Now in order to use these embeddings, we have to represent each tweet as a list of indices into the embedding matrix.
This preprocessing code is available in pr... | session = tf.Session()
# 1.BUILD GRAPH
# Set placeholders with a type for data you'll eventually feed in (like tweets and sentiments)
a = tf.placeholder(tf.int32)
b = tf.placeholder(tf.int32)
# Set up variables, like weight matrices.
# Using tf.get_variable, specify the name, shape, type and initliazer of the variable... | draft/part1.ipynb | yala/introdeeplearning | mit |
Building an MLP
MLP or Multi-layer perceptron is a basic archetecture where where we multiply our representation with some matrix W and add some bias b and then apply some nonlineanity like tanh at each layer. Layers are fully connected to the next. As the network gets deeper, it's expressive power grows exponentially ... | "TODO" | draft/part1.ipynb | yala/introdeeplearning | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.