markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
2nd Step: Run the Computational Graph with batches of training data
Check out the accuracy of test set | # Create test set
idx = np.random.permutation(test_data.shape[0]) # rand permutation
idx = idx[:batch_size]
test_x, test_y = test_data[idx,:], test_labels[idx]
n = train_data.shape[0]
indices = collections.deque()
# Running Computational Graph
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
f... | algorithms/04_sol_tensorflow.ipynb | mdeff/ntds_2016 | mit |
Create Feature Matrix | # Create feature matrix
X = np.array([[1.1, 11.1],
[2.2, 22.2],
[3.3, 33.3],
[4.4, 44.4],
[np.nan, 55]]) | machine-learning/delete_observations_with_missing_values.ipynb | tpin3694/tpin3694.github.io | mit |
Delete Observations With Missing Values | # Remove observations with missing values
X[~np.isnan(X).any(axis=1)] | machine-learning/delete_observations_with_missing_values.ipynb | tpin3694/tpin3694.github.io | mit |
Now create the DrawControl and add it to the Map using add_control. We also register a handler for draw events. This will fire when a drawn path is created, edited or deleted (there are the actions). The geo_json argument is the serialized geometry of the drawn path, along with its embedded style. | dc = DrawControl(marker={'shapeOptions': {'color': '#0000FF'}},
rectangle={'shapeOptions': {'color': '#0000FF'}},
circle={'shapeOptions': {'color': '#0000FF'}},
circlemarker={},
)
def handle_draw(self, action, geo_json):
print(action)
print(ge... | 2019-07-10-CICM/notebooks/DrawControl.ipynb | QuantStack/quantstack-talks | bsd-3-clause |
In addition, the DrawControl also has last_action and last_draw attributes that are created dynamicaly anytime a new drawn path arrives. | dc.last_action
dc.last_draw | 2019-07-10-CICM/notebooks/DrawControl.ipynb | QuantStack/quantstack-talks | bsd-3-clause |
It's possible to remove all drawings from the map | dc.clear_circles()
dc.clear_polylines()
dc.clear_rectangles()
dc.clear_markers()
dc.clear_polygons()
dc.clear() | 2019-07-10-CICM/notebooks/DrawControl.ipynb | QuantStack/quantstack-talks | bsd-3-clause |
Let's draw a second map and try to import this GeoJSON data into it. | m2 = Map(center=center, zoom=zoom, layout=dict(width='600px', height='400px'))
m2 | 2019-07-10-CICM/notebooks/DrawControl.ipynb | QuantStack/quantstack-talks | bsd-3-clause |
We can use link to synchronize traitlets of the two maps: | map_center_link = link((m, 'center'), (m2, 'center'))
map_zoom_link = link((m, 'zoom'), (m2, 'zoom'))
new_poly = GeoJSON(data=dc.last_draw)
m2.add_layer(new_poly) | 2019-07-10-CICM/notebooks/DrawControl.ipynb | QuantStack/quantstack-talks | bsd-3-clause |
Note that the style is preserved! If you wanted to change the style, you could edit the properties.style dictionary of the GeoJSON data. Or, you could even style the original path in the DrawControl by setting the polygon dictionary of that object. See the code for details.
Now let's add a DrawControl to this second ma... | dc2 = DrawControl(polygon={'shapeOptions': {'color': '#0000FF'}}, polyline={},
circle={'shapeOptions': {'color': '#0000FF'}})
m2.add_control(dc2) | 2019-07-10-CICM/notebooks/DrawControl.ipynb | QuantStack/quantstack-talks | bsd-3-clause |
At this point, you can follow along with either the pre-baked Macosko2015 amacrine data, or you can load in your own expression matrices. For the best experience, make sure that the rows are cells and the columns are gene names. | import macosko2015
counts, cell_metadata, gene_metadata = macosko2015.load_big_clusters()
counts.head() | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
Calculate correlation between cells: | correlations = counts.T.rank().corr()
print(correlations.shape)
correlations.head() | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
Correlation != distance
Correlation is not equal to distance. If two things are exactly the same, their correlation value is 1. But in space, if two things are exactly the same, the distance between them is 0. Therefore, correlation is not a distance! Correlation is a similarity metric, where bigger = more similar. But... | sns.distplot(correlations.values.flat) | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
But for building a K-nearest neighbors graph, we want the closest things (in distance space) to be actually close. So we'll convert our correlation ($\rho$) into a distance ($d$) using this equation:
$$
d = \sqrt{2(1-\rho)}
$$
You can look at the code for networkplots.correlation_to_distance to convince yourself that's... | networkplots.correlation_to_distance?? | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
Exercise 1
Create a dataframe called distance using the correlation_to_distance function from networkplots on your corr dataframe. | # YOUR CODE HERE | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
distances = networkplots.correlation_to_distance(correlations)
distances.head() | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit | |
Exercise 2
Let's take a look at our values to make sure we have most of our values far away from zero. Use sns.distplot to look the flattened values of the distances dataframe. | # YOUR CODE HERE | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
sns.distplot(distances.values.flat) | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit | |
Now we'll run phenograph.cluster, which returns three items:
communities: the cluster labels of each cell
sparse_matrix: a sparse matrix representing the connections between cells in the graph
Q: the modularity score. Higher is better, and the highest is 1.
0 means your graph is randomly connected and -1 means your g... | communities, sparse_matrix, Q = phenograph.cluster(distances, k=10) | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
Let's take a look at each of these returned values | communities
sparse_matrix
Q | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
It looks like the communities labels each cell as belonging to a particular cluster, the sparse_matrix is some data type that we can't directly investigate, and Q is the modularity value.
Make a graph from the sparse matrix
To be able to lay out our graph in two dimensions, we'll use the networkx Python Package to buil... | graph = networkx.from_scipy_sparse_matrix(sparse_matrix)
graph | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
We'll use the "Spring layout" which is a force-directed layout that pushes cells and edges away from each other. We'll use the built-in networkx function called spring_layout on our graph: | positions = networkx.spring_layout(graph)
positions | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
Convert positions dict to dataframe with node information
This positions dataframe is a dictionary mapping the node id (in this case, a number) and the $(x, y)$ position. The nodes are in exactly the same order as the rows of the distances dataframe we gave phenograph.cluster. | networkplots.get_nodes_specs?? | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
Looks like this function can deal with if we already have some clusters defined in our metadata! Let's look at our cell_metadata and remind ourselves of which column we might like to use for the other_cluster_col value. | cell_metadata.head() | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
In this case, I'd like to use the cluster_n_celltype column.
Let's take a look at the code again to see how the networkplots.get_nodes_specs function uses the metadata: | networkplots.get_nodes_specs?? | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
Looks like this function uses another one, called labels_to_colors -- what does that do? | networkplots.labels_to_colors?? | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
Now let's use get_nodes_specs to create a dataframe of information about nodes so we can plot them. | nodes_specs = networkplots.get_nodes_specs(
positions, cell_metadata, distances.index,
communities, other_cluster_col='cluster_n_celltype',
palette='Set2')
print(nodes_specs.shape)
nodes_specs.head() | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
Convert positions dict to dataframe with edge information
We've now created a dataframe containing the x,y positions, the community labels, and the colors for the communities and other clusters we were interested in. Now we want to do the same for the edges (lines between cells).
Let's take a look at the function we'll... | networkplots.get_edges_specs?? | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
What arguments does it take? What does it do with them? What does it return?
Exercise 3
Create a variable called edges_specs using the networkplots.get_edges_specs and the correct inputs. | # YOUR CODE HERE | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
edges_specs = networkplots.get_edges_specs(graph, positions)
print(edges_specs.shape)
edges_specs.head() | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit | |
To be able to use the dataframes with the Bokeh plotting language, we need to convert our dataframes into ColumnDataSource objects. | nodes_source = ColumnDataSource(nodes_specs)
edges_source = ColumnDataSource(edges_specs)
# --- First tab: KNN clustering --- #
tab1 = networkplots.plot_graph(nodes_source, edges_source,
legend_col='community',
color_col='community_color', tab=True,
t... | notebooks/2.2_apply_clustering_on_knn_graph.ipynb | olgabot/cshl-singlecell-2017 | mit |
Import the required modules: | import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import scipy.stats | notebooks/avg_quality.ipynb | csieber/yt-dataset | mit |
Read the dataset: | data = pd.read_csv("../data/ifip_networking.csv.gz") | notebooks/avg_quality.ipynb | csieber/yt-dataset | mit |
Convert the shaping to Mbps: | data.loc[:,'shaping_mbps'] = data.loc[:,'net_avg_shaping_rate']*8/1000/1000
data.loc[:,'shaping_mbps_rounded'] = data.loc[:,'shaping_mbps'].round(1) | notebooks/avg_quality.ipynb | csieber/yt-dataset | mit |
Definitions
Dict for translating itags to quality levels and vice-versa: | ITAG_TO_QL = {160: 0,
133: 1,
134: 2,
135: 3,
136: 4}
QL_TO_ITAG = {v: k for k, v in ITAG_TO_QL.items()}
VIDDEF = {160: {'label': '144p', 'color': 'green', 'resolution': '256x144'},
133: {'label': '240p', 'color': 'red' , 'resolution': '320x240'},
... | notebooks/avg_quality.ipynb | csieber/yt-dataset | mit |
Confidence Interval: | def confintv_yerr(values):
n, min_max, mean, var, skew, kurt = scipy.stats.describe(values)
std = np.sqrt(var)
intv = scipy.stats.t.interval(0.95,len(values)-1,loc=mean,scale=std/np.sqrt(len(values)))
yerr = ((intv[1] - intv[0]) / 2)
return yerr | notebooks/avg_quality.ipynb | csieber/yt-dataset | mit |
Plotting shaping to average quality level
The subsequent plot shows the fraction of time the video spent on the a certain quality level and the overall average quality level for a specific network shaping value. For example, at 2.2 Mbps, the player spends nearly 100% of the time on the highest quality level (480p). | fig = plt.figure(figsize=(9, 7))
plt.hold(True)
ax1 = fig.add_subplot(111)
by_shaping = data.groupby('shaping_mbps').mean()
y_offset = 0
cmap = plt.get_cmap('copper')
colors = iter(cmap(np.linspace(0,1,len(QL_TO_ITAG))))
for ql,itag in list(QL_TO_ITAG.items())[0:4]:
idx_itag = 'pl_time_spent_norm_itag%d' %... | notebooks/avg_quality.ipynb | csieber/yt-dataset | mit |
Export notebook to HTML: | !ipython nbconvert avg_quality.ipynb --to html | notebooks/avg_quality.ipynb | csieber/yt-dataset | mit |
2 - Outline of the Assignment
You will be implementing the building blocks of a convolutional neural network! Each function you will implement will have detailed instructions that will walk you through the steps needed:
Convolution functions, including:
Zero Padding
Convolve window
Convolution forward
Convolution bac... | # GRADED FUNCTION: zero_pad
def zero_pad(X, pad):
"""
Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image,
as illustrated in Figure 1.
Argument:
X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images
pad -- i... | course-deeplearning.ai/course4-cnn/week1-cnn/Convolution+model+-+Step+by+Step+-+v2.ipynb | liufuyang/deep_learning_tutorial | mit |
Expected Output:
<table>
<tr>
<td>
**x.shape**:
</td>
<td>
(4, 3, 3, 2)
</td>
</tr>
<tr>
<td>
**x_pad.shape**:
</td>
<td>
(4, 7, 7, 2)
</td>
</tr>
<tr>
<td>
**x[1... | # GRADED FUNCTION: conv_single_step
def conv_single_step(a_slice_prev, W, b):
"""
Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation
of the previous layer.
Arguments:
a_slice_prev -- slice of input data of shape (f, f, n_C_prev)
W -- Weight ... | course-deeplearning.ai/course4-cnn/week1-cnn/Convolution+model+-+Step+by+Step+-+v2.ipynb | liufuyang/deep_learning_tutorial | mit |
Expected Output:
<table>
<tr>
<td>
**Z**
</td>
<td>
-6.99908945068
</td>
</tr>
</table>
3.3 - Convolutional Neural Networks - Forward pass
In the forward pass, you will take many filters and convolve them on the input. Each 'convolution' gives you a 2D m... | # GRADED FUNCTION: conv_forward
def conv_forward(A_prev, W, b, hparameters):
"""
Implements the forward propagation for a convolution function
Arguments:
A_prev -- output activations of the previous layer, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
W -- Weights, numpy array of shap... | course-deeplearning.ai/course4-cnn/week1-cnn/Convolution+model+-+Step+by+Step+-+v2.ipynb | liufuyang/deep_learning_tutorial | mit |
Expected Output:
<table>
<tr>
<td>
**Z's mean**
</td>
<td>
0.0489952035289
</td>
</tr>
<tr>
<td>
**Z[3,2,1]**
</td>
<td>
[-0.61490741 -6.7439236 -2.55153897 1.75698377 3.56208902 0.53036437
5.185317... | # GRADED FUNCTION: pool_forward
def pool_forward(A_prev, hparameters, mode = "max"):
"""
Implements the forward pass of the pooling layer
Arguments:
A_prev -- Input data, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev)
hparameters -- python dictionary containing "f" and "stride"
mod... | course-deeplearning.ai/course4-cnn/week1-cnn/Convolution+model+-+Step+by+Step+-+v2.ipynb | liufuyang/deep_learning_tutorial | mit |
Expected Output:
<table>
<tr>
<td>
A =
</td>
<td>
[[[[ 1.74481176 0.86540763 1.13376944]]]
[[[ 1.13162939 1.51981682 2.18557541]]]]
</td>
</tr>
<tr>
<td>
A =
</td>
<td>
[[[[ 0.02105773 -0.20328806 -0.40389855]]]
[[[-0.22154621 ... | def conv_backward(dZ, cache):
"""
Implement the backward propagation for a convolution function
Arguments:
dZ -- gradient of the cost with respect to the output of the conv layer (Z), numpy array of shape (m, n_H, n_W, n_C)
cache -- cache of values needed for the conv_backward(), output of conv... | course-deeplearning.ai/course4-cnn/week1-cnn/Convolution+model+-+Step+by+Step+-+v2.ipynb | liufuyang/deep_learning_tutorial | mit |
Expected Output:
<table>
<tr>
<td>
**dA_mean**
</td>
<td>
1.45243777754
</td>
</tr>
<tr>
<td>
**dW_mean**
</td>
<td>
1.72699145831
</td>
</tr>
<tr>
<td>
**db_mean**
... | def create_mask_from_window(x):
"""
Creates a mask from an input matrix x, to identify the max entry of x.
Arguments:
x -- Array of shape (f, f)
Returns:
mask -- Array of the same shape as window, contains a True at the position corresponding to the max entry of x.
"""
###... | course-deeplearning.ai/course4-cnn/week1-cnn/Convolution+model+-+Step+by+Step+-+v2.ipynb | liufuyang/deep_learning_tutorial | mit |
Expected Output:
<table>
<tr>
<td>
**x =**
</td>
<td>
[[ 1.62434536 -0.61175641 -0.52817175] <br>
[-1.07296862 0.86540763 -2.3015387 ]]
</td>
</tr>
<tr>
<td>
**mask =**
</td>
<td>
[[ True False False] <br>
[False False False]]
</td>
</tr>
</table>
Why do we keep track of the position of the max? It's b... | def distribute_value(dz, shape):
"""
Distributes the input value in the matrix of dimension shape
Arguments:
dz -- input scalar
shape -- the shape (n_H, n_W) of the output matrix for which we want to distribute the value of dz
Returns:
a -- Array of size (n_H, n_W) for which we dis... | course-deeplearning.ai/course4-cnn/week1-cnn/Convolution+model+-+Step+by+Step+-+v2.ipynb | liufuyang/deep_learning_tutorial | mit |
Expected Output:
<table>
<tr>
<td>
distributed_value =
</td>
<td>
[[ 0.5 0.5]
<br\>
[ 0.5 0.5]]
</td>
</tr>
</table>
5.2.3 Putting it together: Pooling backward
You now have everything you need to compute backward propagation on a pooling layer.
Exercise: Implement the pool_backward function in both modes ("max"... | def pool_backward(dA, cache, mode = "max"):
"""
Implements the backward pass of the pooling layer
Arguments:
dA -- gradient of cost with respect to the output of the pooling layer, same shape as A
cache -- cache output from the forward pass of the pooling layer, contains the layer's input and h... | course-deeplearning.ai/course4-cnn/week1-cnn/Convolution+model+-+Step+by+Step+-+v2.ipynb | liufuyang/deep_learning_tutorial | mit |
<p style="font-family: Arial; font-size:1.75em;color:purple; font-style:bold"><br>
Creating a Pandas DataFrame from a CSV file<br><br></p> | data = pd.read_csv('./weather/minute_weather.csv') | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
<p style="font-family: Arial; font-size:1.75em;color:purple; font-style:bold">Minute Weather Data Description</p>
<br>
The minute weather dataset comes from the same source as the daily weather dataset that we used in the decision tree based classifier notebook. The main difference between these two datasets is that th... | data.shape
data.head() | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
<p style="font-family: Arial; font-size:1.75em;color:purple; font-style:bold"><br>
Data Sampling<br></p>
Lots of rows, so let us sample down by taking every 10th row. <br> | sampled_df = data[(data['rowID'] % 10) == 0]
sampled_df.shape | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
<p style="font-family: Arial; font-size:1.75em;color:purple; font-style:bold"><br>
Statistics
<br><br></p> | sampled_df.describe().transpose()
sampled_df[sampled_df['rain_accumulation'] == 0].shape
sampled_df[sampled_df['rain_duration'] == 0].shape | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
<p style="font-family: Arial; font-size:1.75em;color:purple; font-style:bold"><br>
Drop all the Rows with Empty rain_duration and rain_accumulation
<br><br></p> | del sampled_df['rain_accumulation']
del sampled_df['rain_duration']
rows_before = sampled_df.shape[0]
sampled_df = sampled_df.dropna()
rows_after = sampled_df.shape[0] | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
<p style="font-family: Arial; font-size:1.75em;color:purple; font-style:bold"><br>
How many rows did we drop ?
<br><br></p> | rows_before - rows_after
sampled_df.columns | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
<p style="font-family: Arial; font-size:1.75em;color:purple; font-style:bold"><br>
Select Features of Interest for Clustering
<br><br></p> | features = ['air_pressure', 'air_temp', 'avg_wind_direction', 'avg_wind_speed', 'max_wind_direction',
'max_wind_speed','relative_humidity']
select_df = sampled_df[features]
select_df.columns
select_df | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
<p style="font-family: Arial; font-size:1.75em;color:purple; font-style:bold"><br>
Scale the Features using StandardScaler
<br><br></p> | X = StandardScaler().fit_transform(select_df)
X | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
<p style="font-family: Arial; font-size:1.75em;color:purple; font-style:bold"><br>
Use k-Means Clustering
<br><br></p> | kmeans = KMeans(n_clusters=12)
model = kmeans.fit(X)
print("model\n", model) | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
<p style="font-family: Arial; font-size:1.75em;color:purple; font-style:bold"><br>
What are the centers of 12 clusters we formed ?
<br><br></p> | centers = model.cluster_centers_
centers | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
<p style="font-family: Arial; font-size:2.75em;color:purple; font-style:bold"><br>
Plots
<br><br></p>
Let us first create some utility functions which will help us in plotting graphs: | # Function that creates a DataFrame with a column for Cluster Number
def pd_centers(featuresUsed, centers):
colNames = list(featuresUsed)
colNames.append('prediction')
# Zip with a column called 'prediction' (index)
Z = [np.append(A, index) for index, A in enumerate(centers)]
# Convert to pandas data frame for ... | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
Dry Days | parallel_plot(P[P['relative_humidity'] < -0.5]) | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
Warm Days | parallel_plot(P[P['air_temp'] > 0.5]) | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
Cool Days | parallel_plot(P[(P['relative_humidity'] > 0.5) & (P['air_temp'] < 0.5)]) | Week-7-MachineLearning/Weather Data Clustering using k-Means.ipynb | kkhenriquez/python-for-data-science | mit |
You'll need to download some resources for NLTK (the natural language toolkit) in order to do the kind of processing we want on all the mailing list text. In particular, for this notebook you'll need punkt, the Punkt Tokenizer Models.
To download, from an interactive Python shell, run:
import nltk
nltk.download()
And ... | df = pd.DataFrame(columns=["MessageId","Date","From","In-Reply-To","Count"])
for row in archives[0].data.iterrows():
try:
w = row[1]["Body"].replace("'", "")
k = re.sub(r'[^\w]', ' ', w)
k = k.lower()
t = nltk.tokenize.word_tokenize(k)
subdict = {}
count = 0
... | examples/Single Word Trend.ipynb | npdoty/bigbang | agpl-3.0 |
Group the dataframe by the month and year, and aggregate the counts for the checkword during each month to get a quick histogram of how frequently that word has been used over time. | df.groupby([df.Date.dt.year, df.Date.dt.month]).agg({'Count':np.sum}).plot(y='Count') | examples/Single Word Trend.ipynb | npdoty/bigbang | agpl-3.0 |
9.5. Prescribed Fields Aod Plus Ccn
Is Required: FALSE Type: STRING Cardinality: 0.1
List of species prescribed as AOD plus CCNs. | # PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.concentrations.prescribed_fields_aod_plus_ccn')
# PROPERTY VALUE:
# Set as follows: DOC.set_value("value")
# TODO - please enter value(s)
| notebooks/ipsl/cmip6/models/sandbox-1/aerosol.ipynb | ES-DOC/esdoc-jupyterhub | gpl-3.0 |
13.2. Internal Mixture
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Does H2O impact aerosol internal mixture? | # PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.impact_of_h2o.internal_mixture')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
| notebooks/ipsl/cmip6/models/sandbox-1/aerosol.ipynb | ES-DOC/esdoc-jupyterhub | gpl-3.0 |
13.3. External Mixture
Is Required: TRUE Type: BOOLEAN Cardinality: 1.1
Does H2O impact aerosol external mixture? | # PROPERTY ID - DO NOT EDIT !
DOC.set_id('cmip6.aerosol.optical_radiative_properties.impact_of_h2o.external_mixture')
# PROPERTY VALUE:
# Set as follows: DOC.set_value(value)
# Valid Choices:
# True
# False
# TODO - please enter value(s)
| notebooks/ipsl/cmip6/models/sandbox-1/aerosol.ipynb | ES-DOC/esdoc-jupyterhub | gpl-3.0 |
1. Load Data
Using torchvision and torch.utils.data for data loading. Training a model to classify ants and bees; 120 training images each cat. 75 val images each. data link | # Data augmentation and normalization for training
# Just normalization for validation
data_transforms = {
'train': transforms.Compose([
transforms.RandomSizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485,0.456,0.406],[0.229, 0.224, ... | pytorch/transfer_learning_tutorial.ipynb | WNoxchi/Kaukasos | mit |
Init signature: torchvision.transforms.Scale(*args, **kwargs)
Source:
class Scale(Resize):
"""
Note: This transform is deprecated in favor of Resize.
"""
def __init__(self, *args, **kwargs):
warnings.warn("The use of the transforms.Scale transform is deprecated, " +
... | torchvision.transforms.Resize?? | pytorch/transfer_learning_tutorial.ipynb | WNoxchi/Kaukasos | mit |
```
Init signature: torchvision.transforms.Resize(size, interpolation=2)
Source:
class Resize(object):
"""Resize the input PIL Image to the given size.
Args:
size (sequence or int): Desired output size. If size is a sequence like
(h, w), output size will be matched to this. If size is an int,
... | plt.pause?
def imshow(inp, title=None):
"""Imshow for Tensor"""
inp = inp.numpy().transpose((1,2,0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = std * inp + mean
inp = np.clip(inp, 0, 1)
plt.imshow(inp)
if title is not None:
plt.title(title... | pytorch/transfer_learning_tutorial.ipynb | WNoxchi/Kaukasos | mit |
Huh, cool
3. Training the model
Scheduling the learning rate
Saving the best model
Parameter scheduler is an LR scheduler object from torch.optim.lr_scheduler | def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
since = time.time()
best_model_wts = model.state_dict()
best_acc = 0.0
for epoch in range(num_epochs):
print(f'Epoch {epoch}/{num_epochs-1}')
print('-' * 10)
# Each epoch has a training and... | pytorch/transfer_learning_tutorial.ipynb | WNoxchi/Kaukasos | mit |
4. Visualizing the model's predictions | def visualize_model(model, num_images=6):
images_so_far = 0
fig = plt.figure()
for i, data in enumerate(dataloaders['val']):
inputs, labels = data
if use_gpu:
inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())
else:
inputs, labels = Variabl... | pytorch/transfer_learning_tutorial.ipynb | WNoxchi/Kaukasos | mit |
```
Variable.cpu(self)
Source:
def cpu(self):
return self.type(getattr(torch, type(self.data).name))
``` | # looking at the cpu() method
temp = Variable(torch.FloatTensor([1,2]))
temp.cpu() | pytorch/transfer_learning_tutorial.ipynb | WNoxchi/Kaukasos | mit |
5. Finetuning the ConvNet
Load a pretrained model and reset final fully-connected layer | model_ft = models.resnet18(pretrained=True)
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, 2)
if use_gpu:
model_ft = model_ft.cuda()
criterion = nn.CrossEntropyLoss()
# Observe that all parameters are being optimized
optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)
#... | pytorch/transfer_learning_tutorial.ipynb | WNoxchi/Kaukasos | mit |
```
torch.optim.lr_scheduler.StepLR
--> defines `get_lr(self):
def get_lr(self):
return [base_lr * self.gamma ** (self.last_epoch // self.step_size)
for base_lr in self.base_lrs]
```
so gamma is exponentiated by ( last_epoch // step_size )
5.1 Train and Evaluate
Should take 15-25 min on CPU; < 1... | model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=25)
visualize_model(model_ft) | pytorch/transfer_learning_tutorial.ipynb | WNoxchi/Kaukasos | mit |
6. ConvNet as a fixed feature extractor
Freeze entire network except final layer. Need set requires_grad == False to freeze pars st grads aren't computed in backward().
Link to Documentation | model_conv = torchvision.models.resnet18(pretrained=True)
for par in model_conv.parameters():
par.requires_grad = False
# Parameters of newly constructed modules have requires_grad=True by default
num_ftrs = model_conv.fc.in_features
model_conv.fc = nn.Linear(num_ftrs, 2)
if use_gpu:
model_conv = model_conv.c... | pytorch/transfer_learning_tutorial.ipynb | WNoxchi/Kaukasos | mit |
6.1 Train and evaluate
For CPU: will take about half the time as before. This is expected as grads don't need to be computed for most of the network -- the forward pass though, has to be computed. | model_conv = train_model(model_conv, criterion, optimizer_conv,
exp_lr_scheduler, num_epochs=25)
visualize_model(model_conv)
plt.ioff()
plt.show() | pytorch/transfer_learning_tutorial.ipynb | WNoxchi/Kaukasos | mit |
Parameter prior
bayesloop employs a forward-backward algorithm that is based on Hidden Markov models. This inference algorithm iteratively produces a parameter distribution for each time step, but it has to start these iterations from a specified probability distribution - the parameter prior. All built-in observation ... | # we assume a static rate parameter for simplicity
S.set(bl.tm.Static())
print 'Fit with built-in Jeffreys prior:'
S.set(bl.om.Poisson('accident_rate', bl.oint(0, 6, 1000)))
S.fit()
jeffreys_mean = S.getParameterMeanValues('accident_rate')[0]
print('-----\n')
print 'Fit with custom flat prior:'
... | docs/source/tutorials/priordistributions.ipynb | christophmark/bayesloop | mit |
First note that the model evidence indeed slightly changes due to the different choices of the parameter prior. Second, one may notice that the posterior mean value of the flat-prior-fit does not exactly match the arithmetic mean of the data. This small deviation shows that a flat/uniform prior is not completely non-in... | print('arithmetic mean = {}'.format(np.mean(S.rawData)))
print('flat-prior mean = {}'.format(flat_mean))
print('Jeffreys prior mean = {}'.format(jeffreys_mean)) | docs/source/tutorials/priordistributions.ipynb | christophmark/bayesloop | mit |
SymPy prior
The second option is based on the SymPy module that introduces symbolic mathematics to Python. Its sub-module sympy.stats covers a wide range of discrete and continuous random variables. The keyword argument prior also accepts a list of sympy.stats random variables, one for each parameter (if there is only ... | import sympy.stats
S.set(bl.om.Poisson('accident_rate', bl.oint(0, 6, 1000),
prior=sympy.stats.Exponential('expon', 1)))
S.fit() | docs/source/tutorials/priordistributions.ipynb | christophmark/bayesloop | mit |
Note that one needs to assign a name to each sympy.stats variable. In this case, the output of bayesloop shows the mathematical formula that defines the prior. This is possible because of the symbolic representation of the prior by SymPy.
<div style="background-color: #e7f2fa; border-left: 5px solid #6ab0de; padding: 0... | print 'Fit with flat hyper-prior:'
S = bl.ChangepointStudy()
S.loadExampleData()
L = bl.om.Poisson('accident_rate', bl.oint(0, 6, 1000))
T = bl.tm.ChangePoint('tChange', 'all')
S.set(L, T)
S.fit()
plt.figure(figsize=(8,4))
S.plot('tChange', facecolor='g', alpha=0.7)
plt.xlim([1870, 1930])
plt.show()
print('-----\n')... | docs/source/tutorials/priordistributions.ipynb | christophmark/bayesloop | mit |
Since we used a quite narrow prior (containing a lot of information) in the second case, the resulting distribution is strongly shifted towards the prior. The following example revisits the two break-point-model from here and a linear decrease with a varying slope as a hyper-parameter. Here, we define a Gaussian prior ... | S = bl.HyperStudy()
S.loadExampleData()
L = bl.om.Poisson('accident_rate', bl.oint(0, 6, 1000))
T = bl.tm.SerialTransitionModel(bl.tm.Static(),
bl.tm.BreakPoint('t_1', 1880),
bl.tm.Deterministic(lambda t, slope=np.linspace(-2.0, 0.0, 30): t*slope,
... | docs/source/tutorials/priordistributions.ipynb | christophmark/bayesloop | mit |
Using the familiar statistical modeling API, we import the AgglomerativeClustering
algorithm and specify the desired number of clusters: | from sklearn import cluster
agg = cluster.AgglomerativeClustering(n_clusters=3) | notebooks/08.04-Implementing-Agglomerative-Hierarchical-Clustering.ipynb | mbeyeler/opencv-machine-learning | mit |
Fitting the model to the data works, as usual, via the fit_predict method: | labels = agg.fit_predict(X) | notebooks/08.04-Implementing-Agglomerative-Hierarchical-Clustering.ipynb | mbeyeler/opencv-machine-learning | mit |
We can generate a scatter plot where every data point is colored according to the predicted
label: | import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')
plt.figure(figsize=(10, 6))
plt.scatter(X[:, 0], X[:, 1], c=labels, s=100) | notebooks/08.04-Implementing-Agglomerative-Hierarchical-Clustering.ipynb | mbeyeler/opencv-machine-learning | mit |
Let's open our test project by its name. If you completed the first examples this should all work out of the box. | project = Project('test') | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Open all connections to the MongoDB and Session so we can get started.
An interesting thing to note here is, that since we use a DB in the back, data is synced between notebooks. If you want to see how this works, just run some tasks in the last example, go back here and check on the change of the contents of the proj... | print project.files
print project.generators
print project.models | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Run simulations
Now we really start simulations. The general way to do so is to create a simulation task and then submit it to a cluster to be executed. A Task object is a general description of what should be done and boils down to staging some files to your working directory, executing a bash script and finally movin... | def strategy():
# create a new scheduler
with project.get_scheduler(cores=2) as local_scheduler:
for loop in range(10):
tasks = local_scheduler(project.new_ml_trajectory(
length=100, number=10))
yield tasks.is_done()
task = local_scheduler(modeller.ex... | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
turn a generator of your function use add strategy() and not strategy to the FunctionalEvent | ev = FunctionalEvent(strategy()) | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
and execute the event inside your project | project.add_event(ev) | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
after some time you will have 10 more trajectories. Just like that.
Let's see how our project is growing | import time
from IPython.display import clear_output
try:
while True:
clear_output(wait=True)
print '# of files %8d : %s' % (len(project.trajectories), '#' * len(project.trajectories))
print '# of models %8d : %s' % (len(project.models), '#' * len(project.models))
sys.stdout.flush(... | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
And some analysis | trajs = project.trajectories
q = {}
ins = {}
for f in trajs:
source = f.frame if isinstance(f.frame, File) else f.frame.trajectory
ind = 0 if isinstance(f.frame, File) else f.frame.index
ins[source] = ins.get(source, []) + [ind] | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Event | scheduler = project.get_scheduler(cores=2)
def strategy1():
for loop in range(10):
tasks = scheduler(project.new_ml_trajectory(
length=100, number=10))
yield tasks.is_done()
def strategy2():
for loop in range(10):
num = len(project.trajectories)
task = scheduler(mod... | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Tasks
To actually run simulations you need to have a scheduler (maybe a better name?). This instance can execute tasks or more precise you can use it to submit tasks which will be converted to ComputeUnitDescriptions and executed on the cluster previously chosen. | scheduler = project.get_scheduler(cores=2) # get the default scheduler using 2 cores | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Now we are good to go and can run a first simulation
This works by creating a Trajectory object with a filename, a length and an initial frame. Then the engine will take this information and create a real trajectory with exactly this name, this initil frame and the given length.
Since this is such a common task you can... | trajs = project.new_trajectory(pdb_file, 100, 4) | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Let's submit and see | scheduler.submit(trajs) | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Once the trajectories exist these objects will be saved to the database. It might be a little confusing to have objects before they exist, but this way you can actually work with these trajectories like referencing even before they exist.
This would allow to write now a function that triggers when the trajectory comes ... | scheduler.wait() | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Look at all the files our project now contains. | print '# of files', len(project.files) | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Great! That was easy (I hope you agree).
Next we want to run a simple analysis. | t = modeller.execute(list(project.trajectories))
scheduler(t)
scheduler.wait() | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Let's look at the model we generated | print project.models.last.data.keys() | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
And pick some information | print project.models.last.data['msm']['P'] | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Next example will demonstrate on how to write a full adaptive loop
Events
A new concept. Tasks are great and do work for us. But so far we needed to submit tasks ourselves. In adaptive simulations we want this to happen automagically. To help with some of this events exist. This are basically a task_generator coupled w... | def task_generator():
return [
engine.task_run_trajectory(traj) for traj in
project.new_ml_trajectory(100, 4)]
task_generator() | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Now create an event. | ev = Event().on(project.on_ntraj(range(20,22,2))).do(task_generator) | examples/rp/3_example_adaptive.ipynb | markovmodel/adaptivemd | lgpl-2.1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.