markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Test your style loss implementation. The error should be less than 0.001. | def style_loss_test(correct):
style_layers = [1, 4, 6, 7]
style_weights = [300000, 1000, 15, 3]
feats = model.extract_features()
style_target_vars = []
for idx in style_layers:
style_target_vars.append(gram_matrix(feats[idx]))
style_targets = sess.run(style_target_vars,
... | cs231n/assignment3/StyleTransfer-TensorFlow.ipynb | kabrapratik28/Stanford_courses | apache-2.0 |
Total-variation regularization
It turns out that it's helpful to also encourage smoothness in the image. We can do this by adding another term to our loss that penalizes wiggles or "total variation" in the pixel values.
You can compute the "total variation" as the sum of the squares of differences in the pixel values ... | def tv_loss(img, tv_weight):
"""
Compute total variation loss.
Inputs:
- img: Tensor of shape (1, H, W, 3) holding an input image.
- tv_weight: Scalar giving the weight w_t to use for the TV loss.
Returns:
- loss: Tensor holding a scalar giving the total variation loss
for im... | cs231n/assignment3/StyleTransfer-TensorFlow.ipynb | kabrapratik28/Stanford_courses | apache-2.0 |
Test your TV loss implementation. Error should be less than 0.001. | def tv_loss_test(correct):
tv_weight = 2e-2
t_loss = tv_loss(model.image, tv_weight)
student_output = sess.run(t_loss, {model.image: content_img_test})
error = rel_error(correct, student_output)
print('Error is {:.3f}'.format(error))
tv_loss_test(answers['tv_out']) | cs231n/assignment3/StyleTransfer-TensorFlow.ipynb | kabrapratik28/Stanford_courses | apache-2.0 |
Style Transfer
Lets put it all together and make some beautiful images! The style_transfer function below combines all the losses you coded up above and optimizes for an image that minimizes the total loss. | def style_transfer(content_image, style_image, image_size, style_size, content_layer, content_weight,
style_layers, style_weights, tv_weight, init_random = False):
"""Run style transfer!
Inputs:
- content_image: filename of content image
- style_image: filename of style image
... | cs231n/assignment3/StyleTransfer-TensorFlow.ipynb | kabrapratik28/Stanford_courses | apache-2.0 |
Read in OpSim output for modern versions: (sqlite formats)
Description of OpSim outputs are available on the page https://confluence.lsstcorp.org/display/SIM/OpSim+Datasets+for+Cadence+Workshop+LSST2015http://tusken.astro.washington.edu:8080
Here we will use the opsim output http://ops2.tuc.noao.edu/runs/enigma_1189/da... | # Change dbname to point at your own location of the opsim output
dbname = '/Users/rbiswas/data/LSST/OpSimData/minion_1016_sqlite.db'
opsdb = db.OpsimDatabase(dbname)
propID, propTags = opsdb.fetchPropInfo()
DD = propTags['DD'][0]
WFD = propTags['WFD'][0]
print("The propID for the Deep Drilling Field {0:2d}".format(DD... | example/ExploringOpSimOutputs_others.ipynb | rbiswas4/simlib | mit |
Read in the OpSim DataBase into a pandas dataFrame | engine = create_engine('sqlite:///' + dbname) | example/ExploringOpSimOutputs_others.ipynb | rbiswas4/simlib | mit |
The opsim database is a large file (approx 4.0 GB), but still possible to read into memory on new computers. You usually only need the Summary Table, which is about 900 MB. If you are only interested in the Deep Drilling Fields, you can use the read_sql_query to only select information pertaining to Deep Drilling Obser... | # Load to a dataframe
# Summary = pd.read_hdf('storage.h5', 'table')
# Summary = pd.read_sql_table('Summary', engine, index_col='obsHistID')
# EnigmaDeep = pd.read_sql_query('SELECT * FROM SUMMARY WHERE PROPID is 366', engine)
# EnigmaD = pd.read_sql_query('SELECT * FROM SUMMARY WHERE PROPID is 366', engine) | example/ExploringOpSimOutputs_others.ipynb | rbiswas4/simlib | mit |
If we knew ahead of time the proposal ID, then we could have done this quicker using | OpSim_combined = pd.read_sql_query('SELECT * FROM SUMMARY WHERE PROPID is ' + str(DD) + ' or ' + str(WFD), engine, index_col='obsHistID')
OpSim_Deep = pd.read_sql_query('SELECT * FROM SUMMARY WHERE PROPID is ' + str(DD), engine, index_col='obsHistID')
| example/ExploringOpSimOutputs_others.ipynb | rbiswas4/simlib | mit |
We can also sub-select this from the all-encompassing Summay Table. This can be done in two way:
Some properties of the OpSim Outputs
Construct our Summary | OpSimDeepSummary = so.SummaryOpsim(OpSim_Deep)
OpSimCombinedSummary = so.SummaryOpsim(OpSim_combined)
fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(111, projection='mollweide');
fig = OpSimDeepSummary.showFields(ax=fig.axes[0], marker='o', s=40)
OpSimCombinedSummary.showFields(ax=ax, marker='o', color='r', s... | example/ExploringOpSimOutputs_others.ipynb | rbiswas4/simlib | mit |
First Season
We can visualize the cadence during the first season using the cadence plot for a particular field: The following plot shows how many visits we have in different filters on a particular night: | firstSeasonDeep = OpSimDeepSummary.cadence_plot(fieldID=1427, observedOnly=False, sql_query='night < 366')
firstSeasonCombined = OpSimCombinedSummary.cadence_plot(fieldID=1427, observedOnly=False, sql_query='night < 366')
OpSimCombinedSummary.mjdvalfornight(300)
firstSeasonCombined[0].savefig('minion_1427.pdf')
fir... | example/ExploringOpSimOutputs_others.ipynb | rbiswas4/simlib | mit |
Suppose we have a supernova with a peak around a particular MJD of 49540, and we want to see what the observations happened around it: | SN = OpSimCombinedSummary.cadence_plot(fieldID=1427, #racol='fieldRA', deccol='fieldDec',
observedOnly=False, mjd_center=59580 + 270., mjd_range=[-30., 50.])
# ax = plt.gca()
# ax.axvline(49540, color='r', lw=2.)
# ax.xaxis.get_major_formatter().set_useOffset(False)
SN... | example/ExploringOpSimOutputs_others.ipynb | rbiswas4/simlib | mit |
Scratch | SN_matrix.sum(axis=1).sum()
EnigmaDeep.query('fieldID == 744 and expMJD < 49590 and expMJD > 49510').expMJD.size
SN_matrix[SN_matrix > 0.5] = 1
SN_matrix.sum().sum()
len(SN_matrix.sum(axis=1).dropna())
nightlySN_matrix = SN_matrix.copy(deep=True)
nightlySN_matrix[SN_matrix > 0.5] =1
nightlySN_matrix.sum(axis=1).... | example/ExploringOpSimOutputs_others.ipynb | rbiswas4/simlib | mit |
Step 1: Dataset Summary & Exploration
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contain... | ### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
# TODO: Number of training examples
n_train = X_train.shape[0]
# TODO: Number of validation examples
n_validation = X_valid.shape[0]
# TODO: Number of testing examples.
n_test = X_t... | Traffic_Sign_Classifier.ipynb | deepankarsharma/udacity_traffic_signs | mit |
Include an exploratory visualization of the dataset
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations ... | import matplotlib.pyplot as plt
%matplotlib inline
fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3)
bins = range(n_classes + 1)
ax1.hist(y_train, bins=bins)
ax1.set_title('Train dist', fontsize=12)
ax2.hist(y_test, bins=bins)
ax2.set_title('Test dist', fontsize=12)
ax3.hist(y_valid, bins=bins)
ax3.set_title('... | Traffic_Sign_Classifier.ipynb | deepankarsharma/udacity_traffic_signs | mit |
Step 2: Design and Test a Model Architecture
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change th... | # Function to generate transformed images
# from https://nbviewer.jupyter.org/github/vxy10/SCND_notebooks/blob/master/preprocessing_stuff/img_transform_NB.ipynb
import random
import cv2
from IPython.core.display import Image, display
def transform_image(img,ang_range, trans_range):
'''
This function transforms... | Traffic_Sign_Classifier.ipynb | deepankarsharma/udacity_traffic_signs | mit |
Model Architecture | from tensorflow.contrib.layers import flatten
from sklearn.utils import shuffle
def model_lenet(x):
# Hyperparameters
mu = 0
sigma = 0.1
# Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.
conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 3, 6), mean = mu, stddev = sigma))
... | Traffic_Sign_Classifier.ipynb | deepankarsharma/udacity_traffic_signs | mit |
Train, Validate and Test the Model
A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation
sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting. | ### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
with tf.Session() as sess:
sess.run(tf... | Traffic_Sign_Classifier.ipynb | deepankarsharma/udacity_traffic_signs | mit |
Step 3: Test a Model on New Images
To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual s... | ### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import os
import matplotlib.image as mpimg
def load_extra_images(folder):
images = []
for fname in sorted(os.listdir(folder)):
img = mpimg.imread(os.path.join(folder, fname))
img=cv2.resize(img,(32,32))
... | Traffic_Sign_Classifier.ipynb | deepankarsharma/udacity_traffic_signs | mit |
Predict the Sign Type for Each Image | ### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
... | Traffic_Sign_Classifier.ipynb | deepankarsharma/udacity_traffic_signs | mit |
Analyze Performance | ### Calculate the accuracy for these 5 new images.
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
arr = np.array([x[0] for x in top_k[1]])
print('accuracy is %s' % (np.sum(arr == y_extra)/float(len(arr))))
| Traffic_Sign_Classifier.ipynb | deepankarsharma/udacity_traffic_signs | mit |
Output Top 5 Softmax Probabilities For Each Image Found on the Web
For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.
The example below demonstrates ... | ### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
for i in range(len(top_k[0])):
print('Image', i, '\n\tprobabilities:', top_k[0][i], '\n\tclasses:', top_k[1][i]) | Traffic_Sign_Classifier.ipynb | deepankarsharma/udacity_traffic_signs | mit |
Project Writeup
Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.
Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your w... | ### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.
# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific we... | Traffic_Sign_Classifier.ipynb | deepankarsharma/udacity_traffic_signs | mit |
Connecting to National Data Service: The Lab Benchwork's NBI - MongoDB instance | warnings.filterwarnings(action="ignore")
Client = MongoClient("mongodb://bridges:readonly@nbi-mongo.admin/bridge")
db = Client.bridge
collection = db["bridges"] | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Midwestern+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Extracting Data of Midwestern states of the United states from 1992 - 2016.
The following query will extract data from the mongoDB instance and project only selected attributes such as structure number, yearBuilt, deck, year, superstructure, owner, countryCode, structure type, type of wearing surface, and subtructure. | def getData(state):
pipeline = [{"$match":{"$and":[{"year":{"$gt":1991, "$lt":2017}},{"stateCode":state}]}},
{"$project":{"_id":0,
"structureNumber":1,
"yearBuilt":1,
"yearReconstructed":1,
"deck":1, ## R... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Midwestern+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Filteration of NBI Data
The following routine removes the missing data such as 'N', 'NA' from deck, substructure,and superstructure , and also removing data with structure Type - 19 and type of wearing surface - 6. | ## filter and convert them into interger
def filterConvert(conditionRatings):
before = len(conditionRatings)
print("Total Records before filteration: ",len(conditionRatings))
conditionRatings = conditionRatings.loc[~conditionRatings['deck'].isin(['N','NA'])]
conditionRatings = conditionRatings.loc[~cond... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Midwestern+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Particularly in the area of determining a deterioration model of bridges, There is an observed sudden increase in condition ratings of bridges over the period of time, This sudden increase in the condition rating is attributed to the reconstruction of the bridges. NBI dataset contains an attribute to record this recons... | ## make it into a function
def findSurvivalProbablities(conditionRatings):
i = 1
j = 2
probabilities = []
while j < 121:
v = list(conditionRatings.loc[conditionRatings['Age'] == i]['deck'])
k = list(conditionRatings.loc[conditionRatings['Age'] == i]['structureNumber'])
Age1 ... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Midwestern+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
A utility function to plot the graphs. | def plotCDF(cumsum_probabilities):
fig = plt.figure(figsize=(15,8))
ax = plt.axes()
plt.title('CDF of Reonstruction Vs Age')
plt.xlabel('Age')
plt.ylabel('CDF of Reonstruction')
plt.yticks([0,10,20,30,40,50,60,70,80,90,100])
plt.ylim(0,100)
x = [i for i in range(1,120)]
y = cumsum_... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Midwestern+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
The following script will select all the bridges in the midwestern United States, filter missing and not required data. The script also provides information of how much of the data is being filtered. | states = ['31','19','17','18','20','26','27','29','38','46','39','55']
# Mapping state code to state abbreviation
stateNameDict = {'25':'MA',
'04':'AZ',
'08':'CO',
'38':'ND',
'09':'CT',
'19':'IA',
'26':'MI',
... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Midwestern+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
In following figures, shows the cumulative distribution function of the probability of reconstruction over the bridges' lifespan, of bridges in the midwestern United States, as the bridges grow older the probability of reconstruction increases. | plt.figure(figsize=(12,8))
plt.title("CDF Probability of Reconstruction vs Age")
palette = [
'blue', 'blue', 'green', 'magenta', 'cyan', 'brown', 'grey', 'red', 'silver', 'purple', 'gold', 'black','olive'
]
linestyles =[':','-.','--','-',':','-.','--','-',':','-.','--','-']
for num, state in enumerate(df_cumsum_pr... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Midwestern+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
The below figure presents CDF Probability of reconstruction, of bridge in the midwestern United States. | plt.figure(figsize = (16,12))
plt.xlabel('Age')
plt.ylabel('Mean')
# Initialize the figure
plt.style.use('seaborn-darkgrid')
# create a color palette
palette = [
'blue', 'blue', 'green', 'magenta', 'cyan', 'brown', 'grey', 'red', 'silver', 'purple', 'gold', 'black','olive'
]
# multiple line plot
num = 1
linestyl... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Midwestern+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
In the following figures, provides the probability of reconstruction at every age. Note this is not a cumulative probability function. the constant number of reconstruction of the bridges can be explained by various factors.
one particularly interesting reason could be funding provided to reconstruct bridges, this expl... | plt.figure(figsize=(12,8))
plt.title("Probability of Reconstruction vs Age")
palette = [
'blue', 'blue', 'green', 'magenta', 'cyan', 'brown', 'grey', 'red', 'silver', 'purple', 'gold', 'black','olive'
]
linestyles =[':','-.','--','-',':','-.','--','-',':','-.','--','-']
for num, state in enumerate(df_cumsum_prob_r... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Midwestern+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
A key observation in this investigation of several state reveals a constant number of bridges are reconstructed every year, this could be an effect of fixed budget allocated for reconstruction by the state. This also highlights the fact that not all bridges that might require reconstruction are reconstructed.
To Unders... | plt.figure(figsize = (16,12))
plt.xlabel('Age')
plt.ylabel('Mean')
# Initialize the figure
plt.style.use('seaborn-darkgrid')
# create a color palette
palette = [
'blue', 'blue', 'green', 'magenta', 'cyan', 'brown', 'grey', 'red', 'silver', 'purple', 'gold', 'black','olive'
]
# multiple line plot
num = 1
linesty... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Midwestern+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Repairing artifacts with ICA
This tutorial covers the basics of independent components analysis (ICA) and
shows how ICA can be used for artifact repair; an extended example illustrates
repair of ocular and heartbeat artifacts. For conceptual background on ICA, see
this scikit-learn tutorial
<sphx_glr_auto_examples_d... | import os
import mne
from mne.preprocessing import (ICA, create_eog_epochs, create_ecg_epochs,
corrmap)
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_audvis_filt-0-... | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
<div class="alert alert-info"><h4>Note</h4><p>Before applying ICA (or any artifact repair strategy), be sure to observe
the artifacts in your data to make sure you choose the right repair tool.
Sometimes the right tool is no tool at all — if the artifacts are small
enough you may not even need to repair the... | # pick some channels that clearly show heartbeats and blinks
regexp = r'(MEG [12][45][123]1|EEG 00.)'
artifact_picks = mne.pick_channels_regexp(raw.ch_names, regexp=regexp)
raw.plot(order=artifact_picks, n_channels=len(artifact_picks),
show_scrollbars=False) | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
We can get a summary of how the ocular artifact manifests across each channel
type using ~mne.preprocessing.create_eog_epochs like we did in the
tut-artifact-overview tutorial: | eog_evoked = create_eog_epochs(raw).average()
eog_evoked.apply_baseline(baseline=(None, -0.2))
eog_evoked.plot_joint() | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Now we'll do the same for the heartbeat artifacts, using
~mne.preprocessing.create_ecg_epochs: | ecg_evoked = create_ecg_epochs(raw).average()
ecg_evoked.apply_baseline(baseline=(None, -0.2))
ecg_evoked.plot_joint() | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Filtering to remove slow drifts
Before we run the ICA, an important step is filtering the data to remove
low-frequency drifts, which can negatively affect the quality of the ICA fit.
The slow drifts are problematic because they reduce the independence of the
assumed-to-be-independent sources (e.g., during a slow upward... | filt_raw = raw.copy().filter(l_freq=1., h_freq=None) | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Fitting and plotting the ICA solution
.. sidebar:: Ignoring the time domain
The ICA algorithms implemented in MNE-Python find patterns across
channels, but ignore the time domain. This means you can compute ICA on
discontinuous `~mne.Epochs` or `~mne.Evoked` objects (not
just continuous `~mne.io.Raw` objects), or only ... | ica = ICA(n_components=15, max_iter='auto', random_state=97)
ica.fit(filt_raw)
ica | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Some optional parameters that we could have passed to the
~mne.preprocessing.ICA.fit method include decim (to use only
every Nth sample in computing the ICs, which can yield a considerable
speed-up) and reject (for providing a rejection dictionary for maximum
acceptable peak-to-peak amplitudes for each channel type, ju... | raw.load_data()
ica.plot_sources(raw, show_scrollbars=False) | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Here we can pretty clearly see that the first component (ICA000) captures
the EOG signal quite well, and the second component (ICA001) looks a lot
like a heartbeat <qrs_> (for more info on visually identifying Independent
Components, this EEGLAB tutorial is a good resource). We can also
visualize the scalp field ... | ica.plot_components() | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
<div class="alert alert-info"><h4>Note</h4><p>`~mne.preprocessing.ICA.plot_components` (which plots the scalp
field topographies for each component) has an optional ``inst`` parameter
that takes an instance of `~mne.io.Raw` or `~mne.Epochs`.
Passing ``inst`` makes the scalp topographies interactive: clickin... | # blinks
ica.plot_overlay(raw, exclude=[0], picks='eeg')
# heartbeats
ica.plot_overlay(raw, exclude=[1], picks='mag') | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
We can also plot some diagnostics of each IC using
~mne.preprocessing.ICA.plot_properties: | ica.plot_properties(raw, picks=[0, 1]) | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
In the remaining sections, we'll look at different ways of choosing which ICs
to exclude prior to reconstructing the sensor signals.
Selecting ICA components manually
Once we're certain which components we want to exclude, we can specify that
manually by setting the ica.exclude attribute. Similar to marking bad
channel... | ica.exclude = [0, 1] # indices chosen based on various plots above | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Now that the exclusions have been set, we can reconstruct the sensor signals
with artifacts removed using the ~mne.preprocessing.ICA.apply method
(remember, we're applying the ICA solution from the filtered data to the
original unfiltered signal). Plotting the original raw data alongside the
reconstructed data shows th... | # ica.apply() changes the Raw object in-place, so let's make a copy first:
reconst_raw = raw.copy()
ica.apply(reconst_raw)
raw.plot(order=artifact_picks, n_channels=len(artifact_picks),
show_scrollbars=False)
reconst_raw.plot(order=artifact_picks, n_channels=len(artifact_picks),
show_scrollba... | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Using an EOG channel to select ICA components
It may have seemed easy to review the plots and manually select which ICs to
exclude, but when processing dozens or hundreds of subjects this can become
a tedious, rate-limiting step in the analysis pipeline. One alternative is to
use dedicated EOG or ECG sensors as a "patt... | ica.exclude = []
# find which ICs match the EOG pattern
eog_indices, eog_scores = ica.find_bads_eog(raw)
ica.exclude = eog_indices
# barplot of ICA component "EOG match" scores
ica.plot_scores(eog_scores)
# plot diagnostics
ica.plot_properties(raw, picks=eog_indices)
# plot ICs applied to raw data, with EOG matches ... | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Note that above we used ~mne.preprocessing.ICA.plot_sources on both
the original ~mne.io.Raw instance and also on an
~mne.Evoked instance of the extracted EOG artifacts. This can be
another way to confirm that ~mne.preprocessing.ICA.find_bads_eog has
identified the correct components.
Using a simulated channel to selec... | ica.exclude = []
# find which ICs match the ECG pattern
ecg_indices, ecg_scores = ica.find_bads_ecg(raw, method='correlation',
threshold='auto')
ica.exclude = ecg_indices
# barplot of ICA component "ECG match" scores
ica.plot_scores(ecg_scores)
# plot diagnostics
ica.plot_p... | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
The last of these plots is especially useful: it shows us that the heartbeat
artifact is coming through on two ICs, and we've only caught one of them.
In fact, if we look closely at the output of
~mne.preprocessing.ICA.plot_sources (online, you can right-click →
"view image" to zoom in), it looks like ICA014 has a weak... | # refit the ICA with 30 components this time
new_ica = ICA(n_components=30, max_iter='auto', random_state=97)
new_ica.fit(filt_raw)
# find which ICs match the ECG pattern
ecg_indices, ecg_scores = new_ica.find_bads_ecg(raw, method='correlation',
threshold='auto')
new_ica... | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Much better! Now we've captured both ICs that are reflecting the heartbeat
artifact (and as a result, we got two diagnostic plots: one for each IC that
reflects the heartbeat). This demonstrates the value of checking the results
of automated approaches like ~mne.preprocessing.ICA.find_bads_ecg
before accepting them. | # clean up memory before moving on
del raw, ica, new_ica | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Selecting ICA components using template matching
When dealing with multiple subjects, it is also possible to manually select
an IC for exclusion on one subject, and then use that component as a
template for selecting which ICs to exclude from other subjects' data,
using mne.preprocessing.corrmap :footcite:CamposViolaEt... | mapping = {
'Fc5.': 'FC5', 'Fc3.': 'FC3', 'Fc1.': 'FC1', 'Fcz.': 'FCz', 'Fc2.': 'FC2',
'Fc4.': 'FC4', 'Fc6.': 'FC6', 'C5..': 'C5', 'C3..': 'C3', 'C1..': 'C1',
'Cz..': 'Cz', 'C2..': 'C2', 'C4..': 'C4', 'C6..': 'C6', 'Cp5.': 'CP5',
'Cp3.': 'CP3', 'Cp1.': 'CP1', 'Cpz.': 'CPz', 'Cp2.': 'CP2', 'Cp4.': 'CP4',... | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Now let's run ~mne.preprocessing.corrmap: | # use the first subject as template; use Fpz as proxy for EOG
raw = raws[0]
ica = icas[0]
eog_inds, eog_scores = ica.find_bads_eog(raw, ch_name='Fpz')
corrmap(icas, template=(0, eog_inds[0])) | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
The first figure shows the template map, while the second figure shows all
the maps that were considered a "match" for the template (including the
template itself). There is one match for each subject, but it's a good idea
to also double-check the ICA sources for each subject: | for index, (ica, raw) in enumerate(zip(icas, raws)):
fig = ica.plot_sources(raw, show_scrollbars=False)
fig.subplots_adjust(top=0.9) # make space for title
fig.suptitle('Subject {}'.format(index)) | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Notice that subjects 2 and 3 each seem to have two ICs that reflect ocular
activity (components ICA000 and ICA002), but only one was caught by
~mne.preprocessing.corrmap. Let's try setting the threshold manually: | corrmap(icas, template=(0, eog_inds[0]), threshold=0.9) | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
This time it found 2 ICs for each of subjects 2 and 3 (which is good).
At this point we'll re-run ~mne.preprocessing.corrmap with
parameters label='blink', plot=False to label the ICs from each subject
that capture the blink artifacts (without plotting them again). | corrmap(icas, template=(0, eog_inds[0]), threshold=0.9, label='blink',
plot=False)
print([ica.labels_ for ica in icas]) | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Notice that the first subject has 3 different labels for the IC at index 0:
"eog/0/Fpz", "eog", and "blink". The first two were added by
~mne.preprocessing.ICA.find_bads_eog; the "blink" label was added by the
last call to ~mne.preprocessing.corrmap. Notice also that each subject has
at least one IC index labelled "bli... | icas[3].plot_components(picks=icas[3].labels_['blink'])
icas[3].exclude = icas[3].labels_['blink']
icas[3].plot_sources(raws[3], show_scrollbars=False) | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
As a final note, it is possible to extract ICs numerically using the
~mne.preprocessing.ICA.get_components method of
~mne.preprocessing.ICA objects. This will return a :class:NumPy
array <numpy.ndarray> that can be passed to
~mne.preprocessing.corrmap instead of the :class:tuple of
(subject_index, component_index... | template_eog_component = icas[0].get_components()[:, eog_inds[0]]
corrmap(icas, template=template_eog_component, threshold=0.9)
print(template_eog_component) | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
An advantage of using this numerical representation of an IC to capture a
particular artifact pattern is that it can be saved and used as a template
for future template-matching tasks using ~mne.preprocessing.corrmap
without having to load or recompute the ICA solution that yielded the
template originally. Put another ... | filt_raw.pick_types(meg=True, eeg=False, exclude='bads', stim=True).load_data()
filt_raw.filter(1, 30, fir_design='firwin')
# peak-to-peak amplitude rejection parameters
reject = dict(mag=4e-12)
# create longer and more epochs for more artifact exposure
events = mne.find_events(filt_raw, stim_channel='STI 014')
# don'... | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Fit ICA model using the FastICA algorithm, detect and plot components
explaining ECG artifacts. | ica = ICA(n_components=15, method='fastica', max_iter="auto").fit(epochs)
ecg_epochs = create_ecg_epochs(filt_raw, tmin=-.5, tmax=.5)
ecg_inds, scores = ica.find_bads_ecg(ecg_epochs, threshold='auto')
ica.plot_components(ecg_inds) | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Plot the properties of the ECG components: | ica.plot_properties(epochs, picks=ecg_inds) | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Plot the estimated sources of detected ECG related components: | ica.plot_sources(filt_raw, picks=ecg_inds) | 0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
First we define the possible states in the model. In this case we make them all have normal distributions. | s1 = State( NormalDistribution( 5, 2 ), name="S1" )
s2 = State( NormalDistribution( 15, 2 ), name="S2" )
s3 = State( NormalDistribution( 25, 2 ), name="S3" ) | examples/hmm_infinite.ipynb | jmschrei/pomegranate | mit |
We then create the HMM object, naming it, logically, "infinite". | model = HiddenMarkovModel( "infinite" ) | examples/hmm_infinite.ipynb | jmschrei/pomegranate | mit |
We then add the possible transition, making sure not to add an end state. Thus with no end state, the model is infinite! | model.add_transition( model.start, s1, 0.7 )
model.add_transition( model.start, s2, 0.2 )
model.add_transition( model.start, s3, 0.1 )
model.add_transition( s1, s1, 0.6 )
model.add_transition( s1, s2, 0.1 )
model.add_transition( s1, s3, 0.3 )
model.add_transition( s2, s1, 0.4 )
model.add_transition( s2, s2, 0.4 )
model... | examples/hmm_infinite.ipynb | jmschrei/pomegranate | mit |
Finally we "bake" the model, finalizing the model. | model.bake() | examples/hmm_infinite.ipynb | jmschrei/pomegranate | mit |
Now we can check whether or not our model is infinite. | # Not implemented: print model.is_infinite() | examples/hmm_infinite.ipynb | jmschrei/pomegranate | mit |
Now lets the possible states in the model. | print("States")
print("\n".join( state.name for state in model.states )) | examples/hmm_infinite.ipynb | jmschrei/pomegranate | mit |
Now lets test out our model by feeding it a sequence of values. We feed our sequence of values first through a forward algorithm in our HMM. | sequence = [ 4.8, 5.6, 24.1, 25.8, 14.3, 26.5, 15.9, 5.5, 5.1 ]
print("Forward")
print(model.forward( sequence )) | examples/hmm_infinite.ipynb | jmschrei/pomegranate | mit |
That looks good as well. Now lets feed our sequence into the model through a backwards algorithm. | print("Backward")
print(model.backward( sequence )) | examples/hmm_infinite.ipynb | jmschrei/pomegranate | mit |
Continuing on we now feed the sequence in through a forward-backward algorithm. | print("Forward-Backward")
trans, emissions = model.forward_backward( sequence )
print(trans)
print(emissions) | examples/hmm_infinite.ipynb | jmschrei/pomegranate | mit |
Finally we feed the sequence through a Viterbi algorithm to find the most probable sequence of states. | print("Viterbi")
prob, states = model.viterbi( sequence )
print("Prob: {}".format( prob ))
print("\n".join( state[1].name for state in states ))
print()
print("MAP")
prob, states = model.maximum_a_posteriori( sequence )
print("Prob: {}".format( prob ))
print("\n".join( state[1].name for state in states )) | examples/hmm_infinite.ipynb | jmschrei/pomegranate | mit |
Finally we try and reproduce the transition matrix from 100,000 samples. | print("Should produce a matrix close to the following: ")
print(" [ [ 0.60, 0.10, 0.30 ] ")
print(" [ 0.40, 0.40, 0.20 ] ")
print(" [ 0.05, 0.15, 0.80 ] ] ")
print()
print("Transition Matrix From 100000 Samples:")
sample, path = model.sample( 100000, path=True )
trans = np.zeros((3,3))
for state, n_state in it.izi... | examples/hmm_infinite.ipynb | jmschrei/pomegranate | mit |
Forward pass: compute loss
In the same function, implement the second part that computes the data and regularizaion loss. | loss, _ = net.loss(X, y, reg=0.1)
correct_loss = 1.30378789133
# should be very small, we get < 1e-12
print 'Difference between your loss and correct loss:'
print np.sum(np.abs(loss - correct_loss))
print loss | assignment1/two_layer_net.ipynb | hanezu/cs231n-assignment | mit |
Train a network
To train our network we will use SGD with momentum. In addition, we will adjust the learning rate with an exponential learning rate schedule as optimization proceeds; after each epoch, we will reduce the learning rate by multiplying it by a decay rate. | input_size = 32 * 32 * 3
hidden_size = 50
num_classes = 10
net = TwoLayerNet(input_size, hidden_size, num_classes)
# Train the network
stats = net.train(X_train, y_train, X_val, y_val,
num_iters=1000, batch_size=200,
learning_rate=1e-4, learning_rate_decay=0.95,
reg=0.5, verbose=Tru... | assignment1/two_layer_net.ipynb | hanezu/cs231n-assignment | mit |
Tune your hyperparameters
What's wrong?. Looking at the visualizations above, we see that the loss is decreasing more or less linearly, which seems to suggest that the learning rate may be too low. Moreover, there is no gap between the training and validation accuracy, suggesting that the model we used has low capacity... | best_net = None # store the best model into this
best_val = 0
#################################################################################
# TODO: Tune hyperparameters using the validation set. Store your best trained #
# model in best_net. #
# ... | assignment1/two_layer_net.ipynb | hanezu/cs231n-assignment | mit |
Model 1: Apply the ML.FEATURE_CROSS clause to categorical features
BigQuery ML now has ML.FEATURE_CROSS, a pre-processing clause that performs a feature cross with syntax ML.FEATURE_CROSS(STRUCT(features), degree) where features are comma-separated categorical columns and degree is highest degree of all combinations.
... | %%bigquery
CREATE OR REPLACE MODEL
babyweight.model_1
OPTIONS (
MODEL_TYPE="LINEAR_REG",
INPUT_LABEL_COLS=["weight_pounds"],
L2_REG=0.1,
DATA_SPLIT_METHOD="NO_SPLIT") AS
SELECT
weight_pounds,
is_male,
mother_age,
plurality,
gestation_weeks,
ML.FEATURE_CROSS(
STRUCT(... | courses/machine_learning/deepdive2/structured/solutions/3b_bqml_linear_transform_babyweight.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Create two SQL statements to evaluate the model. | %%bigquery
SELECT
*
FROM
ML.EVALUATE(MODEL babyweight.model_1,
(
SELECT
weight_pounds,
is_male,
mother_age,
plurality,
gestation_weeks,
ML.FEATURE_CROSS(
STRUCT(
is_male,
plurality)
) AS gender_plurality_... | courses/machine_learning/deepdive2/structured/solutions/3b_bqml_linear_transform_babyweight.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Model 2: Apply the BUCKETIZE Function
Bucketize is a pre-processing function that creates "buckets" (e.g bins) - e.g. it bucketizes a continuous numerical feature into a string feature with bucket names as the value with syntax ML.BUCKETIZE(feature, split_points) with split_points being an array of numerical points to... | %%bigquery
CREATE OR REPLACE MODEL
babyweight.model_2
OPTIONS (
MODEL_TYPE="LINEAR_REG",
INPUT_LABEL_COLS=["weight_pounds"],
L2_REG=0.1,
DATA_SPLIT_METHOD="NO_SPLIT") AS
SELECT
weight_pounds,
is_male,
mother_age,
plurality,
gestation_weeks,
ML.FEATURE_CROSS(
STRUCT(... | courses/machine_learning/deepdive2/structured/solutions/3b_bqml_linear_transform_babyweight.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Let's now retrieve the training statistics and evaluate the model. | %%bigquery
SELECT * FROM ML.TRAINING_INFO(MODEL babyweight.model_2) | courses/machine_learning/deepdive2/structured/solutions/3b_bqml_linear_transform_babyweight.ipynb | turbomanage/training-data-analyst | apache-2.0 |
We now evaluate our model on our eval dataset: | %%bigquery
SELECT
*
FROM
ML.EVALUATE(MODEL babyweight.model_2,
(
SELECT
weight_pounds,
is_male,
mother_age,
plurality,
gestation_weeks,
ML.FEATURE_CROSS(
STRUCT(
is_male,
ML.BUCKETIZE(
mother_... | courses/machine_learning/deepdive2/structured/solutions/3b_bqml_linear_transform_babyweight.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Let's select the mean_squared_error from the evaluation table we just computed and square it to obtain the rmse. | %%bigquery
SELECT
SQRT(mean_squared_error) AS rmse
FROM
ML.EVALUATE(MODEL babyweight.model_2,
(
SELECT
weight_pounds,
is_male,
mother_age,
plurality,
gestation_weeks,
ML.FEATURE_CROSS(
STRUCT(
is_male,
ML.BUCKETI... | courses/machine_learning/deepdive2/structured/solutions/3b_bqml_linear_transform_babyweight.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Model 3: Apply the TRANSFORM clause
Before we perform our prediction, we should encapsulate the entire feature set in a TRANSFORM clause. This way we can have the same transformations applied for training and prediction without modifying the queries.
Let's apply the TRANSFORM clause to the model_3 and run the query. | %%bigquery
CREATE OR REPLACE MODEL
babyweight.model_3
TRANSFORM(
weight_pounds,
is_male,
mother_age,
plurality,
gestation_weeks,
ML.FEATURE_CROSS(
STRUCT(
is_male,
ML.BUCKETIZE(
mother_age,
GENERATE_ARRAY(15, 45, 1)
... | courses/machine_learning/deepdive2/structured/solutions/3b_bqml_linear_transform_babyweight.ipynb | turbomanage/training-data-analyst | apache-2.0 |
1. Introduction
In this notebook we explore an application of clustering algorithms to shape segmentation from binary images. We will carry out some exploratory work with a small set of images provided with this notebook. Most of them are not binary images, so we must do some preliminary work to extract he binary shape... | name = "birds.jpg"
name = "Seeds.jpg"
birds = imread("Images/" + name)
birdsG = np.sum(birds, axis=2)
# <SOL>
# </SOL>
| U_lab1.Clustering/Lab_ShapeSegmentation_student/LabSessionClustering_student.ipynb | ML4DS/ML4all | mit |
2. Thresholding
Select an intensity threshold by manual inspection of the image histogram | # <SOL>
# </SOL>
| U_lab1.Clustering/Lab_ShapeSegmentation_student/LabSessionClustering_student.ipynb | ML4DS/ML4all | mit |
Plot the binary image after thresholding. | # <SOL>
# </SOL>
| U_lab1.Clustering/Lab_ShapeSegmentation_student/LabSessionClustering_student.ipynb | ML4DS/ML4all | mit |
3. Dataset generation
Extract pixel coordinates dataset from image and plot them in a scatter plot. | # <SOL>
# </SOL>
print X
plt.scatter(X[:, 0], X[:, 1], s=5);
plt.axis('equal')
plt.show() | U_lab1.Clustering/Lab_ShapeSegmentation_student/LabSessionClustering_student.ipynb | ML4DS/ML4all | mit |
4. k-means clustering algorithm
Use the pixel coordinates as the input data for a k-means algorithm. Plot the result of the clustering by means of a scatter plot, showing each cluster with a different colour. | from sklearn.cluster import KMeans
# <SOL>
# </SOL>
| U_lab1.Clustering/Lab_ShapeSegmentation_student/LabSessionClustering_student.ipynb | ML4DS/ML4all | mit |
5. Spectral clustering algorithm
5.1. Affinity matrix
Compute and visualize the affinity matrix for the given dataset, using a rbf kernel with $\gamma=5$. | from sklearn.metrics.pairwise import rbf_kernel
# <SOL>
# </SOL>
# Visualization
# <SOL>
# </SOL> | U_lab1.Clustering/Lab_ShapeSegmentation_student/LabSessionClustering_student.ipynb | ML4DS/ML4all | mit |
5.2. Spectral clusering
Apply the spectral clustering algorithm, and show the clustering results using a scatter plot. | # <SOL>
# </SOL>
plt.scatter(Xsub[:,0], Xsub[:,1], c=y_kmeans, s=5, cmap='rainbow', linewidth=0.0)
plt.axis('equal')
plt.show() | U_lab1.Clustering/Lab_ShapeSegmentation_student/LabSessionClustering_student.ipynb | ML4DS/ML4all | mit |
<i class="fa fa-book"></i> Primero librerias | import numpy as np
import sklearn as sk
import matplotlib.pyplot as plt
import sklearn.datasets as datasets
import seaborn as sns
%matplotlib inline | Dia4/.ipynb_checkpoints/6_Arboles_de_decisión-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
<i class="fa fa-database"></i> Vamos a crear datos de jugete
Crea varios "blobs"
recuerda la funcion de scikit-learn datasets.make_blobs()
Tambien prueba
python
centers = [[1, 1], [-1, -1], [1, -1]]
X,Y = datasets.make_blobs(n_samples=10000, centers=centers, cluster_std=0.6)
<i class="fa fa-tree"></i> Ahora vamos a ... | from sklearn.tree import DecisionTreeClassifier
| Dia4/.ipynb_checkpoints/6_Arboles_de_decisión-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
<i class="fa fa-question-circle"></i> Que parametros y funciones tiene el classificador?
Hint: usa help(cosa)! | help(clf) | Dia4/.ipynb_checkpoints/6_Arboles_de_decisión-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
vamos a ajustar nuestro modelo con fit y sacar su puntaje con score
<i class="fa fa-question-circle"></i>
Por que no queremos 100%?
Este problema se llama "Overfitting"
<i class="fa fa-list"></i> Pasos para un tipico algoritmo ML:
Crear un modelo
Particionar tus datos en diferentes pedazos (10% entrenar y 90% prueb... | from sklearn.cross_validation import train_test_split
| Dia4/.ipynb_checkpoints/6_Arboles_de_decisión-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
cuales son los tamanios de estos nuevos datos?
y ahora entrenamos nuestro modelo y checamos el error
<i class="fa fa-question-circle"></i>
Como se ve nuestro modelo?
Que fue mas importante para hacer una decision?
Como podemos mejorar y controlar como dividimos nuestros datos?
Validación cruzada y
K-fold
Y lo mejor ... | from sklearn.cross_validation import cross_val_score
| Dia4/.ipynb_checkpoints/6_Arboles_de_decisión-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
<i class="fa fa-question-circle"></i>
Y como podemos mejorar un arbol de decision?
RandomForestClassifier(n_estimators=n_estimators) Al rescate! | from sklearn.ensemble import RandomForestClassifier | Dia4/.ipynb_checkpoints/6_Arboles_de_decisión-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
a probarlo!
mejoro?
Pero ahora tenemos un parametro nuevo, cuantos arboles queremos usar?
<i class="fa fa-tree"></i>,<i class="fa fa-tree"></i>,<i class="fa fa-tree"></i> ...
Que tal si probamos con un for loop!? Y checamos el error conforme al numero de arboles?
Actividad!
Hay que :
Definir nuestro rango de arboles a... | g = sns.PairGrid(iris, hue="species")
g = g.map(plt.scatter)
g = g.add_legend() | Dia4/.ipynb_checkpoints/6_Arboles_de_decisión-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
Actividad:
Objetivo: Entrena un arbol para predecir la especie de la planta
Checa las graficas, que variables podrian ser mas importante?
Agarra los datos, que dimensiones son?
Rompelos en pedacitos y entrena tus modelos
Que scores te da? Que resulto ser importante? | iris = datasets.load_iris()
X = iris.data
Y = iris.target | Dia4/.ipynb_checkpoints/6_Arboles_de_decisión-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
Normal file operations and data preparation for later example
list recursively everything under the root dir
Download some files for later use. The files should already be there. | # 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... | notes/.ipynb_checkpoints/1-hadoop-streaming-py-wordcount-checkpoint.ipynb | dsiufl/2015-Fall-Hadoop | mit |
Delete existing folders under /user/ubuntu/ in hdfs
Create input folder: /user/ubuntu/input
Copy the three books to the input folder in HDFS.
Similiar to normal bash cmd:
cp /home/ubuntu/shortcourse/data/wordcount/* /user/ubuntu/input/
but copy to hdfs.
Show if the files are there.
2. WordCount Example
Let's count ... | Start the hadoop distributed file system
! {hadoop_root + 'sbin/start-yarn.sh'} | notes/.ipynb_checkpoints/1-hadoop-streaming-py-wordcount-checkpoint.ipynb | dsiufl/2015-Fall-Hadoop | mit |
Test locally the mapper.py and reduce.py | # 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/mapper.py
# Reduce: /home/ubuntu/shortcourse/notes/scripts/wordcount1/reducer.py
# T... | notes/.ipynb_checkpoints/1-hadoop-streaming-py-wordcount-checkpoint.ipynb | dsiufl/2015-Fall-Hadoop | mit |
List the output
Download the output file (part-00000) to local fs. | # Let's see what's in the output file
# delete if previous results exist
! tail -n 20 $(THE_DOWNLOADED_FILE) | notes/.ipynb_checkpoints/1-hadoop-streaming-py-wordcount-checkpoint.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... | # 1. go to wordcount2 folder, modify the mapper
# 2. test locally if the mapper is working
# 3. run with hadoop streaming. Input is still the three books, output to 'output2' | notes/.ipynb_checkpoints/1-hadoop-streaming-py-wordcount-checkpoint.ipynb | dsiufl/2015-Fall-Hadoop | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.