markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Test your content loss. You should see errors less than 0.001.
def content_loss_test(correct): content_image = 'styles/tubingen.jpg' image_size = 192 content_layer = 3 content_weight = 6e-2 c_feats, content_img_var = features_from_img(content_image, image_size) bad_img = Variable(torch.zeros(*content_img_var.data.size())) feats = extract_feat...
CS231n/assignment3/StyleTransfer-PyTorch.ipynb
UltronAI/Deep-Learning
mit
Style loss Now we can tackle the style loss. For a given layer $\ell$, the style loss is defined as follows: First, compute the Gram matrix G which represents the correlations between the responses of each filter, where F is as above. The Gram matrix is an approximation to the covariance matrix -- we want the activatio...
def gram_matrix(features, normalize=True): """ Compute the Gram matrix from features. Inputs: - features: PyTorch Variable of shape (N, C, H, W) giving features for a batch of N images. - normalize: optional, whether to normalize the Gram matrix If True, divide the Gram matrix by ...
CS231n/assignment3/StyleTransfer-PyTorch.ipynb
UltronAI/Deep-Learning
mit
Test your Gram matrix code. You should see errors less than 0.001.
def gram_matrix_test(correct): style_image = 'styles/starry_night.jpg' style_size = 192 feats, _ = features_from_img(style_image, style_size) student_output = gram_matrix(feats[5].clone()).data.numpy() error = rel_error(correct, student_output) print('Maximum error is {:.3f}'.format(error)) ...
CS231n/assignment3/StyleTransfer-PyTorch.ipynb
UltronAI/Deep-Learning
mit
Next, implement the style loss:
# Now put it together in the style_loss function... def style_loss(feats, style_layers, style_targets, style_weights): """ Computes the style loss at a set of layers. Inputs: - feats: list of the features at every layer of the current image, as produced by the extract_features function. -...
CS231n/assignment3/StyleTransfer-PyTorch.ipynb
UltronAI/Deep-Learning
mit
Test your style loss implementation. The error should be less than 0.001.
def style_loss_test(correct): content_image = 'styles/tubingen.jpg' style_image = 'styles/starry_night.jpg' image_size = 192 style_size = 192 style_layers = [1, 4, 6, 7] style_weights = [300000, 1000, 15, 3] c_feats, _ = features_from_img(content_image, image_size) feats, _ = f...
CS231n/assignment3/StyleTransfer-PyTorch.ipynb
UltronAI/Deep-Learning
mit
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: PyTorch Variable of shape (1, 3, H, W) holding an input image. - tv_weight: Scalar giving the weight w_t to use for the TV loss. Returns: - loss: PyTorch Variable holding a scalar giving the total variati...
CS231n/assignment3/StyleTransfer-PyTorch.ipynb
UltronAI/Deep-Learning
mit
Test your TV loss implementation. Error should be less than 0.001.
def tv_loss_test(correct): content_image = 'styles/tubingen.jpg' image_size = 192 tv_weight = 2e-2 content_img = preprocess(PIL.Image.open(content_image), size=image_size) content_img_var = Variable(content_img.type(dtype)) student_output = tv_loss(content_img_var, tv_weight).data.numpy()...
CS231n/assignment3/StyleTransfer-PyTorch.ipynb
UltronAI/Deep-Learning
mit
Now we're ready to string it all together (you shouldn't have to modify this function):
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 imag...
CS231n/assignment3/StyleTransfer-PyTorch.ipynb
UltronAI/Deep-Learning
mit
Generate some pretty pictures! Try out style_transfer on the three different parameter sets below. Make sure to run all three cells. Feel free to add your own, but make sure to include the results of style transfer on the third parameter set (starry night) in your submitted notebook. The content_image is the filename ...
# Composition VII + Tubingen params1 = { 'content_image' : 'styles/tubingen.jpg', 'style_image' : 'styles/composition_vii.jpg', 'image_size' : 192, 'style_size' : 512, 'content_layer' : 3, 'content_weight' : 5e-2, 'style_layers' : (1, 4, 6, 7), 'style_weights' : (20000, 500, 12, 1), ...
CS231n/assignment3/StyleTransfer-PyTorch.ipynb
UltronAI/Deep-Learning
mit
Feature Inversion The code you've written can do another cool thing. In an attempt to understand the types of features that convolutional networks learn to recognize, a recent paper [1] attempts to reconstruct an image from its feature representation. We can easily implement this idea using image gradients from the pre...
# Feature Inversion -- Starry Night + Tubingen params_inv = { 'content_image' : 'styles/tubingen.jpg', 'style_image' : 'styles/starry_night.jpg', 'image_size' : 192, 'style_size' : 192, 'content_layer' : 3, 'content_weight' : 6e-2, 'style_layers' : [1, 4, 6, 7], 'style_weights' : [0, 0, ...
CS231n/assignment3/StyleTransfer-PyTorch.ipynb
UltronAI/Deep-Learning
mit
Ride Report Method Here, we use the match method from the OSRM API with the code modified to return only the endpoints of segments. This allows us to aggregate over OSM segments since the node IDs are uniquely associated with a lat/lon pair given sufficient precision in the returned coordinates. The API recommends not ...
rides, readings = data_munging.read_raw_data() readings = data_munging.clean_readings(readings) readings = data_munging.add_proj_to_readings(readings, data_munging.NAD83)
src/Snapping_Readings_OSRM.ipynb
zscore/pavement_analysis
mit
If using a Dockerized OSRM instance, you can get the IP address by linking up to the Docker container running OSRM and pinging it. Usually though, the url here will be correct since it is the default.
digital_ocean_url = 'http://162.243.23.60/osrm-chi-vanilla/' local_docker_url = 'http://172.17.0.2:5000/' url = local_docker_url nearest_request = url + 'nearest?loc={0},{1}' match_request = url + 'match?loc={0},{1}&t={2}&loc={3},{4}&t={5}' def readings_to_match_str(readings): data_str = '&loc={0},{1}&t={2}' o...
src/Snapping_Readings_OSRM.ipynb
zscore/pavement_analysis
mit
This is a small example of how everything should work for troubleshooting and other purposes.
test_request = readings_to_match_str(readings.loc[readings['ride_id'] == 128, :]) print(test_request) matched_ride = requests.get(test_request).json() snapped_points = pd.DataFrame(matched_ride['matchings'][0]['matched_points'], columns=['lat', 'lon']) ax = snapped_points.plot(x='lon', y='lat', kind='scatter') rea...
src/Snapping_Readings_OSRM.ipynb
zscore/pavement_analysis
mit
This section here functions as a shortcut if you just want to load up the aggregate bumpiness instead of having to calculate all of it
with open(agg_path, 'w') as f: f.write(str(agg_road_bumpiness)) with open(agg_path, 'r') as f: agg_road_bumpiness = f.read() agg_road_bumpiness = eval(agg_road_bumpiness) def osm_segment_is_null(osm_segment): return (pd.isnull(osm_segment[0][0]) or pd.isnull(osm_segment[0][1]) or ...
src/Snapping_Readings_OSRM.ipynb
zscore/pavement_analysis
mit
Plot train and valid set NLL
tr = np.array(model.monitor.channels['valid_y_y_1_nll'].time_record) / 3600. fig = plt.figure(figsize=(12,8)) ax1 = fig.add_subplot(111) ax1.plot(model.monitor.channels['valid_y_y_1_nll'].val_record) ax1.plot(model.monitor.channels['train_y_y_1_nll'].val_record) ax1.set_xlabel('Epochs') ax1.legend(['Valid', 'Train']) a...
notebooks/model_run_and_result_analyses/Revisiting alexnet based experiment with 64 inputs (large).ipynb
Neuroglycerin/neukrill-net-work
mit
Plot ratio of update norms to parameter norms across epochs for different layers
h1_W_up_norms = np.array([float(v) for v in model.monitor.channels['mean_update_h1_W_kernel_norm_mean'].val_record]) h1_W_norms = np.array([float(v) for v in model.monitor.channels['valid_h1_kernel_norms_mean'].val_record]) plt.plot(h1_W_norms / h1_W_up_norms) #plt.ylim(0,1000) plt.show() plt.plot(model.monitor.channel...
notebooks/model_run_and_result_analyses/Revisiting alexnet based experiment with 64 inputs (large).ipynb
Neuroglycerin/neukrill-net-work
mit
<img src="image/Mean Variance - Image.png" style="height: 75%;width: 75%; position: relative; right: 5%"> Problem 1 The first problem involves normalizing the features for your training and test data. Implement Min-Max scaling in the normalize() function to a range of a=0.1 and b=0.9. After scaling, the values of the p...
# Problem 1 - Implement Min-Max scaling for grayscale image data def normalize_grayscale(image_data): """ Normalize the image data with Min-Max scaling to a range of [0.1, 0.9] :param image_data: The image data to be normalized :return: Normalized image data """ # TODO: Implement Min-Max scaling...
deeplearning/intro-to-tensorflow/intro_to_tensorflow.ipynb
syednasar/datascience
mit
Problem 2 Now it's time to build a simple neural network using TensorFlow. Here, your network will be just an input layer and an output layer. <img src="image/network_diagram.png" style="height: 40%;width: 40%; position: relative; right: 10%"> For the input here the images have been flattened into a vector of $28 \time...
# All the pixels in the image (28 * 28 = 784) features_count = 784 # All the labels labels_count = 10 # TODO: Set the features and labels tensors # features = # labels = # TODO: Set the weights and biases tensors # weights = # biases = ### DON'T MODIFY ANYTHING BELOW ### #Test Cases from tensorflow.python.ops...
deeplearning/intro-to-tensorflow/intro_to_tensorflow.ipynb
syednasar/datascience
mit
<img src="image/Learn Rate Tune - Image.png" style="height: 70%;width: 70%"> Problem 3 Below are 2 parameter configurations for training the neural network. In each configuration, one of the parameters has multiple options. For each configuration, choose the option that gives the best acccuracy. Parameter configuration...
# Change if you have memory restrictions batch_size = 128 # TODO: Find the best parameters for each configuration # epochs = # learning_rate = ### DON'T MODIFY ANYTHING BELOW ### # Gradient Descent optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) # The accuracy measured against the...
deeplearning/intro-to-tensorflow/intro_to_tensorflow.ipynb
syednasar/datascience
mit
As we can see from the output of the command above, by the straight wording of the question, there are exactly 1,355 mentions of Jo, 683 of Meg, 645 of Amy, and 459 of Beth in Little Women. If we were to assume that diminutive or nickname forms might count as well, we might add mentions of "Megs", "Bethy", and "Meggy"...
!wget https://raw.githubusercontent.com/gwsb-istm-6212-fall-2016/syllabus-and-schedule/master/projects/project-01/romeo.txt
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
First we must recall -- as the problem highlights -- that this text is that of a play. Because of this, we cannot simply count mentions of "Romeo," as we might accidentally inflate the count due to mentions of this character, for example, by other characters in their speaking lines. Instead, we must first look for a ...
!cat romeo.txt | grep "Rom" | head -25
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
In this brief sample, we can see title lines and metadata that include mention of Romeo, and both stage directions ("Enter Romeo") and spoken lines that include his name. What stands out, though, is that lines spoken by Romeo appear to be delineated by "Rom.", so we can search for this specific pattern. Let's verify ...
!cat romeo.txt | grep "Jul" | head -25
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
We see that the pattern seems to hold for both. I will assume that matches of the exact characters "Rom." and "Jul." indicate the start of a speaking line for one or the other characters, and will explicitly count only those lines.
!cat romeo.txt | grep -w "Rom\." \ | grep -oE '\w{{2,}}\.' \ | grep "Rom" \ | sort | uniq -c | sort -rn !cat romeo.txt | grep -w "Jul\." \ | grep -oE '\w{{2,}}\.' \ | grep "Jul" \ | sort | uniq -c | sort -rn
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
The two pipelines above indicate that Romeo has 163 speaking lines, while Juliet has only 117. To match the specific case with a trailing ., the first regular expressions in both above cases use the -w flag to denote a word match and the escape sequence \. to match the literal trailing period. The second regular expr...
!wget https://raw.githubusercontent.com/gwsb-istm-6212-fall-2016/syllabus-and-schedule/master/projects/project-01/2016q1.csv.zip !unzip 2016q1.csv.zip !head -5 2016q1.csv | csvlook !csvcut -n 2016q1.csv !csvcut -c5 2016q1.csv | tail -n +2 | csvsort | uniq -c | sort -rn | head -10
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
As we can see in the above results, the top ten starting stations in this time period were led by Columbus Circle / Union Station with over 13,000 rides, followed by Dupont Circle and the Lincoln Memorial and the rest as listed. In the pipeline above, tail -n +2 ensures we skip the header line before the sort process b...
!csvcut -c7 2016q1.csv | tail -n +2 | csvsort | uniq -c | sort -rn | head -10
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
The above results show us very similar numbers for destination stations during the same time period, with the first four stations unchanged and led again by Union Station with over 13,000 rides. Thomas Circle appears to be a more prominent start station than end station, as does Eastern Market, which does not even mak...
!csvgrep -c5 -m "Columbus Circle / Union Station" 2016q1.csv | head
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
We can further limit the columns used to cut down on the data flowing through the pipe.
!csvcut -c5,8 2016q1.csv | csvgrep -c1 -m "Columbus Circle / Union Station" | head !csvcut -c5,8 2016q1.csv \ | csvgrep -c1 -m "Columbus Circle / Union Station" \ | csvcut -c2 \ | tail -n +2 \ | sort | uniq -c | sort -rn | head -12
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
Above are the most commonly used bikes in trips departing from Union Station, led by bike number W22227. As we might expect it appears that the distribution seems rather uniform. Note that because several bikes had exactly 15 trips starting from Union Station, the list includes the top twelve bikes, rather than the t...
!csvcut -c7,8 2016q1.csv \ | csvgrep -c1 -m "Columbus Circle / Union Station" \ | csvcut -c2 \ | tail -n +2 \ | sort | uniq -c | sort -rn | head -15
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
Above are the most commonly used bikes in trips arriving at Union Station, let by bike number W00485. It is interesting to note that bike W22227, the top departing bike, is in second place, but bike W00485, the top arriving bike, does not appear in the top ten departing bikes. In any case these also seem at first gla...
!wget https://raw.githubusercontent.com/gwsb-istm-6212-fall-2016/syllabus-and-schedule/master/projects/project-01/simplefilter.py !cp simplefilter.py split.py
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
The file split.py is modified from the template to split lines of text into one word per line. To demonstrate this, we can compare the original pipeline with a new pipeline with split.py substituting for the first grep command.
!cat women.txt \ | grep -oE '\w{{1,}}' \ | tr '[:upper:]' '[:lower:]' \ | sort \ | uniq -c \ | sort -rn \ | head -10
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
We can ignore the broken pipe and related errors as the output appears to be correct. Next, we repeat the pipeline with split.py substituted:
!chmod +x split.py
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
Examining the filter script below, the key line, #14, removes trailing newlines, splits tokens by the space (' '), and removes words that are not entirely alphabetical.
!grep -n '' split.py !cat women.txt \ | ./split.py \ | tr '[:upper:]' '[:lower:]' \ | sort \ | uniq -c \ | sort -rn \ | head -10
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
Almost the exact words listed appear in nearly the same order, but with lower counts for each. We can examine the output of each command to see if there are obvious differences:
!cat women.txt | grep -oE '\w{{2,}}' | head -25 !cat women.txt | ./split.py | head -25
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
We can see straight away on the first few lines that there is a difference. Let's look at the text itself:
!head -3 women.txt
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
Three obvious issues jump out. First, the initial "The" is elided; it is not clear why. Next, "Women" is removed, perhaps due to the trailing comma, which will cause the token to fail the isalpha() test. Also, "Alcott" is removed, perhaps having to do with its position at the end of the line. We can update the filte...
!grep -n '' split.py !cat women.txt | ./split.py | head -25
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
This looks much better. We can try the full pipeline again:
!cat women.txt \ | ./split.py \ | tr '[:upper:]' '[:lower:]' \ | sort \ | uniq -c \ | sort -rn \ | head -10
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
This looks to be an exact match.
!cp simplefilter.py lowercase.py
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
The filter lowercase.py is modified from the template to lowercase incoming lines of text.
!chmod +x lowercase.py !grep -n '' lowercase.py
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
Note that the only line aside from the comments that changes in the above script is line #12, which adds the lower() to the print statement.
!head women.txt | ./lowercase.py
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
This looks correct, so we'll first attempt to replace the original pipeline's use of tr with lowercase.py:
!cat women.txt \ | grep -oE '\w{{1,}}' \ | ./lowercase.py \ | sort \ | uniq -c \ | sort -rn \ | head -10
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
Looks good so far, we are seeing the exact same counts. To address the problem's challenge, we finally replace both filters at once.
!cat women.txt \ | ./split.py \ | ./lowercase.py \ | sort \ | uniq -c \ | sort -rn \ | head -10
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
This completes Problem 3 - Part A. Part B - stop words Write a Python filter that removes at least ten common words of English text, commonly known as "stop words". Sources of English stop word lists are readily available online, or you may generate your own list from the text. We begin by acquiring a common list of En...
!wget http://www.textfixer.com/resources/common-english-words.txt !head common-english-words.txt
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
Next we copy the template filter script as before, renaming it appropriately.
!cp simplefilter.py stopwords.py !chmod +x stopwords.py !grep -n '' stopwords.py
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
The key changes in stopwords.py from the template are line #13, which imports the list of stopwords, and line #20, which checks whether an incoming word is in the stopword list. Note also that in line #19 the removal of a trailing newline occurs before checking for stopwords. The assumption that incoming text will alr...
!head women.txt | ./split.py | ./lowercase.py | ./stopwords.py
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
This appears to be correct. Let's put it all together:
!cat women.txt \ | ./split.py \ | ./lowercase.py \ | ./stopwords.py \ | sort \ | uniq -c \ | sort -rn \ | head -25
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
This would seem to be correct - we see the names we looked for earlier appearing near the top of the list, and common stop words are indeed removed - however the list starts with odd "words", in "t", "s", "m", and "ll". Is it possible that these are occurences of contractions? We can check a few different ways. Firs...
!cat women.txt \ | grep -oE '\w{{1,}}' \ | ./lowercase.py \ | ./stopwords.py \ | sort \ | uniq -c \ | sort -rn \ | head -25
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
No, the results are exactly the same. Instead, we'll need to look for occurrences of "t" and "s" by themselves. The --context option to grep might help us here, pointing out surrounding text to search for in the source.
!cat women.txt \ | ./split.py \ | ./lowercase.py \ | grep --context=2 -oE '^t$' \ | head -20 !grep -i "we haven't got" women.txt
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
Aha, it does appear that the occurences of a bare "t" are from contractions. Let's repeat with "s", which might occur in possessives.
!cat women.txt \ | ./split.py \ | ./lowercase.py \ | grep --context=2 -oE '^s$' \ | head -20 !grep -i "amy's valley" women.txt
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
There we have it - the counts from above were correct, and we could eliminate "t" and "s" from consideration with a grep -v, and we can further assume that the "ll" and "m" occurences are also from contractions, so we'll remove them as well.
!cat women.txt \ | ./split.py \ | ./lowercase.py \ | ./stopwords.py \ | grep -v -oE '^s|t|m|ll$' \ | sort \ | uniq -c \ | sort -rn \ | head -25
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
Here we have a final count. It is interesting to note that these counts of character names (Jo, Meg, etc.) are slightly different from before, perhaps due to punctuation handling, but it seems beyond the scope of the question to answer it precisely. Extra credit - parallel stop words Use GNU parallel to count the 25 m...
!wget https://raw.githubusercontent.com/gwsb-istm-6212-fall-2016/syllabus-and-schedule/master/projects/project-01/texts.zip !unzip -l texts.zip | head -5 !mkdir all-texts !unzip -d all-texts texts.zip !time ls all-texts/*.txt \ | parallel --eta -j+0 "grep -oE '\w{1,}' {} | tr '[:upper:]' '[:lower:]' | grep -v -...
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
In the above line, I've limited the word size to one character, removed common contractions, and piped the overall result through the new stopwords.py Python filter.
!wc -l all-words.txt !time sort all-words.txt | uniq -c | sort -rn | head -25
projects/project-01/solution/problem-01-solution.ipynb
gwsb-istm-6212-fall-2016/syllabus-and-schedule
cc0-1.0
Authenticate with the docker registry first bash gcloud auth configure-docker If using TPUs please also authorize Cloud TPU to access your project as described here. Set up your output bucket
BUCKET = "gs://" # your bucket here assert re.search(r'gs://.+', BUCKET), 'A GCS bucket is required to store your results.'
courses/fast-and-lean-data-science/fairing_train.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Build a base image to work with fairing
!cat Dockerfile !docker build . -t {base_image} !docker push {base_image}
courses/fast-and-lean-data-science/fairing_train.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Start an AI Platform job
additional_files = '' # If your code requires additional files, you can specify them here (or include everything in the current folder with glob.glob('./**', recursive=True)) # If your code does not require any dependencies or config changes, you can directly start from an official Tensorflow docker image #fairing.conf...
courses/fast-and-lean-data-science/fairing_train.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Parameters
BATCH_SIZE = 32 #@param {type:"integer"} BUCKET = 'gs://' #@param {type:"string"} assert re.search(r'gs://.+', BUCKET), 'You need a GCS bucket for your Tensorboard logs. Head to http://console.cloud.google.com/storage and create one.' training_images_file = 'gs://mnist-public/train-images-idx3-ubyte' training_label...
courses/fast-and-lean-data-science/06_MNIST_Estimator_to_TPUEstimator.ipynb
turbomanage/training-data-analyst
apache-2.0
Colab-only auth for this notebook and the TPU
IS_COLAB_BACKEND = 'COLAB_GPU' in os.environ # this is always set on Colab, the value is 0 or 1 depending on GPU presence if IS_COLAB_BACKEND: from google.colab import auth auth.authenticate_user() # Authenticates the backend and also the TPU using your credentials so that they can access your private GCS buckets
courses/fast-and-lean-data-science/06_MNIST_Estimator_to_TPUEstimator.ipynb
turbomanage/training-data-analyst
apache-2.0
TPU detection
#TPU REFACTORING: detect the TPU try: # TPU detection tpu = tf.contrib.cluster_resolver.TPUClusterResolver() # Picks up a connected TPU on Google's Colab, ML Engine, Kubernetes and Deep Learning VMs accessed through the 'ctpu up' utility #tpu = tf.contrib.cluster_resolver.TPUClusterResolver('MY_TPU_NAME') # If auto...
courses/fast-and-lean-data-science/06_MNIST_Estimator_to_TPUEstimator.ipynb
turbomanage/training-data-analyst
apache-2.0
tf.data.Dataset: parse files and prepare training and validation datasets Please read the best practices for building input pipelines with tf.data.Dataset
def read_label(tf_bytestring): label = tf.decode_raw(tf_bytestring, tf.uint8) label = tf.reshape(label, []) label = tf.one_hot(label, 10) return label def read_image(tf_bytestring): image = tf.decode_raw(tf_bytestring, tf.uint8) image = tf.cast(image, tf.float32)/256.0 image = tf.reshape(...
courses/fast-and-lean-data-science/06_MNIST_Estimator_to_TPUEstimator.ipynb
turbomanage/training-data-analyst
apache-2.0
Let's have a look at the data
N = 24 (training_digits, training_labels, validation_digits, validation_labels) = dataset_to_numpy_util(training_dataset, validation_dataset, N) display_digits(training_digits, training_labels, training_labels, "training digits and their labels", N) display_digits(validation_digits[:N], validation_labels[:N], validati...
courses/fast-and-lean-data-science/06_MNIST_Estimator_to_TPUEstimator.ipynb
turbomanage/training-data-analyst
apache-2.0
Estimator model If you are not sure what cross-entropy, dropout, softmax or batch-normalization mean, head here for a crash-course: Tensorflow and deep learning without a PhD
# This model trains to 99.4% sometimes 99.5% accuracy in 10 epochs # TPU REFACTORING: model_fn must have a params argument. TPUEstimator passes batch_size and use_tpu into it #def model_fn(features, labels, mode): def model_fn(features, labels, mode, params): is_training = (mode == tf.estimator.ModeKeys.TRAIN) x...
courses/fast-and-lean-data-science/06_MNIST_Estimator_to_TPUEstimator.ipynb
turbomanage/training-data-analyst
apache-2.0
Train and validate the model, this time on TPU
EPOCHS = 10 # TPU_REFACTORING: to use all 8 cores, increase the batch size by 8 GLOBAL_BATCH_SIZE = BATCH_SIZE * 8 # TPU_REFACTORING: TPUEstimator increments the step once per GLOBAL_BATCH_SIZE: must adjust epoch length accordingly # steps_per_epoch = 60000 // BATCH_SIZE # 60,000 images in training dataset steps_per...
courses/fast-and-lean-data-science/06_MNIST_Estimator_to_TPUEstimator.ipynb
turbomanage/training-data-analyst
apache-2.0
Visualize predictions
# recognize digits from local fonts # TPU REFACTORING: TPUEstimator.predict requires a 'params' in ints input_fn so that it can pass params['batch_size'] #predictions = estimator.predict(lambda: tf.data.Dataset.from_tensor_slices(font_digits).batch(N), predictions = estimator.predict(lambda params: tf.data.Dataset.fr...
courses/fast-and-lean-data-science/06_MNIST_Estimator_to_TPUEstimator.ipynb
turbomanage/training-data-analyst
apache-2.0
Deploy the trained model to ML Engine Push your trained model to production on ML Engine for a serverless, autoscaled, REST API experience. You will need a GCS bucket and a GCP project for this. Models deployed on ML Engine autoscale to zero if not used. There will be no ML Engine charges after you are done testing. Go...
PROJECT = "" #@param {type:"string"} NEW_MODEL = True #@param {type:"boolean"} MODEL_NAME = "estimator_mnist_tpu" #@param {type:"string"} MODEL_VERSION = "v0" #@param {type:"string"} assert PROJECT, 'For this part, you need a GCP project. Head to http://console.cloud.google.com/ and create one.' #TPU REFACTORING: TPU...
courses/fast-and-lean-data-science/06_MNIST_Estimator_to_TPUEstimator.ipynb
turbomanage/training-data-analyst
apache-2.0
Deploy the model This uses the command-line interface. You can do the same thing through the ML Engine UI at https://console.cloud.google.com/mlengine/models
# Create the model if NEW_MODEL: !gcloud ml-engine models create {MODEL_NAME} --project={PROJECT} --regions=us-central1 # Create a version of this model (you can add --async at the end of the line to make this call non blocking) # Additional config flags are available: https://cloud.google.com/ml-engine/reference/re...
courses/fast-and-lean-data-science/06_MNIST_Estimator_to_TPUEstimator.ipynb
turbomanage/training-data-analyst
apache-2.0
Test the deployed model Your model is now available as a REST API. Let us try to call it. The cells below use the "gcloud ml-engine" command line tool but any tool that can send a JSON payload to a REST endpoint will work.
# prepare digits to send to online prediction endpoint digits = np.concatenate((font_digits, validation_digits[:100-N])) labels = np.concatenate((font_labels, validation_labels[:100-N])) with open("digits.json", "w") as f: for digit in digits: # the format for ML Engine online predictions is: one JSON object per ...
courses/fast-and-lean-data-science/06_MNIST_Estimator_to_TPUEstimator.ipynb
turbomanage/training-data-analyst
apache-2.0
Let's generate a mesh in PHOEBE
b = phoebe.default_binary() b.add_dataset('mesh', times=[0], columns=['teffs', 'vws']) b.run_compute() verts = b.get_value(qualifier='uvw_elements', component='primary', context='model') print(verts.shape) # [polygon, vertex, dimension] teffs = b.get_value(qualifier='teffs', component='primary', context='model') prin...
docs/tutorials/mesh.ipynb
kecnry/autofig
gpl-3.0
Meshes can be drawn by calling the mesh (instead of plot) method of a figure. Most syntax and features are identical between the two, with the following exceptions: * NO 'c' or 's' dimensions * ADDITION of 'fc' (facecolor) and 'ec' (edgecolor) dimensions * linestyle applies to the edges * NO highlight * uncover DEFAUL...
autofig.reset() autofig.mesh(x=xs, y=ys, z=zs, xlabel='x', xunit='solRad', ylabel='y', yunit='solRad') mplfig = autofig.draw()
docs/tutorials/mesh.ipynb
kecnry/autofig
gpl-3.0
As was the case for dimensions in plot, 'fc' (facecolor) and 'ec' (edgecolor) accept the following suffixes: * label * unit * map * lim
autofig.reset() autofig.mesh(x=xs, y=ys, z=zs, xlabel='x', xunit='solRad', ylabel='y', yunit='solRad', fc=teffs, fcmap='afmhot', fclabel='teff', fcunit='K') mplfig = autofig.draw()
docs/tutorials/mesh.ipynb
kecnry/autofig
gpl-3.0
The edges can be turned off by passing ec='none'. Also see how fclim='symmetric' will force the white in the 'bwr' colormap to correspond to vz=0.
autofig.reset() autofig.mesh(x=xs, y=ys, z=zs, xlabel='x', xunit='solRad', ylabel='y', yunit='solRad', fc=-vzs, fcmap='bwr', fclim='symmetric', fclabel='rv', fcunit='solRad/d', ec='none') mplfig = autofig.draw()
docs/tutorials/mesh.ipynb
kecnry/autofig
gpl-3.0
The facecolor default to 'none' allows you to see "through" the mesh:
autofig.reset() autofig.mesh(x=xs, y=ys, z=zs, xlabel='x', xunit='solRad', ylabel='y', yunit='solRad', ec=-vzs, ecmap='bwr', eclim='symmetric', eclabel='rv', ecunit='solRad/d') mplfig = autofig.draw()
docs/tutorials/mesh.ipynb
kecnry/autofig
gpl-3.0
In order to not see through the mesh, set the facecolor to 'white':
autofig.reset() autofig.mesh(x=xs, y=ys, z=zs, xlabel='x', xunit='solRad', ylabel='y', yunit='solRad', ec=-vzs, ecmap='bwr', eclim='symmetric', eclabel='rv', ecunit='solRad/d', fc='white') mplfig = autofig.draw()
docs/tutorials/mesh.ipynb
kecnry/autofig
gpl-3.0
We can of course provide different arrays and colormaps for the edge and face:
autofig.reset() autofig.mesh(x=xs, y=ys, z=zs, xlabel='x', xunit='solRad', ylabel='y', yunit='solRad', fc=teffs, fcmap='afmhot', fclabel='teff', fcunit='K', ec=-vzs, ecmap='bwr', eclim='symmetric', eclabel='rv', ecunit='solRad/d') mplfig = autofig.draw()
docs/tutorials/mesh.ipynb
kecnry/autofig
gpl-3.0
Animate and Limits
times = np.linspace(0,1,21) b = phoebe.default_binary() b.add_dataset('mesh', times=times, columns='vws') b.run_compute()
docs/tutorials/mesh.ipynb
kecnry/autofig
gpl-3.0
Rather than add an extra dimension, we can make a separate call to mesh for each time and pass the time to the 'i' dimension as a float.
autofig.reset() for t in times: for c in ['primary', 'secondary']: verts = b.get_value(time=t, component=c, qualifier='uvw_elements', context='model') vzs = b.get_value(time=t, component=c, qualifier='vws', context='model') xs = verts[:, :, 0] ys = verts[:, :, 1] zs = verts[:...
docs/tutorials/mesh.ipynb
kecnry/autofig
gpl-3.0
autofig.gcf().axes[0].x.lim = None anim = autofig.animate(i=times, save='mesh_2.gif', save_kwargs={'writer': 'imagemagick'})
docs/tutorials/mesh.ipynb
kecnry/autofig
gpl-3.0
autofig.gcf().axes[0].x.lim = 4 anim = autofig.animate(i=times, save='mesh_3.gif', save_kwargs={'writer': 'imagemagick'})
docs/tutorials/mesh.ipynb
kecnry/autofig
gpl-3.0
1) How does gradient checking work? Backpropagation computes the gradients $\frac{\partial J}{\partial \theta}$, where $\theta$ denotes the parameters of the model. $J$ is computed using forward propagation and your loss function. Because forward propagation is relatively easy to implement, you're confident you got tha...
# GRADED FUNCTION: forward_propagation def forward_propagation(x, theta): """ Implement the linear forward propagation (compute J) presented in Figure 1 (J(theta) = theta * x) Arguments: x -- a real-valued input theta -- our parameter, a real number as well Returns: J -- the value...
deeplearning.ai/C2.ImproveDeepNN/week1-hw/Gradient Checking/Gradient+Checking+v1.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
Expected Output: <table style=> <tr> <td> ** J ** </td> <td> 8</td> </tr> </table> Exercise: Now, implement the backward propagation step (derivative computation) of Figure 1. That is, compute the derivative of $J(\theta) = \theta x$ with respect to $\theta$. To save you from doing the calcul...
# GRADED FUNCTION: backward_propagation def backward_propagation(x, theta): """ Computes the derivative of J with respect to theta (see Figure 1). Arguments: x -- a real-valued input theta -- our parameter, a real number as well Returns: dtheta -- the gradient of the cost with res...
deeplearning.ai/C2.ImproveDeepNN/week1-hw/Gradient Checking/Gradient+Checking+v1.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
Expected Output: <table> <tr> <td> ** dtheta ** </td> <td> 2 </td> </tr> </table> Exercise: To show that the backward_propagation() function is correctly computing the gradient $\frac{\partial J}{\partial \theta}$, let's implement gradient checking. Instructions: - First compute "gradapprox" ...
# GRADED FUNCTION: gradient_check def gradient_check(x, theta, epsilon = 1e-7): """ Implement the backward propagation presented in Figure 1. Arguments: x -- a real-valued input theta -- our parameter, a real number as well epsilon -- tiny shift to the input to compute approximated gradien...
deeplearning.ai/C2.ImproveDeepNN/week1-hw/Gradient Checking/Gradient+Checking+v1.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
Expected Output: The gradient is correct! <table> <tr> <td> ** difference ** </td> <td> 2.9193358103083e-10 </td> </tr> </table> Congrats, the difference is smaller than the $10^{-7}$ threshold. So you can have high confidence that you've correctly computed the gradient in backward_propagatio...
def forward_propagation_n(X, Y, parameters): """ Implements the forward propagation (and computes the cost) presented in Figure 3. Arguments: X -- training set for m examples Y -- labels for m examples parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3",...
deeplearning.ai/C2.ImproveDeepNN/week1-hw/Gradient Checking/Gradient+Checking+v1.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
Now, run backward propagation.
def backward_propagation_n(X, Y, cache): """ Implement the backward propagation presented in figure 2. Arguments: X -- input datapoint, of shape (input size, 1) Y -- true "label" cache -- cache output from forward_propagation_n() Returns: gradients -- A dictionary with the grad...
deeplearning.ai/C2.ImproveDeepNN/week1-hw/Gradient Checking/Gradient+Checking+v1.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
You obtained some results on the fraud detection test set but you are not 100% sure of your model. Nobody's perfect! Let's implement gradient checking to verify if your gradients are correct. How does gradient checking work?. As in 1) and 2), you want to compare "gradapprox" to the gradient computed by backpropagation....
# GRADED FUNCTION: gradient_check_n def gradient_check_n(parameters, gradients, X, Y, epsilon = 1e-7): """ Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n Arguments: parameters -- python dictionary containing your parameters "W1", "b1", ...
deeplearning.ai/C2.ImproveDeepNN/week1-hw/Gradient Checking/Gradient+Checking+v1.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
Recommending movies: ranking This tutorial is a slightly adapted version of the basic ranking tutorial from TensorFlow Recommenders documentation. Imports Let's first get our imports out of the way.
!pip install -q tensorflow-recommenders !pip install -q --upgrade tensorflow-datasets import os import pprint import tempfile from typing import Dict, Text import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_recommenders as tfrs
tfrs-flutter/step5/backend/ranking/ranking.ipynb
flutter/codelabs
bsd-3-clause
Preparing the dataset We're continuing to use the MovieLens dataset. This time, we're also going to keep the ratings: these are the objectives we are trying to predict.
ratings = tfds.load("movielens/100k-ratings", split="train") ratings = ratings.map(lambda x: { "movie_title": x["movie_title"], "user_id": x["user_id"], "user_rating": x["user_rating"] })
tfrs-flutter/step5/backend/ranking/ranking.ipynb
flutter/codelabs
bsd-3-clause
We'll split the data by putting 80% of the ratings in the train set, and 20% in the test set.
tf.random.set_seed(42) shuffled = ratings.shuffle(100_000, seed=42, reshuffle_each_iteration=False) train = shuffled.take(80_000) test = shuffled.skip(80_000).take(20_000)
tfrs-flutter/step5/backend/ranking/ranking.ipynb
flutter/codelabs
bsd-3-clause
Next we figure out unique user ids and movie titles present in the data so that we can create the embedding user and movie embedding tables.
movie_titles = ratings.batch(1_000_000).map(lambda x: x["movie_title"]) user_ids = ratings.batch(1_000_000).map(lambda x: x["user_id"]) unique_movie_titles = np.unique(np.concatenate(list(movie_titles))) unique_user_ids = np.unique(np.concatenate(list(user_ids)))
tfrs-flutter/step5/backend/ranking/ranking.ipynb
flutter/codelabs
bsd-3-clause
Implementing a model Architecture Ranking models do not face the same efficiency constraints as retrieval models do, and so we have a little bit more freedom in our choice of architectures. We can implement our ranking model as follows:
class RankingModel(tf.keras.Model): def __init__(self): super().__init__() embedding_dimension = 32 # Compute embeddings for users. self.user_embeddings = tf.keras.Sequential([ tf.keras.layers.StringLookup( vocabulary=unique_user_ids, mask_token=None), tf.keras.layers.Embedding(l...
tfrs-flutter/step5/backend/ranking/ranking.ipynb
flutter/codelabs
bsd-3-clause
Loss and metrics We'll make use of the Ranking task object: a convenience wrapper that bundles together the loss function and metric computation. We'll use it together with the MeanSquaredError Keras loss in order to predict the ratings.
task = tfrs.tasks.Ranking( loss = tf.keras.losses.MeanSquaredError(), metrics=[tf.keras.metrics.RootMeanSquaredError()] )
tfrs-flutter/step5/backend/ranking/ranking.ipynb
flutter/codelabs
bsd-3-clause
The full model We can now put it all together into a model.
class MovielensModel(tfrs.models.Model): def __init__(self): super().__init__() self.ranking_model: tf.keras.Model = RankingModel() self.task: tf.keras.layers.Layer = tfrs.tasks.Ranking( loss = tf.keras.losses.MeanSquaredError(), metrics=[tf.keras.metrics.RootMeanSquaredError()] ) def ...
tfrs-flutter/step5/backend/ranking/ranking.ipynb
flutter/codelabs
bsd-3-clause
Fitting and evaluating After defining the model, we can use standard Keras fitting and evaluation routines to fit and evaluate the model. Let's first instantiate the model.
model = MovielensModel() model.compile(optimizer=tf.keras.optimizers.Adagrad(learning_rate=0.1))
tfrs-flutter/step5/backend/ranking/ranking.ipynb
flutter/codelabs
bsd-3-clause
Then shuffle, batch, and cache the training and evaluation data.
cached_train = train.shuffle(100_000).batch(8192).cache() cached_test = test.batch(4096).cache()
tfrs-flutter/step5/backend/ranking/ranking.ipynb
flutter/codelabs
bsd-3-clause
Then train the model:
model.fit(cached_train, epochs=3)
tfrs-flutter/step5/backend/ranking/ranking.ipynb
flutter/codelabs
bsd-3-clause
As the model trains, the loss is falling and the RMSE metric is improving. Finally, we can evaluate our model on the test set:
model.evaluate(cached_test, return_dict=True)
tfrs-flutter/step5/backend/ranking/ranking.ipynb
flutter/codelabs
bsd-3-clause
The lower the RMSE metric, the more accurate our model is at predicting ratings. Exporting for serving The model can be easily exported for serving:
tf.saved_model.save(model, "exported-ranking/123")
tfrs-flutter/step5/backend/ranking/ranking.ipynb
flutter/codelabs
bsd-3-clause
We will deploy the model with TensorFlow Serving soon.
# Zip the SavedModel folder for easier download !zip -r exported-ranking.zip exported-ranking/
tfrs-flutter/step5/backend/ranking/ranking.ipynb
flutter/codelabs
bsd-3-clause
Wir öffnen die Datenbank und lassen uns die Keys der einzelnen Tabellen ausgeben. 
hdf = pd.HDFStore('../../data/raw/TestMessungen_NEU.hdf') print(hdf.keys)
notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb
hhain/sdap17
mit
Aufgabe 2: Inspektion eines einzelnen Dataframes Wir laden den Frame x1_t1_trx_1_4 und betrachten seine Dimension.
df_x1_t1_trx_1_4 = hdf.get('/x1/t1/trx_1_4') print("Rows:", df_x1_t1_trx_1_4.shape[0]) print("Columns:", df_x1_t1_trx_1_4.shape[1])
notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb
hhain/sdap17
mit
Als nächstes Untersuchen wir exemplarisch für zwei Empfänger-Sender-Gruppen die Attributzusammensetzung.
# first inspection of columns from df_x1_t1_trx_1_4 df_x1_t1_trx_1_4.head(5)
notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb
hhain/sdap17
mit
Für die Analyse der Frames definieren wir einige Hilfsfunktionen.
# Little function to retrieve sender-receiver tuples from df columns def extract_snd_rcv(df): regex = r"trx_[1-4]_[1-4]" # creates a set containing the different pairs snd_rcv = {x[4:7] for x in df.columns if re.search(regex, x)} return [(x[0],x[-1]) for x in snd_rcv] # Sums the number of columns for e...
notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb
hhain/sdap17
mit
Bestimme nun die Spaltezusammensetzung von df_x1_t1_trx_1_4.
analyse_columns(df_x1_t1_trx_1_4)
notebooks/pawel_ueb2/mustererkennung_in_funkmessdaten_PCA.ipynb
hhain/sdap17
mit