markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Executing commands in the VM can be done with ssh method: | res = vm.ssh(['hostname', '-f'])
res | docs/examples/lago_sdk_one_vm_one_net.ipynb | lago-project/lago | gpl-2.0 |
Lets stop the environment, here we will use the destroy method, however you may also use stop and start if you would like to turn the environment off. | env.destroy() | docs/examples/lago_sdk_one_vm_one_net.ipynb | lago-project/lago | gpl-2.0 |
You can also call display on fig.canvas to display the interactive plot anywhere in the notebooke | fig.canvas.toolbar_visible = True
display(fig.canvas) | notebooks/ipympl.ipynb | ozak/CompEcon | gpl-3.0 |
Or you can display(fig) to embed the current plot as a png | display(fig) | notebooks/ipympl.ipynb | ozak/CompEcon | gpl-3.0 |
3D plotting | from mpl_toolkits.mplot3d import axes3d
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Grab some test data.
X, Y, Z = axes3d.get_test_data(0.05)
# Plot a basic wireframe.
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
plt.show() | notebooks/ipympl.ipynb | ozak/CompEcon | gpl-3.0 |
Subplots | # A more complex example from the matplotlib gallery
np.random.seed(0)
n_bins = 10
x = np.random.randn(1000, 3)
fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2, ax3 = axes.flatten()
colors = ['red', 'tan', 'lime']
ax0.hist(x, n_bins, density=1, histtype='bar', color=colors, label=colors)
ax0.legend(prop={'s... | notebooks/ipympl.ipynb | ozak/CompEcon | gpl-3.0 |
Interactions with other widgets and layouting
When you want to embed the figure into a layout of other widgets you should call plt.ioff() before creating the figure otherwise plt.figure() will trigger a display of the canvas automatically and outside of your layout.
Without using ioff
Here we will end up with the figu... | import ipywidgets as widgets
# ensure we are interactive mode
# this is default but if this notebook is executed out of order it may have been turned off
plt.ion()
fig = plt.figure()
ax = fig.gca()
ax.imshow(Z)
widgets.AppLayout(
center=fig.canvas,
footer=widgets.Button(icon='check'),
pane_heights=[0, 6... | notebooks/ipympl.ipynb | ozak/CompEcon | gpl-3.0 |
Fixing the double display with ioff
If we make sure interactive mode is off when we create the figure then the figure will only display where we want it to.
There is ongoing work to allow usage of ioff as a context manager, see the ipympl issue and the matplotlib issue | plt.ioff()
fig = plt.figure()
plt.ion()
ax = fig.gca()
ax.imshow(Z)
widgets.AppLayout(
center=fig.canvas,
footer=widgets.Button(icon='check'),
pane_heights=[0, 6, 1]
) | notebooks/ipympl.ipynb | ozak/CompEcon | gpl-3.0 |
Interacting with other widgets
Changing a line plot with a slide | # When using the `widget` backend from ipympl,
# fig.canvas is a proper Jupyter interactive widget, which can be embedded in
# an ipywidgets layout. See https://ipywidgets.readthedocs.io/en/stable/examples/Layout%20Templates.html
# One can bound figure attributes to other widget values.
from ipywidgets import AppLayou... | notebooks/ipympl.ipynb | ozak/CompEcon | gpl-3.0 |
Update image data in a performant manner
Two useful tricks to improve performance when updating an image displayed with matplolib are to:
1. Use the set_data method instead of calling imshow
2. Precompute and then index the array | # precomputing all images
x = np.linspace(0,np.pi,200)
y = np.linspace(0,10,200)
X,Y = np.meshgrid(x,y)
parameter = np.linspace(-5,5)
example_image_stack = np.sin(X)[None,:,:]+np.exp(np.cos(Y[None,:,:]*parameter[:,None,None]))
plt.ioff()
fig = plt.figure()
plt.ion()
im = plt.imshow(example_image_stack[0])
def update(... | notebooks/ipympl.ipynb | ozak/CompEcon | gpl-3.0 |
Debugging widget updates and matplotlib callbacks
If an error is raised in the update function then will not always display in the notebook which can make debugging difficult. This same issue is also true for matplotlib callbacks on user events such as mousemovement, for example see issue. There are two ways to see the... | plt.ioff()
fig = plt.figure()
plt.ion()
im = plt.imshow(example_image_stack[0])
out = widgets.Output()
@out.capture()
def update(change):
with out:
if change['name'] == 'value':
im.set_data(example_image_stack[change['new']])
fig.canvas.draw_idle
slider = widgets.IntSlider... | notebooks/ipympl.ipynb | ozak/CompEcon | gpl-3.0 |
Connecting to National Data Service: The Lab Benchwork's NBI - MongoDB instance | Client = MongoClient("mongodb://bridges:readonly@nbi-mongo.admin/bridge")
db = Client.bridge
collection = db["bridges"] | Deterioration Curves/(Southwest) Deterioration+Curves+and+Classification+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Deterioration curves of Southwest United states
For demonstration purposes, the results only focuses on the states in the Southwest United States which includes:
Texas, Oklahoma, New Mexico, Arizona
The classification of the bridge into slow deteriorating, fast deteriorating, and average deteriorating is done based on... | def getData(state):
pipeline = [{"$match":{"$and":[{"year":{"$gt":1991, "$lt":2017}},{"stateCode":state}]}},
{"$project":{"_id":0,
"structureNumber":1,
"yearBuilt":1,
"deck":1, ## rating of deck
"year":1,... | Deterioration Curves/(Southwest) Deterioration+Curves+and+Classification+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Filtering Null Values, Converting JSON format to Dataframes, and Calculating Mean Condition Ratings of Deck, Superstructure, and Substucture
After NBI data is extracted. The Data has to be filtered to remove data points with missing values such as 'N', 'NA'.
The mean condition rating for all the components: Deck, Subs... | def getMeanRatings(state,startAge, endAge, startYear, endYear):
conditionRatings = getData(state)
conditionRatings = conditionRatings[['structureNumber','Age','superstructure','deck','substructure','year']]
conditionRatings = conditionRatings.loc[~conditionRatings['superstructure'].isin(['N','NA'])]
con... | Deterioration Curves/(Southwest) Deterioration+Curves+and+Classification+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Creating DataFrames of the Mean condition ratings of the deck, superstructure and substructure
The calculated Mean Condition Ratings of deck, superstructure, and substructure are now stored in seperate dataframe for the convience. | #Texas, Oklahoma, New Mexico, Arizona
states = ['48','40','35','04']
# state code to state abbreviation
stateNameDict = {'25':'MA',
'04':'AZ',
'08':'CO',
'38':'ND',
'09':'CT',
'19':'IA',
'26':'MI',
'48':'TX... | Deterioration Curves/(Southwest) Deterioration+Curves+and+Classification+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Deterioration Curves - Deck | %matplotlib inline
palette = [ 'blue', 'blue', 'green', 'magenta', 'cyan', 'brown', 'grey',
'red','silver','purple', 'gold', 'black','olive' ]
plt.figure(figsize = (10,8))
index = 0
for state in states:
index = index + 1
stateName = stateNameDict[state]
plt.plot(df_mean_deck['Age'],df_mean_deck[stateNa... | Deterioration Curves/(Southwest) Deterioration+Curves+and+Classification+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Deterioration Curve - Superstructure | palette = [ 'blue', 'blue', 'green', 'magenta', 'cyan', 'brown', 'grey',
'red','silver','purple', 'gold', 'black','olive' ]
plt.figure(figsize = (10,8))
index = 0
for state in states:
index = index + 1
stateName = stateNameDict[state]
plt.plot(df_mean_sub['Age'],df_mean_sup[stateName], color = palette[... | Deterioration Curves/(Southwest) Deterioration+Curves+and+Classification+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Deterioration Curves - Substructure | palette = [ 'blue', 'blue', 'green', 'magenta', 'cyan', 'brown', 'grey',
'red','silver','purple', 'gold', 'black','olive' ]
plt.figure(figsize = (10,8))
index = 0
for state in states:
index = index + 1
stateName = stateNameDict[state]
plt.plot(df_mean_sub['Age'],df_mean_sub[stateName], color = palette[... | Deterioration Curves/(Southwest) Deterioration+Curves+and+Classification+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
The mean deterioration curve can be a measure to evaluate the rate of deterioration. If the condition rating of a bridge lies above the deterioration curve then the bridge is deteriorating at a slower pace than mean deterioration of the bridges, and if the condition rating of the bridge lies below the deterioration cur... | stat = ['48','40','35','04']
AgeList = list(df_nbi_sw['Age'])
deckList = list(df_nbi_sw['deck'])
num = 1
for st in stat:
deckR = []
deckR = getDataOneYear(st)
deckR = deckR[['Age','deck']]
deckR= deckR.loc[~deckR['deck'].isin(['N','NA'])]
stateName = stateNameDict[st]
labels = []
for deckRat... | Deterioration Curves/(Southwest) Deterioration+Curves+and+Classification+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Classification of all the bridges in the Southwest United States | D = dict((x,labels.count(x)) for x in set(labels))
plt.figure(figsize=(12,6))
plt.title('Classification of Bridges in Southwest United States')
plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
plt.xlabel('Categories of Bridges')
plt.ylabel('Number of Bridges')
plt.show(... | Deterioration Curves/(Southwest) Deterioration+Curves+and+Classification+of+Bridges+in+the+Southwest+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Initialize classifier
Classification algorithm can be set to "Naive Bayes" or "Decision Tree" | cl = LogbookClassifier(classification_algorithm="Naive Bayes") | scripts/classifier-example.ipynb | clarka34/exploring-ship-logbooks | mit |
Load Data, Clean data, and Perform Classification
This function loads, cleans, and classifies data
Options include:
fuzz - boolean value for whether to perform fuzzy string matching on values or not
export_csv - boolean value to determine whether classification output is saved. The csv contains information for every l... | cl.load_clean_and_classify(fuzz=False, export_csv=True) | scripts/classifier-example.ipynb | clarka34/exploring-ship-logbooks | mit |
How to access data from outside of the classifier | # data that was classified (unknown class before classification)
cl.unclassified_logs.head()
# data used for validation: 20% of slave voyage logs
cl.validation_set_2.head()
# data used for validation: logs that mention slaves in cliwoc data set
cl.validation_set_1.head()
# data used for training classifier
cl.traini... | scripts/classifier-example.ipynb | clarka34/exploring-ship-logbooks | mit |
Sample plots of data | import exploringShipLogbooks
import os.path as op
import matplotlib.pyplot as plt
import matplotlib
%matplotlib inline
import pandas as pd
# load un-cleaned slave_voyage_logs data
data_path = op.join(exploringShipLogbooks.__path__[0], 'data')
file_name = data_path + '/tastdb-exp-2010'
slave_voyage_logs = pd.read_pickl... | scripts/classifier-example.ipynb | clarka34/exploring-ship-logbooks | mit |
Solver
In the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.
Open the file cs231n/solver.py and read through it to familiarize yourself with the API. After do... | model = TwoLayerNet()
solver = None
##############################################################################
# TODO: Use a Solver instance to train a TwoLayerNet that achieves at least #
# 50% accuracy on the validation set. #
##############################################... | Visual Recognision - Stanford/assignment2/FullyConnectedNets.ipynb | dvirsamuel/MachineLearningCourses | gpl-3.0 |
As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy within 20 epochs. | # TODO: Use a three-layer Net to overfit 50 training examples.
num_train = 50
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
learning_rate = 1e-3
weight_scale = 1e-1
model = FullyConnectedNet([100, 100],
... | Visual Recognision - Stanford/assignment2/FullyConnectedNets.ipynb | dvirsamuel/MachineLearningCourses | gpl-3.0 |
Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs. | # TODO: Use a five-layer Net to overfit 50 training examples.
import random
num_train = 50
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
max_count = 1 #before=30
# find the best learning rate and weight scale by ... | Visual Recognision - Stanford/assignment2/FullyConnectedNets.ipynb | dvirsamuel/MachineLearningCourses | gpl-3.0 |
Inline question:
Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net?
Answer:
It took the five layer net more epochs to overfit the small data. This is ofcourse becouse the net is much bigger and we need to adjsut more parameters
Update rules
So far we... | from cs231n.optim import sgd_momentum
N, D = 4, 5
w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D)
dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D)
v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D)
config = {'learning_rate': 1e-3, 'velocity': v}
next_w, _ = sgd_momentum(w, dw, config=config)
expected_next_w = np.a... | Visual Recognision - Stanford/assignment2/FullyConnectedNets.ipynb | dvirsamuel/MachineLearningCourses | gpl-3.0 |
Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster. | num_train = 4000
small_data = {
'X_train': data['X_train'][:num_train],
'y_train': data['y_train'][:num_train],
'X_val': data['X_val'],
'y_val': data['y_val'],
}
solvers = {}
for update_rule in ['sgd', 'sgd_momentum']:
print 'running with ', update_rule
model = FullyConnectedNet([100, 100, 100, 100, 100],... | Visual Recognision - Stanford/assignment2/FullyConnectedNets.ipynb | dvirsamuel/MachineLearningCourses | gpl-3.0 |
Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules: | learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3}
for update_rule in ['adam', 'rmsprop']:
print 'running with ', update_rule
model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2)
solver = Solver(model, small_data,
num_epochs=5, batch_size=100,
update_rule=upda... | Visual Recognision - Stanford/assignment2/FullyConnectedNets.ipynb | dvirsamuel/MachineLearningCourses | gpl-3.0 |
Train a good model!
Train the best fully-connected model that you can on CIFAR-10, storing your best model in the best_model variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.
If you are careful it should be possible to get accuracies above 55%, but we don't require... | best_model = None
################################################################################
# TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might #
# batch normalization and dropout useful. Store your best model in the #
# best_model variable. ... | Visual Recognision - Stanford/assignment2/FullyConnectedNets.ipynb | dvirsamuel/MachineLearningCourses | gpl-3.0 |
Test you model
Run your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set. | y_test_pred = np.argmax(best_model.loss(data['X_test']), axis=1)
y_val_pred = np.argmax(best_model.loss(data['X_val']), axis=1)
print 'Validation set accuracy: ', (y_val_pred == data['y_val']).mean()
print 'Test set accuracy: ', (y_test_pred == data['y_test']).mean() | Visual Recognision - Stanford/assignment2/FullyConnectedNets.ipynb | dvirsamuel/MachineLearningCourses | gpl-3.0 |
Usando el contecto anterior, creamos un DStream que representa el flujo de datos de una fuente TCP (socket), se especifica un hostname y un puerto. | lines = ssc.socketTextStream("localhost", 9999) | spark_streaming_class/Spark_Streaming.ipynb | israelzuniga/spark_streaming_class | mit |
El DStream lines representa un flujo de datos que serán recibidos desde otro servidor. Cada registro en este DStream es una línea de texto. Después de recibir el registro, separaremos las palabras usando los espacios entre ellas. | words = lines.flatMap(lambda line: line.split(" ")) | spark_streaming_class/Spark_Streaming.ipynb | israelzuniga/spark_streaming_class | mit |
flatMap es una operación (transformación one-to-many) para DStream que crea un nuevo objeto al generar multiples registros por cada registro en el DStream de la fuente. En este caso, cada línea será cortada para obtener multiples palabras y representarse en el DStream words. Después, vamos a imprimir esas palabras. | pairs = words.map(lambda word: (word, 1))
wordCounts = pairs.reduceByKey(lambda x, y: x + y)
wordCounts.pprint() | spark_streaming_class/Spark_Streaming.ipynb | israelzuniga/spark_streaming_class | mit |
El DStream words es transformado (map, one-to-one) al siguiente DStream de pares llave-valor con el siguiente formato (palabra, 1), donde se reduce para obtener la frecuencia de palabras en cada batch de datos. Finalmente, wordCounts.pprint() imprime el conteo generado en ese intervalo.
Debemos recordar, que aún cuand... | ssc.start()
ssc.awaitTermination()
ssc.stop() # 😉 | spark_streaming_class/Spark_Streaming.ipynb | israelzuniga/spark_streaming_class | mit |
Basic interact
At the most basic level, interact autogenerates UI controls for function arguments, and then calls the function with those arguments when you manipulate the controls interactively. To use interact, you need to define a function that you want to explore. Here is a function that returns its only argument x... | def f(x):
return x | docs/source/examples/Using Interact.ipynb | jupyter-widgets/ipywidgets | bsd-3-clause |
When you move the slider, the function is called, and its return value is printed.
If you pass True or False, interact will generate a checkbox: | interact(f, x=True); | docs/source/examples/Using Interact.ipynb | jupyter-widgets/ipywidgets | bsd-3-clause |
If you pass a string, interact will generate a text box. | interact(f, x='Hi there!'); | docs/source/examples/Using Interact.ipynb | jupyter-widgets/ipywidgets | bsd-3-clause |
The following table gives an overview of different argument types, and how they map to interactive controls:
<table class="table table-condensed table-bordered">
<tr><td><strong>Keyword argument</strong></td><td><strong>Widget</strong></td></tr>
<tr><td>`True` or `False`</td><td>Checkbox</td></tr>
<tr><td>`'H... | interact(f, x=(0,4)); | docs/source/examples/Using Interact.ipynb | jupyter-widgets/ipywidgets | bsd-3-clause |
A float-valued slider is produced if any of the elements of the tuples are floats. Here the minimum is 0.0, the maximum is 10.0 and step size is 0.1 (the default). | interact(f, x=(0.0,10.0)); | docs/source/examples/Using Interact.ipynb | jupyter-widgets/ipywidgets | bsd-3-clause |
If you want a dropdown menu that passes non-string values to the Python function, you can pass a list of ('label', value) pairs. The first items are the names in the dropdown menu UI and the second items are values that are the arguments passed to the underlying Python function. | interact(f, x=[('one', 10), ('two', 20)]); | docs/source/examples/Using Interact.ipynb | jupyter-widgets/ipywidgets | bsd-3-clause |
Finally, if you need more granular control than that afforded by the abbreviation, you can pass a ValueWidget instance as the argument. A ValueWidget is a widget that aims to control a single value. Most of the widgets bundled with ipywidgets inherit from ValueWidget. For more information, see this section on widget ty... | interact(f, x=widgets.Combobox(options=["Chicago", "New York", "Washington"], value="Chicago")); | docs/source/examples/Using Interact.ipynb | jupyter-widgets/ipywidgets | bsd-3-clause |
interactive
In addition to interact, IPython provides another function, interactive, that is useful when you want to reuse the widgets that are produced or access the data that is bound to the UI controls.
Note that unlike interact, the return value of the function will not be displayed automatically, but you can displ... | from IPython.display import display
def f(a, b):
display(a + b)
return a+b | docs/source/examples/Using Interact.ipynb | jupyter-widgets/ipywidgets | bsd-3-clause |
You can do the same thing with interactive by using a dict as the second argument, as shown below. | slow = interactive(slow_function, {'manual': True}, i=widgets.FloatSlider(min=1e4, max=1e6, step=1e4))
slow | docs/source/examples/Using Interact.ipynb | jupyter-widgets/ipywidgets | bsd-3-clause |
More control over the user interface: interactive_output
interactive_output provides additional flexibility: you can control how the UI elements are laid out.
Unlike interact, interactive, and interact_manual, interactive_output does not generate a user interface for the widgets. This is powerful, because it means you ... | a = widgets.IntSlider()
b = widgets.IntSlider()
c = widgets.IntSlider()
ui = widgets.HBox([a, b, c])
def f(a, b, c):
print((a, b, c))
out = widgets.interactive_output(f, {'a': a, 'b': b, 'c': c})
display(ui, out) | docs/source/examples/Using Interact.ipynb | jupyter-widgets/ipywidgets | bsd-3-clause |
Interact with multiple functions
You may want to have a single widget interact with multiple functions. This is possible by simply linking the widget to both functions using the interactive_output() function. The order of execution of the functions will be the order they were linked to the widget. | import ipywidgets as widgets
from IPython.display import display
a = widgets.IntSlider(value=5, min=0, max=10)
def f1(a):
display(a)
def f2(a):
display(a * 2)
out1 = widgets.interactive_output(f1, {'a': a})
out2 = widgets.interactive_output(f2, {'a': a})
display(a)
display(out1)
display(out2) | docs/source/examples/Using Interact.ipynb | jupyter-widgets/ipywidgets | bsd-3-clause |
Part 1. Frequency Tables
1. Let's create a frequency table of our variables | # frequency table for prestige and whether or not someone was admitted
print df.columns # finding columns for dataframe
pd.crosstab(df['admit'],df['prestige']) # displaying var presitge over var admit in a pandas crosstab function | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
Part 2. Return of dummy variables
2.1 Create class or dummy variables for prestige | # creating dummy variables for var 'prestige' using pandas get_dummies function
dummy_ranks = pd.get_dummies(df['prestige'],prefix = 'prestige')
print dummy_ranks.head(5)
# still need to append these dummy values to df using .join function; see part 3 | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
2.2 When modeling our class variables, how many do we need?
Answer: When modeling dummy or class variables in general, n-1 variables are required. We assume prestige value '4' to be the base case as this, comparatively, the lowest ranked. For modeling purposes of this model, we will need three (3) class variables
Part ... | cols_to_keep = ['admit', 'gre', 'gpa']
handCalc = df[cols_to_keep].join(dummy_ranks.ix[:, 'prestige_1':])
print handCalc.head()
# crosstab prestige 1 admission
# frequency table cutting prestige and whether or not someone was admitted
print handCalc.columns
pd.crosstab(handCalc['prestige_1.0'],handCalc['admit']) | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
3.1 Use the cross tab above to calculate the odds of being admitted to grad school if you attended a #1 ranked college | OR = float(33.0/93.0)
print OR | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
3.2 Now calculate the odds of admission if you did not attend a #1 ranked college | OR = float(28.0/243.0)
print OR | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
3.3 Calculate the odds ratio
3.4 Write this finding in a sentence:
Answer: For every 93 times a non-prestige_1.0 individual gets into UCLA, a non-prestige_1.0 individual will not get accepted 243 times.
3.5 Print the cross tab for prestige_4 | pd.crosstab(handCalc['prestige_4.0'],handCalc['admit']) | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
3.6 Calculate the OR
3.7 Write this finding in a sentence
Answer: For every 12 times an prestige_4.0 individual gets into UCLA, an individual from prestige_4.0 will not get accepted 114 times.
Part 4. Analysis | # create a clean data frame for the regression
cols_to_keep = ['admit', 'gre', 'gpa']
data = df[cols_to_keep].join(dummy_ranks.ix[:, 'prestige_2':])
print data.head() | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
We're going to add a constant term for our Logistic Regression. The statsmodels function we're going to be using requires that intercepts/constants are specified explicitly. | # manually add the intercept
data['intercept'] = 1 | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
4.1 Set the covariates to a variable called train_cols | train_cols = ['prestige_2.0','prestige_3.0','prestige_4.0','gre', 'gpa'] | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
4.2 Fit the model | data_predictors = data[train_cols]
print data_predictors.head(2)
logit = sm.Logit(data['admit'], data_predictors)
results = logit.fit() | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
4.3 Print the summary results | results.summary() | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
4.4 Calculate the odds ratios of the coeffiencents and their 95% CI intervals
hint 1: np.exp(X)
hint 2: conf['OR'] = params
conf.columns = ['2.5%', '97.5%', 'OR'] | print np.exp(-0.9562)
print np.exp(-1.5375)
print np.exp(-1.8699)
print np.exp(0.0014)
print np.exp(-0.1323)
| AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
4.5 Interpret the OR of Prestige_2
Answer: Prestige_2.0 decreases your odds by 0.38 or a probability of 20 percent (p=0.38/0.83+1). This is statistically significant due to the fact that 0 is not included in the CI.
4.6 Interpret the OR of GPA
Answer: GPA decreases your odds but we cannot say that it is statistically s... | def cartesian(arrays, out=None):
"""
Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray
Array to place the cartesian product in.
Returns
-------
out : ndarray
... | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
5.1 Recreate the dummy variables | # recreate the dummy variables
dummy_ranks = pd.get_dummies(df['prestige'],prefix = 'prestige')
# keep only what we need for making predictions
pred_cols=['gres','gpas']
training_data = combos[pred_cols].join(dummy_ranks.ix[:, 'prestige_2':])
training_data.head(2) | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
5.2 Make predictions on the enumerated dataset | logit = sm.Logit(training_data['admit'], pred_cols) | AdmissionsProject/Part3/starter-code/Flautt-project3-submission.ipynb | eflautt/ga-data-science | mit |
Load candidates and training marginals | from snorkel.models import candidate_subclass
from snorkel.contrib.models.text import RawText
Tweet = candidate_subclass('Tweet', ['tweet'], cardinality=5)
train_tweets = session.query(Tweet).filter(Tweet.split == 0).order_by(Tweet.id).all()
len(train_tweets)
from snorkel.annotations import load_marginals
train_margin... | test/learning/tensorflow/test_TF_notebook.ipynb | HazyResearch/snorkel | apache-2.0 |
Train LogisticRegression | # Simple unigram featurizer
def get_unigram_tweet_features(c):
for w in c.tweet.text.split():
yield w, 1
# Construct feature matrix
from snorkel.annotations import FeatureAnnotator
featurizer = FeatureAnnotator(f=get_unigram_tweet_features)
%time F_train = featurizer.apply(split=0)
F_train
%time F_test =... | test/learning/tensorflow/test_TF_notebook.ipynb | HazyResearch/snorkel | apache-2.0 |
Train SparseLogisticRegression
Note: Testing doesn't currently work with LogisticRegression above, but no real reason to use that over this... | from snorkel.learning.tensorflow import SparseLogisticRegression
model = SparseLogisticRegression(cardinality=Tweet.cardinality)
model.train(F_train, train_marginals, n_epochs=50, print_freq=10)
import numpy as np
test_labels = np.load('crowdsourcing_test_labels.npy')
acc = model.score(F_test, test_labels)
print(acc)... | test/learning/tensorflow/test_TF_notebook.ipynb | HazyResearch/snorkel | apache-2.0 |
Train basic LSTM
With dev set scoring during execution (note we use test set here to be simple) | from snorkel.learning.tensorflow import TextRNN
test_tweets = session.query(Tweet).filter(Tweet.split == 1).order_by(Tweet.id).all()
train_kwargs = {
'dim': 100,
'lr': 0.001,
'n_epochs': 25,
'dropout': 0.2,
'print_freq': 5
}
lstm = TextRNN(seed=123, cardinality=Tweet.cardinality... | test/learning/tensorflow/test_TF_notebook.ipynb | HazyResearch/snorkel | apache-2.0 |
Run GridSearch | from snorkel.learning.utils import GridSearch
# Searching over learning rate
param_ranges = {'lr': [1e-3, 1e-4], 'dim': [50, 100]}
model_class_params = {'seed' : 123, 'cardinality': Tweet.cardinality}
model_hyperparams = {
'dim': 100,
'n_epochs': 20,
'dropout': 0.1,
'print_freq': 10
}
searc... | test/learning/tensorflow/test_TF_notebook.ipynb | HazyResearch/snorkel | apache-2.0 |
Reload saved model outside of GridSearch | lstm = TextRNN(seed=123, cardinality=Tweet.cardinality)
lstm.load('TextRNN_best', save_dir='checkpoints/grid_search')
acc = lstm.score(test_tweets, test_labels)
print(acc)
assert acc > 0.60 | test/learning/tensorflow/test_TF_notebook.ipynb | HazyResearch/snorkel | apache-2.0 |
Reload a model with different structure | lstm.load('TextRNN_0', save_dir='checkpoints/grid_search')
acc = lstm.score(test_tweets, test_labels)
print(acc)
assert acc < 0.60 | test/learning/tensorflow/test_TF_notebook.ipynb | HazyResearch/snorkel | apache-2.0 |
Testing GenerativeModel
Testing GridSearch on crowdsourcing data | from snorkel.annotations import load_label_matrix
import numpy as np
L_train = load_label_matrix(session, split=0)
train_labels = np.load('crowdsourcing_train_labels.npy')
from snorkel.learning import GenerativeModel
# Searching over learning rate
searcher = GridSearch(GenerativeModel, {'epochs': [0, 10, 30]}, L_tra... | test/learning/tensorflow/test_TF_notebook.ipynb | HazyResearch/snorkel | apache-2.0 |
Next, let's actually import the data. | # Set to 'True' if you want to use the handwritten digit dataset instead
do_handwritten_digit_mnist = False
X_train, X_test, y_train, y_test = import_data(do_handwritten_digit_mnist) | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
To see the shape of numpy arrays, you can do the following: | print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape) | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
We can quickly plot a few examples of the images from the dataset to get an idea of what they look like (each image is an array of 28x28 pixels). matplotlib.pyplot.imshow is useful for plotting arrays. | # TODO: will be explanined on tuesday
import matplotlib.pyplot as plt
# plot 4 images as gray scale
plt.subplot(221)
plt.imshow(X_train[0], cmap=plt.get_cmap('gray'))
plt.subplot(222)
plt.imshow(X_train[1], cmap=plt.get_cmap('gray'))
plt.subplot(223)
plt.imshow(X_train[2], cmap=plt.get_cmap('gray'))
plt.subplot(224)
p... | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
1. Simple feed-forward Neural Network
Before we get to the more complex convolutional neural network, let's start with a simple multi-layer perceptron model as a baseline.
Initialize a random number generator, which is useful if you want to reproduce the results later. | import numpy as np
# fix random seed for reproducibility
seed = 7
np.random.seed(seed) | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
Load the dataset again, just to make sure we start with a clean slate. | # Set to 'True' if you want to use the handwritten digit dataset instead
do_handwritten_digit_mnist = False
X_train, X_test, y_train, y_test = import_data(do_handwritten_digit_mnist) | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
When training this simple Neural Network we will first flatten the 28x28 2D images into a vector of 784 (28x28) 1D-array for each image. This is because when training a simple Neural Network there is no 2D shape information in the inputs.
Let's perform some numpy array tricks. | print("Before flattening:")
print("X_train.shape {}".format(X_train.shape))
# flatten 28*28 images to a 784 vector for each image
num_pixels = X_train.shape[1] * X_train.shape[2] # 28x28
X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32')
X_test = X_test.reshape(X_test.shape[0], num_pixels).astype... | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
Before training, input features are often normalized to within the range [0, 1]. | # normalize inputs from 0-255 to 0-1
X_train = X_train / 255
X_test = X_test / 255 | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
The training labels (i.e. the 'y' values) are often converted into what's called "one-hot" encoding. All this means is that instead of encoding the labels with scalar values between 0-9 (as in the table above), each y-label is represented by a vector of length 10 where the ith entry, corresponding to the scalar value o... | from keras.utils import np_utils
# Ex. say we have the following labels
yy = np.array([0, 1, 2, 3, 4 , 5, 6 ,7 ,8 ,9], np.float32)
print('yy',yy)
print('yy.shape',yy.shape)
yy_onehot = np_utils.to_categorical(yy)
print('yy_onehot',yy_onehot)
print('yy_onehot.shape',yy_onehot.shape) | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
Let's now do the same thing for our actual dataset. | # one hot encode outputs
from keras.utils import np_utils
y_train_onehot = np_utils.to_categorical(y_train)
y_test_onehot = np_utils.to_categorical(y_test)
num_classes = y_test_onehot.shape[1]
print("y_train.shape: ",y_train.shape)
print("y_train_onehot.shape: ",y_train_onehot.shape) | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
Alright, so let's start doing some machine learning. Again, you are strongly encouraged to go and read the Keras documentation.
The core data structure of Keras is a model, a way to organize layers. The simplest type of model is the Sequential model, a linear stack of layers. For more complex architectures, you should ... | # Import the Sequential model
from keras.models import Sequential
# Dense is just your the regular densely-connected NN layer
from keras.layers import Dense
# define baseline model
def baseline_model():
# create model
model = Sequential()
model.add(Dense(num_pixels, input_dim=num_pixels, kernel_initializer... | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
Build and show the model architecuture. | # build the model
model = baseline_model()
model.summary() | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
We then train our model in the training data. Keras automatically runs validation on the test data.
You can experiment with the number of 'epochs' the 'batch size':
- one epoch = One forward pass and one backward pass of all the training examples.
- batch size = The number of training examples in one forward/backward p... | # Fit (train) the model
history = model.fit(X_train, y_train_onehot, validation_data=(X_test, y_test_onehot), epochs=10, batch_size=200, verbose=2)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test_onehot, verbose=0)
print("Baseline Error: %.2f%%" % (100-scores[1]*100)) | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
The baseline error for this simple multi-layer perceptron neural net should be around 11%.
You can plot the accuracy and loss vs. epoch. | # list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize histor... | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
Simple Convolutional Neural Network
In this section we will create a simple CNN for MNIST that demonstrates how to use all of the aspects of a modern CNN implementation, including Convolutional layers, Pooling layers and Dropout layers.
We start by importing the classes and functions needed. | import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from... | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
Next we define our neural network model.
Convolutional neural networks are more complex than standard multi-layer perceptrons, so we will start by using a simple structure to begin with that uses all of the elements for state of the art results. Below summarizes the network architecture.
The first hidden layer is a con... | def baseline_model():
# create model
model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(1, 28, 28), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes,... | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
We evaluate the model the same way as before with the multi-layer perceptron. The CNN is fit over 10 epochs with a batch size of 200. | # build the model
model = baseline_model()
# Print a summary of the model structure
model.summary()
# Fit the model
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200, verbose=2)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("CNN ... | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
The error for this simple convolutional neural net should be about 8.5% (after 10 epochs). | # list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history ... | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
Larger Convolutional Neural Network
Finally, let's implement closer to the state of the art results. | # Larger CNN for the MNIST Dataset
import numpy
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from ker... | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
This time we define a large CNN architecture with additional convolutional, max pooling layers and fully connected layers. The network topology can be summarized as follows.
Convolutional layer with 30 feature maps of size 5×5.
Pooling layer taking the max over 2*2 patches.
Convolutional layer with 15 feature maps of ... | # define the larger model
def larger_model():
# create model
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(1, 28, 28), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(15, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
mod... | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
Training: Like the previous two experiments, the model is fit over 10 epochs with a batch size of 200. | # build the model
model = larger_model()
# Print a summary of the model structure
model.summary()
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Large CNN Error: %.2f%%" % ... | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
It is often very useful to save a partly trained model. This is easy in Keras. | # Save partly trained model
model.save('partly_trained.h5') | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
To the reload the model and continue training you can do: | # Load partly trained model
from keras.models import load_model
model = load_model('partly_trained.h5')
# model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200) | tutorial/DeepLearningImages/DeepLearning-MNIST.ipynb | ivukotic/ML_platform_tests | gpl-3.0 |
Next, let's define an easy objective function (a Tune Trainable) that reports a random loss to Tune.
The objective function itself is not important for this example, since we want to focus on the Weights & Biases
integration primarily. | def objective(config, checkpoint_dir=None):
for i in range(30):
loss = config["mean"] + config["sd"] * np.random.randn()
tune.report(loss=loss) | doc/source/tune/examples/tune-wandb.ipynb | ray-project/ray | apache-2.0 |
Given that you provide an api_key_file pointing to your Weights & Biases API key, you cna define a
simple grid-search Tune run using the WandbLoggerCallback as follows: | def tune_function(api_key_file):
"""Example for using a WandbLoggerCallback with the function API"""
analysis = tune.run(
objective,
metric="loss",
mode="min",
config={
"mean": tune.grid_search([1, 2, 3, 4, 5]),
"sd": tune.uniform(0.2, 0.8),
},
... | doc/source/tune/examples/tune-wandb.ipynb | ray-project/ray | apache-2.0 |
To use the wandb_mixin decorator, you can simply decorate the objective function from earlier.
Note that we also use wandb.log(...) to log the loss to Weights & Biases as a dictionary.
Otherwise, the decorated version of our objective is identical to its original. | @wandb_mixin
def decorated_objective(config, checkpoint_dir=None):
for i in range(30):
loss = config["mean"] + config["sd"] * np.random.randn()
tune.report(loss=loss)
wandb.log(dict(loss=loss)) | doc/source/tune/examples/tune-wandb.ipynb | ray-project/ray | apache-2.0 |
With the decorated_objective defined, running a Tune experiment is as simple as providing this objective and
passing the api_key_file to the wandb key of your Tune config: | def tune_decorated(api_key_file):
"""Example for using the @wandb_mixin decorator with the function API"""
analysis = tune.run(
decorated_objective,
metric="loss",
mode="min",
config={
"mean": tune.grid_search([1, 2, 3, 4, 5]),
"sd": tune.uniform(0.2, 0.8)... | doc/source/tune/examples/tune-wandb.ipynb | ray-project/ray | apache-2.0 |
Finally, you can also define a class-based Tune Trainable by using the WandbTrainableMixin to define your objective: | class WandbTrainable(WandbTrainableMixin, Trainable):
def step(self):
for i in range(30):
loss = self.config["mean"] + self.config["sd"] * np.random.randn()
wandb.log({"loss": loss})
return {"loss": loss, "done": True} | doc/source/tune/examples/tune-wandb.ipynb | ray-project/ray | apache-2.0 |
Running Tune with this WandbTrainable works exactly the same as with the function API.
The below tune_trainable function differs from tune_decorated above only in the first argument we pass to
tune.run(): | def tune_trainable(api_key_file):
"""Example for using a WandTrainableMixin with the class API"""
analysis = tune.run(
WandbTrainable,
metric="loss",
mode="min",
config={
"mean": tune.grid_search([1, 2, 3, 4, 5]),
"sd": tune.uniform(0.2, 0.8),
... | doc/source/tune/examples/tune-wandb.ipynb | ray-project/ray | apache-2.0 |
Since you may not have an API key for Wandb, we can mock the Wandb logger and test all three of our training
functions as follows.
If you do have an API key file, make sure to set mock_api to False and pass in the right api_key_file below. | import tempfile
from unittest.mock import MagicMock
mock_api = True
api_key_file = "~/.wandb_api_key"
if mock_api:
WandbLoggerCallback._logger_process_cls = MagicMock
decorated_objective.__mixins__ = tuple()
WandbTrainable._wandb = MagicMock()
wandb = MagicMock() # noqa: F811
temp_file = tempfil... | doc/source/tune/examples/tune-wandb.ipynb | ray-project/ray | apache-2.0 |
Data file | print(data.keys())
print('Number of examples ', data.target.shape[0]) | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.