markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Negative Indexing We can also use negative indexing with strings: Negative index can help us to count the element from the end of the string. The last element is given by the index -1:
# Print the last element in the string print(name[-1])
n
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
The first element can be obtained by index -15:
# Print the first element in the string print(name[-15])
M
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
We can find the number of characters in a string by using len, short for length:
# Find the length of string len("Michael Jackson")
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Slicing We can obtain multiple characters from a string using slicing, we can obtain the 0 to 4th and 8th to the 12th element: [Tip]: When taking the slice, the first number means the index (start at 0), and the second number means the length from the index to the last element you want (start at 1)
# Take the slice on variable name with only index 0 to index 3 name[0:4] # Take the slice on variable name with only index 8 to index 11 name[8:12]
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Stride We can also input a stride value as follows, with the '2' indicating that we are selecting every second variable:
# Get every second element. The elments on index 1, 3, 5 ... name[::2]
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
We can also incorporate slicing with the stride. In this case, we select the first five elements and then use the stride:
# Get every second element in the range from index 0 to index 4 name[0:5:2]
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Concatenate Strings We can concatenate or combine strings by using the addition symbols, and the result is a new string that is a combination of both:
# Concatenate two strings statement = name + "is the best" statement
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
To replicate values of a string we simply multiply the string by the number of times we would like to replicate it. In this case, the number is three. The result is a new string, and this new string consists of three copies of the original string:
# Print the string for 3 times 3 * "Michael Jackson"
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
You can create a new string by setting it to the original variable. Concatenated with a new string, the result is a new string that changes from Michael Jackson to “Michael Jackson is the best".
# Concatenate strings name = "Michael Jackson" name = name + " is the best" name
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Escape Sequences Back slashes represent the beginning of escape sequences. Escape sequences represent strings that may be difficult to input. For example, back slash "n" represents a new line. The output is given by a new line after the back slash "n" is encountered:
# New line escape sequence print(" Michael Jackson \n is the best" )
Michael Jackson is the best
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Similarly, back slash "t" represents a tab:
# Tab escape sequence print(" Michael Jackson \t is the best" )
Michael Jackson is the best
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
If you want to place a back slash in your string, use a double back slash:
# Include back slash in string print(" Michael Jackson \\ is the best" )
Michael Jackson \ is the best
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
We can also place an "r" before the string to display the backslash:
# r will tell python that string will be display as raw string print(r" Michael Jackson \ is the best" )
Michael Jackson \ is the best
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
String Operations There are many string operation methods in Python that can be used to manipulate the data. We are going to use some basic string operations on the data. Let's try with the method upper; this method converts lower case characters to upper case characters:
# Convert all the characters in string to upper case a = "Thriller is the sixth studio album" print("before upper:", a) b = a.upper() print("After upper:", b)
before upper: Thriller is the sixth studio album After upper: THRILLER IS THE SIXTH STUDIO ALBUM
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
The method replace replaces a segment of the string, i.e. a substring with a new string. We input the part of the string we would like to change. The second argument is what we would like to exchange the segment with, and the result is a new string with the segment changed:
# Replace the old substring with the new target substring is the segment has been found in the string a = "Michael Jackson is the best" b = a.replace('Michael', 'Janet') b
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
The method find finds a sub-string. The argument is the substring you would like to find, and the output is the first index of the sequence. We can find the sub-string jack or el.
# Find the substring in the string. Only the index of the first elment of substring in string will be the output name = "Michael Jackson" name.find('el') # Find the substring in the string. name.find('Jack')
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
If the sub-string is not in the string then the output is a negative one. For example, the string 'Jasdfasdasdf' is not a substring:
# If cannot find the substring in the string name.find('Jasdfasdasdf')
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Quiz on Strings What is the value of the variable a after the following code is executed?
# Write your code below and press Shift+Enter to execute a = "1"
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Click here for the solution```python"1"``` What is the value of the variable b after the following code is executed?
# Write your code below and press Shift+Enter to execute b = "2"
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Click here for the solution```python"2"``` What is the value of the variable c after the following code is executed?
# Write your code below and press Shift+Enter to execute c = a + b
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Click here for the solution```python"12"``` Consider the variable d use slicing to print out the first three elements:
# Write your code below and press Shift+Enter to execute d = "ABCDEFG" print(d[:3])
ABC
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Click here for the solution```pythonprint(d[:3]) or print(d[0:3])``` Use a stride value of 2 to print out every second character of the string e:
# Write your code below and press Shift+Enter to execute e = 'clocrkr1e1c1t' print(e[::2])
correct
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Click here for the solution```pythonprint(e[::2])``` Print out a backslash:
# Write your code below and press Shift+Enter to execute print("\\")
\
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Click here for the solution```pythonprint("\\\\")orprint(r"\ ")``` Convert the variable f to uppercase:
# Write your code below and press Shift+Enter to execute f = "You are wrong" f.upper()
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Click here for the solution```pythonf.upper()``` Consider the variable g, and find the first index of the sub-string snow:
# Write your code below and press Shift+Enter to execute g = "Mary had a little lamb Little lamb, little lamb Mary had a little lamb \ Its fleece was white as snow And everywhere that Mary went Mary went, Mary went \ Everywhere that Mary went The lamb was sure to go" g.find('snow')
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
Click here for the solution```pythong.find("snow")``` In the variable g, replace the sub-string Mary with Bob:
# Write your code below and press Shift+Enter to execute g.replace("Mary", "Bob")
_____no_output_____
Unlicense
PY0101EN-1-2-Strings.ipynb
ferm36/IBMPforDS
**[Pandas Home Page](https://www.kaggle.com/learn/pandas)**--- IntroductionIn this set of exercises we will work with the [Wine Reviews dataset](https://www.kaggle.com/zynicide/wine-reviews). Run the following cell to load your data and some utility functions (including code to check your answers).
import pandas as pd reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv", index_col=0) pd.set_option("display.max_rows", 5) from learntools.core import binder; binder.bind(globals()) from learntools.pandas.indexing_selecting_and_assigning import * print("Setup complete.")
_____no_output_____
MIT
Pandas/2.Indexing, Selecting & Assigning.ipynb
nakshatra-garg/kaggle-learn-courses
Look at an overview of your data by running the following line.
reviews.head()
_____no_output_____
MIT
Pandas/2.Indexing, Selecting & Assigning.ipynb
nakshatra-garg/kaggle-learn-courses
Exercises 1.Select the `description` column from `reviews` and assign the result to the variable `desc`.
# Your code here desc = reviews['description'] #or reviews.description # Check your answer q1.check()
_____no_output_____
MIT
Pandas/2.Indexing, Selecting & Assigning.ipynb
nakshatra-garg/kaggle-learn-courses
Follow-up question: what type of object is `desc`? If you're not sure, you can check by calling Python's `type` function: `type(desc)`.
#q1.hint() #q1.solution() type(desc)
_____no_output_____
MIT
Pandas/2.Indexing, Selecting & Assigning.ipynb
nakshatra-garg/kaggle-learn-courses
2.Select the first value from the description column of `reviews`, assigning it to variable `first_description`.
first_description = reviews.description[0] # Check your answer q2.check() first_description #q2.hint() #q2.solution()
_____no_output_____
MIT
Pandas/2.Indexing, Selecting & Assigning.ipynb
nakshatra-garg/kaggle-learn-courses
3. Select the first row of data (the first record) from `reviews`, assigning it to the variable `first_row`.
first_row = reviews.iloc[0] # Check your answer q3.check() first_row #q3.hint() #q3.solution()
_____no_output_____
MIT
Pandas/2.Indexing, Selecting & Assigning.ipynb
nakshatra-garg/kaggle-learn-courses
4.Select the first 10 values from the `description` column in `reviews`, assigning the result to variable `first_descriptions`.Hint: format your output as a pandas Series.
first_descriptions = reviews.loc[:9, 'description'] # Check your answer q4.check() first_descriptions #q4.hint() #q4.solution()
_____no_output_____
MIT
Pandas/2.Indexing, Selecting & Assigning.ipynb
nakshatra-garg/kaggle-learn-courses
5.Select the records with index labels `1`, `2`, `3`, `5`, and `8`, assigning the result to the variable `sample_reviews`.In other words, generate the following DataFrame:![](https://i.imgur.com/sHZvI1O.png)
sample_reviews = reviews.loc[[1, 2, 3, 5, 8]] # Check your answer q5.check() sample_reviews q5.hint() #q5.solution()
_____no_output_____
MIT
Pandas/2.Indexing, Selecting & Assigning.ipynb
nakshatra-garg/kaggle-learn-courses
6.Create a variable `df` containing the `country`, `province`, `region_1`, and `region_2` columns of the records with the index labels `0`, `1`, `10`, and `100`. In other words, generate the following DataFrame:![](https://i.imgur.com/FUCGiKP.png)
df = reviews.loc[[0, 1, 10, 100], ['country', 'province', 'region_1', 'region_2']] # Check your answer q6.check() df #q6.hint() #q6.solution()
_____no_output_____
MIT
Pandas/2.Indexing, Selecting & Assigning.ipynb
nakshatra-garg/kaggle-learn-courses
7.Create a variable `df` containing the `country` and `variety` columns of the first 100 records. Hint: you may use `loc` or `iloc`. When working on the answer this question and the several of the ones that follow, keep the following "gotcha" described in the tutorial:> `iloc` uses the Python stdlib indexing scheme, w...
df = reviews.loc[0:99, ['country', 'variety']] # Check your answer q7.check() df #q7.hint() #q7.solution()
_____no_output_____
MIT
Pandas/2.Indexing, Selecting & Assigning.ipynb
nakshatra-garg/kaggle-learn-courses
8.Create a DataFrame `italian_wines` containing reviews of wines made in `Italy`. Hint: `reviews.country` equals what?
italian_wines = reviews.loc[reviews.country == "Italy"] # Check your answer q8.check() italian_wines #q8.hint() #q8.solution()
_____no_output_____
MIT
Pandas/2.Indexing, Selecting & Assigning.ipynb
nakshatra-garg/kaggle-learn-courses
9.Create a DataFrame `top_oceania_wines` containing all reviews with at least 95 points (out of 100) for wines from Australia or New Zealand.
top_oceania_wines = reviews.loc[(reviews.country.isin(["Australia", "New Zealand"])) & (reviews.points >= 95)] # Check your answer q9.check() top_oceania_wines q9.hint() #q9.solution()
_____no_output_____
MIT
Pandas/2.Indexing, Selecting & Assigning.ipynb
nakshatra-garg/kaggle-learn-courses
Content-based recommender using Deep Structured Semantic ModelAn example of how to build a Deep Structured Semantic Model (DSSM) for incorporating complex content-based features into a recommender system. See [Learning Deep Structured Semantic Models for Web Search using Clickthrough Data](https://www.microsoft.com/e...
import warnings import mxnet as mx from mxnet import gluon, nd, autograd, sym import numpy as np from sklearn.random_projection import johnson_lindenstrauss_min_dim # Define some constants max_user = int(1e5) title_vocab_size = int(3e4) query_vocab_size = int(3e4) num_samples = int(1e4) hidden_units = 128 epsilon_pro...
_____no_output_____
Apache-2.0
example/recommenders/demo2-dssm.ipynb
wangyouze/incubator-mxnet
Bag of words random projection A previous version of this example contained a bag of word random projection example, it is kept here for reference but not used in the next example.Random Projection is a dimension reduction technique that guarantees the disruption of the pair-wise distance between your original data po...
proj_dim = johnson_lindenstrauss_min_dim(num_samples, epsilon_proj) print("To keep a distance disruption ~< {}% of our {} samples we need to randomly project to at least {} dimensions".format(epsilon_proj*100, num_samples, proj_dim)) class BagOfWordsRandomProjection(gluon.HybridBlock): def __init__(self, vocab_size...
_____no_output_____
Apache-2.0
example/recommenders/demo2-dssm.ipynb
wangyouze/incubator-mxnet
With padding:
bowrp(mx.nd.array([[10, 50, 100, 0], [5, 10, 0, 0]]))
_____no_output_____
Apache-2.0
example/recommenders/demo2-dssm.ipynb
wangyouze/incubator-mxnet
Content-based recommender / ranking system using DSSM For example in the search result ranking problem:You have users, that have performed text-based searches. They were presented with results, and selected one of them.Results are composed of a title and an image.Your positive examples will be the clicked items in the...
proj_dim = 128 class DSSMRecommenderNetwork(gluon.HybridBlock): def __init__(self, query_vocab_size, proj_dim, max_user, title_vocab_size, hidden_units, random_seed=54321, p=0.5): super(DSSMRecommenderNetwork, self).__init__() with self.name_scope(): # User/Query pipeline ...
_____no_output_____
Apache-2.0
example/recommenders/demo2-dssm.ipynb
wangyouze/incubator-mxnet
It is quite hard to visualize the network since it is relatively complex but you can see the two-pronged structure, and the resnet18 branch
mx.viz.plot_network(network( mx.sym.var('user'), mx.sym.var('query_text'), mx.sym.var('title'), mx.sym.var('image')), shape={'user': (1,1), 'query_text': (1,30), 'title': (1,30), 'image': (1,3,224,224)}, node_attrs={"fixedsize":"False"})
_____no_output_____
Apache-2.0
example/recommenders/demo2-dssm.ipynb
wangyouze/incubator-mxnet
We can print the summary of the network using dummy data. We can see it is already training on 32M parameters!
user = mx.nd.array([[200], [100]], ctx) query = mx.nd.array([[10, 20, 0, 0, 0], [40, 50, 0, 0, 0]], ctx) # Example of an encoded text title = mx.nd.array([[10, 20, 0, 0, 0], [40, 50, 0, 0, 0]], ctx) # Example of an encoded text image = mx.nd.random.uniform(shape=(2,3, 224,224), ctx=ctx) # Example of an encoded image ...
_____no_output_____
Apache-2.0
example/recommenders/demo2-dssm.ipynb
wangyouze/incubator-mxnet
Plots for logistic regression, consistent vs inconsistent noiseless AT, increasing epsilon
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches import dotenv import pandas as pd import mlflow import plotly import plotly.graph_objects as go import plotly.express as px import plotly.subplots import plotly.io as pio import typing import os import shutil import sys import warnings EXPORT...
_____no_output_____
MIT
logistic_regression/consistent_vs_inconsistent/plots_wide.ipynb
michaelaerni/interpolation_robustness
Load experiment data
client = mlflow.tracking.MlflowClient() experiment = client.get_experiment_by_name(EXPERIMENT_NAME) runs = mlflow.search_runs( experiment.experiment_id ) runs = runs.set_index('run_id', drop=False) # set index, but keep column to not break stuff depending on it # Convert some parameters to numbers and sort accord...
_____no_output_____
MIT
logistic_regression/consistent_vs_inconsistent/plots_wide.ipynb
michaelaerni/interpolation_robustness
Plots
robust_consistent_color_idx = 1 robust_inconsistent_color_idx = 2 population_linestyle = ir.plots.LINESTYLE_MAP[0] training_linestyle = ir.plots.LINESTYLE_MAP[2] BASELINE_LAMBDA = 0 warnings.simplefilter(action='ignore', category=pd.errors.PerformanceWarning) fig, ax = plt.subplots(figsize=FIGURE_SIZE) target_num_sam...
_____no_output_____
MIT
logistic_regression/consistent_vs_inconsistent/plots_wide.ipynb
michaelaerni/interpolation_robustness
RNN - LSTM - Toxic CommentsA corpus of manually labeled comments - classifying each comment by its type of toxicity is available on Kaggle. We will aim to do a binary classification of whether a comment is toxic or not.Approach:- Learning Embedding with the Task- LSTM- BiLSTM
import numpy as np import pandas as pd import keras import matplotlib.pyplot as plt %matplotlib inline import vis
Using TensorFlow backend.
MIT
011-RNN-LSTM-Toxic.ipynb
SaketJNU/deep-learning
Get the Data Uncomment these shell lines to get the data
# !wget http://bit.do/deep_toxic_train -P data/ # !mv data/deep_toxic_train data/train.zip df = pd.read_csv("data/train.zip") df.head()
_____no_output_____
MIT
011-RNN-LSTM-Toxic.ipynb
SaketJNU/deep-learning
Import the required libraries
from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences
_____no_output_____
MIT
011-RNN-LSTM-Toxic.ipynb
SaketJNU/deep-learning
Create the Input & Output Data
train_sentences = df["comment_text"] train_sentences.head()
_____no_output_____
MIT
011-RNN-LSTM-Toxic.ipynb
SaketJNU/deep-learning
**Pre-processing the train data**- Tokenization: "This is an apple" -> ["This", "is", "an", "apple"]- Indexing: {0: "This", 1: "is", 2: "an", 3: "apple"}- Index Representation: [0, 1, 2, 3]
from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences # Tokenizer max_words = 20000 tokenizer = Tokenizer(num_words=max_words, oov_token='UNK') tokenizer.fit_on_texts(list(train_sentences))
_____no_output_____
MIT
011-RNN-LSTM-Toxic.ipynb
SaketJNU/deep-learning
Tokenizer Fix from https://github.com/keras-team/keras/issues/8092
tokenizer.word_index = {e:i for e,i in tokenizer.word_index.items() if i <= max_words} # <= because tokenizer is 1 indexed tokenizer.word_index[tokenizer.oov_token] = max_words + 1 # Index Representation tokenized_train = tokenizer.texts_to_sequences(train_sentences) # Selecting Padding # find length of each sentence a...
_____no_output_____
MIT
011-RNN-LSTM-Toxic.ipynb
SaketJNU/deep-learning
Step 2: Create the Model Architecture
from keras.models import Sequential from keras.layers import Dense, LSTM, Embedding, Dropout, Bidirectional model = Sequential() model.add(Embedding(max_words, output_dim=128, mask_zero=True)) model.add(LSTM(60)) model.add(Dropout(0.1)) model.add(Dense(2, activation='sigmoid'))
_____no_output_____
MIT
011-RNN-LSTM-Toxic.ipynb
SaketJNU/deep-learning
Step 3: Compile the Model & Fit on the Data
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) output = model.fit(X_train, y_train, batch_size=128, epochs=5, validation_split=0.2)
Train on 102124 samples, validate on 25532 samples Epoch 1/5 102124/102124 [==============================] - 398s 4ms/step - loss: 0.1625 - acc: 0.9454 - val_loss: 0.1185 - val_acc: 0.9601 Epoch 2/5 102124/102124 [==============================] - 352s 3ms/step - loss: 0.1096 - acc: 0.9618 - val_loss: 0.1050 - val_acc...
MIT
011-RNN-LSTM-Toxic.ipynb
SaketJNU/deep-learning
Step 4: Evaluate the Model
vis.metrics(output.history) score = model.evaluate(X_test, y_test, verbose=1) print('Test loss:', score[0]) print('Test accuracy:', score[1])
Test loss: 0.10434365738769805 Test accuracy: 0.9634654551151496
MIT
011-RNN-LSTM-Toxic.ipynb
SaketJNU/deep-learning
Step 5: Visualise evaluation & Make a prediction
predict_classes = model.predict_classes(X_test) actual_classes = np.dot(y_test,np.array([[0],[1]])).reshape(-1) pd.crosstab(actual_classes, predict_classes)
_____no_output_____
MIT
011-RNN-LSTM-Toxic.ipynb
SaketJNU/deep-learning
Mask Adaptivity Detection Using YOLOMask became an essential accessory post COVID-19. Most of the countries are making face masks mandatory to avail services like transport, fuel and any sort of outside activity. It is become utmost necessary to keep track of the adaptivity of the crowd. This notebook contains impleme...
import warnings import numpy as np import argparse import time import cv2 import os warnings.filterwarnings("ignore")
_____no_output_____
MIT
Notebook/YOLO_Mask_Adaptivity.ipynb
arpan65/Mask-Adaptivity-Detection-Computer-Vision-
Prepare DarkNet Environment
# Create DarkNet Environment def prepare_environment(): os.environ['PATH'] += ':/usr/local/cuda/bin' !rm -fr darknet !git clone https://github.com/AlexeyAB/darknet/ !apt install gcc-5 g++-5 -y !ln -s /usr/bin/gcc-5 /usr/local/cuda/bin/gcc !ln -s /usr/bin/g++-5 /usr/local/cuda/bin/g++ %cd da...
_____no_output_____
MIT
Notebook/YOLO_Mask_Adaptivity.ipynb
arpan65/Mask-Adaptivity-Detection-Computer-Vision-
Get Tiny YOLO Weight (Skip if Resuming Training)
!wget --header="Host: pjreddie.com" --header="User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" --header="Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" -...
CUDA-version: 10010 (10010), GPU count: 1 OpenCV version: 3.2.0 GPU isn't used net.optimized_memory = 0 mini_batch = 1, batch = 1, time_steps = 1, train = 0 layer filters size/strd(dil) input output 0 conv 16 3 x 3/ 1 416 x 416 x 3 -> 416 x 416 x 16 0.150 BF 1 ma...
MIT
Notebook/YOLO_Mask_Adaptivity.ipynb
arpan65/Mask-Adaptivity-Detection-Computer-Vision-
Copy Required Files from Drive
# Copy fils from Google Drive to the VM local filesystem !cp -r "/content/drive/My Drive/darknet/YOLO_Custom" /content/darknet/YOLO_Custom
_____no_output_____
MIT
Notebook/YOLO_Mask_Adaptivity.ipynb
arpan65/Mask-Adaptivity-Detection-Computer-Vision-
Train Use the below command to train yolo: !./darknet detector train data_file_path config_file_path training_weights_path log_path To train yolov3 instead of tiny yolo, replace the following files:use ***yolov3_train_cfg*** instead of ***yolov3-tiny_obj_train.cfg***use ***yolov3_test_cfg*** instead of...
!./darknet detector train "/content/darknet/YOLO_Custom/obj.data" "/content/darknet/YOLO_Custom/yolov3-tiny_obj_train.cfg" "/content/darknet/yolov3-tiny.conv.15" "train.log" -dont_show
CUDA-version: 10010 (10010), GPU count: 1 OpenCV version: 3.2.0 yolov3-tiny_obj_train 0 : compute_capability = 600, cudnn_half = 0, GPU: Tesla P100-PCIE-16GB net.optimized_memory = 0 mini_batch = 4, batch = 64, time_steps = 1, train = 1 layer filters size/strd(dil) input output 0 co...
MIT
Notebook/YOLO_Mask_Adaptivity.ipynb
arpan65/Mask-Adaptivity-Detection-Computer-Vision-
Utility Functions
# Define threshold for confidence score and Non max supression here confthres=0.2 nmsthres=0.1 path="./" def get_labels(label_dir): return open(label_dir).read().split('\n') def get_colors(LABELS): # initialize a list of colors to represent each possible class label np.random.seed(42) COLORS = np...
_____no_output_____
MIT
Notebook/YOLO_Mask_Adaptivity.ipynb
arpan65/Mask-Adaptivity-Detection-Computer-Vision-
Set the Variables (Must before Prediction)
# Set the pah for test config file, label directory and weights CFG='/content/darknet/YOLO_Custom/yolov3-tiny_obj_test.cfg' label_dir='/content/darknet/YOLO_Custom/obj.names' #cfgpath=test_config_path Weights='/content/darknet/YOLO_Custom/yolov3-tiny_obj_train_tiny8.weights' Lables=get_labels(label_dir)
_____no_output_____
MIT
Notebook/YOLO_Mask_Adaptivity.ipynb
arpan65/Mask-Adaptivity-Detection-Computer-Vision-
Predict Image
from google.colab.patches import cv2_imshow img_path='/content/buckey.jpg' predict_image(img_path)
[INFO] loading YOLO from disk...
MIT
Notebook/YOLO_Mask_Adaptivity.ipynb
arpan65/Mask-Adaptivity-Detection-Computer-Vision-
Predict Video
input_path='/content/in.mp4' output_path='/content/out.mp4' predict_video(input_path,output_path)
processing.. [INFO] Cleaning up...
MIT
Notebook/YOLO_Mask_Adaptivity.ipynb
arpan65/Mask-Adaptivity-Detection-Computer-Vision-
Precision-Recall Curves in MulticlassFor multiclass classification, we have 2 options:- determine a PR curve for each class.- determine the overall PR curve as the micro-average of all classesLet's see how to do both.
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_wine from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.multiclass import OneVsRestClassifier ...
_____no_output_____
BSD-3-Clause
Section-03-Metrics/03-11-Precision-Recall-Curves-Multiclass.ipynb
Bhaskar-JR/machine-learning-imbalanced-data
Load data (multiclass)
# load data data = load_wine() data = pd.concat([ pd.DataFrame(data.data, columns=data.feature_names), pd.DataFrame(data.target, columns=['target']), ], axis=1) data.head() # target distribution: # multiclass and (fairly) balanced data.target.value_counts(normalize=True) # separate dataset into train and...
_____no_output_____
BSD-3-Clause
Section-03-Metrics/03-11-Precision-Recall-Curves-Multiclass.ipynb
Bhaskar-JR/machine-learning-imbalanced-data
Train ML modelsThe dataset we are using is very, extremely simple, so I am creating dumb models intentionally, that is few trees and very shallow for the random forests and few iterations for the logit. This is, so that we can get the most out of the PR curves by inspecting them visually. Random ForestsThe Random Fore...
# set up the model, wrapped by the OneVsRestClassifier rf = OneVsRestClassifier( RandomForestClassifier( n_estimators=10, random_state=39, max_depth=1, n_jobs=4, ) ) # train the model rf.fit(X_train, y_train) # produce the predictions (as probabilities) y_train_rf = rf.predict_proba(X_train) y_test_rf...
_____no_output_____
BSD-3-Clause
Section-03-Metrics/03-11-Precision-Recall-Curves-Multiclass.ipynb
Bhaskar-JR/machine-learning-imbalanced-data
Logistic RegressionThe Logistic regression supports 1 vs rest automatically though its multi_class parameter:
# set up the model logit = LogisticRegression( random_state=0, multi_class='ovr', max_iter=10, ) # train logit.fit(X_train, y_train) # obtain the probabilities y_train_logit = logit.predict_proba(X_train) y_test_logit = logit.predict_proba(X_test) # note that the predictions are an array of 3 columns # first co...
_____no_output_____
BSD-3-Clause
Section-03-Metrics/03-11-Precision-Recall-Curves-Multiclass.ipynb
Bhaskar-JR/machine-learning-imbalanced-data
Precision-Recall Curve Per class with Sklearn
# with label_binarize we transform the target vector # into a multi-label matrix, so that it matches the # outputs of the models # then we have 1 class per column y_test = label_binarize(y_test, classes=[0, 1, 2]) y_test[0:10, :] # now we determine the precision and recall at different thresholds # considering only...
_____no_output_____
BSD-3-Clause
Section-03-Metrics/03-11-Precision-Recall-Curves-Multiclass.ipynb
Bhaskar-JR/machine-learning-imbalanced-data
Go ahead and examine the precision and recall for the other classes see how these values change.
# now let's do these for all classes and capture the results in # dictionaries, so we can plot the values afterwards # determine the Precision and recall # at various thresholds of probability # in a 1 vs all fashion, for each class precision_rf = dict() recall_rf = dict() # for each class for i in range(3): ...
_____no_output_____
BSD-3-Clause
Section-03-Metrics/03-11-Precision-Recall-Curves-Multiclass.ipynb
Bhaskar-JR/machine-learning-imbalanced-data
We see that the Random Forest does a better job for all classes. Micro-average with sklearnIn order to do this, we concatenate all the probability vectors 1 after the other, and so we do with the real values.
# probability vectors for all classes in 1-d vector y_test_rf.ravel() # see that the unravelled prediction vector has 3 times the size # of the origina target len(y_test), len(y_test_rf.ravel()) # A "micro-average": quantifying score on all classes jointly # for random forests precision_rf["micro"], recall_rf["micro"...
_____no_output_____
BSD-3-Clause
Section-03-Metrics/03-11-Precision-Recall-Curves-Multiclass.ipynb
Bhaskar-JR/machine-learning-imbalanced-data
Yellowbrick Per class with Yellobrickhttps://www.scikit-yb.org/en/latest/api/classifier/prcurve.html**Note:**In the cells below, we are passing to Yellobrick classes a model that is already fit. When we fit() the Yellobrick class, it will check if the model is fit, in which case it will do nothing.If we pass a model t...
visualizer = PrecisionRecallCurve( rf, per_class=True, cmap="cool", micro=False, ) visualizer.fit(X_train, y_train) # Fit the training data to the visualizer visualizer.score(X_test, y_test) # Evaluate the model on the test data visualizer.show() # Finalize and show the figure v...
C:\Users\Sole\Documents\Repositories\envs\imbalanced\lib\site-packages\sklearn\linear_model\_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1): STOP: TOTAL NO. of ITERATIONS REACHED LIMIT. Increase the number of iterations (max_iter) or scale the data as shown in: https://scikit-learn.org/st...
BSD-3-Clause
Section-03-Metrics/03-11-Precision-Recall-Curves-Multiclass.ipynb
Bhaskar-JR/machine-learning-imbalanced-data
Micro yellowbrick
visualizer = PrecisionRecallCurve( rf, cmap="cool", micro=True, ) visualizer.fit(X_train, y_train) # Fit the training data to the visualizer visualizer.score(X_test, y_test) # Evaluate the model on the test data visualizer.show() # Finalize and show the figure visualizer = Preci...
C:\Users\Sole\Documents\Repositories\envs\imbalanced\lib\site-packages\sklearn\linear_model\_logistic.py:814: ConvergenceWarning: lbfgs failed to converge (status=1): STOP: TOTAL NO. of ITERATIONS REACHED LIMIT. Increase the number of iterations (max_iter) or scale the data as shown in: https://scikit-learn.org/st...
BSD-3-Clause
Section-03-Metrics/03-11-Precision-Recall-Curves-Multiclass.ipynb
Bhaskar-JR/machine-learning-imbalanced-data
**Goal of Environment:** "A car is on a one-dimensional track, positioned between two "mountains". The goal is to drive up the mountain on the right; however, the car's engine is not strong enough to scale the mountain in a single pass. Therefore, the only way to succeed is to drive back and forth to build up momentum....
#start server in terminal with $python gym_http_server.py #install.packages("gym") library(gym) #start server in terminal with $python gym_http_server.py remote_base <- "http://127.0.0.1:5000" client <- create_GymClient(remote_base) print(client) #create environment env_name <- "MountainCar-v0" #create instance instan...
[[1]] [1] -0.4617028 [[2]] [1] -0.001472405 [[1]] [1] -0.4941456 [[2]] [1] 0.0007852553 [[1]] [1] -0.5091516 [[2]] [1] 0.0008984122 [[1]] [1] -0.4069091 [[2]] [1] -0.001870572 [[1]] [1] -0.5272334 [[2]] [1] 0.001035021 [[1]] [1] -0.555347 [[2]] [1] 0.00124706 [[1]] [1] -0.4683965 [[2]] [1] 0.0005922543 [[...
MIT
Section 3/Monte Carlo R.ipynb
PacktPublishing/Practical-Reinforcement-Learning-Agents-and-Environments
Copyright 2017 Google LLC.
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the L...
_____no_output_____
Apache-2.0
ml/cc/exercises/synthetic_features_and_outliers.ipynb
direkshan-digital/eng-edu
Synthetic Features and Outliers **Learning Objectives:** * Create a synthetic feature that is the ratio of two other features * Use this new feature as an input to a linear regression model * Improve the effectiveness of the model by identifying and clipping (removing) outliers out of the input data Let's revisit o...
from __future__ import print_function import math from IPython import display from matplotlib import cm from matplotlib import gridspec import matplotlib.pyplot as plt import numpy as np import pandas as pd import sklearn.metrics as metrics import tensorflow as tf from tensorflow.python.data import Dataset tf.loggin...
_____no_output_____
Apache-2.0
ml/cc/exercises/synthetic_features_and_outliers.ipynb
direkshan-digital/eng-edu
Next, we'll set up our input function, and define the function for model training:
def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None): """Trains a linear regression model of one feature. Args: features: pandas DataFrame of features targets: pandas DataFrame of targets batch_size: Size of batches to be passed to the model shuffle: True or...
_____no_output_____
Apache-2.0
ml/cc/exercises/synthetic_features_and_outliers.ipynb
direkshan-digital/eng-edu
Task 1: Try a Synthetic FeatureBoth the `total_rooms` and `population` features count totals for a given city block.But what if one city block were more densely populated than another? We can explore how block density relates to median house value by creating a synthetic feature that's a ratio of `total_rooms` and `po...
# # YOUR CODE HERE # california_housing_dataframe["rooms_per_person"] = calibration_data = train_model( learning_rate=0.00005, steps=500, batch_size=5, input_feature="rooms_per_person" )
_____no_output_____
Apache-2.0
ml/cc/exercises/synthetic_features_and_outliers.ipynb
direkshan-digital/eng-edu
SolutionClick below for a solution.
california_housing_dataframe["rooms_per_person"] = ( california_housing_dataframe["total_rooms"] / california_housing_dataframe["population"]) calibration_data = train_model( learning_rate=0.05, steps=500, batch_size=5, input_feature="rooms_per_person")
_____no_output_____
Apache-2.0
ml/cc/exercises/synthetic_features_and_outliers.ipynb
direkshan-digital/eng-edu
Task 2: Identify OutliersWe can visualize the performance of our model by creating a scatter plot of predictions vs. target values. Ideally, these would lie on a perfectly correlated diagonal line.Use Pyplot's [`scatter()`](https://matplotlib.org/gallery/shapes_and_collections/scatter.html) to create a scatter plot o...
# YOUR CODE HERE
_____no_output_____
Apache-2.0
ml/cc/exercises/synthetic_features_and_outliers.ipynb
direkshan-digital/eng-edu
SolutionClick below for the solution.
plt.figure(figsize=(15, 6)) plt.subplot(1, 2, 1) plt.scatter(calibration_data["predictions"], calibration_data["targets"])
_____no_output_____
Apache-2.0
ml/cc/exercises/synthetic_features_and_outliers.ipynb
direkshan-digital/eng-edu
The calibration data shows most scatter points aligned to a line. The line is almost vertical, but we'll come back to that later. Right now let's focus on the ones that deviate from the line. We notice that they are relatively few in number.If we plot a histogram of `rooms_per_person`, we find that we have a few outlie...
plt.subplot(1, 2, 2) _ = california_housing_dataframe["rooms_per_person"].hist()
_____no_output_____
Apache-2.0
ml/cc/exercises/synthetic_features_and_outliers.ipynb
direkshan-digital/eng-edu
Task 3: Clip OutliersSee if you can further improve the model fit by setting the outlier values of `rooms_per_person` to some reasonable minimum or maximum.For reference, here's a quick example of how to apply a function to a Pandas `Series`: clipped_feature = my_dataframe["my_feature_name"].apply(lambda x: max(x, ...
# YOUR CODE HERE
_____no_output_____
Apache-2.0
ml/cc/exercises/synthetic_features_and_outliers.ipynb
direkshan-digital/eng-edu
SolutionClick below for the solution. The histogram we created in Task 2 shows that the majority of values are less than `5`. Let's clip `rooms_per_person` to 5, and plot a histogram to double-check the results.
california_housing_dataframe["rooms_per_person"] = ( california_housing_dataframe["rooms_per_person"]).apply(lambda x: min(x, 5)) _ = california_housing_dataframe["rooms_per_person"].hist()
_____no_output_____
Apache-2.0
ml/cc/exercises/synthetic_features_and_outliers.ipynb
direkshan-digital/eng-edu
To verify that clipping worked, let's train again and print the calibration data once more:
calibration_data = train_model( learning_rate=0.05, steps=500, batch_size=5, input_feature="rooms_per_person") _ = plt.scatter(calibration_data["predictions"], calibration_data["targets"])
_____no_output_____
Apache-2.0
ml/cc/exercises/synthetic_features_and_outliers.ipynb
direkshan-digital/eng-edu
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns train = pd.read_csv('/content/sample_data/california_housing_test.csv') test = pd.read_csv('/content/sample_data/california_housing_test.csv') train.head() test.head() train.describe() train.hist(figsize=(15,13) , grid=False ,...
_____no_output_____
MIT
test2.ipynb
AgingCurve/new-repository1
Analysis of QM files QCORR analysis including isomerization filter
# QCORR analysis of Gaussian 16 output files including isomerization check and generation of json files import os from aqme.qcorr import qcorr w_dir_main=os.getcwd()+'/QCORR_2' # run the QCORR analyzer, with: # 1) Working directory (w_dir_main=w_dir_main) # 2) Names of the QM output files (files='*.log') # 3) Detect ...
_____no_output_____
MIT
Example_workflows/QCORR_processing_QM_outputs/QCORR_Analysis_with_isomerization_check.ipynb
shreesowndarya/aqme
A motivating example: harmonic oscillator created by Yuying Liu, 11/02/2019
# imports import os import sys import torch import numpy as np import scipy as sp from scipy import integrate from tqdm.notebook import tqdm import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from mpl_toolkits.mplot3d import Axes3D import warnings warnings.filterwarnings('ignore') module_path = os...
_____no_output_____
MIT
scripts/.ipynb_checkpoints/motivating_example-checkpoint.ipynb
luckystarufo/multiscale_HiTS
simulation
np.random.seed(2) train_steps = 10000 test_steps = 2**15 n_train = 500 n_test = 50 n_steps = 5 dt = 0.002; n = 2 A = np.array([[0, -1], [1, 0]]) def harmonic_oscillator_rhs(x): # rhs of harmonic oscillator return A.dot(x) if load_data: # # # # # # # # # # # # # # # # # # # # # load simulated data fro...
_____no_output_____
MIT
scripts/.ipynb_checkpoints/motivating_example-checkpoint.ipynb
luckystarufo/multiscale_HiTS
visualize & load data
# load the data to dataset object datasets = list() step_sizes = list() print('Dt\'s: ') for i in range(2, 10): step_size = 2**i print(step_size * dt) step_sizes.append(step_size) datasets.append(net.VaryingStepDataSet(train_data, test_data, dt, n_steps=n_steps, step_size=step_size)) # # # # # # # # # ...
_____no_output_____
MIT
scripts/.ipynb_checkpoints/motivating_example-checkpoint.ipynb
luckystarufo/multiscale_HiTS
RKNN with varying timesteps
models = list() max_epoch=10000 if load_model: # load the model for step_size in step_sizes: models.append(torch.load(os.path.join(model_dir, 'model_D{}.pt'.format(step_size)), map_location='cpu')) # fix model consistencies trained on gpus (optional) for model in models: model.device = ...
_____no_output_____
MIT
scripts/.ipynb_checkpoints/motivating_example-checkpoint.ipynb
luckystarufo/multiscale_HiTS
Table 1
diff_scale_mse = torch.zeros(len(models)+1, len(step_sizes)) for i in range(len(models)): for j in range(len(step_sizes)): step_size = step_sizes[j] diff_scale_mse[i, j] = preds_mse[i][:, 0:5*step_size:step_size].mean() for j in range(len(step_sizes)): diff_scale_mse[-1, j] = multiscale...
_____no_output_____
MIT
scripts/.ipynb_checkpoints/motivating_example-checkpoint.ipynb
luckystarufo/multiscale_HiTS
Flow maps
xvalues, yvalues = np.meshgrid(np.arange(-1.0,1.0,0.02), np.arange(-1.0,1.0,0.02)) inits = np.stack([xvalues, yvalues], 2) t = [0.] + [10 * dt * step_size for step_size in step_sizes] flow = np.zeros((inits.shape[0], inits.shape[1], len(t), 2)) for i in range(inits.shape[0]): for j in range(inits.shape[1]): ...
_____no_output_____
MIT
scripts/.ipynb_checkpoints/motivating_example-checkpoint.ipynb
luckystarufo/multiscale_HiTS
Supervised training for RANS flows around airfoils Overview For this example of supervised trainingwe have a turbulent airflow around wing profiles, and we'd like to know the average motionand pressure distribution around this airfoil for different Reynolds numbers and angles of attack.Thus, given an airfoil shape, R...
# import numpy as np # import os.path, random # import torch # from torch.utils.data import Dataset # print("Torch version {}".format(torch.__version__)) # # get training data # dir = "./" # if True: # # download # if not os.path.isfile('data-airfoils.npz'): # import requests # print("Downloadi...
_____no_output_____
MIT
notebooks/supervised_airfoils_normalized.ipynb
gmshashank/Deep_Flow_Prediction
If you run this notebook in colab, the `else` statement above (which is deactivated by default) might be interesting for you: instead of downloading the training data anew every time, you can manually download it once and store it in your google drive. We assume it's stored in the root directory as `data-airfoils.npz`....
!git clone https://github.com/thunil/Deep-Flow-Prediction.git %cd /content/Deep-Flow-Prediction # Reduced data set with 6.4k samples plus test data (1.2GB) # https://dataserv.ub.tum.de/s/m1470791/download?path=%2F&files=data_6k.tar.gz import requests with open("data_6k.tar.gz", 'wb') as datafile: resp = requests.get...
_____no_output_____
MIT
notebooks/supervised_airfoils_normalized.ipynb
gmshashank/Deep_Flow_Prediction
Dataset generation using OpenFoam
# !git clone https://github.com/thunil/Deep-Flow-Prediction.git # !pip install torch numpy # # !apt-get install openfoam5 gmsh # %%bash # sh -c "wget -O - http://dl.openfoam.org/gpg.key | apt-key add -" # add-apt-repository http://dl.openfoam.org/ubuntu # apt-get update # apt-get -y install openfoam6 gmsh # %%bash # s...
_____no_output_____
MIT
notebooks/supervised_airfoils_normalized.ipynb
gmshashank/Deep_Flow_Prediction
RANS training dataNow we have some training data. In general it's very important to understand the data we're working with as much as possible (for any ML task the _garbage-in-gargabe-out_ principle definitely holds). We should at least understand the data in terms of dimensions and rough statistics, but ideally also ...
import pylab # helper to show three target channels: normalized, with colormap, side by side def showSbs(a1,a2, stats=False, bottom="NN Output", top="Reference", title=None): c=[] for i in range(3): b = np.flipud( np.concatenate((a2[i],a1[i]),axis=1).transpose()) min, mean, max = np.min(b), np.mean(b), np...
_____no_output_____
MIT
notebooks/supervised_airfoils_normalized.ipynb
gmshashank/Deep_Flow_Prediction
Next, let's define a small helper class `DfpDataset` to organize inputs and targets. We'll transfer the corresponding data to the pytorch `DataLoader` class. We also set up some globals to control training parameters, maybe most importantly: the learning rate `LR`, i.e. $\eta$ from the previous setions. When your train...
# # some global training constants # # number of training epochs # EPOCHS = 100 # # batch size # BATCH_SIZE = 10 # # learning rate # LR = 0.00002 # class DfpDataset(): # def __init__(self, inputs,targets): # self.inputs = inputs # self.targets = targets # def __len__(self): # return...
_____no_output_____
MIT
notebooks/supervised_airfoils_normalized.ipynb
gmshashank/Deep_Flow_Prediction