markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
To be able to process our data in the notebook environment and explore the PCollections, we will use the interactive runner. We create this pipeline object in the same manner as usually, but passing in InteractiveRunner() as the runner.
p = beam.Pipeline(InteractiveRunner())
courses/dataflow/demos/beam_notebooks/beam_notebooks_demo.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Now we're ready to start processing our data! We first apply our ReadWordsFromText transform to read in the lines of text from Google Cloud Storage and parse into individual words.
words = p | 'ReadWordsFromText' >> ReadWordsFromText('gs://apache-beam-samples/shakespeare/kinglear.txt')
courses/dataflow/demos/beam_notebooks/beam_notebooks_demo.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Now we will see some capabilities of the interactive runner. First we can use ib.show to view the contents of a specific PCollection from any point of our pipeline.
ib.show(words)
courses/dataflow/demos/beam_notebooks/beam_notebooks_demo.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Great! We see that we have 28,001 words in our PCollection and we can view the words in our PCollection. We can also view the current DAG for our graph by using the ib.show_graph() method. Note that here we pass in the pipeline object rather than a PCollection
ib.show_graph(p)
courses/dataflow/demos/beam_notebooks/beam_notebooks_demo.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
In the above graph, the rectanglar boxes correspond to PTransforms and the circles correspond to PCollections. Next we will add a simple schema to our PCollection and convert the PCollection into a dataframe using the to_dataframe method.
word_rows = words | 'ToRows' >> beam.Map(lambda word: beam.Row(word=word)) df = to_dataframe(word_rows)
courses/dataflow/demos/beam_notebooks/beam_notebooks_demo.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
We can now explore our PCollection as a Pandas-like dataframe! One of the first things many data scientists do as soon as they load data into a dataframe is explore the first few rows of data using the head method. Let's see what happens here.
df.head()
courses/dataflow/demos/beam_notebooks/beam_notebooks_demo.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Notice that we got a very specific type of error! The WontImplementError is for Pandas methods that will not be implemented for Beam dataframes. These are methods that violate the Beam model for one reason or another. For example, in this case the head method depends on the order of the dataframe. However, this is in c...
df['count'] = 1 counted = df.groupby('word').sum()
courses/dataflow/demos/beam_notebooks/beam_notebooks_demo.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
That's it! It looks exactly like the code one would write when using Pandas. However, what does this look like in the DAG for the pipeline? We can see this by executing ib.show_graph(p) as before.
ib.show_graph(p)
courses/dataflow/demos/beam_notebooks/beam_notebooks_demo.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
We can see that the dataframe manipulations added a new PTransform to our pipeline. Let us convert the dataframe back to a PCollection so we can use ib.show to view the contents.
word_counts = to_pcollection(counted, include_indexes=True) ib.show(word_counts)
courses/dataflow/demos/beam_notebooks/beam_notebooks_demo.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Great! We can now see that the words have been successfully counted. Finally let us build in a sink into the pipeline. We can do this in two ways. If we wish to write to a CSV file, then we can use the dataframe's to_csv method. We can also use the WriteToText transform after converting back to a PCollection. Let's do ...
counted.to_csv('from_df.csv') _ = word_counts | beam.io.WriteToText('from_pcoll.csv') ib.show_graph(p)
courses/dataflow/demos/beam_notebooks/beam_notebooks_demo.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Note that we can see the branching with two different sinks, also we can see where the dataframe is converted back to a PCollection. We can run our entire pipeline by using p.run() as normal.
p.run()
courses/dataflow/demos/beam_notebooks/beam_notebooks_demo.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Let us now look at the beginning of the CSV files using the bash line magic with the head command to compare.
!head from_df* !head from_pcoll*
courses/dataflow/demos/beam_notebooks/beam_notebooks_demo.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Next, import the relevant modules: Hint: Find corresponding bio-entity representation used in BioThings Explorer based on user input (could be any database IDs, symbols, names) FindConnection: Find intermediate bio-entities which connects user specified input and output
from biothings_explorer.hint import Hint from biothings_explorer.user_query_dispatcher import FindConnection import nest_asyncio nest_asyncio.apply()
jupyter notebooks/Multi intermediate nodes query.ipynb
biothings/biothings_explorer
apache-2.0
Step 1: Find representation of "Anisindione" in BTE In this step, BioThings Explorer translates our query string "Anisindioine" into BioThings objects, which contain mappings to many common identifiers. Generally, the top result returned by the Hint module will be the correct item, but you should confirm that using t...
ht = Hint() anisindione = ht.query("Anisindione")['ChemicalSubstance'][0] anisindione
jupyter notebooks/Multi intermediate nodes query.ipynb
biothings/biothings_explorer
apache-2.0
Step 2: Find phenotypes that are associated with Anisindione through Gene and DiseaseOrPhenotypicFeature as intermediate nodes In this section, we find all paths in the knowledge graph that connect Anisindione to any entity that is a phenotypic feature. To do that, we will use FindConnection. This class is a convenie...
fc = FindConnection(input_obj=anisindione, output_obj='PhenotypicFeature', intermediate_nodes=['Gene', 'Disease']) fc.connect(verbose=True) df = fc.display_table_view() df.head()
jupyter notebooks/Multi intermediate nodes query.ipynb
biothings/biothings_explorer
apache-2.0
The df object contains the full output from BioThings Explorer. Each row shows one path that joins the input node (ANISINDIONE) to an intermediate node (a gene or protein) to another intermediate node (a DisseaseOrPhenotypicFeature) to an ending node (a Phenotypic Feature). The data frame includes a set of columns with...
dfFilt = df.loc[df['output_name'].notnull()].query('pred1 == "physically_interacts_with" and pred2 == "prevents"') dfFilt
jupyter notebooks/Multi intermediate nodes query.ipynb
biothings/biothings_explorer
apache-2.0
This line create a CSV (comma seperated file) called hw1data.csv in the current working directory.
%%file hw1data.csv id,sex,weight 1,M,190 2,F,120 3,F,110 4,M,150 5,O,120 6,M,120 7,F,140
homework/homework1.ipynb
AlJohri/DAT-DC-12
mit
Basic
def double(x): """ double the value x """ assert double(10) == 20 def apply_to_100(f): """ runs some abitrary function f on the value 100 and returns the output """ assert(apply_to_100(double) == 200) """ create a an anonymous function using lambda that takes some value x and adds 1 to x """...
homework/homework1.ipynb
AlJohri/DAT-DC-12
mit
Working with Files
def create_list_of_lines_in_hw1data(): """ Read each line of hw1data.csv into a list and return the list of lines. Remove the newline character ("\n") at the end of each line. What is a newline character? https://en.wikipedia.org/wiki/Newline Hint: Reading a File (https://docs.python.org/3...
homework/homework1.ipynb
AlJohri/DAT-DC-12
mit
Project Euler
def sum_of_multiples_of_three_and_five_below_1000(): """ https://projecteuler.net/problem=1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Hint: Modulo Oper...
homework/homework1.ipynb
AlJohri/DAT-DC-12
mit
Strings
from collections import Counter def remove_punctuation(s): """remove periods, commas, and semicolons """ return s.replace() def tokenize(s): """return a list of lowercased tokens (words) in a string without punctuation """ return remove_punctuation(s.lower()) def word_count(s): """count t...
homework/homework1.ipynb
AlJohri/DAT-DC-12
mit
Linear Algebra Please find the following empty functions and write the code to complete the logic. These functions are focused around implementing vector algebra operations. The vectors can be of any length. If a function accepts two vectors, assume they are the same length. Khan Academy has a decent introduction: [htt...
def vector_add(v, w): """adds two vectors componentwise and returns the result hint: use zip() v + w = [4, 5, 1] + [9, 8, 1] = [13, 13, 2] """ return [] def vector_subtract(v, w): """subtracts two vectors componentwise and returns the result hint use zip() v + w = [4, 5,...
homework/homework1.ipynb
AlJohri/DAT-DC-12
mit
Run a simulation
nregions = [fp.Region(0,1,1),fp.Region(2,3,1)] sregions = [fp.ExpS(1,2,1,-0.1),fp.ExpS(1,2,0.01,0.001)] rregions = [fp.Region(0,3,1)] rng = fp.GSLrng(101) popsizes = np.array([1000],dtype=np.uint32) popsizes=np.tile(popsizes,10000) #Initialize a vector with 1 population of size N = 1,000 pops=fp.SpopVec(1,1000) #This s...
docs/examples/trajectories.ipynb
molpopgen/fwdpy
gpl-3.0
Group mutation trajectories by position and effect size Max mutation frequencies
mfreq = traj.groupby(['pos','esize']).max().reset_index() #Print out info for all mutations that hit a frequency of 1 (e.g., fixed) mfreq[mfreq['freq']==1]
docs/examples/trajectories.ipynb
molpopgen/fwdpy
gpl-3.0
The only fixation has an 'esize' $> 0$, which means that it was positively selected, Frequency trajectory of fixations
#Get positions of mutations that hit q = 1 mpos=mfreq[mfreq['freq']==1]['pos'] #Frequency trajectories of fixations fig = plt.figure() ax = plt.subplot(111) plt.xlabel("Time (generations)") plt.ylabel("Mutation frequency") ax.set_xlim(traj['generation'].min(),traj['generation'].max()) for i in mpos: plt.plot(traj[...
docs/examples/trajectories.ipynb
molpopgen/fwdpy
gpl-3.0
Input Parameter
# Discretization c1=30 # Number of grid points per dominant wavelength c2=0.2 # CFL-Number nx=300 # Number of grid points in X ny=300 # Number of grid points in Y T=1 # Total propagation time # Source Signal f0= 5 # Center frequency Ricker-wavelet q0= 100 # Maximum amplitude Ricker-Wavelet xscr = 150...
JupyterNotebook/2D/FD_2D_DX4_DT2_fast.ipynb
florianwittkamp/FD_ACOUSTIC
gpl-3.0
Preparation
# Init wavefields vx=np.zeros(shape = (ny,nx)) vy=np.zeros(shape = (ny,nx)) p=np.zeros(shape = (ny,nx)) vx_x=np.zeros(shape = (ny,nx)) vy_y=np.zeros(shape = (ny,nx)) p_x=np.zeros(shape = (ny,nx)) p_y=np.zeros(shape = (ny,nx)) # Calculate first Lame-Paramter l=rho * modell_v * modell_v cmin=min(modell_v.flatten()) # ...
JupyterNotebook/2D/FD_2D_DX4_DT2_fast.ipynb
florianwittkamp/FD_ACOUSTIC
gpl-3.0
Create space and time vector
x=np.arange(0,dx*nx,dx) # Space vector in X y=np.arange(0,dy*ny,dy) # Space vector in Y t=np.arange(0,T,dt) # Time vector nt=np.size(t) # Number of time steps # Plotting model fig, (ax1, ax2) = plt.subplots(1, 2) fig.subplots_adjust(wspace=0.4,right=1.6) ax1.plot(x,modell_v) ax1.set_ylabel('VP in m/s') a...
JupyterNotebook/2D/FD_2D_DX4_DT2_fast.ipynb
florianwittkamp/FD_ACOUSTIC
gpl-3.0
Source signal - Ricker-wavelet
tau=np.pi*f0*(t-1.5/f0) q=q0*(1.0-2.0*tau**2.0)*np.exp(-tau**2) # Plotting source signal plt.figure(3) plt.plot(t,q) plt.title('Source signal Ricker-Wavelet') plt.ylabel('Amplitude') plt.xlabel('Time in s') plt.draw()
JupyterNotebook/2D/FD_2D_DX4_DT2_fast.ipynb
florianwittkamp/FD_ACOUSTIC
gpl-3.0
Time stepping
# Init Seismograms Seismogramm=np.zeros((3,nt)); # Three seismograms # Calculation of some coefficients i_dx=1.0/(dx) i_dy=1.0/(dy) c1=9.0/(8.0*dx) c2=1.0/(24.0*dx) c3=9.0/(8.0*dy) c4=1.0/(24.0*dy) c5=1.0/np.power(dx,3) c6=1.0/np.power(dy,3) c7=1.0/np.power(dx,2) c8=1.0/np.power(dy,2) c9=np.power(dt,3)/24.0 # Prepare...
JupyterNotebook/2D/FD_2D_DX4_DT2_fast.ipynb
florianwittkamp/FD_ACOUSTIC
gpl-3.0
Save seismograms
## Save seismograms np.save("Seismograms/FD_2D_DX4_DT2_fast",Seismogramm)
JupyterNotebook/2D/FD_2D_DX4_DT2_fast.ipynb
florianwittkamp/FD_ACOUSTIC
gpl-3.0
Plotting
## Image plot fig, ax = plt.subplots(1,1) img = ax.imshow(p); ax.set_title('P-Wavefield') ax.set_xticks(range(0,nx+1,int(nx/5))) ax.set_yticks(range(0,ny+1,int(ny/5))) ax.set_xlabel('Grid-points in X') ax.set_ylabel('Grid-points in Y') fig.colorbar(img) ## Plot seismograms fig, (ax1, ax2, ax3) = plt.subplots(3, 1) fig...
JupyterNotebook/2D/FD_2D_DX4_DT2_fast.ipynb
florianwittkamp/FD_ACOUSTIC
gpl-3.0
Import the digits dataset (http://scikit-learn.org/stable/auto_examples/datasets/plot_digits_last_image.html) and show its attributes
from sklearn.datasets import load_digits digits = load_digits() X_digits, y_digits = digits.data, digits.target print digits.keys()
scikit-learn/scikit-learn-book/Chapter 3 - Unsupervised Learning - Principal Component Analysis.ipynb
marcelomiky/PythonCodes
mit
Let's show how the digits look like...
n_row, n_col = 2, 5 def print_digits(images, y, max_n=10): # set up the figure size in inches fig = plt.figure(figsize=(2. * n_col, 2.26 * n_row)) i=0 while i < max_n and i < images.shape[0]: p = fig.add_subplot(n_row, n_col, i + 1, xticks=[], yticks=[]) p.imshow(images[i], cmap=plt.cm....
scikit-learn/scikit-learn-book/Chapter 3 - Unsupervised Learning - Principal Component Analysis.ipynb
marcelomiky/PythonCodes
mit
Now, let's define a function that will plot a scatter with the two-dimensional points that will be obtained by a PCA transformation. Our data points will also be colored according to their classes. Recall that the target class will not be used to perform the transformation; we want to investigate if the distribution af...
def plot_pca_scatter(): colors = ['black', 'blue', 'purple', 'yellow', 'white', 'red', 'lime', 'cyan', 'orange', 'gray'] for i in xrange(len(colors)): px = X_pca[:, 0][y_digits == i] py = X_pca[:, 1][y_digits == i] plt.scatter(px, py, c=colors[i]) plt.legend(digits.target_names) ...
scikit-learn/scikit-learn-book/Chapter 3 - Unsupervised Learning - Principal Component Analysis.ipynb
marcelomiky/PythonCodes
mit
At this point, we are ready to perform the PCA transformation. In scikit-learn, PCA is implemented as a transformer object that learns n number of components through the fit method, and can be used on new data to project it onto these components. In scikit-learn, we have various classes that implement different kinds o...
from sklearn.decomposition import PCA n_components = n_row * n_col # 10 estimator = PCA(n_components=n_components) X_pca = estimator.fit_transform(X_digits) plot_pca_scatter() # Note that we only plot the first and second principal component
scikit-learn/scikit-learn-book/Chapter 3 - Unsupervised Learning - Principal Component Analysis.ipynb
marcelomiky/PythonCodes
mit
To finish, let us look at principal component transformations. We will take the principal components from the estimator by accessing the components attribute. Each of its components is a matrix that is used to transform a vector from the original space to the transformed space. In the scatter we previously plotted, we ...
def print_pca_components(images, n_col, n_row): plt.figure(figsize=(2. * n_col, 2.26 * n_row)) for i, comp in enumerate(images): plt.subplot(n_row, n_col, i + 1) plt.imshow(comp.reshape((8, 8)), interpolation='nearest') plt.text(0, -1, str(i + 1) + '-component') plt.xticks(()) ...
scikit-learn/scikit-learn-book/Chapter 3 - Unsupervised Learning - Principal Component Analysis.ipynb
marcelomiky/PythonCodes
mit
The BERT repo uses Tensorflow 1 and thus a few of the functions have been moved/changed/renamed in Tensorflow 2. In order for the BERT tokenizer to be used, one of the lines in the repo that was just cloned needs to be modified to comply with Tensorflow 2. Line 125 in the BERT tokenization.py file must be changed as fo...
import tokenization
examples/Document_representation_from_BERT.ipynb
google/patents-public-data
apache-2.0
Load BERT
MAX_SEQ_LENGTH = 512 MODEL_DIR = 'path/to/model' VOCAB = 'path/to/vocab' tokenizer = tokenization.FullTokenizer(VOCAB, do_lower_case=True) model = tf.compat.v2.saved_model.load(export_dir=MODEL_DIR, tags=['serve']) model = model.signatures['serving_default'] # Mean pooling layer for combining pooling = tf.keras.laye...
examples/Document_representation_from_BERT.ipynb
google/patents-public-data
apache-2.0
Get a couple of Patents Here we do a simple query from the BigQuery patents data to collect the claims for a sample set of patents.
# Put your publications here. test_pubs = ( 'US-8000000-B2', 'US-2007186831-A1', 'US-2009030261-A1', 'US-10722718-B2' ) js = r""" // Regex to find the separations of the claims data var pattern = new RegExp(/[.][\\s]+[0-9]+[\\s]*[.]/, 'g'); if (pattern.test(text)) { return text.split(pattern); } """ q...
examples/Document_representation_from_BERT.ipynb
google/patents-public-data
apache-2.0
3. Enter DV360 Report To Sheets Recipe Parameters Specify either report name or report id to move a report. The most recent valid file will be moved to the sheet. Modify the values below for your use case, can be done multiple times, then click play.
FIELDS = { 'auth_read':'user', # Credentials used for reading data. 'report_id':'', # DV360 report ID given in UI, not needed if name used. 'report_name':'', # Name of report, not needed if ID used. 'sheet':'', # Full URL to sheet being written to. 'tab':'', # Existing tab in sheet to write to. } print(...
colabs/dbm_to_sheets.ipynb
google/starthinker
apache-2.0
4. Execute DV360 Report To Sheets This does NOT need to be modified unless you are changing the recipe, click play.
from starthinker.util.configuration import execute from starthinker.util.recipe import json_set_fields TASKS = [ { 'dbm':{ 'auth':{'field':{'name':'auth_read','kind':'authentication','order':1,'default':'user','description':'Credentials used for reading data.'}}, 'report':{ 'report_id':{'fiel...
colabs/dbm_to_sheets.ipynb
google/starthinker
apache-2.0
https://docs.scipy.org/doc/scipy-1.3.0/reference/tutorial/integrate.html https://docs.scipy.org/doc/scipy-1.3.0/reference/integrate.html Integrating functions, given callable object (scipy.integrate.quad) See: - https://docs.scipy.org/doc/scipy-1.3.0/reference/tutorial/integrate.html#general-integration-quad - https:/...
f = lambda x: np.power(x, 2) result = scipy.integrate.quad(f, 0, 3) result
nb_dev_python/python_scipy_integrate.ipynb
jdhp-docs/python_notebooks
mit
The return value is a tuple, with the first element holding the estimated value of the integral and the second element holding an upper bound on the error. Integrating functions, given fixed samples https://docs.scipy.org/doc/scipy-1.3.0/reference/tutorial/integrate.html#integrating-using-samples
x = np.linspace(0., 3., 100) y = f(x) plt.plot(x, y);
nb_dev_python/python_scipy_integrate.ipynb
jdhp-docs/python_notebooks
mit
In case of arbitrary spaced samples, the two functions trapz and simps are available.
result = scipy.integrate.simps(y, x) result result = scipy.integrate.trapz(y, x) result
nb_dev_python/python_scipy_integrate.ipynb
jdhp-docs/python_notebooks
mit
Notice that I've updated the assert to include the word "To-Do" instead of "Django". Now our test should fail. Let's check that it fails.
# First start up the server: #!python3 manage.py runserver # Run test !python3 functional_tests.py
wk9/notebooks/Ch.2-Extending our functional test using the unittest module.ipynb
ThunderShiviah/code_guild
mit
We got what was called an expected fail which is what we wanted! Python Standard Library's unittest Module There are a couple of little annoyances we should probably deal with. Firstly, the message "AssertionError" isn’t very helpful—it would be nice if the test told us what it actually found as the browser title. Also...
%%writefile functional_tests.py from selenium import webdriver import unittest class NewVisitorTest(unittest.TestCase): #1 def setUp(self): #2 self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) # Wait three seconds before trying anything. def tearDown(self): #3 sel...
wk9/notebooks/Ch.2-Extending our functional test using the unittest module.ipynb
ThunderShiviah/code_guild
mit
Some things to notice about our new test file: Tests are organised into classes, which inherit from unittest.TestCase. and setUp and tearDown are special methods which get run before and after each test. I’m using them to start and stop our browser—note that they’re a bit like a try/except, in that tearDown will ...
!python3 functional_tests.py
wk9/notebooks/Ch.2-Extending our functional test using the unittest module.ipynb
ThunderShiviah/code_guild
mit
Visualizing the Tracked Object Distance The next cell visualizes the simulating data. The first visualization shows the object distance over time. You can see that the car is moving forward although decelerating. Then the car stops for 5 seconds and then drives backwards for 5 seconds.
ax1 = data_groundtruth.plot(kind='line', x='time', y='distance', title='Object Distance Versus Time') ax1.set(xlabel='time (milliseconds)', ylabel='distance (meters)')
matrix/kalman_filter_demo.ipynb
jingr1/SelfDrivingCar
mit
Visualizing Velocity Over Time The next cell outputs a visualization of the velocity over time. The tracked car starts at 100 km/h and decelerates to 0 km/h. Then the car idles and eventually starts to decelerate again until reaching -10 km/h.
ax2 = data_groundtruth.plot(kind='line', x='time', y='velocity', title='Object Velocity Versus Time') ax2.set(xlabel='time (milliseconds)', ylabel='velocity (km/h)')
matrix/kalman_filter_demo.ipynb
jingr1/SelfDrivingCar
mit
Visualizing Acceleration Over Time This cell visualizes the tracked cars acceleration. The vehicle declerates at 10 m/s^2. Then the vehicle stops for 5 seconds and briefly accelerates again.
data_groundtruth['acceleration'] = data_groundtruth['acceleration'] * 1000 / math.pow(60 * 60, 2) ax3 = data_groundtruth.plot(kind='line', x='time', y='acceleration', title='Object Acceleration Versus Time') ax3.set(xlabel='time (milliseconds)', ylabel='acceleration (m/s^2)')
matrix/kalman_filter_demo.ipynb
jingr1/SelfDrivingCar
mit
Simulate Lidar Data The following code cell creates simulated lidar data. Lidar data is noisy, so the simulator takes ground truth measurements every 0.05 seconds and then adds random noise.
# make lidar measurements lidar_standard_deviation = 0.15 lidar_measurements = datagenerator.generate_lidar(distance_groundtruth, lidar_standard_deviation) lidar_time = time_groundtruth
matrix/kalman_filter_demo.ipynb
jingr1/SelfDrivingCar
mit
Visualize Lidar Meausrements Run the following cell to visualize the lidar measurements versus the ground truth. The ground truth is shown in red, and you can see that the lidar measurements are a bit noisy.
data_lidar = pd.DataFrame( {'time': time_groundtruth, 'distance': distance_groundtruth, 'lidar': lidar_measurements }) matplotlib.rcParams.update({'font.size': 22}) ax4 = data_lidar.plot(kind='line', x='time', y ='distance', label='ground truth', figsize=(20, 15), alpha=0.8, title = '...
matrix/kalman_filter_demo.ipynb
jingr1/SelfDrivingCar
mit
Part 2 - Using a Kalman Filter The next part of the demonstration will use your matrix class to run a Kalman filter. This first cell initializes variables and defines a few functions. The following cell runs the Kalman filter using the lidar data.
# Kalman Filter Initialization initial_distance = 0 initial_velocity = 0 x_initial = m.Matrix([[initial_distance], [initial_velocity * 1e-3 / (60 * 60)]]) P_initial = m.Matrix([[5, 0],[0, 5]]) acceleration_variance = 50 lidar_variance = math.pow(lidar_standard_deviation, 2) H = m.Matrix([[1, 0]]) R = m.Matrix([[lid...
matrix/kalman_filter_demo.ipynb
jingr1/SelfDrivingCar
mit
Run the Kalman filter The next code cell runs the Kalman filter. In this demonstration, the prediction step starts with the second lidar measurement. When the first lidar signal arrives, there is no previous lidar measurement with which to calculate velocity. In other words, the Kalman filter predicts where the vehicle...
# Kalman Filter Implementation x = x_initial P = P_initial x_result = [] time_result = [] v_result = [] for i in range(len(lidar_measurements) - 1): # calculate time that has passed between lidar measurements delta_t = (lidar_time[i + 1] - lidar_time[i]) / 1000.0 # Prediction Step - estimates ...
matrix/kalman_filter_demo.ipynb
jingr1/SelfDrivingCar
mit
Visualize the Results The following code cell outputs a visualization of the Kalman filter. The chart contains ground turth, the lidar measurements, and the Kalman filter belief. Notice that the Kalman filter tends to smooth out the information obtained from the lidar measurement. It turns out that using multiple senso...
ax6 = data_lidar.plot(kind='line', x='time', y ='distance', label='ground truth', figsize=(22, 18), alpha=.3, title='Lidar versus Kalman Filter versus Ground Truth') ax7 = data_lidar.plot(kind='scatter', x ='time', y ='lidar', label='lidar sensor', ax=ax6) ax8 = result.plot(kind='scatter', x = 'time', y = 'distance', l...
matrix/kalman_filter_demo.ipynb
jingr1/SelfDrivingCar
mit
Visualize the Velocity One of the most interesting benefits of Kalman filters is that they can give you insights into variables that you cannot directly measured. Although lidar does not directly give velocity information, the Kalman filter can infer velocity from the lidar measurements. This visualization shows the Ka...
ax1 = data_groundtruth.plot(kind='line', x='time', y ='velocity', label='ground truth', figsize=(22, 18), alpha=.8, title='Kalman Filter versus Ground Truth Velocity') ax2 = result.plot(kind='scatter', x = 'time', y = 'velocity', label='kalman', ax=ax1, color='r') ax2.set(xlabel='time (milliseconds)', ylabel='velocity ...
matrix/kalman_filter_demo.ipynb
jingr1/SelfDrivingCar
mit
Scrape swear word list We scrape swear words from the web from the site: http://www.noswearing.com/ It is a community driven list of swear words.
import string import os import requests from fake_useragent import UserAgent from lxml import html def requests_get(url): ua = UserAgent().random return requests.get(url, headers={'User-Agent': ua}) def get_swear_words(save_file='swear-words.txt'): """ Scrapes a comprehensive list of swear ...
notebooks/exploratory/02-raw-lyric-analysis.ipynb
tylerwmarrs/billboard-hot-100-lyric-analysis
mit
Testing TextBlob I don't really like TextBlob as it tries to be "nice", but lacks a lot of basic functionality. Stop words not included Tokenizer is pretty meh. No built in way to obtain word frequency
import os import operator import pandas as pd from textblob import TextBlob, WordList from nltk.corpus import stopwords def get_data_paths(): dir_path = os.path.dirname(os.path.realpath('.')) data_dir = os.path.join(dir_path, 'billboard-hot-100-data') dirs = [os.path.join(data_dir, d, 'songs.csv') for d i...
notebooks/exploratory/02-raw-lyric-analysis.ipynb
tylerwmarrs/billboard-hot-100-lyric-analysis
mit
Repetitive songs skewing data? Some songs may be super reptitive. Lets look at a couple of songs that have the word in the title. These songs probably repeat the title a decent amount in their song. Hence treating all lyrics as one group of text less reliable in analyzing frequency. To simplify this process, we can loo...
for i, song in songs.iterrows(): title = song['title'] title_words = title.split(' ') if len(title_words) > 1: continue lyrics = song['lyrics'] words = nltk.tokenize.word_tokenize(lyrics) clean_words = [w.lower() for w in remove_extra_junk(remove_stop_words(words))] di...
notebooks/exploratory/02-raw-lyric-analysis.ipynb
tylerwmarrs/billboard-hot-100-lyric-analysis
mit
Seems pretty reptitive There are a handful of single word song titles that repeat the title within the song at least 10% of the time. This gives us a general idea that there is most likely a skew to the data. I think it is safe to assume that if a single word is repeated many times, the song is most likely reptitive. L...
song_title_to_analyze = 'Water' lyrics = songs['lyrics'].where(songs['title'] == song_title_to_analyze, '').max() print(lyrics) words = nltk.tokenize.word_tokenize(lyrics) clean_words = [w.lower() for w in remove_extra_junk(remove_stop_words(words))] water_dist = nltk.FreqDist(clean_words) water_dist.plot(25) water_d...
notebooks/exploratory/02-raw-lyric-analysis.ipynb
tylerwmarrs/billboard-hot-100-lyric-analysis
mit
Looking at swear word distribution Let's look at the distribution of swear words...
sws = [] for sw in set(corpus.swear_words()): sws.append({'word': sw, 'dist': freq_dist.freq(sw)}) sw_df = pd.DataFrame.from_dict(sws) sw_df.nlargest(10, 'dist').plot(x='word', kind='bar')
notebooks/exploratory/02-raw-lyric-analysis.ipynb
tylerwmarrs/billboard-hot-100-lyric-analysis
mit
Create Variables The xs array is a tuple of SymPy symbolic variables, and the ys array is a PyEDA function array.
xs = sympy.symbols(",".join("x%d" % i for i in range(64))) ys = pyeda.boolalg.bfarray.exprvars('y', 64)
ipynb/SymPy_Comparison.ipynb
karissa/pyeda
bsd-2-clause
Basic Boolean Functions Create a SymPy XOR function:
f = sympy.Xor(*xs[:4])
ipynb/SymPy_Comparison.ipynb
karissa/pyeda
bsd-2-clause
Create a PyEDA XOR function:
g = pyeda.boolalg.expr.Xor(*ys[:4])
ipynb/SymPy_Comparison.ipynb
karissa/pyeda
bsd-2-clause
SymPy atoms method is similar to PyEDA's support property:
f.atoms() g.support
ipynb/SymPy_Comparison.ipynb
karissa/pyeda
bsd-2-clause
SymPy's subs method is similar to PyEDA's restrict method:
f.subs({xs[0]: 0, xs[1]: 1}) g.restrict({ys[0]: 0, ys[1]: 1})
ipynb/SymPy_Comparison.ipynb
karissa/pyeda
bsd-2-clause
Conversion to NNF Conversion to negation normal form is also similar. One difference is that SymPy inverts the variables by applying a Not operator, but PyEDA converts inverted variables to complements (a negative literal).
sympy.to_nnf(f) type(sympy.Not(xs[0])) g.to_nnf() type(~ys[0])
ipynb/SymPy_Comparison.ipynb
karissa/pyeda
bsd-2-clause
Conversion to DNF Conversion to disjunctive normal form, on the other hand, has some differences. With only four input variables, SymPy takes a couple seconds to do the calculation. The output is large, with unsimplified values and redundant clauses.
sympy.to_dnf(f)
ipynb/SymPy_Comparison.ipynb
karissa/pyeda
bsd-2-clause
PyEDA's DNF conversion is minimal:
g.to_dnf()
ipynb/SymPy_Comparison.ipynb
karissa/pyeda
bsd-2-clause
It's a little hard to do an apples-to-apples comparison, because 1) SymPy is pure Python and 2) the algorithms are probably different. The simplify_logic function actually looks better for comparison:
from sympy.logic import simplify_logic simplify_logic(f) simplify_logic(f)
ipynb/SymPy_Comparison.ipynb
karissa/pyeda
bsd-2-clause
Running this experiment from N=2 to N=6 shows that PyEDA's runtime grows significantly slower.
import numpy as np import matplotlib.pyplot as plt %matplotlib inline N = 5 sympy_times = (.000485, .000957, .00202, .00426, .0103) pyeda_times = (.0000609, .000104, .000147, .00027, .000451) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots()...
ipynb/SymPy_Comparison.ipynb
karissa/pyeda
bsd-2-clause
Going a bit further, things get worse. These numbers are from my laptop: | N | sympy | pyeda | ratio | |----|----------|----------|--------| | 2 | .000485 | .0000609 | 7.96 | | 3 | .000957 | .000104 | 9.20 | | 4 | .00202 | .000147 | 13.74 | | 5 | .00426 | .00027 | 15.78 | | 6 | .0103 | ....
sympy.Equivalent(xs[0], xs[1], 0) pyeda.boolalg.expr.Equal(ys[0], ys[1], 0) sympy.ITE(xs[0], 0, xs[1]) pyeda.boolalg.expr.ITE(ys[0], 0, ys[1]) sympy.Or(xs[0], sympy.Or(xs[1], xs[2])) pyeda.boolalg.expr.Or(ys[0], pyeda.boolalg.expr.Or(ys[1], ys[2])) sympy.Xor(xs[0], sympy.Not(sympy.Xor(xs[1], xs[2]))) pyeda.boola...
ipynb/SymPy_Comparison.ipynb
karissa/pyeda
bsd-2-clause
Vertex SDK: Submit a HyperParameter tuning training job with TensorFlow Installation Install the latest (preview) version of Vertex SDK.
! pip3 install -U google-cloud-aiplatform --user
notebooks/community/migration/UJ11 HyperParameter Tuning Training Job with TensorFlow.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Set up variables Next, set up some variables used throughout the tutorial. Import libraries and define constants Import Vertex SDK Import the Vertex SDK into our Python environment.
import os import sys import time from google.cloud.aiplatform import gapic as aip from google.protobuf import json_format from google.protobuf.json_format import MessageToJson, ParseDict from google.protobuf.struct_pb2 import Struct, Value
notebooks/community/migration/UJ11 HyperParameter Tuning Training Job with TensorFlow.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Prepare a trainer script Package assembly
# Make folder for python training script ! rm -rf custom ! mkdir custom # Add package information ! touch custom/README.md setup_cfg = "[egg_info]\n\ tag_build =\n\ tag_date = 0" ! echo "$setup_cfg" > custom/setup.cfg setup_py = "import setuptools\n\ # Requires TensorFlow Datasets\n\ setuptools.setup(\n\ install...
notebooks/community/migration/UJ11 HyperParameter Tuning Training Job with TensorFlow.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Task.py contents
%%writefile custom/trainer/task.py # hyperparameter tuningfor Boston Housing import tensorflow_datasets as tfds import tensorflow as tf from tensorflow.python.client import device_lib from hypertune import HyperTune import numpy as np import argparse import os import sys tfds.disable_progress_bar() parser = argpars...
notebooks/community/migration/UJ11 HyperParameter Tuning Training Job with TensorFlow.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Store training script on your Cloud Storage bucket
! rm -f custom.tar custom.tar.gz ! tar cvf custom.tar custom ! gzip custom.tar ! gsutil cp custom.tar.gz gs://$BUCKET_NAME/hpt_boston_housing.tar.gz
notebooks/community/migration/UJ11 HyperParameter Tuning Training Job with TensorFlow.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Train a model projects.locations.hyperparameterTuningJob.create Request
JOB_NAME = "hyperparameter_tuning_" + TIMESTAMP WORKER_POOL_SPEC = [ { "replica_count": 1, "machine_spec": {"machine_type": "n1-standard-4", "accelerator_count": 0}, "python_package_spec": { "executor_image_uri": "gcr.io/cloud-aiplatform/training/tf-cpu.2-1:latest", ...
notebooks/community/migration/UJ11 HyperParameter Tuning Training Job with TensorFlow.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example output: { "parent": "projects/migration-ucaip-training/locations/us-central1", "hyperparameterTuningJob": { "displayName": "hyperparameter_tuning_20210226020029", "studySpec": { "metrics": [ { "metricId": "val_loss", "goal": "MINIMIZE" } ], "para...
request = clients["job"].create_hyperparameter_tuning_job( parent=PARENT, hyperparameter_tuning_job=hyperparameter_tuning_job )
notebooks/community/migration/UJ11 HyperParameter Tuning Training Job with TensorFlow.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example output: { "name": "projects/116273516712/locations/us-central1/hyperparameterTuningJobs/5264408897233354752", "displayName": "hyperparameter_tuning_20210226020029", "studySpec": { "metrics": [ { "metricId": "val_loss", "goal": "MINIMIZE" } ], "parameters": [ {...
# The full unique ID for the hyperparameter tuningjob hyperparameter_tuning_id = request.name # The short numeric ID for the hyperparameter tuningjob hyperparameter_tuning_short_id = hyperparameter_tuning_id.split("/")[-1] print(hyperparameter_tuning_id)
notebooks/community/migration/UJ11 HyperParameter Tuning Training Job with TensorFlow.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
projects.locations.hyperparameterTuningJob.get Call
request = clients["job"].get_hyperparameter_tuning_job(name=hyperparameter_tuning_id)
notebooks/community/migration/UJ11 HyperParameter Tuning Training Job with TensorFlow.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example output: { "name": "projects/116273516712/locations/us-central1/hyperparameterTuningJobs/5264408897233354752", "displayName": "hyperparameter_tuning_20210226020029", "studySpec": { "metrics": [ { "metricId": "val_loss", "goal": "MINIMIZE" } ], "parameters": [ {...
while True: response = clients["job"].get_hyperparameter_tuning_job( name=hyperparameter_tuning_id ) if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED: print("Study trials have not completed:", response.state) if response.state == aip.PipelineState.PIPELINE_STATE_FAILED...
notebooks/community/migration/UJ11 HyperParameter Tuning Training Job with TensorFlow.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Review the results of the study
best = (None, None, None, 0.0) response = clients["job"].get_hyperparameter_tuning_job(name=hyperparameter_tuning_id) for trial in response.trials: print(MessageToJson(trial.__dict__["_pb"])) # Keep track of the best outcome try: if float(trial.final_measurement.metrics[0].value) > best[3]: ...
notebooks/community/migration/UJ11 HyperParameter Tuning Training Job with TensorFlow.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example output: ``` { "id": "1", "state": "SUCCEEDED", "parameters": [ { "parameterId": "lr", "value": 0.1 }, { "parameterId": "units", "value": 80.0 } ], "finalMeasurement": { "stepCount": "19", "metrics": [ { "metricId": "val_loss", "valu...
delete_hpt_job = True delete_bucket = True # Delete the hyperparameter tuningusing the Vertex AI fully qualified identifier for the custome training try: if delete_hpt_job: clients["job"].delete_hyperparameter_tuning_job(name=hyperparameter_tuning_id) except Exception as e: print(e) if delete_bucket a...
notebooks/community/migration/UJ11 HyperParameter Tuning Training Job with TensorFlow.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Download the dataset of characters 'A' to 'J' rendered in various fonts as 28x28 images. There is training set of about 500k images and a test set of about 19000 images.
url = "http://yaroslavvb.com/upload/notMNIST/" data_path = outputer.setup_directory("notMNIST") def maybe_download(path, filename, expected_bytes): """Download a file if not present, and make sure it's the right size.""" file_path = os.path.join(path, filename) if not os.path.exists(file_path): fil...
notMNIST_setup.ipynb
ponderousmad/pyndent
mit
Extract the dataset from the compressed .tar.gz file. This should give you a set of directories, labelled A through J.
def extract(filename, root, class_count): # remove path and .tar.gz dir_name = os.path.splitext(os.path.splitext(os.path.basename(filename))[0])[0] path = os.path.join(root, dir_name) print("Extracting", filename, "to", path) tar = tarfile.open(filename) tar.extractall(path=root) tar.close()...
notMNIST_setup.ipynb
ponderousmad/pyndent
mit
Inspect Data Verify that the images contain rendered glyphs.
Image(filename="notMNIST/notMNIST_small/A/MDEtMDEtMDAudHRm.png") Image(filename="notMNIST/notMNIST_large/A/a2F6b28udHRm.png") Image(filename="notMNIST/notMNIST_large/C/ZXVyb2Z1cmVuY2UgaXRhbGljLnR0Zg==.png") # This I is all white Image(filename="notMNIST/notMNIST_small/I/SVRDIEZyYW5rbGluIEdvdGhpYyBEZW1pLnBmYg==.png")
notMNIST_setup.ipynb
ponderousmad/pyndent
mit
Convert the data into an array of normalized grayscale floating point images, and an array of classification labels. Unreadable images are skipped.
def normalize_separator(path): return path.replace("\\", "/") def load(data_folders, set_id, min_count, max_count): # Create arrays large enough for maximum expected data. dataset = np.ndarray(shape=(max_count, image_size, image_size), dtype=np.float32) labels = np.ndarray(shape=(max_count), dtype=np....
notMNIST_setup.ipynb
ponderousmad/pyndent
mit
Verify Proccessed Data
exemplar = plt.imshow(train_dataset[0]) train_labels[0] exemplar = plt.imshow(train_dataset[373]) train_labels[373] exemplar = plt.imshow(test_dataset[18169]) test_labels[18169] exemplar = plt.imshow(train_dataset[-9]) train_labels[-9]
notMNIST_setup.ipynb
ponderousmad/pyndent
mit
Compress and Store Data
pickle_file = 'notMNIST/full.pickle' try: f = gzip.open(pickle_file, 'wb') save = { 'train_dataset': train_dataset, 'train_labels': train_labels, 'test_dataset': test_dataset, 'test_labels': test_labels } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except...
notMNIST_setup.ipynb
ponderousmad/pyndent
mit
Peak finding Write a function find_peaks that finds and returns the indices of the local maxima in a sequence. Your function should: Properly handle local maxima at the endpoints of the input array. Return a Numpy array of integer indices. Handle any Python iterable as input.
np.array(range(5)).max() list(range(1,5)) find_peaks([2,0,1,0,2,0,1]) def find_peaks(a): """Find the indices of the local maxima in a sequence.""" b=[] c=np.array(a) if c[0]>c[1]: b.append(0) for i in range(1,len(c)-1): if c[i]>c[i-1] and c[i]>c[i+1]: b.append(i) if...
assignments/assignment07/AlgorithmsEx02.ipynb
hunterherrin/phys202-2015-work
mit
Here is a string with the first 10000 digits of $\pi$ (after the decimal). Write code to perform the following: Convert that string to a Numpy array of integers. Find the indices of the local maxima in the digits of $\pi$. Use np.diff to find the distances between consequtive local maxima. Visualize that distribution ...
from sympy import pi, N pi_digits_str = str(N(pi, 10001))[2:] first_10000=np.array(list(pi_digits_str), dtype=int) peaks=find_peaks(first_10000) differences=np.diff(peaks) plt.figure(figsize=(10,10)) plt.hist(differences, 20, (1,20)) plt.title('Hoe Far Apart the Local Maxima of the First 10,0000 Digits of $\pi$ Are') ...
assignments/assignment07/AlgorithmsEx02.ipynb
hunterherrin/phys202-2015-work
mit
Define the variables for this analysis. 1. how many percentiles the data is divided into 2. where the Z-Maps (from neurosynth) lie 3. where the binned gradient maps lie 4. where a mask of the brain lies (not used at the moment).
percentiles = range(10) # unthresholded z-maps from neurosynth: zmaps = [os.path.join(os.getcwd(), 'ROIs_Mask', fname) for fname in os.listdir(os.path.join(os.getcwd(), 'ROIs_Mask')) if 'z.nii' in fname] # individual, binned gradient maps, in a list of lists: gradmaps = [[os.path.join(os.getcwd(), 'data', 'O...
6b_networks-inside-gradients.ipynb
autism-research-centre/Autism-Gradients
gpl-3.0
Next define a function to take the average of an image inside a mask and return it:
def zinsidemask(zmap, mask): # zaverage = zmap.dataobj[ np.logical_and(np.not_equal(mask.dataobj, 0), brainmask.dataobj>0) ].mean() return zaverage
6b_networks-inside-gradients.ipynb
autism-research-centre/Autism-Gradients
gpl-3.0
This next cell will step through each combination of gradient, subject and network file to calculate the average z-score inside the mask defined by the gradient percentile. This will take a long time to run!
zaverages = np.zeros([len(zmaps), len(gradmaps), len(gradmaps[0])]) # load first gradmap just for resampling gradmap = nib.load(gradmaps[0][0]) # Load a brainmask brainmask = nib.load(brainmaskfile) brainmask = resample_img(brainmask, target_affine=gradmap.affine, target_shape=gradmap.shape) # Initialise a progress ...
6b_networks-inside-gradients.ipynb
autism-research-centre/Autism-Gradients
gpl-3.0
To save time next time, we'll save the result of this to file:
# np.save(os.path.join(os.getcwd(), 'data', 'average-abs-z-scores'), zaverages) zaverages = np.load(os.path.join(os.getcwd(), 'data', 'average-z-scores.npy'))
6b_networks-inside-gradients.ipynb
autism-research-centre/Autism-Gradients
gpl-3.0
Extract a list of which group contains which participants.
df_phen = pd.read_csv('data' + os.sep + 'SelectedSubjects.csv') diagnosis = df_phen.loc[:, 'DX_GROUP'] fileids = df_phen.loc[:, 'FILE_ID'] groupvec = np.zeros(len(gradmaps[0])) for filenum, filename in enumerate(gradmaps[0]): fileid = os.path.split(filename)[-1][5:-22] groupvec[filenum] = (diagnosis[fileids.st...
6b_networks-inside-gradients.ipynb
autism-research-centre/Autism-Gradients
gpl-3.0
Make a plot of the z-scores inside each parcel for each gradient, split by group!
fig = plt.figure(figsize=(15, 8)) grouplabels = ['Control group', 'Autism group'] for group in np.unique(groupvec): ylabels = [os.path.split(fname)[-1][0:-23].replace('_', ' ') for fname in zmaps] # remove duplicates! includenetworks = [] seen = set() for string in ylabels: includenetwo...
6b_networks-inside-gradients.ipynb
autism-research-centre/Autism-Gradients
gpl-3.0
Spacy Documentation Spacy is an NLP/Computational Linguistics package built from the ground up. It's written in Cython so it's fast!! Let's check it out. Here's some text from Alice in Wonderland free on Gutenberg.
text = """'Please would you tell me,' said Alice, a little timidly, for she was not quite sure whether it was good manners for her to speak first, 'why your cat grins like that?' 'It's a Cheshire cat,' said the Duchess, 'and that's why. Pig!' She said the last word with such sudden violence that Alice quite jumped; but...
notebooks/nlp_spacy.ipynb
AlJohri/DAT-DC-12
mit