markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Logarithmic axis
The axis scale can be adapted with the xscale and yscale settings. | import tellurium as te
te.setDefaultPlottingEngine('matplotlib')
%matplotlib inline
r = te.loadTestModel('feedback.xml')
r.integrator.variable_step_size = True
s = r.simulate(0, 50)
r.plot(s, logx=True, xlim=[10E-4, 10E2],
title="Logarithmic x-Axis with grid", ylabel="concentration"); | examples/notebooks/core/tellurium_plotting.ipynb | kirichoi/tellurium | apache-2.0 |
Mine titles and abstracts for topics | #import dependencies
import pandas as pd
from textblob import TextBlob
#import spacy
#nlp = spacy.load('en')
#run once if you need to download nltk corpora, igonre otherwise
import nltk
nltk.download()
df=pd.read_csv('../a.csv')
p=df[df.columns[1]].values.astype(str)
#get topical nouns for title and abstract using ... | test/gcrf-hub/wordcloud/wordcloud.ipynb | csaladenes/csaladenes.github.io | mit |
Minimal steps:
queue = [A]
next = A; queue = [B,C]
next = B; queue = [I,D,E,C]
next = I -> STOP
There are 3 iterations needed to find node I in minimum.
Question II (a) | import pandas as pd
adjacency = pd.DataFrame({'A':[0,1,1,0,0,0,0,0,0],
'B':[0,0,0,1,1,0,0,0,1],
'C':[0,0,0,0,0,1,1,0,0],
'D':[0,0,0,0,1,0,0,1,0],
'E':[0,0,0,0,0,0,0,0,1],
'F':[1,0,0,0,0,0,1... | Algorithmic_Basics_of_Bioinformatics/Algorithmic Basics of Bioinformatics Tutorial Sheet 3.ipynb | Oli4/lsi-material | mit |
Question II (b)
A graph is acyclic if it contains not only one cycle and directed if the edges have a direction. This grahp contains a cycle (A->C->F->A) so it is not acyclic but the edges have a directions so it is directed.
Question II (c)
Yes there are Eulerian cycles in the graph. Eulerian cycles use every edge exa... | def dfs(matrix, query, start):
# Return True if the query was found
if query == start:
return True
# Return False if Node is already visited
elif start not in matrix.index:
return False
# Return False if there are not outgoing edges
elif not 1 in matrix.loc[start].values:
... | Algorithmic_Basics_of_Bioinformatics/Algorithmic Basics of Bioinformatics Tutorial Sheet 3.ipynb | Oli4/lsi-material | 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
"""
return {
'.': '||Period||',
',': '||Comma||',
'"': '||QuotationMark||',
';': '||Semicolon||',
... | tv-script-generation/dlnd_tv_script_generation.ipynb | yuanotes/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)
"""
inputs = tf.placeholder(tf.int32, shape=[None, None], name="input")
targets = tf.placeholder(tf.int32, shape=[None, None])
learning_rate = tf.placeholder(tf.... | tv-script-generation/dlnd_tv_script_generation.ipynb | yuanotes/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)
"""
n_layers = 1
# keep_prob = 0.5
lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size)
# dorp ... | tv-script-generation/dlnd_tv_script_generation.ipynb | yuanotes/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 | yuanotes/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
"""
n_batches = len(int_te... | tv-script-generation/dlnd_tv_script_generation.ipynb | yuanotes/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 = 30
# Batch Size
batch_size = 500
# RNN Size
rnn_size = 500
# Embedding Dimension Size
embed_dim = 300
# Sequence Length
seq_length = 10
# Learning Rate
learning_rate = 0.03
# Show stats for every n number of batches
show_every_n_batches = 10
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT I... | tv-script-generation/dlnd_tv_script_generation.ipynb | yuanotes/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
"""
choice = np.random.choice(len... | tv-script-generation/dlnd_tv_script_generation.ipynb | yuanotes/deep-learning | mit |
If you zoom in you will note that the plot rerenders depending on the zoom level, which allows the full dataset to be explored interactively even though only an image of it is ever sent to the browser. The way this works is that datashade is a dynamic operation that also declares some linked streams. These linked stre... | datashade.streams
# Exercise: Plot the taxi pickup locations ('pickup_x' and 'pickup_y' columns)
# Warning: Don't try to display hv.Points() directly; it's too big! Use datashade() for any display
# Optional: Change the cmap on the datashade operation to inferno
from datashader.colors import inferno
points = hv.Poin... | solutions/07-working-with-large-datasets-with-solutions.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Adding a tile source
Using the GeoViews (geographic) extension for HoloViews, we can display a map in the background. Just declare a Bokeh WMTSTileSource and pass it to the gv.WMTS Element, then we can overlay it: | %opts RGB [xaxis=None yaxis=None]
import geoviews as gv
from bokeh.models import WMTSTileSource
url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg'
wmts = WMTSTileSource(url=url)
gv.WMTS(wmts) * datashade(points)
%opts RGB [xaxis=None yaxis=None]
# Exercise: Overla... | solutions/07-working-with-large-datasets-with-solutions.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Aggregating with a variable
So far we have simply been counting taxi dropoffs, but our dataset is much richer than that. We have information about a number of variables including the total cost of a taxi ride, the total_amount. Datashader provides a number of aggregator functions, which you can supply to the datashade ... | selected = points.select(total_amount=(None, 1000))
selected.data = selected.data.persist()
gv.WMTS(wmts) * datashade(selected, aggregator=ds.mean('total_amount'))
# Exercise: Use the ds.min or ds.max aggregator to visualize ``tip_amount`` by dropoff location
# Optional: Eliminate outliers by using select
selected =... | solutions/07-working-with-large-datasets-with-solutions.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Grouping by a variable
Because datashading happens only just before visualization, you can use any of the techniques shown in previous sections to select, filter, or group your data before visualizing it, such as grouping it by the hour of day: | %opts Image [width=600 height=500 logz=True xaxis=None yaxis=None]
taxi_ds = hv.Dataset(ddf)
grouped = taxi_ds.to(hv.Points, ['dropoff_x', 'dropoff_y'], groupby=['hour'], dynamic=True)
aggregate(grouped).redim.values(hour=range(24))
%%opts Image [width=300 height=200 xaxis=None yaxis=None]
# Exercise: Facet the trips ... | solutions/07-working-with-large-datasets-with-solutions.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Chargement du modèle | from code_beatrix.ai import DLImageSegmentation
model = DLImageSegmentation(fLOG=print) | _doc/notebooks/ai/image_segmentation.ipynb | sdpython/code_beatrix | mit |
Sur une petite image | img = 'images/Tesla_circa_1890c.jpg'
feat, pred = model.predict(img)
pred.shape
viz = model.plot(img, pred) # img ou feat
import skimage.io as skio
skio.imshow(viz) | _doc/notebooks/ai/image_segmentation.ipynb | sdpython/code_beatrix | mit |
Sur une image dont on change la taille | from PIL import Image
img = 'images/Tesla_circa_1890c.jpg'
pilimg = Image.open(img)
si = pilimg.size
pilimg2 = pilimg.resize((si[0]//2, si[1]//2))
from skimage.io._plugins.pil_plugin import pil_to_ndarray
skimg = pil_to_ndarray(pilimg2)
skimg.shape
feat, pred = model.predict(skimg)
pred.shape
viz = model.plot(skim... | _doc/notebooks/ai/image_segmentation.ipynb | sdpython/code_beatrix | mit |
Sur une grande image | img = 'images/h2015_2.jpg'
pilimg = Image.open(img)
si = pilimg.size
pilimg2 = pilimg.resize((si[0]//2, si[1]//2))
skimg = pil_to_ndarray(pilimg2)
skimg.shape
skio.imshow(skimg)
feat, pred = model.predict(skimg)
pred.shape
viz = model.plot(feat, pred)
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1, ... | _doc/notebooks/ai/image_segmentation.ipynb | sdpython/code_beatrix | mit |
Now let's find the celebrities. The most basic centrality is Degree Centrality which is the sum of all in and out nodes (in the case of directed graph). | dg_centrality = nx.degree_centrality(g_fb)
sorted_dg_centrality = sorted(dg_centrality.items(), key=operator.itemgetter(1), reverse=True)
sorted_dg_centrality[:10] | Centralities.ipynb | noppanit/social-network-analysis | mit |
We can see that the node 107 has the highest degree centrality which means node 107 has the highest number of connected nodes. We can prove this by getting the degree of node 107 to see how many friends of node 107 has | nx.degree(g_fb, [107]) | Centralities.ipynb | noppanit/social-network-analysis | mit |
Node 107 has 1045 friends and we can divide that by number of nodes to get the normalized degree centrality | float(nx.degree(g_fb, [107]).values()[0]) / g_fb.number_of_nodes() | Centralities.ipynb | noppanit/social-network-analysis | mit |
Degree centrality might be the easiest number to calculate but it only shows the number of nodes connected which in real social network it might not be very useful as you might have a million followers but if the majority of them is bots then the number is not telling anything new.
Now let's try Betweenness which count... | from multiprocessing import Pool
import itertools
def partitions(nodes, n):
"Partitions the nodes into n subsets"
nodes_iter = iter(nodes)
while True:
partition = tuple(itertools.islice(nodes_iter,n))
if not partition:
return
yield partition
def btwn_pool(G_tuple):
... | Centralities.ipynb | noppanit/social-network-analysis | mit |
Let's try with multiprocesser. | start = timeit.default_timer()
bt = between_parallel(g_fb)
stop = timeit.default_timer()
top = 10
max_nodes = sorted(bt.iteritems(), key = lambda v: -v[1])[:top]
bt_values = [5]*len(g_fb.nodes())
bt_colors = [0]*len(g_fb.nodes())
for max_key, max_val in max_nodes:
bt_values[max_key] = 150
bt_colors[max_key] =... | Centralities.ipynb | noppanit/social-network-analysis | mit |
Now let's try with just one processor | start = timeit.default_timer()
bt = nx.betweenness_centrality(g_fb)
stop = timeit.default_timer()
top = 10
max_nodes = sorted(bt.iteritems(), key = lambda v: -v[1])[:top]
bt_values = [5]*len(g_fb.nodes())
bt_colors = [0]*len(g_fb.nodes())
for max_key, max_val in max_nodes:
bt_values[max_key] = 150
bt_colors[m... | Centralities.ipynb | noppanit/social-network-analysis | mit |
Page rank
We're going to try PageRank algorithm. This is very similar to Google's PageRank which they use incoming links to determine the "popularity" | g_fb_pr = nx.pagerank(g_fb)
top = 10
max_pagerank = sorted(g_fb_pr.iteritems(), key = lambda v: -v[1])[:top]
max_pagerank | Centralities.ipynb | noppanit/social-network-analysis | mit |
We can see that now the score is different as node 3437 is more popular than node 107.
Who is a "Gray Cardinal"
There's another metric that we can measure most influential node. It's called eigenvector centrality. To put it simply it means that if you're well connected to a lot of important people that means you're imp... | g_fb_eg = nx.eigenvector_centrality(g_fb)
top = 10
max_eg = sorted(g_fb_eg.iteritems(), key = lambda v: -v[1])[:top]
max_eg | Centralities.ipynb | noppanit/social-network-analysis | mit |
Now we get quite a different result. This would mean that node 1912 is connected to more important people in the entire network that means that node is more influential than the rest of the network.
iGraph with SNAP Facebook Dataset
Networkx is easy to install and great to start with. However, as it's written in Python... | from igraph import *
import timeit
igraph_fb = Graph.Read_Edgelist('facebook_combined.txt', directed=False)
print igraph_fb.summary() | Centralities.ipynb | noppanit/social-network-analysis | mit |
Betweenness | def betweenness_centralization(G):
vnum = G.vcount()
if vnum < 3:
raise ValueError("graph must have at least three vertices")
denom = (vnum-1)*(vnum-2)
temparr = [2*i/denom for i in G.betweenness()]
return temparr
start = timeit.default_timer()
igraph_betweenness = betweenness_centralizat... | Centralities.ipynb | noppanit/social-network-analysis | mit |
Closeness | start = timeit.default_timer()
igraph_closeness = igraph_fb.closeness()
stop = timeit.default_timer()
print 'It takes {} seconds to finish'.format(stop - start)
igraph_closeness.sort(reverse=True)
print igraph_closeness[:10] | Centralities.ipynb | noppanit/social-network-analysis | mit |
Eigen Value | start = timeit.default_timer()
igraph_eg = igraph_fb.evcent()
stop = timeit.default_timer()
print 'It takes {} seconds to finish'.format(stop - start)
igraph_eg.sort(reverse=True)
print igraph_eg[:10] | Centralities.ipynb | noppanit/social-network-analysis | mit |
PageRank | start = timeit.default_timer()
igraph_pr = igraph_fb.pagerank()
stop = timeit.default_timer()
print 'It takes {} seconds to finish'.format(stop - start)
igraph_pr.sort(reverse=True)
print igraph_pr[:10] | Centralities.ipynb | noppanit/social-network-analysis | mit |
We can see that iGraph yields similar result from networkx but it's a lot quicker in the same machine.
Graph_tool with SNAP Facebook Dataset
I'm going to try another library which is supposed to be the fastest than networkx and igraph. Graph_tool is also C based which it has OpenMP enabled so a lot of algorithms is mul... | import sys
from graph_tool.all import *
import timeit
show_config()
graph_tool_fb = Graph(directed=False)
with open('facebook_combined.txt', 'r') as f:
for line in f:
edge_list = line.split()
source, target = tuple(edge_list)
graph_tool_fb.add_edge(source, target)
print graph_tool_fb.nu... | Centralities.ipynb | noppanit/social-network-analysis | mit |
Betweeness | start = timeit.default_timer()
vertext_betweenness, edge_betweenness = betweenness(graph_tool_fb)
stop = timeit.default_timer()
print 'It takes {} seconds to finish'.format(stop - start)
vertext_betweenness.a[107] | Centralities.ipynb | noppanit/social-network-analysis | mit |
Closeness | start = timeit.default_timer()
v_closeness = closeness(graph_tool_fb)
stop = timeit.default_timer()
print 'It takes {} seconds to finish'.format(stop - start)
v_closeness.a[107] | Centralities.ipynb | noppanit/social-network-analysis | mit |
Eigenvalue | start = timeit.default_timer()
v_closeness = eigenvector(graph_tool_fb)
stop = timeit.default_timer()
print 'It takes {} seconds to finish'.format(stop - start) | Centralities.ipynb | noppanit/social-network-analysis | mit |
Page Rank | start = timeit.default_timer()
v_closeness = pagerank(graph_tool_fb)
stop = timeit.default_timer()
print 'It takes {} seconds to finish'.format(stop - start) | Centralities.ipynb | noppanit/social-network-analysis | mit |
Information diffusion modelling
I'm going to information diffusion model to simulate how information travels in the graph. | %matplotlib inline
import random as r
import networkx as nx
import matplotlib.pyplot as plot
class Person(object):
def __init__(self, id):
#Start with a single initial preference
self.id = id
self.i = r.random()
self.a = self.i
# we value initial opinion and subsequent infor... | Centralities.ipynb | noppanit/social-network-analysis | mit |
Networkx Independent Cascade Model | import copy
import networkx as nx
import random
def independent_cascade(G, seeds, steps = 0):
"""
"Return the active nodes of each diffusion step by the independent cascade
model
Parameters
-- -- -- -- -- -
G: graph
A NetworkX graph
seeds: list of nodes
The seed nodes for diffu... | Centralities.ipynb | noppanit/social-network-analysis | mit |
<div class="alert alert-success">
<b>EXERCISE</b>: Use groupby() to plot the number of "Hamlet" films made each decade.
</div> | hamlet = titles[titles['title'] == 'Hamlet']
hamlet.groupby(hamlet.year // 10 * 10).size().plot(kind='bar') | solved - 04b - Advanced groupby operations.ipynb | jorisvandenbossche/2015-EuroScipy-pandas-tutorial | bsd-2-clause |
<div class="alert alert-success">
<b>EXERCISE</b>: How many leading (n=1) roles were available to actors, and how many to actresses, in each year of the 1950s?
</div> | cast1950 = cast[cast.year // 10 == 195]
cast1950 = cast1950[cast1950.n == 1]
cast1950.groupby(['year', 'type']).size() | solved - 04b - Advanced groupby operations.ipynb | jorisvandenbossche/2015-EuroScipy-pandas-tutorial | bsd-2-clause |
<div class="alert alert-success">
<b>EXERCISE</b>: List the 10 actors/actresses that have the most leading roles (n=1) since the 1990's.
</div> | cast1990 = cast[cast['year'] >= 1990]
cast1990 = cast1990[cast1990.n == 1]
cast1990.groupby('name').size().nlargest(10) | solved - 04b - Advanced groupby operations.ipynb | jorisvandenbossche/2015-EuroScipy-pandas-tutorial | bsd-2-clause |
<div class="alert alert-success">
<b>EXERCISE</b>: List each of the characters that Frank Oz has portrayed at least twice.
</div> | c = cast
c = c[c.name == 'Frank Oz']
g = c.groupby(['character']).size()
g[g > 1].sort_values() | solved - 04b - Advanced groupby operations.ipynb | jorisvandenbossche/2015-EuroScipy-pandas-tutorial | bsd-2-clause |
<div class="alert alert-success">
<b>EXERCISE</b>: Add a column to the `cast` dataframe that indicates the number of roles for the film.
</div> | cast['n_total'] = cast.groupby('title')['n'].transform('max')
cast.head() | solved - 04b - Advanced groupby operations.ipynb | jorisvandenbossche/2015-EuroScipy-pandas-tutorial | bsd-2-clause |
<div class="alert alert-success">
<b>EXERCISE</b>: Calculate the ratio of leading actor and actress roles to the total number of leading roles per decade.
</div>
Tip: you can to do a groupby twice in two steps, once calculating the numbers, and then the ratios. | leading = cast[cast['n'] == 1]
sums_decade = leading.groupby([cast['year'] // 10 * 10, 'type']).size()
sums_decade
#sums_decade.groupby(level='year').transform(lambda x: x / x.sum())
ratios_decade = sums_decade / sums_decade.groupby(level='year').transform('sum')
ratios_decade
ratios_decade[:, 'actor'].plot()
ratios_... | solved - 04b - Advanced groupby operations.ipynb | jorisvandenbossche/2015-EuroScipy-pandas-tutorial | bsd-2-clause |
For an overview of all string methods, see: http://pandas.pydata.org/pandas-docs/stable/api.html#string-handling
<div class="alert alert-success">
<b>EXERCISE</b>: We already plotted the number of 'Hamlet' films released each decade, but not all titles are exactly called 'Hamlet'. Give an overview of the titles tha... | hamlets = titles[titles['title'].str.contains('Hamlet')]
hamlets['title'].value_counts()
hamlets = titles[titles['title'].str.match('Hamlet')]
hamlets['title'].value_counts() | solved - 04b - Advanced groupby operations.ipynb | jorisvandenbossche/2015-EuroScipy-pandas-tutorial | bsd-2-clause |
<div class="alert alert-success">
<b>EXERCISE</b>: List the 10 movie titles with the longest name.
</div> | title_longest = titles['title'].str.len().nlargest(10)
title_longest
pd.options.display.max_colwidth = 210
titles.loc[title_longest.index] | solved - 04b - Advanced groupby operations.ipynb | jorisvandenbossche/2015-EuroScipy-pandas-tutorial | bsd-2-clause |
We need two new columns for $x$ and $y$ error. We can calculate this by first calulating the theoretical coordinate and then subtracting the observed coordinate. | dynamixel_range = 300.0
gear_ratio = 76.0 / 32.0
l_1 = 15.25
l_2 = 13.75
x_offset = 17.0
y_offset = -2.97
gripper_offset = 0.5
def f_with_theta(s, theta_prime_1, theta_prime_2):
theta_1 = ((1023.0-s[:,0])/1023.0) * np.deg2rad(dynamixel_range / gear_ratio) + theta_prime_1
theta_2 = ((1023.0-s[:,1])/1023.0) * np... | notebooks/arm_error_correction.ipynb | joeymeyer/raspberryturk | mit |
Optimization of Theta Values
$\theta'_1$ and $\theta'_2$ were measured by hand to be 4° and 40° respectively. To find a more accurate measurement, we will brute force values close to those and find the two values that results in the smallest mean squared error when comparing the theoretical results to the known values ... | from sklearn.metrics import mean_squared_error
from scipy.optimize import brute
def mse(theta):
xy = f_with_theta(data.values[:,0:2], theta[0], theta[1])
return np.array([mean_squared_error(data.x, xy[:,0]), mean_squared_error(data.y, xy[:,1])]).mean()
theta_prime_1_estimate = np.deg2rad(4.0)
theta_prime_2_es... | notebooks/arm_error_correction.ipynb | joeymeyer/raspberryturk | mit |
Visualizing Error
Below is a visualization of the error. The x and y axis on the graph represent inches from the bottom left corner of the chessboard. The actual $x,y$ is in blue, and the theoretical values are red. The equation is pretty accurate, but in the far corners, there is noticable error. | import matplotlib.pyplot as plt
def scatter(x, y):
plt.scatter(data.x, data.y, color='blue')
plt.scatter(x, y, color='red', marker=',')
plt.show()
scatter(data.x_theory, data.y_theory) | notebooks/arm_error_correction.ipynb | joeymeyer/raspberryturk | mit |
Below is another way to visualize the error. This time the x and y axes represent servo values. | from matplotlib import cm
from matplotlib.colors import Normalize
plt.scatter(data.s1, data.s2, c=data.x_error, cmap=cm.coolwarm, norm=Normalize(-0.5, 0.5), linewidth=0.4, s=40.0)
plt.xlim(0,1023)
plt.ylim(0,1023)
plt.show()
plt.scatter(data.s1, data.s2, c=data.y_error, cmap=cm.coolwarm, norm=Normalize(-0.5, 0.5), lin... | notebooks/arm_error_correction.ipynb | joeymeyer/raspberryturk | mit |
Model
The model is a simple polynomial regression. | from sklearn.model_selection import cross_val_score
from sklearn.model_selection import ShuffleSplit
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline
S_train = data.values[:,0:2]
z_train = data.values[:,6:8]
poly = PolynomialFe... | notebooks/arm_error_correction.ipynb | joeymeyer/raspberryturk | mit |
Below is a plot of the predict_error function with the real error plotted in circles on top. | from itertools import product
s_plot = np.array(list(product(np.linspace(0.0, 1023.0, 32), np.linspace(0.0, 1023.0, 32))))
predicted_error = predict_error(s_plot)
x_error_predicted = predicted_error[:,0]
y_error_predicted = predicted_error[:,1]
plt.scatter(s_plot[:,0], s_plot[:,1], c=x_error_predicted, marker=',', cm... | notebooks/arm_error_correction.ipynb | joeymeyer/raspberryturk | mit |
Building the Final Equation
Using the predict_error function $f'(s)$ can now be created,. | def f_prime(s):
return f(s) + predict_error(s) | notebooks/arm_error_correction.ipynb | joeymeyer/raspberryturk | mit |
To visualize the difference $f'(s)$ makes, we can, once again, plot the predicted $x,y$ (red) on top of the real $x,y$ (blue) for each given $s_1,s_2$. | xy_theoretical_with_error = f_prime(data.values[:,0:2])
data['x_theory_with_error'] = xy_theoretical_with_error[:,0]
data['y_theory_with_error'] = xy_theoretical_with_error[:,1]
scatter(data.x_theory_with_error, data.y_theory_with_error) | notebooks/arm_error_correction.ipynb | joeymeyer/raspberryturk | mit |
Now that we have a working $f'(s)$, we can set out to accomplish our original goal, to create $g(x, y)$. The function $f'$ takes a $s_1, s_2$ and returns $x, y$. The function $g$ takes $x, y$ and returns $s_1, s_2$. In order to find $g$, we just need to invert $f'$! But $f'$ doesn't invert easily and we actually don't ... | srange = np.array(list(product(range(1024), range(1024))))
pts = f_prime(srange)
from sklearn.neighbors import KDTree
tree = KDTree(pts, metric='euclidean')
def g(pts):
return np.array(srange[tree.query(pts, return_distance=False)]).reshape(-1,2) | notebooks/arm_error_correction.ipynb | joeymeyer/raspberryturk | mit |
Visualizing the Final Equation
Below are two plots visualizing the function $g(x,y)$ over the entire 18"x18" chessboard. The first plot is $s_1$ and the second is $s_2$. | pts_grid = np.array(list(product(np.linspace(0.0, 18.0, 32), np.linspace(0.0, 18.0, 32))))
projected_s = g(pts_grid)
plt.scatter(pts_grid[:,0], pts_grid[:,1], c=projected_s[:,0], marker=',', cmap=cm.coolwarm, norm=Normalize(0, 1023), linewidth=0.0, s=120.0)
plt.xlim(0,18)
plt.ylim(0,18)
plt.colorbar()
plt.title("s1")
... | notebooks/arm_error_correction.ipynb | joeymeyer/raspberryturk | mit |
Saving the Model
The $x,y$ associated with the each $s_1,s_2$ from 0 to 1023 is saved to disk so the lookup tree can be created on demand for the Raspberry Turk to use. | path = project.path('data', 'processed', 'arm_movement_engine_pts.npy')
with open(path, 'w') as f:
np.save(f, pts) | notebooks/arm_error_correction.ipynb | joeymeyer/raspberryturk | mit |
Data Pre-Processing
First, let's load the dataset and add a binary affair column. | # load dataset
dta = sm.datasets.fair.load_pandas().data
# add "affair" column: 1 represents having affairs, 0 represents not
dta['affair'] = (dta.affairs > 0).astype(int) | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
Data Exploration | dta.groupby('affair').mean() | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
We can see that on average, women who have affairs rate their marriages lower, which is to be expected. Let's take another look at the rate_marriage variable. | dta.groupby('rate_marriage').mean() | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
An increase in age, yrs_married, and children appears to correlate with a declining marriage rating.
Data Visualization | # show plots in the notebook
%matplotlib inline | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
Let's start with histograms of education and marriage rating. | # histogram of education
dta.educ.hist()
plt.title('Histogram of Education')
plt.xlabel('Education Level')
plt.ylabel('Frequency')
# histogram of marriage rating
dta.rate_marriage.hist()
plt.title('Histogram of Marriage Rating')
plt.xlabel('Marriage Rating')
plt.ylabel('Frequency') | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
Let's take a look at the distribution of marriage ratings for those having affairs versus those not having affairs. | # barplot of marriage rating grouped by affair (True or False)
pd.crosstab(dta.rate_marriage, dta.affair.astype(bool)).plot(kind='bar')
plt.title('Marriage Rating Distribution by Affair Status')
plt.xlabel('Marriage Rating')
plt.ylabel('Frequency') | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
Logistic Regression
Let's go ahead and run logistic regression on the entire data set, and see how accurate it is! | # instantiate a logistic regression model, and fit with X and y
model = LogisticRegression()
model = model.fit(X, y)
# check the accuracy on the training set
model.score(X, y) | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
73% accuracy seems good, but what's the null error rate? | # what percentage had affairs?
y.mean() | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
Only 32% of the women had affairs, which means that you could obtain 68% accuracy by always predicting "no". So we're doing better than the null error rate, but not by much.
Let's examine the coefficients to see what we learn. | # examine the coefficients
trans = np.transpose(model.coef_)
zipi = list(zip(X.columns, trans))
pd.DataFrame(zipi) | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
Increases in marriage rating and religiousness correspond to a decrease in the likelihood of having an affair. For both the wife's occupation and the husband's occupation, the lowest likelihood of having an affair corresponds to the baseline occupation (student), since all of the dummy coefficients are positive.
Model ... | # evaluate the model by splitting into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
model2 = LogisticRegression()
model2.fit(X_train, y_train) | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
We now need to predict class labels for the test set. We will also generate the class probabilities, just to take a look. | # predict class labels for the test set
predicted = model2.predict(X_test)
print(predicted)
# generate class probabilities
probs = model2.predict_proba(X_test)
print(probs) | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
As you can see, the classifier is predicting a 1 (having an affair) any time the probability in the second column is greater than 0.5.
Now let's generate some evaluation metrics. | # generate evaluation metrics
print(metrics.accuracy_score(y_test, predicted))
print(metrics.roc_auc_score(y_test, probs[:, 1])) | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
The accuracy is 73%, which is the same as we experienced when training and predicting on the same data.
We can also see the confusion matrix and a classification report with other metrics. | print(metrics.confusion_matrix(y_test, predicted))
print(metrics.classification_report(y_test, predicted)) | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
Model Evaluation Using Cross-Validation
Now let's try 10-fold cross-validation, to see if the accuracy holds up more rigorously. | # evaluate the model using 10-fold cross-validation
scores = cross_val_score(LogisticRegression(), X, y, scoring='accuracy', cv=10)
print(scores)
print(scores.mean()) | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
Looks good. It's still performing at 73% accuracy.
Predicting the Probability of an Affair
Just for fun, let's predict the probability of an affair for a random woman not present in the dataset. She's a 25-year-old teacher who graduated college, has been married for 3 years, has 1 child, rates herself as strongly relig... | model.predict_proba(np.array([[1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 3, 25, 3, 1, 4,
16]])) | Jupyter/Logistic.ipynb | davidgutierrez/HeartRatePatterns | gpl-3.0 |
Create a raw data set, then compute season and apply basic filters
(also export to CSV file) | raw_data = pynsqd.NSQData().data
clean_data = (
raw_data
.query("primary_landuse != 'Unknown'")
.query("parameter in @nsqd_params")
.query("fraction == 'Total'")
.query("epa_rain_zone == 1")
.assign(station='outflow')
.assign(cvcparam=lambda df: df['parameter'].apply... | examples/medians/0 - Setup NSQD Median computation.ipynb | Geosyntec/pycvc | bsd-3-clause |
Show the sample counts for each parameter | clean_data.groupby(by=['parameter', 'season']).size().unstack(level='season') | examples/medians/0 - Setup NSQD Median computation.ipynb | Geosyntec/pycvc | bsd-3-clause |
Export TSS to a CSV file | (
clean_data
.query("parameter == 'Total Suspended Solids'")
.to_csv('NSQD_Res_TSS.csv', index=False)
) | examples/medians/0 - Setup NSQD Median computation.ipynb | Geosyntec/pycvc | bsd-3-clause |
Identifier for storing these features on disk and referring to them later. | feature_list_id = 'wmd' | notebooks/feature-wmd.ipynb | YuriyGuts/kaggle-quora-question-pairs | mit |
Build Features | def wmd(pair):
return embedding_model.wmdistance(pair[0], pair[1])
wmds = kg.jobs.map_batch_parallel(
tokens,
item_mapper=wmd,
batch_size=1000,
)
wmds = np.array(wmds).reshape(-1, 1)
X_train = wmds[:len(tokens_train)]
X_test = wmds[len(tokens_train):]
print('X_train:', X_train.shape)
print('X_test: ... | notebooks/feature-wmd.ipynb | YuriyGuts/kaggle-quora-question-pairs | mit |
Save features | feature_names = [
'wmd',
]
project.save_features(X_train, X_test, feature_names, feature_list_id) | notebooks/feature-wmd.ipynb | YuriyGuts/kaggle-quora-question-pairs | mit |
The non-regularized model is obviously overfitting the training set. It is fitting the noisy points! Lets now look at two techniques to reduce overfitting.
2 - L2 Regularization
The standard way to avoid overfitting is called L2 regularization. It consists of appropriately modifying your cost function, from:
$$J = -\fr... | # GRADED FUNCTION: compute_cost_with_regularization
def compute_cost_with_regularization(A3, Y, parameters, lambd):
"""
Implement the cost function with L2 regularization. See formula (2) above.
Arguments:
A3 -- post-activation, output of forward propagation, of shape (output size, number of examp... | CourseraDeepLearningSpecialization/2.HyperparameterTrainingRegularizationAndOptimization/Week1/Exercises/Regularization.ipynb | bhattacharjee/courses | mit |
Expected Output:
<table>
<tr>
<td>
**cost**
</td>
<td>
1.78648594516
</td>
</tr>
</table>
Of course, because you changed the cost, you have to change backward propagation as well! All the gradients have to be computed with respect to this new cost.
Exercise: Implement the chang... | # GRADED FUNCTION: backward_propagation_with_regularization
def backward_propagation_with_regularization(X, Y, cache, lambd):
"""
Implements the backward propagation of our baseline model to which we added an L2 regularization.
Arguments:
X -- input dataset, of shape (input size, number of example... | CourseraDeepLearningSpecialization/2.HyperparameterTrainingRegularizationAndOptimization/Week1/Exercises/Regularization.ipynb | bhattacharjee/courses | mit |
Observations:
- The value of $\lambda$ is a hyperparameter that you can tune using a dev set.
- L2 regularization makes your decision boundary smoother. If $\lambda$ is too large, it is also possible to "oversmooth", resulting in a model with high bias.
What is L2-regularization actually doing?:
L2-regularization relie... | # GRADED FUNCTION: forward_propagation_with_dropout
def forward_propagation_with_dropout(X, parameters, keep_prob = 0.5):
"""
Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID.
Arguments:
X -- input dataset, of shape (2, number of example... | CourseraDeepLearningSpecialization/2.HyperparameterTrainingRegularizationAndOptimization/Week1/Exercises/Regularization.ipynb | bhattacharjee/courses | mit |
Expected Output:
<table>
<tr>
<td>
**A3**
</td>
<td>
[[ 0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]]
</td>
</tr>
</table>
3.2 - Backward propagation with dropout
Exercise: Implement the backward propagation with dropout. As before, you are training a 3 layer netw... | # GRADED FUNCTION: backward_propagation_with_dropout
def backward_propagation_with_dropout(X, Y, cache, keep_prob):
"""
Implements the backward propagation of our baseline model to which we added dropout.
Arguments:
X -- input dataset, of shape (2, number of examples)
Y -- "true" labels vector... | CourseraDeepLearningSpecialization/2.HyperparameterTrainingRegularizationAndOptimization/Week1/Exercises/Regularization.ipynb | bhattacharjee/courses | mit |
Imagine that in the above program, 23 is the temperature which was read by some sensor or manually entered by the user and Normal is the response of the program. | a = "apple"
b = "banana"
c = "Mango"
if a == "apple":
print("apple")
elif b == "Mango":
print("mango")
elif c == "Mango":
print("My Mango farm")
x = list(range(10))
a = 0
x.reverse()
print(x)
while x:
a = x.pop()
print(a)
print(a)
x = list(range(10))
print(x)
a = 0
x.reverse()
while x:
a = x.... | Section 1 - Core Python/Chapter 04 - Control Flow/3.1 Compound Statements.ipynb | mayankjohri/LetsExplorePython | gpl-3.0 |
4. Model Training
This notebook demonstrates how to train a Propensity Model using BigQuery ML.
Requirements
Input features used for training needs to be stored as a BigQuery table. This can be done using 2. ML Data Preparation Notebook.
Install and import required modules | # Uncomment to install required python modules
# !sh ../utils/setup.sh
# Add custom utils module to Python environment
import os
import sys
sys.path.append(os.path.abspath(os.pardir))
from gps_building_blocks.cloud.utils import bigquery as bigquery_utils
from utils import model
from utils import helpers | packages/propensity/04.model_training.ipynb | google/compass | apache-2.0 |
Set paramaters | configs = helpers.get_configs('config.yaml')
dest_configs, run_id_configs = configs.destination, configs.run_id
# GCP project ID
PROJECT_ID = dest_configs.project_id
# Name of the BigQuery dataset
DATASET_NAME = dest_configs.dataset_name
# To distinguish the separate runs of the training pipeline
RUN_ID = run_id_conf... | packages/propensity/04.model_training.ipynb | google/compass | apache-2.0 |
Next, let's configure modeling options.
Model and features configuration
Model options can be configured in detail based on BigQuery ML specifications
listed in The CREATE MODEL statement.
NOTE: Propensity modeling supports only following four types of models available in BigQuery ML:
- LOGISTIC_REG
- AUTOML_CLASSIFIER... | # Read in Features table schema to select feature names for model training
sql = ("SELECT column_name "
f"FROM `{PROJECT_ID}.{DATASET_NAME}`.INFORMATION_SCHEMA.COLUMNS "
f"WHERE table_name='{FEATURES_DEV_TABLE}';")
print(sql)
features_schema = bq_utils.run_query(sql).to_dataframe()
# Columns to remove f... | packages/propensity/04.model_training.ipynb | google/compass | apache-2.0 |
Train the model
First, we initialize PropensityModel with config parameters. | propensity_model = model.PropensityModel(bq_utils=bq_utils,
params=params) | packages/propensity/04.model_training.ipynb | google/compass | apache-2.0 |
Next cell triggers model training job in BigQuery which takes some time to finish depending on dataset size and model complexity. Set verbose=True, if you want to verify training query details. | propensity_model.train(verbose=False) | packages/propensity/04.model_training.ipynb | google/compass | apache-2.0 |
Following cell allows you to see detailed information about the input features used to train a model. It provides following columns:
- input — The name of the column in the input training data.
- min — The sample minimum. This column is NULL for non-numeric inputs.
- max — The sample maximum. This column is NULL for no... | propensity_model.get_feature_info() | packages/propensity/04.model_training.ipynb | google/compass | apache-2.0 |
Evaluate the model
This section helps to do quick model evaluation to get following model metrics:
recall
accuracy
f1_score
log_loss
roc_auc
Two optional parameters can be specified for evaluation:
eval_table: BigQuery table containing evaluation dataset
threshold: Custom probability threshold to be used for evaluat... | # Model performance on the model development dataset on which the final
# model has been trained
EVAL_TABLE_NAME = FEATURES_DEV_TABLE
eval_params = {
'eval_table_path': f'{PROJECT_ID}.{DATASET_NAME}.{EVAL_TABLE_NAME}',
'threshold': 0.5
}
propensity_model.evaluate(eval_params, verbose=False)
# Model performance ... | packages/propensity/04.model_training.ipynb | google/compass | apache-2.0 |
Implement Preprocessing Function
Text to Word Ids
As you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids(), you'll turn source_text and target_text from words to ids. However, you need to add the <EOS> word id at the end of each sentence fr... | def text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int):
"""
Convert source and target text to proper word ids
:param source_text: String that contains all the source text.
:param target_text: String that contains all the target text.
:param source_vocab_to_int: Dictionar... | language-translation/dlnd_language_translation.ipynb | retnuh/deep-learning | mit |
Check Point
This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
import helper
import problem_unittests as tests
(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()
target_vocab_to_int['<UNK>'] | language-translation/dlnd_language_translation.ipynb | retnuh/deep-learning | mit |
Build the Neural Network
You'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below:
- model_inputs
- process_decoding_input
- encoding_layer
- decoding_layer_train
- decoding_layer_infer
- decoding_layer
- seq2seq_model
Input
Implement the model_inputs() f... | def model_inputs():
"""
Create TF Placeholders for input, targets, and learning rate.
:return: Tuple (input, targets, learning rate, keep probability)
"""
input_text = tf.placeholder(tf.int32, [None, None], name="input")
targets = tf.placeholder(tf.int32, [None, None])
lr = tf.placeholder(tf... | language-translation/dlnd_language_translation.ipynb | retnuh/deep-learning | mit |
Encoding
Implement encoding_layer() to create a Encoder RNN layer using tf.nn.dynamic_rnn(). | def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob):
"""
Create encoding layer
:param rnn_inputs: Inputs for the RNN
:param rnn_size: RNN Size
:param num_layers: Number of layers
:param keep_prob: Dropout keep probability
:return: RNN state
"""
# Encoder
cell = tf.con... | language-translation/dlnd_language_translation.ipynb | retnuh/deep-learning | mit |
Decoding - Training
Create training logits using tf.contrib.seq2seq.simple_decoder_fn_train() and tf.contrib.seq2seq.dynamic_rnn_decoder(). Apply the output_fn to the tf.contrib.seq2seq.dynamic_rnn_decoder() outputs. | def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_length, decoding_scope,
output_fn, keep_prob):
"""
Create a decoding layer for training
:param encoder_state: Encoder State
:param dec_cell: Decoder RNN Cell
:param dec_embed_input: Decoder embedded ... | language-translation/dlnd_language_translation.ipynb | retnuh/deep-learning | mit |
Decoding - Inference
Create inference logits using tf.contrib.seq2seq.simple_decoder_fn_inference() and tf.contrib.seq2seq.dynamic_rnn_decoder(). | def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id,
maximum_length, vocab_size, decoding_scope, output_fn, keep_prob):
"""
Create a decoding layer for inference
:param encoder_state: Encoder state
:param dec_cell: Decoder R... | language-translation/dlnd_language_translation.ipynb | retnuh/deep-learning | mit |
Build the Decoding Layer
Implement decoding_layer() to create a Decoder RNN layer.
Create RNN cell for decoding using rnn_size and num_layers.
Create the output fuction using lambda to transform it's input, logits, to class logits.
Use the your decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_le... | def decoding_layer(dec_embed_input, dec_embeddings, encoder_state, vocab_size, sequence_length, rnn_size,
num_layers, target_vocab_to_int, keep_prob):
"""
Create decoding layer
:param dec_embed_input: Decoder embedded input
:param dec_embeddings: Decoder embeddings
:param encoder_... | language-translation/dlnd_language_translation.ipynb | retnuh/deep-learning | mit |
Build the Neural Network
Apply the functions you implemented above to:
Apply embedding to the input data for the encoder.
Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob).
Process target data using your process_decoding_input(target_data, target_vocab_to_int, batch_size) function... | def seq2seq_model(input_data, target_data, keep_prob, batch_size, sequence_length, source_vocab_size, target_vocab_size,
enc_embedding_size, dec_embedding_size, rnn_size, num_layers, target_vocab_to_int):
"""
Build the Sequence-to-Sequence part of the neural network
:param input_data: Inpu... | language-translation/dlnd_language_translation.ipynb | retnuh/deep-learning | mit |
Neural Network Training
Hyperparameters
Tune the following parameters:
Set epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set num_layers to the number of layers.
Set encoding_embedding_size to the size of the embedding for the encoder.
Set decoding_embedding_siz... | # Number of Epochs
epochs = 20
# Batch Size
batch_size = 1370
# RNN Size
rnn_size = 250
# Number of Layers
num_layers = 2
# Embedding Size
encoding_embedding_size = 256
decoding_embedding_size = 256
# Learning Rate
learning_rate = 0.01
# Dropout Keep Probability
keep_probability = 0.75 | language-translation/dlnd_language_translation.ipynb | retnuh/deep-learning | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.