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
Laplacian Pyramid Gradient NormalizationThis looks better, but the resulting images mostly contain high frequencies. Can we improve it? One way is to add a smoothness prior into the optimization objective. This will effectively blur the image a little every iteration, suppressing the higher frequencies, so that the lo...
k = np.float32([1,4,6,4,1]) k = np.outer(k, k) k5x5 = k[:,:,None,None]/k.sum()*np.eye(3, dtype=np.float32) def lap_split(img): '''Split the image into lo and hi frequency components''' with tf.name_scope('split'): lo = tf.nn.conv2d(img, k5x5, [1,2,2,1], 'SAME') lo2 = tf.nn.conv2d_transpose(lo, ...
_____no_output_____
Apache-2.0
tensorflow/examples/tutorials/deepdream/deepdream.ipynb
espuer/tensorflow
Playing with feature visualizationsWe got a nice smooth image using only 10 iterations per octave. In case of running on GPU this takes just a few seconds. Let's try to visualize another channel from the same layer. The network can generate wide diversity of patterns.
render_lapnorm(T(layer)[:,:,:,65])
_____no_output_____
Apache-2.0
tensorflow/examples/tutorials/deepdream/deepdream.ipynb
espuer/tensorflow
Lower layers produce features of lower complexity.
render_lapnorm(T('mixed3b_1x1_pre_relu')[:,:,:,101])
_____no_output_____
Apache-2.0
tensorflow/examples/tutorials/deepdream/deepdream.ipynb
espuer/tensorflow
There are many interesting things one may try. For example, optimizing a linear combination of features often gives a "mixture" pattern.
render_lapnorm(T(layer)[:,:,:,65]+T(layer)[:,:,:,139], octave_n=4)
_____no_output_____
Apache-2.0
tensorflow/examples/tutorials/deepdream/deepdream.ipynb
espuer/tensorflow
DeepDreamNow let's reproduce the [DeepDream algorithm](https://github.com/google/deepdream/blob/master/dream.ipynb) with TensorFlow.
def render_deepdream(t_obj, img0=img_noise, iter_n=10, step=1.5, octave_n=4, octave_scale=1.4): t_score = tf.reduce_mean(t_obj) # defining the optimization objective t_grad = tf.gradients(t_score, t_input)[0] # behold the power of automatic differentiation! # split the image into a num...
_____no_output_____
Apache-2.0
tensorflow/examples/tutorials/deepdream/deepdream.ipynb
espuer/tensorflow
Let's load some image and populate it with DogSlugs (in case you've missed them).
img0 = PIL.Image.open('pilatus800.jpg') img0 = np.float32(img0) showarray(img0/255.0) render_deepdream(tf.square(T('mixed4c')), img0)
_____no_output_____
Apache-2.0
tensorflow/examples/tutorials/deepdream/deepdream.ipynb
espuer/tensorflow
Note that results can differ from the [Caffe](https://github.com/BVLC/caffe)'s implementation, as we are using an independently trained network. Still, the network seems to like dogs and animal-like features due to the nature of the ImageNet dataset.Using an arbitrary optimization objective still works:
render_deepdream(T(layer)[:,:,:,139], img0)
_____no_output_____
Apache-2.0
tensorflow/examples/tutorials/deepdream/deepdream.ipynb
espuer/tensorflow
Visualize project progress PrerequisitesFetch project experiment view (leaderboard).
from neptune.sessions import Session session = Session() project = session.get_projects('neptune-ml')['neptune-ml/Salt-Detection'] leadearboard = project.get_leaderboard()
_____no_output_____
MIT
docs/examples/project_progress.ipynb
david1309/neptune-contrib
Extract project progress informationUse the `extract_project_progress_info` function and specify your metric column and a timestamp column.
from neptunecontrib.api.utils import extract_project_progress_info progress_df = extract_project_progress_info(leadearboard, metric_colname='channel_IOUT', time_colname='finished') progress_df.head()
_____no_output_____
MIT
docs/examples/project_progress.ipynb
david1309/neptune-contrib
Visualize the project progressSimply use the `project_progress` visualization funcion.
from neptunecontrib.viz.projects import project_progress project_progress(progress_df, width=400, heights=[50, 200])
_____no_output_____
MIT
docs/examples/project_progress.ipynb
david1309/neptune-contrib
**[Introduction to Machine Learning Home Page](https://www.kaggle.com/learn/intro-to-machine-learning)**--- RecapHere's the code you've written so far.
# code you have previously used # load data import pandas as pd iowa_file_path = '../input/home-data-for-ml-course/train.csv' home_data = pd.read_csv(iowa_file_path) # create target object and call it y y = home_data['SalePrice'] # create X features = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'Bed...
Validation MAE when not specifying max_leaf_nodes: 29,653 Validation MAE for best value of max_leaf_nodes: 27,283 Setup complete
MIT
machine-learning-intro/exercise/random-forests.ipynb
hmdprs/data-scientist
ExercisesData science isn't always this easy. But replacing the decision tree with a Random Forest is going to be an easy win. Step 1: Use a Random Forest
from sklearn.ensemble import RandomForestRegressor # specify model. set random_state to 1 rf_model = RandomForestRegressor(random_state=1) # fit model rf_model.fit(train_X, train_y) # calculate the mean absolute error of your Random Forest model on the validation data val_ft_predictions = rf_model.predict(val_X) rf_...
_____no_output_____
MIT
machine-learning-intro/exercise/random-forests.ipynb
hmdprs/data-scientist
We will use this notebook to calculate and visualize statistics of our chess move dataset. This will allow us to better understand our limitations and help diagnose problems we may encounter down the road when training/defining our model.
import pdb import numpy as np import matplotlib.pyplot as plt %matplotlib inline def get_move_freqs(moves, sort=True): freq_dict = {} for move in moves: if move not in freq_dict: freq_dict[move] = 0 freq_dict[move] = freq_dict[move] + 1 tuples = [(w, c) for w, c in freq_dict.item...
_____no_output_____
MIT
notebooks/plot_move_frequency.ipynb
brannondorsey/ChessEmbeddings
Load our concatonated moves data.
with open('../data/train_moves.txt', 'r') as f: moves = f.read().split(' ') print('{} moves loaded'.format(len(moves))) counts, moves = get_move_freqs(moves) game_lengths, total_games = get_game_lengths(moves) # plot_repeat_states(moves)
_____no_output_____
MIT
notebooks/plot_move_frequency.ipynb
brannondorsey/ChessEmbeddings
Plot Move FrequencyHere we can see which moves appear most frequently in the dataset. These moves are the most popular moves played by chess champions.
plot_frequency(counts)
_____no_output_____
MIT
notebooks/plot_move_frequency.ipynb
brannondorsey/ChessEmbeddings
We will list the most common few moves along with what percentage of the entire moves dataset this move represents.
top_n = 10 for w in counts[0:top_n]: print((w[0]).ljust(8), '{:.2f}%'.format((w[1]/len(moves)) * 100.00))
O-O 2.00% Nf6 1.40% Nf3 1.31% d4 1.26% Nc3 1.15% d5 1.09% e4 1.09% c4 1.07% c5 1.01% e5 0.94%
MIT
notebooks/plot_move_frequency.ipynb
brannondorsey/ChessEmbeddings
Plot Unique MovesHere we compare the number of unique moves over the total move count. Take notice that the number of unique moves converges towards a constant as the number of total moves increase. This would suggest that there is a subset of all possible moves that actually make sense for a chess champion to play.
plot_uniq_over_count(moves)
_____no_output_____
MIT
notebooks/plot_move_frequency.ipynb
brannondorsey/ChessEmbeddings
Plot Game Lengths
plot_game_lengths(game_lengths) top_n = 10 sorted_lengths = sorted(game_lengths, key=lambda x: -x[1]) for l in sorted_lengths[0:top_n]: print((str(l[0])).ljust(8), '{:.3f}%'.format((l[1]/total_games) * 100.00))
82 2.684% 80 1.926% 84 1.843% 70 1.790% 78 1.784% 66 1.760% 68 1.747% 74 1.736% 76 1.725% 72 1.718%
MIT
notebooks/plot_move_frequency.ipynb
brannondorsey/ChessEmbeddings
Before you begin1. Have a GCP projrect ready. 3. [Enable Iam Recommender](https://console.cloud.google.com/flows/enableapi?apiid=recommender.googleapis.com) APIs for the project. Provide your credentials to the runtime
from google.colab import auth auth.authenticate_user() print('Authenticated')
_____no_output_____
Apache-2.0
iam_recommender_basics.ipynb
misabhishek/gcp-iam-recommender
Understand GCP IAM Recommender **Declare the Cloud project ID which will be used throughout this notebook**
project_id = "Enter-your-project"
_____no_output_____
Apache-2.0
iam_recommender_basics.ipynb
misabhishek/gcp-iam-recommender
**A helper function to execute `gcloud` commands**
import json import subprocess def execute_command(command): return json.loads(subprocess.check_output(filter(lambda x: x, command.split(" "))).decode("utf-8")) recommender_command = f"""gcloud recommender recommendations list \ --location=global \ --recommender=goog...
_____no_output_____
Apache-2.0
iam_recommender_basics.ipynb
misabhishek/gcp-iam-recommender
Getting insight for the recommendations
insight_command = f"""gcloud recommender insights list \ --project={project_id} \ --location=global \ --insight-type=google.iam.policy.Insight \ --format=json """ insights = execute_command(insight_command) insights[0]
_____no_output_____
Apache-2.0
iam_recommender_basics.ipynb
misabhishek/gcp-iam-recommender
Generate diff view
recommendation_name = "Enter-the-recommendation-name" #@title A helper to generate diff view. It uses IAM roles api also. import pandas as pd def generate_diff_view(recommendation_name): role_to_permission_command = "gcloud iam roles describe {} --format=json" recommendation = [r for r in recommendations if r["nam...
_____no_output_____
Apache-2.0
iam_recommender_basics.ipynb
misabhishek/gcp-iam-recommender
Analyze Text for PII EntitiesUsing Presidio Analyzer, analyze a text to identify PII entities. The Presidio analyzer is using pre-defined entity recognizers, and offers the option to create custom recognizers.The following code sample will:Set up the Analyzer engine - load the NLP module (spaCy model by default) and o...
text_to_anonymize = "His name is Mr. Jones and his phone number is 212-555-5555" analyzer = AnalyzerEngine() analyzer_results = analyzer.analyze(text=text_to_anonymize, entities=["PHONE_NUMBER"], language='en') print(analyzer_results)
_____no_output_____
MIT
docs/samples/python/presidio_notebook.ipynb
hkarakose/presidio
Create Custom PII Entity RecognizersPresidio Analyzer comes with a pre-defined set of entity recognizers. It also allows adding new recognizers without changing the analyzer base code,by creating custom recognizers. In the following example, we will create two new recognizers of type `PatternRecognizer` to identify ti...
titles_recognizer = PatternRecognizer(supported_entity="TITLE", deny_list=["Mr.","Mrs.","Miss"]) pronoun_recognizer = PatternRecognizer(supported_entity="PRONOUN", deny_list=["he", "He", "his", "His", "she", "She", "hers" "Hers"]) analyzer.re...
_____no_output_____
MIT
docs/samples/python/presidio_notebook.ipynb
hkarakose/presidio
Call Presidio Analyzer and get analyzed results with all the configured recognizers - default and new custom recognizers
analyzer_results = analyzer.analyze(text=text_to_anonymize, language='en') analyzer_results
_____no_output_____
MIT
docs/samples/python/presidio_notebook.ipynb
hkarakose/presidio
Anonymize Text with Identified PII EntitiesPresidio Anonymizer iterates over the Presidio Analyzer result, and provides anonymization capabilities for the identified text.The anonymizer provides 5 types of anonymizers - replace, redact, mask, hash and encrypt. The default is **replace**The following code sample will:S...
anonymizer = AnonymizerEngine() anonymized_results = anonymizer.anonymize( text=text_to_anonymize, analyzer_results=analyzer_results, anonymizers_config={"DEFAULT": AnonymizerConfig("replace", {"new_value": "<ANONYMIZED>"}), "PHONE_NUMBER": AnonymizerConfig("mask", {"type": "ma...
_____no_output_____
MIT
docs/samples/python/presidio_notebook.ipynb
hkarakose/presidio
ML/DL techniques for Tabular Modeling PART I> In this part, I have explained Decision Trees.- toc: true - badges: true- comments: true
#hide # !pip install -Uqq fastbook import fastbook fastbook.setup_book() #hide from fastbook import * from kaggle import api from pandas.api.types import is_string_dtype, is_numeric_dtype, is_categorical_dtype from fastai.tabular.all import * from sklearn.ensemble import RandomForestRegressor from sklearn.tree import ...
_____no_output_____
Apache-2.0
_notebooks/2020-11-10-DLforCNN.ipynb
nitishsaDire/dLBlog
IntroductionTabular Modelling takes data in the form of a table, where generally we want to learn about a column's value from all the other columns' values. The column we want to learn is known as a dependent variable and others are known as independent variables. The learning could be both like a classification probl...
df.head()
_____no_output_____
Apache-2.0
_notebooks/2020-11-10-DLforCNN.ipynb
nitishsaDire/dLBlog
The key fields are in train.csv are:- SalesID: the unique identifier of the sale- MachineID: the unique identifier of a machine. A machine can be sold multiple times- saleprice: what the machine sold for at auction (only provided in train.csv)- saledate: the date of the saleFor this competition, we need to predict the...
x = np.linspace(0, 10, 110) y = x + np.random.randn(110) my_list = [0]*30 + [1]*80 random.shuffle(my_list) my_list = [True if i==1 else False for i in my_list] tr_x, tr_y = x[np.where(my_list)[0]],y[np.where(my_list)[0]] my_list = [not elem for elem in my_list] val_x, val_y = x[np.where(my_list)[0]],y[np.where(my_list)...
_____no_output_____
Apache-2.0
_notebooks/2020-11-10-DLforCNN.ipynb
nitishsaDire/dLBlog
Underfitting CaseIn the underfitting case, I have set max_leaf_nodes=2, so that bias will be high.
m = DecisionTreeRegressor(max_leaf_nodes=2) m.fit(tr_x, tr_y); fig, ax = plt.subplots(figsize=(16,8)) ax.scatter(x,y, marker='+', label='actual data') ax.scatter(tr_x, m.predict(tr_x), label='predicted data on training dataset') ax.scatter(val_x, m.predict(val_x), label='predicted data on validation dataset') ax.xaxi...
_____no_output_____
Apache-2.0
_notebooks/2020-11-10-DLforCNN.ipynb
nitishsaDire/dLBlog
In the above example, I have generated a dataset with $x = y + \epsilon$, where $\epsilon \in N(0,1)$ is the random noise. I have generated this data because it's 2-d data, much simpler, and easy to visualize than the complex Kaggle dataset.A decision tree is implemented which tries to learn the relationship between x ...
print(f'Training rmse is {m_rmse(m, tr_x, tr_y)}, and validation rmse is {m_rmse(m, val_x, val_y)}') draw_tree(m, pd.DataFrame([tr_x,tr_y], columns=['tr_y']))
Training rmse is 1.6552681120862984, and validation rmse is 1.787770216476971
Apache-2.0
_notebooks/2020-11-10-DLforCNN.ipynb
nitishsaDire/dLBlog
Overfitting CaseIn the overfitting case, I have set max_leaf_nodes=100. This leads to a huge decision tree with each leaf node containing one training example only. Therefore, bias will be zero, the variance will be high and there will be overfitting.
m = DecisionTreeRegressor(max_leaf_nodes=100) m.fit(tr_x, tr_y); fig, ax = plt.subplots(figsize=(16,8)) ax.scatter(x,y, marker='+', label='actual data') ax.scatter(tr_x, m.predict(tr_x), label='predicted data on training dataset') ax.scatter(val_x, m.predict(val_x), label='predicted data on validation dataset') ax.xa...
Training rmse is 0.0, and validation rmse is 1.2925307400522905
Apache-2.0
_notebooks/2020-11-10-DLforCNN.ipynb
nitishsaDire/dLBlog
Balanced CaseIn the balanced case, I have set max_leaf_nodes=10. This leads to a nice decision tree implementation with better generalization power than both above cases, which could be confirmed by seeing training and validation losses.
m = DecisionTreeRegressor(max_leaf_nodes=10) m.fit(tr_x, tr_y); fig, ax = plt.subplots(figsize=(16,8)) ax.scatter(x,y, marker='+', label='actual data') ax.scatter(tr_x, m.predict(tr_x), label='predicted data on training dataset') ax.scatter(val_x, m.predict(val_x), label='predicted data on validation dataset') ax.xax...
_____no_output_____
Apache-2.0
_notebooks/2020-11-10-DLforCNN.ipynb
nitishsaDire/dLBlog
It seems like a good fit because it's neither overfitting nor underfitting. Below is the training and validation losses and complete decision tree as generated by the algorithm.
print(f'Training rmse is {m_rmse(m, tr_x, tr_y)}, and validation rmse is {m_rmse(m, val_x, val_y)}') draw_tree(m, pd.DataFrame([tr_x,tr_y], columns=['tr_y']))
Training rmse is 0.7629283571148474, and validation rmse is 1.0146270166850742
Apache-2.0
_notebooks/2020-11-10-DLforCNN.ipynb
nitishsaDire/dLBlog
Extrapolation problemThe decision tree suffers from a serious drawback when trying to predict them on data outside the domain of the current dataset. Suppose we have split the dataset into training and validation such as included the first 80 datapoints in the training and the remaining 30 datapoints in the validation...
m = DecisionTreeRegressor(max_leaf_nodes=10) tr_x, tr_y = x[:80], y[:80] val_x, val_y = x[80:], y[80:] tr_x = tr_x.reshape(80,1) val_x = val_x.reshape(30,1) m.fit(tr_x, tr_y); fig, ax = plt.subplots(figsize=(16,8)) ax.scatter(x,y, marker='+', label='actual data') ax.scatter(tr_x, m.predict(tr_x), label='predicted data ...
_____no_output_____
Apache-2.0
_notebooks/2020-11-10-DLforCNN.ipynb
nitishsaDire/dLBlog
Visualization principles1. Log scale2. Jitter3. Set the scale4. Text on plot
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import matplotlib as mpl
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
Plotting binary variablesNot directly connected to today's lesson. But many of you asked.Let look at a case were we have 2 binary variables: 'sex' and 'survived'
titanic = sns.load_dataset("titanic") titanic.head() titanic.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 891 entries, 0 to 890 Data columns (total 15 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 survived 891 non-null int64 1 pclass 891 non-null int64 2 sex 891 non-null object ...
MIT
vizualations.ipynb
NirNagary/DataS
Use a barplot (two variables) or a countplot (one variable)
sns.barplot(x="sex", y="survived", hue="class", data=titanic) plt.show() sns.countplot(x="sex", hue="class", data=titanic) plt.show()
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
Or use a catplot for categorical data:
sns.catplot(x="sex", y="survived", hue="class", kind="bar", data=titanic) plt.show() sns.catplot(x="sex", hue="class", kind="count", data=titanic) plt.show()
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
Log scale
diamonds = sns.load_dataset("diamonds") diamonds.head() sns.histplot(diamonds.price[diamonds.cut == 'Ideal'])
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
One option:
sns.histplot(diamonds.price[diamonds.cut == 'Ideal'], log_scale = True)
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
Another option:
sns.histplot(np.log2(diamonds.price[diamonds.cut == 'Ideal']))
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
Stack histogram:
sns.histplot( diamonds, x="price", hue="cut", multiple="stack", ) sns.set_theme(style="ticks") f, ax = plt.subplots(figsize=(7, 5)) sns.despine(f) sns.histplot( diamonds, x="price", hue="cut", multiple="stack", palette="colorblind", edgecolor=".3", linewidth=.5, log_scale =...
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
Jitter in pythonGoogle it: [Jitter in python](https://www.google.com/search?q=jitter+in+python&sxsrf=ALeKk01NFy18kBeX8CmyToZAT-l4YIlJeQ%3A1621252840686&ei=6FqiYPSmKYzdkwXckaGgCw&oq=jitter&gs_lcp=Cgdnd3Mtd2l6EAMYADIECCMQJzIFCAAQkQIyBQgAEMsBMgUIABDLATICCAAyAggAMgUIABDLATICCAAyAggAMgIIADoECAAQQzoFCAAQsQM6CAgAELEDEJECOggI...
tips = sns.load_dataset("tips") tips.head() sns.stripplot(x="day", y="total_bill", data=tips)
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
Use a smaller amount of jitter:
sns.stripplot(x="day", y="total_bill", data=tips, jitter=0.05)
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
Jitter plus a boxplot:
ax = sns.boxplot(x="tip", y="day", data=tips) ax = sns.stripplot(x="tip", y="day", data=tips, color=".3") ax = sns.boxplot(x="tip", y="day", data=tips)
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
Set the scaleGoogle it: [set scale seaborn](https://www.google.com/search?q=set+scale+seaborn&sxsrf=ALeKk02NiH79RWrRRXIqusuG-vHfuyIm2A%3A1621254123926&ei=61-iYOiGOMyxkwWAiZjICQ&oq=set+scale+sea&gs_lcp=Cgdnd3Mtd2l6EAMYADIECCMQJzIGCAAQFhAeMgYIABAWEB4yBggAEBYQHjoHCCMQsAMQJzoHCAAQRxCwAzoCCAA6BQghEKABOggIABAIEA0QHlC8EVjyJm...
ax = sns.stripplot(x="day", y="total_bill", data=tips, jitter=0.05) ax.set(ylim=(0, 100))
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
Another option:
plt.ylim(0, 400) ax = sns.stripplot(x="day", y="total_bill", data=tips, jitter=0.05)
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
Add labels onto the plotGoogle it: [add text to plot seaborn](https://www.google.com/search?q=add+text+to+plot+seaborn&sxsrf=ALeKk01vym2w-SfYoAOBXBgUbDCr0I04Uw%3A1621255993821&ei=OWeiYObWMdCTkwXRoIngCw&oq=add+text+to+plot+seaborn&gs_lcp=Cgdnd3Mtd2l6EAMyAggAMgYIABAWEB4yBggAEBYQHjoHCCMQsAMQJzoHCAAQRxCwAzoECAAQQzoGCAAQBx...
penguins = sns.load_dataset("penguins") penguins.head()
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
With a legend:
ax = sns.scatterplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue = 'species', palette = 'colorblind')
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
Without a legend but with text:
ax = sns.scatterplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue = 'species', palette = 'colorblind', legend=False) style = dict(size=12, color='black') ax.text(35, 15, "Adelie", **style) ax.text(55, 20, "Chinstrap", **style) ax.text(52, 14, "Gentoo", **style) plt.show()
_____no_output_____
MIT
vizualations.ipynb
NirNagary/DataS
This notebook will set up colab so that you can run the SYCL blur lab for the module "Introduction to SYCYL programming" created by the TOUCH project. (https://github.com/TeachingUndergradsCHC/modules/tree/master/Programming/sycl). The initial setup instructions are created following slides by Aksel Alpayhttps://www....
!apt update -qq; !apt-get update -qq; !add-apt-repository -y ppa:ubuntu-toolchain-r/test !apt update !apt install gcc-11 g++-11 !bash -c "$(wget -O - https://apt.llvm.org/llvm.sh)" !apt-get install libboost-all-dev libclang-13-dev cmake python -qq; !git clone --recurse-submodules https://github.com/illuhad/hipSYCL !apt...
_____no_output_____
CC-BY-4.0
Programming/sycl/syclBlur.ipynb
rkurniawati/modules
Now build hipSYCL
!mkdir hipSYCL_build %cd hipSYCL_build !export CC=/usr/bin/gcc-11 !export CXX=/usr/bin/g++-11 !cmake -DCMAKE_INSTALL_PREFIX=/content/hipSYCL_install -DCMAKE_C_COMPILER=/usr/bin/gcc-11 -DCMAKE_CXX_COMPILER=/usr/bin/g++-11 /content/hipSYCL !make install %cd ..
_____no_output_____
CC-BY-4.0
Programming/sycl/syclBlur.ipynb
rkurniawati/modules
Get the examples
!git clone https://github.com/TeachingUndergradsCHC/modules %cd modules/Programming/sycl
_____no_output_____
CC-BY-4.0
Programming/sycl/syclBlur.ipynb
rkurniawati/modules
Examine hello.cpp
!cat hello.cpp
_____no_output_____
CC-BY-4.0
Programming/sycl/syclBlur.ipynb
rkurniawati/modules
Now compile hello.cpp
!/content/hipSYCL_install/bin/syclcc --hipsycl-platform=cpu -o hello hello.cpp
_____no_output_____
CC-BY-4.0
Programming/sycl/syclBlur.ipynb
rkurniawati/modules
Then run it
!./hello
_____no_output_____
CC-BY-4.0
Programming/sycl/syclBlur.ipynb
rkurniawati/modules
Now try the addVector program, first view it
!cat addVectors.cpp
_____no_output_____
CC-BY-4.0
Programming/sycl/syclBlur.ipynb
rkurniawati/modules
Then compile it
!/content/hipSYCL_install/bin/syclcc --hipsycl-platform=cpu -o addVectors addVectors.cpp
_____no_output_____
CC-BY-4.0
Programming/sycl/syclBlur.ipynb
rkurniawati/modules
Finally run it
!./addVectors
_____no_output_____
CC-BY-4.0
Programming/sycl/syclBlur.ipynb
rkurniawati/modules
Next, examine the files that you'll need for the blur project. These are the library code for managing bmp files (stb_image.h and stb_image_write.h), the image that you'll be using (I provide 640x426.bmp, but you could use another file instead) and the program itself noRed.cpp. Then compile it
!/content/hipSYCL_install/bin/syclcc --hipsycl-platform=cpu -o noRed noRed.cpp
_____no_output_____
CC-BY-4.0
Programming/sycl/syclBlur.ipynb
rkurniawati/modules
Now run the code
!./noRed
_____no_output_____
CC-BY-4.0
Programming/sycl/syclBlur.ipynb
rkurniawati/modules
Original Image
from IPython.display import display from PIL import Image path="/content/modules/Programming/sycl/640x426.bmp" display(Image.open(path))
_____no_output_____
CC-BY-4.0
Programming/sycl/syclBlur.ipynb
rkurniawati/modules
Final Image
from IPython.display import display from PIL import Image path="/content/modules/Programming/sycl/out.bmp" display(Image.open(path))
_____no_output_____
CC-BY-4.0
Programming/sycl/syclBlur.ipynb
rkurniawati/modules
Classification of Chest and Abdominal X-rays Code Source: Lakhani, P., Gray, D.L., Pett, C.R. et al. J Digit Imaging (2018) 31: 283. https://doi.org/10.1007/s10278-018-0079-6The code to download and prepare dataset had been modified form the original source code.
# load requirements for the Keras library from keras import applications from keras.preprocessing.image import ImageDataGenerator from keras import optimizers from keras.models import Sequential from keras.layers import Dropout, Flatten, Dense, GlobalAveragePooling2D from keras.models import Model from keras.optimizers...
_____no_output_____
MIT
Classification_of_Chest_and_Abdominal_X_rays.ipynb
sabiipoks/AI-in-healthcare
Zesty AI Data Science Interview Task - Hadi Sotudeh To perform this task, I had access to the [`2009 RESIDENTIAL ENERGY CONSUMPTION SURVEY`](https://www.eia.gov/consumption/residential/data/2009/index.php?view=microdata) to predict `electricity consumption`.Libraries available in Python such as `scikit-learn` and `f...
%%capture # install dependencies !pip install fastai --upgrade # Import Libraries # general libraries import warnings import os from datetime import datetime from tqdm import tqdm_notebook as tqdm # machine learning libraries import pandas as pd import matplotlib import numpy as np import matplotlib.pyplot as plt fr...
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
Set Global parameters The electric consumption is located in the `KWH` field of the dataset.
#show plots inside the jupyter notebook %matplotlib inline # pandas settings to show more columns are rows in the jupyter notebook pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 50000) # don't show warnings warnings.filterwarnings('ignore') # dataset file path dataset = "recs2009_public....
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
Read the dataset from CSV files, Perform Data Cleaning, and Feature Engineering Following a typical machine learning project, I first clean up the dataset to prevent data-leakage related features or non-relevant features.It is important to mention that I did not first look at each column to figure out which feature to...
# read the train file df = pd.read_csv(dataset) # remove data-leakage and non-relevant features non_essential_features = ["KWHSPH","KWHCOL","KWHWTH","KWHRFG","KWHOTH","BTUEL","BTUELSPH","BTUELCOL", "BTUELWTH","BTUELRFG","BTUELOTH","DOLLAREL","DOLELSPH","DOLELCOL","DOLELWTH", ...
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
I created train and validation sets with random selection (80% vs.20% rule) from the dataset[link text](https://) file in the next step.
splits = RandomSplitter(valid_pct=0.2)(range_of(df)) procs = [Categorify, FillMissing] cont, cat = cont_cat_split(df, 1, dep_var=dep_var) to = TabularPandas(df, procs, cat, cont, y_names=dep_var, splits = splits)
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
The following cell shows 5 random instances of the dataset (after cleaning and feature engineering).
to.show(5)
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
Train the ML Model Since model interpretation is also important for me, I chose RandomForest for both prediction and interpretation and knowledge discovery.
def rf(xs, y, n_estimators=40, max_features=0.5, min_samples_leaf=5, **kwargs): "randomforst regressor" return RandomForestRegressor(n_jobs=-1, n_estimators=n_estimators, max_features=max_features, min_samples_leaf=min_samples_leaf, oob_score=True).fit(xs, y) xs,y = to.train.xs,to.train.y valid_xs,valid_y = to.vali...
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
The predictions are evaluated based on [Root-Mean-Squared-Error (RMSE) between the logarithm of the predicted value and the logarithm of the observed sales price](https://www.kaggle.com/c/house-prices-advanced-regression-techniques/overview/evaluation) (Taking logs means that errors in predicting high electricity consu...
def r_mse(pred,y): return round(math.sqrt(((pred-y)**2).mean()), 6) def m_rmse(m, xs, y): return r_mse(m.predict(xs), y)
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
Print the Mean Root Squared Error of the logarithmic `KWH` on the train set:
m_rmse(m, xs, y)
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
Print the Mean Root Squared Error of the logarithmic `KWH` on the validation set:
m_rmse(m, valid_xs, valid_y)
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
Calculate Feature Importance and remove non-important features and re-train the model.
def rf_feat_importance(m, df): return pd.DataFrame({'cols':df.columns, 'imp':m.feature_importances_}).sort_values('imp', ascending=False) # show the top 10 features fi = rf_feat_importance(m, xs) fi[:10]
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
Only keep features with importance of more than 0.005 for re-training.
to_keep = fi[fi.imp>0.005].cols print(f"features to keep are : {list(to_keep)}")
features to keep are : ['TOTALDOLOTH', 'PELHOTWA', 'TOTALDOLRFG', 'ACROOMS', 'FUELHEAT', 'TEMPHOMEAC', 'FUELH2O', 'TYPEHUQ', 'REGIONC', 'WASHLOAD', 'TEMPNITEAC', 'DRYRFUEL', 'PELHEAT', 'CDD30YR', 'USECENAC', 'CUFEETNG', 'TEMPGONEAC', 'CUFEETNGOTH', 'BEDROOMS', 'CUFEETNGWTH']
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
Some of the features to keep for re-training are:1. `TOTALDOLOTH`: Total cost for appliances, electronics, lighting, and miscellaneous2. `PELHOTWA`: Who pays for electricity used for water heating3. `ACROOMS`: Number of rooms cooled4. `TOTALDOLRFG`: Total cost for refrigerators, in whole dollars5. `REGIONC`: Census Reg...
xs_imp = xs[to_keep] valid_xs_imp = valid_xs[to_keep] m = rf(xs_imp, y)
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
Print the loss function of the re-trained model on train and validation sets.
m_rmse(m, xs_imp, y), m_rmse(m, valid_xs_imp, valid_y)
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
Check the correlation among the final features and adjust the set of features to remove at the beginning of the code.
from scipy.cluster import hierarchy as hc def cluster_columns(df, figsize=(10,6), font_size=12): corr = np.round(scipy.stats.spearmanr(df).correlation, 4) corr_condensed = hc.distance.squareform(1-corr) z = hc.linkage(corr_condensed, method='average') fig = plt.figure(figsize=figsize) hc.dendrogram...
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
Store the re-trained model.
joblib.dump(m, 'model.joblib')
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
Interpret the Model and Do Knowledge Discovery When I plot the feature importances of the trained model, I can clearly see that `TOTALDOLOTH` (Total cost for appliances, electronics, lighting, and miscellaneous uses in whole dollars) is the most important factor for the model to make its decisions.
def plot_fi(fi): return fi.plot('cols', 'imp', 'barh', figsize=(12,7), legend=False) plot_fi(rf_feat_importance(m, xs_imp));
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
In this section, I make use of the [Partial Dependence Plots](https://christophm.github.io/interpretable-ml-book/pdp.html) to interpret the learned function (ML model) and understand how this function makes decisions and predicts house prices for sale.The 1D-feature plots show by changing one unit (increase or decrease...
explore_cols = ['TOTALDOLOTH','TOTALDOLRFG','ACROOMS','TEMPHOMEAC','TEMPNITEAC','CDD30YR','CUFEETNGOTH','WASHLOAD','CUFEETNG'] explore_cols_vals = ["Total cost for appliances, electronics, lighting, and miscellaneous uses, in whole dollars", "Total cost for refrigerators, in whole dollars", ...
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
The 2D-feature plots show by changing one unit (increase or decrease) of the features shown in the x and y axes, how much the dependent variable changes.Here, the plot shows how much the model (learned function) changes its `log KWH` prediction on average when the two dimensions on the x and y axes change.
paired_features = [("TEMPNITEAC","TEMPHOMEAC"),("CUFEETNG","CUFEETNGOTH")] paired_features_vals = [("Temperature at night (summer)","Temperature when someone is home during the day (summer)"), ("Total Natural Gas usage, in hundred cubic feet","Natural Gas usage for other purposes (all end-uses e...
_____no_output_____
MIT
Zesty_AI_Data_Scientist_Assignment_|_Hadi_Sotudeh.ipynb
hadisotudeh/zestyAI_challenge
Day and Night Image Classifier---The day/night image dataset consists of 200 RGB color images in two categories: day and night. There are equal numbers of each example: 100 day images and 100 night images.We'd like to build a classifier that can accurately label these images as day or night, and that relies on finding...
import cv2 # computer vision library import helpers import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg %matplotlib inline
_____no_output_____
MIT
1_1_Image_Representation/6_5. Accuracy and Misclassification.ipynb
Abdulrahman-Adel/CVND-Exercises
Training and Testing DataThe 200 day/night images are separated into training and testing datasets. * 60% of these images are training images, for you to use as you create a classifier.* 40% are test images, which will be used to test the accuracy of your classifier.First, we set some variables to keep track of some w...
# Image data directories image_dir_training = "day_night_images/training/" image_dir_test = "day_night_images/test/"
_____no_output_____
MIT
1_1_Image_Representation/6_5. Accuracy and Misclassification.ipynb
Abdulrahman-Adel/CVND-Exercises
Load the datasetsThese first few lines of code will load the training day/night images and store all of them in a variable, `IMAGE_LIST`. This list contains the images and their associated label ("day" or "night"). For example, the first image-label pair in `IMAGE_LIST` can be accessed by index: ``` IMAGE_LIST[0][:]``...
# Using the load_dataset function in helpers.py # Load training data IMAGE_LIST = helpers.load_dataset(image_dir_training)
_____no_output_____
MIT
1_1_Image_Representation/6_5. Accuracy and Misclassification.ipynb
Abdulrahman-Adel/CVND-Exercises
Construct a `STANDARDIZED_LIST` of input images and output labels.This function takes in a list of image-label pairs and outputs a **standardized** list of resized images and numerical labels.
# Standardize all training images STANDARDIZED_LIST = helpers.standardize(IMAGE_LIST)
_____no_output_____
MIT
1_1_Image_Representation/6_5. Accuracy and Misclassification.ipynb
Abdulrahman-Adel/CVND-Exercises
Visualize the standardized dataDisplay a standardized image from STANDARDIZED_LIST.
# Display a standardized image and its label # Select an image by index image_num = 0 selected_image = STANDARDIZED_LIST[image_num][0] selected_label = STANDARDIZED_LIST[image_num][1] # Display image and data about it plt.imshow(selected_image) print("Shape: "+str(selected_image.shape)) print("Label [1 = day, 0 = nig...
Shape: (600, 1100, 3) Label [1 = day, 0 = night]: 1
MIT
1_1_Image_Representation/6_5. Accuracy and Misclassification.ipynb
Abdulrahman-Adel/CVND-Exercises
Feature ExtractionCreate a feature that represents the brightness in an image. We'll be extracting the **average brightness** using HSV colorspace. Specifically, we'll use the V channel (a measure of brightness), add up the pixel values in the V channel, then divide that sum by the area of the image to get the average...
# Find the average Value or brightness of an image def avg_brightness(rgb_image): # Convert image to HSV hsv = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV) # Add up all the pixel values in the V channel sum_brightness = np.sum(hsv[:,:,2]) area = 600*1100.0 # pixels # find the avg avg = ...
Avg brightness: 35.217
MIT
1_1_Image_Representation/6_5. Accuracy and Misclassification.ipynb
Abdulrahman-Adel/CVND-Exercises
Classification and Visualizing ErrorIn this section, we'll turn our average brightness feature into a classifier that takes in a standardized image and returns a `predicted_label` for that image. This `estimate_label` function should return a value: 0 or 1 (night or day, respectively). --- TODO: Build a complete class...
# This function should take in RGB image input def estimate_label(rgb_image): # Extract average brightness feature from an RGB image avg = avg_brightness(rgb_image) # Use the avg brightness feature to predict a label (0, 1) predicted_label = 0 threshold = 100 if(avg > threshold): ...
_____no_output_____
MIT
1_1_Image_Representation/6_5. Accuracy and Misclassification.ipynb
Abdulrahman-Adel/CVND-Exercises
Testing the classifierHere is where we test your classification algorithm using our test set of data that we set aside at the beginning of the notebook!Since we are using a pretty simple brightess feature, we may not expect this classifier to be 100% accurate. We'll aim for around 75-85% accuracy usin this one feature...
import random # Using the load_dataset function in helpers.py # Load test data TEST_IMAGE_LIST = helpers.load_dataset(image_dir_test) # Standardize the test data STANDARDIZED_TEST_LIST = helpers.standardize(TEST_IMAGE_LIST) # Shuffle the standardized test data random.shuffle(STANDARDIZED_TEST_LIST)
_____no_output_____
MIT
1_1_Image_Representation/6_5. Accuracy and Misclassification.ipynb
Abdulrahman-Adel/CVND-Exercises
Determine the AccuracyCompare the output of your classification algorithm (a.k.a. your "model") with the true labels and determine the accuracy.This code stores all the misclassified images, their predicted labels, and their true labels, in a list called `misclassified`.
# Constructs a list of misclassified images given a list of test images and their labels def get_misclassified_images(test_images): # Track misclassified images by placing them into a list misclassified_images_labels = [] # Iterate through all the test images # Classify each image and compare to the tr...
Accuracy: 0.925 Number of misclassified images = 12 out of 160
MIT
1_1_Image_Representation/6_5. Accuracy and Misclassification.ipynb
Abdulrahman-Adel/CVND-Exercises
--- Visualize the misclassified imagesVisualize some of the images you classified wrong (in the `MISCLASSIFIED` list) and note any qualities that make them difficult to classify. This will help you identify any weaknesses in your classification algorithm.
# Visualize misclassified example(s) num = 0 test_mis_im = MISCLASSIFIED[num][0] ## TODO: Display an image in the `MISCLASSIFIED` list plt.imshow(test_mis_im) ## TODO: Print out its predicted label - ## to see what the image *was* incorrectly classified as print("Misslabeled as: ",MISCLASSIFIED[num][1])
Misslabeled as: 0
MIT
1_1_Image_Representation/6_5. Accuracy and Misclassification.ipynb
Abdulrahman-Adel/CVND-Exercises
Bengaluru House Price
import numpy as np import pandas as pd import matplotlib.pyplot as plt pd.set_option("display.max_rows", None, "display.max_columns", None) df1=pd.read_csv("Dataset/Bengaluru_House_Data.csv") df1.head()
_____no_output_____
MIT
model/Real State Price prediction.ipynb
Rishikeshrajrxl/Real_State_Price_Estimator_Model
Data Cleaning
df1.info() df1.isnull().sum() df1.groupby('area_type')['area_type'].agg('count') df2=df1.drop(['area_type','availability','society','balcony'], axis='columns') df2.head() df2.isnull().sum() df2.shape df2['location'].fillna(df2['location'].mode().values[0],inplace=True) df2['size'].fillna(df2['size'].mode().values[0],in...
_____no_output_____
MIT
model/Real State Price prediction.ipynb
Rishikeshrajrxl/Real_State_Price_Estimator_Model
Dimension Reduction
def infloat(x): try: float(x) except: return False return True df2[~df2['total_sqft'].apply(infloat)].head(10) def convert(x): token=x.split('-') if(len(token)==2): return (float(token[0])+float(token[1]))/2 try: return float(x) except: return 16...
_____no_output_____
MIT
model/Real State Price prediction.ipynb
Rishikeshrajrxl/Real_State_Price_Estimator_Model
Copyright 2019 The TensorFlow Authors.
#@title 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...
_____no_output_____
Apache-2.0
site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb
minamstar/docs-l10n
Multi-worker training with Keras View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook OverviewThis tutorial demonstrates multi-worker distributed training with Keras model using `tf.distribute.Strategy` API, specifically `tf.distribute.MultiWorkerMirroredStrat...
import json import os import sys
_____no_output_____
Apache-2.0
site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb
minamstar/docs-l10n
Before importing TensorFlow, make a few changes to the environment.Disable all GPUs. This prevents errors caused by the workers all trying to use the same GPU. For a real application each worker would be on a different machine.
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
_____no_output_____
Apache-2.0
site/en-snapshot/tutorials/distribute/multi_worker_with_keras.ipynb
minamstar/docs-l10n