markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Getting day time features for the order_file. | order_comp['day']=order_comp.created_at.dt.day
order_comp['hour']=order_comp.created_at.dt.hour
order_comp['weekday']=order_comp.created_at.dt.dayofweek
order_comp['geography']=order_comp.pickup_locality
order_comp_test['day']=order_comp_test.created_at.dt.day
order_comp_test['hour']=order_comp_test.created_at.dt.hour... | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
<a id='nlp'>4.Preprocessing the data. </a> | def lower(x):
return x.lower()
order_comp.geography=order_comp.geography.apply(lower)
train.geography=train.geography.apply(lower)
train.head()
order_comp.replace({'hsr layout':'hsr_layout'},inplace=True)
from sklearn.preprocessing import LabelEncoder
le_geo=LabelEncoder()
order_comp.geography=le_geo.fit_transfo... | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
Authors of the data have very cleverly organised data by only removing the data of 2nd Jan to 12th Jan and remaining data is now used for the predicting the orders per hour,order per week and orders per day-hour combinaiton | train.head() | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
correct the weekday | order_comp.head()
train.weekday=train.weekday-1
test.weekday=test.weekday-1 | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
<a id='ot5'>3.5 Aggregate features on order file.</a>
Aggregate features.
1) Total orders within a geography in an hour of a weekday<br>
2) Total orders in a weekday<br>
3) Total orders in a day of hour.<br>
Combiing all of them with train | order_comp.loc[order_comp.day>1].groupby(by=['geography','weekday','hour'],as_index=False).count_order.sum()
order_comp.loc[order_comp.day>1].groupby(by=['weekday'],as_index=False).count_order.sum()
order_comp.loc[order_comp.day>1].groupby(by=['day','hour'],as_index=False).count_order.sum()
order_comp_test.loc[order_c... | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
<a id='nlp'>4.Making Model. </a>
<a id='nlp'>4.Preparing validation set. </a>
Making validation set !
Here normal train and test won't work so divide according to date and treat it as a test. | valid =train.loc[train.dt == '31-Jan-18'].reset_index(drop=True)
train_val =train.loc[train.dt != '31-Jan-18'].reset_index(drop=True)
len(test.columns)
len(train.columns)
test.columns
train.columns
col = [ 'Latitude', 'Longitude', 'res_id',
'minute', 'geography',
'stockout_hour', 'stockout_week_h... | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
using RandomForest model | from sklearn.ensemble import RandomForestClassifier,GradientBoostingClassifier,BaggingClassifier,AdaBoostClassifier
import xgboost as xgb
X=train[col]
y=train.stockout
train_X=train_val[col]
train_y=train_val.stockout
test_X=valid[col]
test_y=valid.stockout | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
<a id='nlp2'>4.2 Applying the RandomForestclassifier</a> | clf=RandomForestClassifier(n_estimators=30,max_depth=7)#highest_accuracy
clf=RandomForestClassifier(n_estimators=30,max_depth=7,)#highest_accuracy
#clf=AdaBoostClassifier(base_estimator=clf)
import lightgbm as lgb
from sklearn.tree import ExtraTreeClassifier
#clf = lgb.LGBMClassifier(max_depth=8,n_estimators=1000,rand... | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
Feature Importance chart | import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
plt.figure(figsize=(20,5))
sns.barplot(col,clf.feature_importances_)
pd.DataFrame(clf.feature_importances_,index=col).sort_values(by=0)
sub=pd.read_csv('test/submission_online_testcase.csv')
clf.fit(X,y)
sub['stockout']=clf.predict(test[X.col... | ZOMATO_final.ipynb | kanavanand/kanavanand.github.io | mit |
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold">
Creating a numpy array from an image file:</p>
<br>
Lets choose a WIFIRE satellite image file as an ndarray and display its type. | from skimage import data
photo_data = misc.imread('./wifire/sd-3layers.jpg')
type(photo_data)
| python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
Let's see what is in this image. | plt.figure(figsize=(15,15))
plt.imshow(photo_data)
photo_data.shape
#print(photo_data) | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
The shape of the ndarray show that it is a three layered matrix. The first two numbers here are length and width, and the third number (i.e. 3) is for three layers: Red, Green and Blue.
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold">
RGB Color Mapping in the Photo:</p>
<br>
<ul>
<li><p s... | photo_data.size
photo_data.min(), photo_data.max()
photo_data.mean() | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold"><br>
Pixel on the 150th Row and 250th Column</p> | photo_data[150, 250]
photo_data[150, 250, 1] | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold"><br>
Set a Pixel to All Zeros</p>
<br/>
We can set all three layer in a pixel as once by assigning zero globally to that (row,column) pairing. However, setting one pixel to zero is not noticeable. | #photo_data = misc.imread('./wifire/sd-3layers.jpg')
photo_data[150, 250] = 0
plt.figure(figsize=(10,10))
plt.imshow(photo_data) | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold"><br>
Changing colors in a Range<p/>
<br/>
We can also use a range to change the pixel values. As an example, let's set the green layer for rows 200 t0 800 to full intensity. | photo_data = misc.imread('./wifire/sd-3layers.jpg')
photo_data[200:800, : ,1] = 255
plt.figure(figsize=(10,10))
plt.imshow(photo_data)
photo_data = misc.imread('./wifire/sd-3layers.jpg')
photo_data[200:800, :] = 255
plt.figure(figsize=(10,10))
plt.imshow(photo_data)
photo_data = misc.imread('./wifire/sd-3layers.jpg... | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold"><br>
Pick all Pixels with Low Values</p> | photo_data = misc.imread('./wifire/sd-3layers.jpg')
print("Shape of photo_data:", photo_data.shape)
low_value_filter = photo_data < 200
print("Shape of low_value_filter:", low_value_filter.shape) | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold">
Filtering Out Low Values</p>
Whenever the low_value_filter is True, set value to 0.
<br/> | #import random
plt.figure(figsize=(10,10))
plt.imshow(photo_data)
photo_data[low_value_filter] = 0
plt.figure(figsize=(10,10))
plt.imshow(photo_data) | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold">
More Row and Column Operations</p>
<br>
You can design complex patters by making cols a function of rows or vice-versa. Here we try a linear relationship between rows and columns. | rows_range = np.arange(len(photo_data))
cols_range = rows_range
print(type(rows_range))
photo_data[rows_range, cols_range] = 255
plt.figure(figsize=(15,15))
plt.imshow(photo_data) | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold"><br>
Masking Images</p>
<br>Now let us try something even cooler...a mask that is in shape of a circular disc.
<img src="./1494532821.png" align="left" style="width:550px;height:360px;"/> | total_rows, total_cols, total_layers = photo_data.shape
#print("photo_data = ", photo_data.shape)
X, Y = np.ogrid[:total_rows, :total_cols]
#print("X = ", X.shape, " and Y = ", Y.shape)
center_row, center_col = total_rows / 2, total_cols / 2
#print("center_row = ", center_row, "AND center_col = ", center_col)
#print(... | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold">
Further Masking</p>
<br/>You can further improve the mask, for example just get upper half disc. | X, Y = np.ogrid[:total_rows, :total_cols]
half_upper = X < center_row # this line generates a mask for all rows above the center
half_upper_mask = np.logical_and(half_upper, circular_mask)
photo_data = misc.imread('./wifire/sd-3layers.jpg')
photo_data[half_upper_mask] = 255
#photo_data[half_upper_mask] = random.randi... | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
<p style="font-family: Arial; font-size:2.75em;color:purple; font-style:bold"><br>
Further Processing of our Satellite Imagery </p>
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold">
Processing of RED Pixels</p>
Remember that red pixels tell us about the height. Let us try to highlight al... | photo_data = misc.imread('./wifire/sd-3layers.jpg')
red_mask = photo_data[:, : ,0] < 150
photo_data[red_mask] = 0
plt.figure(figsize=(15,15))
plt.imshow(photo_data) | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold"><br>
Detecting Highl-GREEN Pixels</p> | photo_data = misc.imread('./wifire/sd-3layers.jpg')
green_mask = photo_data[:, : ,1] < 150
photo_data[green_mask] = 0
plt.figure(figsize=(15,15))
plt.imshow(photo_data) | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold"><br>
Detecting Highly-BLUE Pixels</p> | photo_data = misc.imread('./wifire/sd-3layers.jpg')
blue_mask = photo_data[:, : ,2] < 150
photo_data[blue_mask] = 0
plt.figure(figsize=(15,15))
plt.imshow(photo_data) | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
<p style="font-family: Arial; font-size:1.75em;color:#2462C0; font-style:bold"><br>
Composite mask that takes thresholds on all three layers: RED, GREEN, BLUE</p> | photo_data = misc.imread('./wifire/sd-3layers.jpg')
red_mask = photo_data[:, : ,0] < 150
green_mask = photo_data[:, : ,1] > 100
blue_mask = photo_data[:, : ,2] < 100
final_mask = np.logical_and(red_mask, green_mask, blue_mask)
photo_data[final_mask] = 0
plt.figure(figsize=(15,15))
plt.imshow(photo_data) | python_for_data_sci_dse200x/week3/Satellite Image Analysis using numpy.ipynb | rvm-segfault/edx | apache-2.0 |
Forests of randomized trees
The sklearn.ensemble module includes two averaging algorithms based on randomized decision trees: the RandomForest algorithm and the Extra-Trees method. These two has perturb-and-combine style: a diverse set of classifiers is created by introducing randomness in the classifier construction. ... | from sklearn.ensemble import RandomForestClassifier
X = [[0,0], [1,1]]
Y = [0, 1]
clf = RandomForestClassifier(n_estimators=10)
clf = clf.fit(X,Y)
| ML Algorithm - Random Forests.ipynb | machlearn/ipython-notebooks | mit |
DP references
Dynamic Programming - From Novice to Advanced, by Dumitru topcoder member (link)
Monge arrays
Have a look at https://en.wikipedia.org/wiki/Monge_array | def parity_numbered_rows(matrix, parity, include_index=False):
start = 0 if parity == 'even' else 1
return [(i, r) if include_index else r
for i in range(start, len(matrix), 2)
for r in [matrix[i]]]
def argmin(iterable, only_index=True):
index, minimum = index_min = min(enumera... | tutorials/dynamic-programming.ipynb | massimo-nocentini/competitive-programming | mit |
The following is a Monge array: | matrix = [
[10, 17, 13, 28, 23],
[17, 22, 16, 29, 23],
[24, 28, 22, 34, 24],
[11, 13, 6, 17, 7],
[45, 44, 32, 37, 23],
[36, 33, 19, 21, 6],
[75, 66, 51, 53, 34],
]
minima(matrix)
minima_indexes(matrix)
is_not_monge(matrix) | tutorials/dynamic-programming.ipynb | massimo-nocentini/competitive-programming | mit |
The following is not a Monge array: | matrix = [
[37, 23, 22, 32],
[21, 6, 7, 10],
[53, 34, 30, 31],
[32, 13, 9, 6],
[43, 21, 15, 8],
]
minima(matrix) # produces a wrong answer!!!
minima_indexes(matrix)
is_not_monge(matrix) | tutorials/dynamic-programming.ipynb | massimo-nocentini/competitive-programming | mit |
longest_increasing_subsequence | @memo_holder
def longest_increasing_subsequence(seq):
L = []
for i, current in enumerate(seq):
"""opt, arg = max([(l, j) for (l, j) in L[:i] if l[-1] < current],
key=lambda p: len(p[0]),
default=([], tuple()))
L.append(opt + [current], (arg, i))"... | tutorials/dynamic-programming.ipynb | massimo-nocentini/competitive-programming | mit |
a simple test case taken from page 157: | seq = [5, 2, 8, 6, 3, 6, 9, 7] # see page 157
subseq, memo_table = longest_increasing_subsequence(seq, memo_table=True)
subseq | tutorials/dynamic-programming.ipynb | massimo-nocentini/competitive-programming | mit |
memoization table shows that [2,3,6,7] is another solution: | memo_table
lis_rec(seq) | tutorials/dynamic-programming.ipynb | massimo-nocentini/competitive-programming | mit |
The following is an average case where the sequence is generated randomly: | length = int(5e3)
seq = [randint(0, length) for _ in range(length)]
%timeit longest_increasing_subsequence(seq)
%timeit lis_rec(seq) | tutorials/dynamic-programming.ipynb | massimo-nocentini/competitive-programming | mit |
worst scenario where the sequence is a sorted list, in increasing order: | seq = range(length)
%timeit longest_increasing_subsequence(seq)
%timeit lis_rec(seq) | tutorials/dynamic-programming.ipynb | massimo-nocentini/competitive-programming | mit |
edit_distance | @memo_holder
def edit_distance(xs, ys,
gap_in_xs=lambda y: 1, # cost of putting a gap in `xs` when reading `y`
gap_in_ys=lambda x: 1, # cost of putting a gap in `ys` when reading `x`
mismatch=lambda x, y: 1, # cost of mismatch (x, y) in the sense of `==`
... | tutorials/dynamic-programming.ipynb | massimo-nocentini/competitive-programming | mit |
matrix_product_ordering | @memo_holder
def matrix_product_ordering(o, w, op):
n = len(o)
T = {(i,i):(lambda: o[i], 0) for i in range(n)}
def combine(i,r,j):
t_ir, c_ir = T[i, r]
t_rj, c_rj = T[r+1, j]
return (lambda: op(t_ir(), t_rj()), c_ir + c_rj + w(i, r+1, j+1)) # w[i]*w[r+1]*w[j+1])
fo... | tutorials/dynamic-programming.ipynb | massimo-nocentini/competitive-programming | mit |
http://oeis.org/A180118 | from sympy import fibonacci, Matrix, init_printing
init_printing()
(opt, cost), memo_table = parens_str_proxy(w={i:fibonacci(i+1) for i in range(10)}, memo_table=True)
opt, cost
{k:(thunk(), cost) for k,(thunk, cost) in memo_table.items()} | tutorials/dynamic-programming.ipynb | massimo-nocentini/competitive-programming | mit |
http://oeis.org/A180664 | def to_matrix_cost(dim, memo_table):
n, m = dim
return Matrix(n, m, lambda n,k: memo_table.get((n, k), (lambda: None, 0))[-1])
to_matrix_cost(dim=(9,9), memo_table=memo_table) | tutorials/dynamic-programming.ipynb | massimo-nocentini/competitive-programming | mit |
longest_common_subsequence | @memo_holder
def longest_common_subsequence(A, B, gap_A, gap_B,
equal=lambda a, b: 1, shrink_A=lambda a: 0, shrink_B=lambda b: 0,
reduce=sum):
T = {}
T.update({(i, 0):([gap_A]*i, 0) for i in range(len(A)+1)})
T.update({(0, j):([gap_B]*... | tutorials/dynamic-programming.ipynb | massimo-nocentini/competitive-programming | mit |
NOTE on notation
* _x, _y, _z, ...: NumPy 0-d or 1-d arrays
* _X, _Y, _Z, ...: NumPy 2-d or higer dimensional arrays
* x, y, z, ...: 0-d or 1-d tensors
* X, Y, Z, ...: 2-d or higher dimensional tensors
Control Flow Operations
Q1. Let x and y be random 0-D tensors. Return x + y
if x < y and x - y otherwise.
Q2. Let x a... | x = tf.constant([True, False, False], tf.bool)
y = tf.constant([True, True, False], tf.bool)
| programming/Python/tensorflow/exercises/Control_Flow.ipynb | diegocavalca/Studies | cc0-1.0 |
Q5. Given x, return the truth value of NOT x element-wise. | x = tf.constant([True, False, False], tf.bool)
| programming/Python/tensorflow/exercises/Control_Flow.ipynb | diegocavalca/Studies | cc0-1.0 |
Normal file operations and data preparation for later example | # list recursively everything under the root dir
! {hadoop_root + 'bin/hdfs dfs -ls -R /'} | instructor-notes/1-hadoop-streaming-py-wordcount.ipynb | dsiufl/2015-Fall-Hadoop | mit |
Download some files for later use. | # We will use three ebooks from Project Gutenberg for later example
# Pride and Prejudice by Jane Austen: http://www.gutenberg.org/ebooks/1342.txt.utf-8
! wget http://www.gutenberg.org/ebooks/1342.txt.utf-8 -O /home/ubuntu/shortcourse/data/wordcount/pride-and-prejudice.txt
# Alice's Adventures in Wonderland by Lewis C... | instructor-notes/1-hadoop-streaming-py-wordcount.ipynb | dsiufl/2015-Fall-Hadoop | mit |
2. WordCount Example
Let's count the single word frequency in the uploaded three books.
Start Yarn, the resource allocator for Hadoop. | # start the hadoop distributed file system
! {hadoop_root + 'sbin/start-yarn.sh'}
# wordcount 1 the scripts
# Map: /home/ubuntu/shortcourse/notes/scripts/wordcount1/mapper.py
# Test locally the map script
! echo "go gators gators beat everyone go glory gators" | \
/home/ubuntu/shortcourse/notes/scripts/wordcount1/ma... | instructor-notes/1-hadoop-streaming-py-wordcount.ipynb | dsiufl/2015-Fall-Hadoop | mit |
3. Exercise: WordCount2
Count the single word frequency, where the words are given in a pattern file.
For example, given pattern.txt file, which contains:
"a b c d"
And the input file is:
"d e a c f g h i a b c d".
Then the output shoule be:
"a 1
b 1
c 2
d 2"
Please copy the mapper.py and reduce.py from the fi... | # execise: count the words existing in the given pattern file for the three books
cmd = hadoop_root + 'bin/hadoop jar ' + hadoop_root + 'hadoop-streaming-2.7.1.jar ' + \
'-cmdenv PATTERN_FILE=wc2-pattern.txt ' + \
'-input input ' + \
'-output output2 ' + \
'-mapper /home/ubuntu/shortcourse/notes/script... | instructor-notes/1-hadoop-streaming-py-wordcount.ipynb | dsiufl/2015-Fall-Hadoop | mit |
Verify Results
Copy the output file to local
run the following command, and compare with the downloaded output
sort -nrk 2,2 part-00000 | head -n 20
The wc1-part-00000 is the output of the previous wordcount (wordcount1) | ! rm -rf /home/ubuntu/shortcourse/tmp/wc2-part-00000
! {hadoop_root + 'bin/hdfs dfs -copyToLocal output2/part-00000 /home/ubuntu/shortcourse/tmp/wc2-part-00000'}
! cat /home/ubuntu/shortcourse/tmp/wc2-part-00000 | sort -nrk2,2
! sort -nr -k2,2 /home/ubuntu/shortcourse/tmp/wc1-part-00000 | head -n 20
# stop dfs and ya... | instructor-notes/1-hadoop-streaming-py-wordcount.ipynb | dsiufl/2015-Fall-Hadoop | mit |
Setting some notebook-wide options
Let's start by setting some normalization options (discussed below) and always enable colorbars for the elements we will be displaying: | iris.FUTURE.strict_grib_load = True
%opts Image {+framewise} [colorbar=True] Contours [colorbar=True] {+framewise} Curve [xrotation=60] | doc/Introductory_Tutorial.ipynb | ContinuumIO/cube-explorer | bsd-3-clause |
Note that it is easy to set global defaults for a project allowing any suitable settings can be made into a default on a per-element basis. Now lets specify the maximum number of frames we will be displaying: | %output max_frames=1000 | doc/Introductory_Tutorial.ipynb | ContinuumIO/cube-explorer | bsd-3-clause |
<div class="alert alert-info" role="alert">When working on a live server append ``widgets='live'`` to the line above for greatly improved performance and memory usage </div>
Loading our first cube
Here is the summary of the first cube containing some surface temperature data: | iris_cube = iris.load_cube(iris.sample_data_path('GloSea4', 'ensemble_001.pp'))
iris_cube.coord('latitude').guess_bounds()
iris_cube.coord('longitude').guess_bounds()
print iris_cube.summary() | doc/Introductory_Tutorial.ipynb | ContinuumIO/cube-explorer | bsd-3-clause |
Now we can wrap this Iris cube in a HoloCube: | surface_temperature = hc.HoloCube(iris_cube)
surface_temperature | doc/Introductory_Tutorial.ipynb | ContinuumIO/cube-explorer | bsd-3-clause |
A Simple example
Here is a simple example of viewing the surface_temperature cube over time with a single line of code. In HoloViews, this datastructure is a HoloMap of Image elements: | surface_temperature.to.image(['longitude', 'latitude']) | doc/Introductory_Tutorial.ipynb | ContinuumIO/cube-explorer | bsd-3-clause |
You can drag the slider to view the surface temperature at different times. Here is how you can view the values of time in the cube via the HoloViews API: | surface_temperature.dimension_values('time') | doc/Introductory_Tutorial.ipynb | ContinuumIO/cube-explorer | bsd-3-clause |
The times shown in the slider are long making the text rather small. We can use the fact that all times are recorded in the year 2011 on the 16th of each month to shorten these dates. Defining how all dates should be formatted as follows will help with readability: | hv.Dimension.type_formatters[datetime.datetime] = "%m/%y %Hh" | doc/Introductory_Tutorial.ipynb | ContinuumIO/cube-explorer | bsd-3-clause |
Now let us load a cube showing the pre-industrial air temperature: | air_temperature = hc.HoloCube(iris.load_cube(iris.sample_data_path('pre-industrial.pp')),
group='Pre-industrial air temperature')
air_temperature.data.coord('longitude').guess_bounds()
air_temperature.data.coord('latitude').guess_bounds()
air_temperature # Use air_temperature.data.summa... | doc/Introductory_Tutorial.ipynb | ContinuumIO/cube-explorer | bsd-3-clause |
Note that we have the air_temperature available over longitude and latitude but not the time dimensions. As a result, this cube is a single frame when visualized as a temperature map. | (surface_temperature.to.image(['longitude', 'latitude'])+
air_temperature.to.image(['longitude', 'latitude'])(plot=dict(projection=crs.PlateCarree()))) | doc/Introductory_Tutorial.ipynb | ContinuumIO/cube-explorer | bsd-3-clause |
Next is a fairly involved example that plots data side-by-side in a Layout without using the + operator.
This shows how complex plots can be generated with little code and also demonstrates how different HoloViews elements can be combined together. In the following visualization, the curve is a sample of the surface_t... | %%opts Layout [fig_inches=(12,7)] Curve [aspect=2 xticks=4 xrotation=20] Points (color=2) Overlay [aspect='equal']
%%opts Image [projection=crs.PlateCarree()]
# Sample the surface_temperature at (0,10)
temp_curve = surface_temperature.to.curve('time', dynamic=True)[0, 10]
# Show surface_temperature and air_temperature ... | doc/Introductory_Tutorial.ipynb | ContinuumIO/cube-explorer | bsd-3-clause |
Overlaying data and normalization
Lets view the surface temperatures together with the global coastline: | cf.COASTLINE.scale='1000m'
%%opts Image [projection=crs.Geostationary()] (cmap='Greens')
surface_temperature.to.image(['longitude', 'latitude']) * hc.GeoFeature(cf.COASTLINE) | doc/Introductory_Tutorial.ipynb | ContinuumIO/cube-explorer | bsd-3-clause |
Notice that every frame uses the full dynamic range of the Greens color map. This is because normalization is set to +framewise at the top of the notebook which means every frame is normalized independently.
To control normalization, we need to decide on the normalization limits. Let's see the maximum temperature in t... | max_surface_temp = surface_temperature.data.data.max()
max_surface_temp
%%opts Image [projection=crs.Geostationary()] (cmap='Greens')
# Declare a humidity dimension with a range from 0 to 0.01
surface_temp_dim = hv.Dimension('surface_temperature', range=(300, max_surface_temp))
# Use it to declare the value dimension ... | doc/Introductory_Tutorial.ipynb | ContinuumIO/cube-explorer | bsd-3-clause |
By specifying the normalization range we can reveal different aspects of the data. In the example above we can see a warming effect over time as the dark green areas close to the bottom of the normalization range (200K) vanish. Values outside this range are clipped to the ends of the color map.
Lastly, here is a demo o... | %%opts Contours [levels=10]
(surface_temperature.to.contours(['longitude', 'latitude']) * hc.GeoFeature(cf.COASTLINE)) | doc/Introductory_Tutorial.ipynb | ContinuumIO/cube-explorer | bsd-3-clause |
That behavior makes a lot of sense
The highest Q happens when an action's 'favorite state' (i.e. when the transform is equal to state) is in s
It's annoying to have all those separate $Q$ neurons
Perfect opportunity to use the EnsembleArray again (see last lecture)
Doesn't change the model at all
It just groups th... | import nengo
model = nengo.Network('Selection')
with model:
stim = nengo.Node(lambda t: [np.sin(t), np.cos(t)])
s = nengo.Ensemble(200, dimensions=2)
Qs = nengo.networks.EnsembleArray(50, n_ensembles=4)
nengo.Connection(s, Qs.input, transform=[[1,0],[-1,0],[0,1],[0,-1]])
nengo.Connec... | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
Yay, Network Arrays make shorter code!
Back to the model: How do we implement the $max$ function?
Well, it's just a function, so let's implement it
Need to combine all the $Q$ values into one 4-dimensional ensemble
Why? | import nengo
def maximum(x):
result = [0,0,0,0]
result[np.argmax(x)] = 1
return result
model = nengo.Network('Selection')
with model:
stim = nengo.Node(lambda t: [np.sin(t), np.cos(t)])
s = nengo.Ensemble(200, dimensions=2)
Qs = nengo.networks.EnsembleArray(50, n_ensembles=4)
Qal... | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
Not so great (it looks pretty much the same as the linear case)
Very nonlinear function, so neurons are not able to approximate it well
Other options?
The Standard Neural Network Approach (modified)
If you give this problem to a standard neural networks person, what would they do?
They'll say this is exactly what neu... | import nengo
model = nengo.Network('Selection')
with model:
stim = nengo.Node(lambda t: [.5,.4] if t <1. else [0,0] )
s = nengo.Ensemble(200, dimensions=2)
Qs = nengo.networks.EnsembleArray(50, n_ensembles=4)
nengo.Connection(s, Qs.input, transform=[[1,0],[-1,0],[0,1],[0,-1]])
e... | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
Oops, that's not quite right
Why is it selecting more than one action? | import nengo
model = nengo.Network('Selection')
with model:
stim = nengo.Node(lambda t: [.5,.4] if t <1. else [0,0] )
s = nengo.Ensemble(200, dimensions=2)
Qs = nengo.networks.EnsembleArray(50, n_ensembles=4)
Action = nengo.networks.EnsembleArray(50, n_ensembles=4)
nengo.Connection(s... | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
Now we only influence other Actions when we have a positive value
Note: Is there a more neurally efficient way to do this?
Much better
Selects one action reliably
But still gives values smaller than 1.0 for the output a lot
Can we fix that?
What if we adjust e? | %pylab inline
import nengo
def stimulus(t):
if t<.3:
return [.5,.4]
elif .3<t<.5:
return [.4,.5]
else:
return [0,0]
model = nengo.Network('Selection')
with model:
stim = nengo.Node(stimulus)
s = nengo.Ensemble(200, dimensions=2)
Qs = nengo.networks.Ensemb... | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
That seems to introduce a new problem
The self-excitation is so strong that it can't respond to changes in the input
Indeed, any method like this is going to have some form of memory effects
Notice that what has been implemented is an integrator (sort of)
Could we do anything to help without increasing e too much? | %pylab inline
import nengo
def stimulus(t):
if t<.3:
return [.5,.4]
elif .3<t<.5:
return [.3,.5]
else:
return [0,0]
model = nengo.Network('Selection')
with model:
stim = nengo.Node(stimulus)
s = nengo.Ensemble(200, dimensions=2)
Qs = nengo.networks.Ensemb... | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
Better behaviour
But there's still situations where there's too much memory (see the visualizer)
We can reduce this by reducing e | %pylab inline
import nengo
def stimulus(t):
if t<.3:
return [.5,.4]
elif .3<t<.5:
return [.3,.5]
else:
return [0,0]
model = nengo.Network('Selection')
with model:
stim = nengo.Node(stimulus)
s = nengo.Ensemble(200, dimensions=2)
Qs = nengo.networks.Ensemb... | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
Much less memory, but it's still there
And slower to respond to changes
Note that this speed is dependent on $e$, $i$, and the time constant of the neurotransmitter used
Can be hard to find good values
And this gets harder to balance as the number of actions increases
Also hard to balance for a wide range of $Q$ va... | %pylab inline
mm=1
mp=1
me=1
mg=1
#connection strengths from original model
ws=1
wt=1
wm=1
wg=1
wp=0.9
we=0.3
#neuron lower thresholds for various populations
e=0.2
ep=-0.25
ee=-0.2
eg=-0.2
le=0.2
lg=0.2
D = 10
tau_ampa=0.002
tau_gaba=0.008
N = 50
radius = 1.5
import nengo
from nengo.dists import Uniform
model ... | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
Notice that we are also flipping the output from [1, 1, 0, 1] to [0, 0, 1, 0]
Mostly for our convenience, but we can also add some mutual inhibition there
Works pretty well
Scales up to many actions
Selects quickly
Gets behavioural match to empirical data, including timing predictions (!)
Also shows interestin... | %pylab inline
import nengo
from nengo.dists import Uniform
model = nengo.Network(label='Selection')
D=4
with model:
stim = nengo.Node([0,0])
s = nengo.Ensemble(200, dimensions=2)
Qs = nengo.networks.EnsembleArray(50, n_ensembles=D)
nengo.Connection(stim, s)
nengo.Connection(s, Qs.input,... | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
This system seems to work well
Still not perfect
Matches biology nicely, because of how we implemented it
Some more details on the basal ganglia implementation
all those parameters come from here
<img src="files/lecture_selection/gpr-diagram.png" width="500">
In the original model, each action has a single "neu... | %pylab inline
import nengo
from nengo.dists import Uniform
model = nengo.Network(label='Selection')
D=4
with model:
stim = nengo.Node([0,0])
s = nengo.Ensemble(200, dimensions=2)
Qs = nengo.networks.EnsembleArray(50, n_ensembles=4)
nengo.Connection(stim, s)
nengo.Connection(s, Qs.input,... | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
What about more complex actions?
Consider a simple creature that goes where it's told, or runs away if it's scared
Action 1: set $m$ to the direction it's told to do
Action 2: set $m$ to the direction we started from
Need to pass information from one group of neurons to another
But only do this when the action is cho... | %pylab inline
import nengo
from nengo.dists import Uniform
model = nengo.Network('Creature')
with model:
stim = nengo.Node([0,0], label='stim')
command = nengo.Ensemble(100, dimensions=2, label='command')
motor = nengo.Ensemble(100, dimensions=2, label='motor')
position = nengo.Ensemble(1000, dimensio... | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
There's also another way to do this
A special case for forcing a function to go to zero when a particular group of neurons is active | %pylab inline
import nengo
from nengo.dists import Uniform
model = nengo.Network('Creature')
with model:
stim = nengo.Node([0,0], label='stim')
command = nengo.Ensemble(100, dimensions=2, label='command')
motor = nengo.Ensemble(100, dimensions=2, label='motor')
position = nengo.Ensemble(1000, dimensio... | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
This is a situation where it makes sense to ignore the NEF!
All we want to do is shut down the neural activity
So just do a very inhibitory connection
The Cortex-Basal Ganglia-Thalamus loop
We now have everything we need for a model of one of the primary structures in the mammalian brain
Basal ganglia: action selec... | %pylab inline
import nengo
from nengo import spa
D = 16
def start(t):
if t < 0.05:
return 'A'
else:
return '0'
model = spa.SPA(label='Sequence_Module', seed=5)
with model:
model.cortex = spa.Buffer(dimensions=D, label='cortex')
model.input = spa.Input(cortex=start, label='input')... | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
Behavioural Evidence
Is there any evidence that this is the way it works in brains?
Consistent with anatomy/connectivity
What about behavioural evidence?
A few sources of support
Timing data
How long does it take to do an action?
There are lots of existing computational (non-neural) cognitive models that have ... | from IPython.display import YouTubeVideo
YouTubeVideo('sUvHCs5y0o8', width=640, height=390, loop=1, autoplay=0) | SYDE 556 Lecture 9 Action Selection.ipynb | celiasmith/syde556 | gpl-2.0 |
Read in the surveys | all_survey = pd.read_csv("../data/schools/survey_all.txt", delimiter="\t", encoding='windows-1252')
d75_survey = pd.read_csv("../data/schools/survey_d75.txt", delimiter="\t", encoding='windows-1252')
survey = pd.concat([all_survey, d75_survey], axis=0)
survey["DBN"] = survey["dbn"]
survey_fields = [
"DBN",
"... | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
Convert columns to numeric | cols = ['SAT Math Avg. Score', 'SAT Critical Reading Avg. Score', 'SAT Writing Avg. Score']
for c in cols:
data["sat_results"][c] = pd.to_numeric(data["sat_results"][c], errors="coerce")
data['sat_results']['sat_score'] = data['sat_results'][cols[0]] + data['sat_results'][cols[1]] + data['sat_results'][cols[2]]
d... | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
Condense datasets | class_size = data["class_size"]
class_size = class_size[class_size["GRADE "] == "09-12"]
class_size = class_size[class_size["PROGRAM TYPE"] == "GEN ED"]
class_size = class_size.groupby("DBN").agg(np.mean)
class_size.reset_index(inplace=True)
data["class_size"] = class_size
data["demographics"] = data["demographics"][... | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
Convert AP scores to numeric | cols = ['AP Test Takers ', 'Total Exams Taken', 'Number of Exams with scores 3 4 or 5']
for col in cols:
data["ap_2010"][col] = pd.to_numeric(data["ap_2010"][col], errors="coerce") | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
Find correlations | correlations = combined.corr()
correlations = correlations["sat_score"]
correlations = correlations.dropna()
correlations.sort_values(ascending=False, inplace=True)
# Interesting correlations tend to have r value > .25 or < -.25
interesting_correlations = correlations[abs(correlations) > 0.25]
print(interesting_correl... | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
Survey Correlations | # Make a bar plot of the correlations between survey fields and sat_score
correlations[survey_fields].plot.bar(figsize=(9,7)) | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
From the survey fields, two stand out due to their significant positive correlations:
* N_s - Number of student respondents
* N_p - Number of parent respondents
* aca_s_11 - Academic expectations score based on student responses
* saf_s_11 - Safety and Respect score based on student responses
Why are some possible reas... | # Make a scatterplot of the saf_s_11 column vs the sat-score in combined
combined.plot.scatter(x='sat_score', y='saf_s_11', figsize=(9,5)) | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
So a high saf_s_11 student safety and respect score doesn't really have any predictive value regarding SAT score. However, a low saf_s_11 has a very strong correlation with low SAT scores.
Map out Safety Scores | # Find the average values for each column for each school_dist in combined
districts = combined.groupby('school_dist').agg(np.mean)
# Reset the index of districts, making school_dist a column again
districts.reset_index(inplace=True)
# Make a map that shows afety scores by district
from mpl_toolkits.basemap import Ba... | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
So it looks like the safest schools are in Manhattan, while the least safe schools are in Brooklyn.
This jives with crime statistics by borough
Race and SAT Scores
There are a few columsn that indicate the percentage of each race at a given school:
* white_per
* asian_per
* black_per
* hispanic_per
By plotting out the... | # Make a plot of the correlations between racial cols and sat_score
race_cols = ['white_per', 'asian_per', 'black_per', 'hispanic_per']
race_corr = correlations[race_cols]
race_corr.plot(kind='bar') | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
A higher percentage of white and asian students correlates positively with SAT scores and a higher percentage of black or hispanic students correlates negatively with SAT scores. I wouldn't say any of this is suprising. My guess would be that there is an underlying economic factor which is the cause - white and asian... | # Explore schools with low SAT scores and a high hispanic_per
combined.plot.scatter(x='hispanic_per', y='sat_score') | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
The above scatterplot shows that a low hispanic percentage isn't particularly predictive of SAT score. However, a high hispanic percentage is highly predictive of a low SAT score. | # Research any schools with a greater than 95% hispanic_per
high_hispanic = combined[combined['hispanic_per'] > 95]
# Find the names of schools from the data
high_hispanic['SCHOOL NAME'] | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
The above schools appear to contain a lot of international schools focused on recent immigrants who are learning English as a 2nd language. It makes sense that they would have a harder time on the SAT which is given soley in English. | # Research any schools with less than 10% hispanic_per and greater than
# 1800 average SAT score
high_sat_low_hispanic = combined[(combined['hispanic_per'] < 10) &
(combined['sat_score'] > 1800)]
high_sat_low_hispanic['SCHOOL NAME'] | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
Most of the schools above appear to be specialized science and technology schools which receive extra funding and require students to do well on a standardized test before being admitted. So it is reasonable that students at these schools would have a high average SAT score.
Gender and SAT Scores
There are two columns... | # Investigate gender differences in SAT scores
gender_cols = ['male_per', 'female_per']
gender_corr = correlations[gender_cols]
gender_corr
# Make a plot of the gender correlations
gender_corr.plot.bar() | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
In the plot above, we can see that a high percentage of females at a school positively correlates with SAT score, whereas a high percentage of males at a school negatively correlates with SAT score. Neither correlation is extremely strong.
More data would be required before I was wiling to say that this is a significan... | # Investigate schools with high SAT scores and a high female_per
combined.plot.scatter(x='female_per', y='sat_score') | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
The above plot appears to show that either very low or very high percentage of females in a school leads to a low average SAT score. However, a percentage in the range 40 to 80 or so can lead to good scores. There doesn't appear to be a strong overall correlation. | # Research any schools with a greater than 60% female_per, and greater
# than 1700 average SAT score.
high_female_high_sat = combined[(combined['female_per'] > 60) &
(combined['sat_score'] > 1700)]
high_female_high_sat['SCHOOL NAME'] | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
These schools appears to be very selective liberal arts schools that have high academic standards.
AP Scores vs SAT Scores
The Advanced Placement (AP) exams are exams that high schoolers take in order to gain college credit. AP exams can be taken in many different subjects, and passing the AP exam means that colleges ... | # Compute the percentage of students in each school that took the AP exam
combined['ap_per'] = combined['AP Test Takers '] / combined['total_enrollment']
# Investigate the relationship between AP scores and SAT scores
combined.plot.scatter(x='ap_per', y='sat_score') | dataquest/DataCleaning/Analyzing_NYC_High_School_Data.ipynb | tleonhardt/CodingPlayground | mit |
Below is an example for how to get precision of your model
Attention : You need to finish one line of code to implement the whole example. | #Let's load iris data again
iris = datasets.load_iris()
X = iris.data
y = iris.target
# Let's split the data to training and testing data.
random_state = np.random.RandomState(0)
n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]
# Limit to the two first classes, and split i... | notebooks/machinelearning/precisionrecall.ipynb | cloudmesh/book | apache-2.0 |
Get the average precision score, Run the cell below | from sklearn.metrics import average_precision_score
average_precision = average_precision_score(y_test, y_score)
print('Average precision-recall score: {0:0.2f}'.format(
average_precision)) | notebooks/machinelearning/precisionrecall.ipynb | cloudmesh/book | apache-2.0 |
Train Deep Learning model and validate on test set
LeNET 1989
In this demo you will learn how to use a simple LeNET Model using TensorFlow.
Using the LeNET model architecture for training in H2O
We are ready to start the training procedure. | from h2o.estimators.deepwater import H2ODeepWaterEstimator
lenet_model = H2ODeepWaterEstimator(
epochs=10,
learning_rate=1e-3,
mini_batch_size=64,
network='lenet',
image_shape=[28,28],
problem_type='dataset', ## Not 'image' since we're not passing paths to image files, but raw num... | examples/deeplearning/notebooks/deeplearning_tensorflow_mnist.ipynb | mathemage/h2o-3 | apache-2.0 |
ConvNet Codes
Below, we'll run through all the images in our dataset and get codes for each of them. That is, we'll run the images through the VGGNet convolutional layers and record the values of the first fully connected layer. We can then write these to a file for later when we build our own classifier.
Here we're us... | import os
import numpy as np
import tensorflow as tf
from tensorflow_vgg import vgg16
from tensorflow_vgg import utils
data_dir = 'flower_photos/'
contents = os.listdir(data_dir)
classes = [each for each in contents if os.path.isdir(data_dir + each)] | 08_transfer-learning/Transfer_Learning.ipynb | adrianstaniec/deep-learning | mit |
Below I'm running images through the VGG network in batches. | # Set the batch size higher if you can fit in in your GPU memory
batch_size = 100
codes_list = []
labels = []
batch = []
codes = None
vgg = vgg16.Vgg16()
input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])
with tf.name_scope("content_vgg"):
vgg.build(input_)
with tf.Session() as sess:
for each i... | 08_transfer-learning/Transfer_Learning.ipynb | adrianstaniec/deep-learning | mit |
Data prep
As usual, now we need to one-hot encode our labels and create validation/test sets. First up, creating our labels!
From scikit-learn, use LabelBinarizer to create one-hot encoded vectors from the labels. | from sklearn.preprocessing import LabelBinarizer
lb = LabelBinarizer()
lb.fit(labels)
labels_vecs = lb.transform(labels)
labels_vecs | 08_transfer-learning/Transfer_Learning.ipynb | adrianstaniec/deep-learning | mit |
Now you'll want to create your training, validation, and test sets. An important thing to note here is that our labels and data aren't randomized yet. We'll want to shuffle our data so the validation and test sets contain data from all classes. Otherwise, you could end up with testing sets that are all one class. Typic... | from sklearn.model_selection import StratifiedShuffleSplit
sss = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=0)
for train_index, test_index in sss.split(codes, labels_vecs):
train_x, rest_x = codes[train_index], codes[test_index]
train_y, rest_y = labels_vecs[train_index], labels_vecs[test_i... | 08_transfer-learning/Transfer_Learning.ipynb | adrianstaniec/deep-learning | mit |
Classifier layers
Once you have the convolutional codes, you just need to build a classfier from some fully connected layers. You use the codes as the inputs and the image labels as targets. Otherwise the classifier is a typical neural network.
Exercise: With the codes and labels loaded, build the classifier. Consider... | from tensorflow import layers
inputs_ = tf.placeholder(tf.float32, shape=[None, codes.shape[1]])
labels_ = tf.placeholder(tf.int64, shape=[None, labels_vecs.shape[1]])
fc = tf.layers.dense(inputs_, 2000, activation=tf.nn.relu)
logits = tf.layers.dense(fc, labels_vecs.shape[1], activation=None)
cost = tf.reduce_sum(t... | 08_transfer-learning/Transfer_Learning.ipynb | adrianstaniec/deep-learning | mit |
Training
Here, we'll train the network. | epochs = 10
batches = 100
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for e in range(epochs):
b = 0
for x, y in get_batches(train_x, train_y, batches):
feed = {inputs_: x,
labels_: y}
batch_cost, _ = ... | 08_transfer-learning/Transfer_Learning.ipynb | adrianstaniec/deep-learning | mit |
Below, feel free to choose images and see how the trained classifier predicts the flowers in them. | test_img_path = 'flower_photos/daisy/144603918_b9de002f60_m.jpg'
test_img = imread(test_img_path)
plt.imshow(test_img)
# Run this cell if you don't have a vgg graph built
if 'vgg' in globals():
print('"vgg" object already exists. Will not create again.')
else:
#create vgg
with tf.Session() as sess:
... | 08_transfer-learning/Transfer_Learning.ipynb | adrianstaniec/deep-learning | mit |
Find photos that were mistakenly calassified | data_dir = 'flower_photos/'
contents = os.listdir(data_dir)
classes = [each for each in contents if os.path.isdir(data_dir + each)]
with tf.Session() as sess:
saver = tf.train.Saver()
with tf.Session() as sess2:
saver.restore(sess2, tf.train.latest_checkpoint('checkpoints'))
for e... | 08_transfer-learning/Transfer_Learning.ipynb | adrianstaniec/deep-learning | mit |
Exceptions
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
You've already seen some exceptions:
- syntax errors
- divide by 0
Many programs want to know about exceptions when they occur. For example, if the input to a program is a fi... | def divide1(numerator, denominator):
try:
result = numerator/denominator
print("result = %f" % result)
except:
print("You can't divide by 0!!")
divide1(1.0, 2)
divide1(1.0, 0)
divide1("x", 2) | Spring2018/Debugging-and-Exceptions/Exceptions.ipynb | UWSEDS/LectureNotes | bsd-2-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.