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 |
|---|---|---|---|---|---|
**Expected Output**: **out** [ 0.94822985 0. 1.16101444 2.747859 0. 1.36677003] 2.2 - The convolutional blockThe ResNet "convolutional block" is the second block type. You can use this type of block when the input and output dimensions... | def convolutional_block(X, f, filters, stage, block, s = 2):
"""
Implementation of the convolutional block as defined in Figure 4
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for the main path
filters ... | out = [ 0.09018463 1.23489773 0.46822017 0.0367176 0. 0.65516603]
| MIT | Convolutional Neural Networks/Residual_Networks_v2a.ipynb | joyfinder/Deep_Learning_Specialisation |
**Expected Output**: **out** [ 0.09018463 1.23489773 0.46822017 0.0367176 0. 0.65516603] 3 - Building your first ResNet model (50 layers)You now have the necessary blocks to build a very deep ResNet. The following figure describes in detail the... | # GRADED FUNCTION: ResNet50
def ResNet50(input_shape = (64, 64, 3), classes = 6):
"""
Implementation of the popular ResNet50 the following architecture:
CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3
-> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGP... | _____no_output_____ | MIT | Convolutional Neural Networks/Residual_Networks_v2a.ipynb | joyfinder/Deep_Learning_Specialisation |
Run the following code to build the model's graph. If your implementation is not correct you will know it by checking your accuracy when running `model.fit(...)` below. | model = ResNet50(input_shape = (64, 64, 3), classes = 6) | _____no_output_____ | MIT | Convolutional Neural Networks/Residual_Networks_v2a.ipynb | joyfinder/Deep_Learning_Specialisation |
As seen in the Keras Tutorial Notebook, prior training a model, you need to configure the learning process by compiling the model. | model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) | _____no_output_____ | MIT | Convolutional Neural Networks/Residual_Networks_v2a.ipynb | joyfinder/Deep_Learning_Specialisation |
The model is now ready to be trained. The only thing you need is a dataset. Let's load the SIGNS Dataset. **Figure 6** : **SIGNS dataset** | X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()
# Normalize image vectors
X_train = X_train_orig/255.
X_test = X_test_orig/255.
# Convert training and test labels to one hot matrices
Y_train = convert_to_one_hot(Y_train_orig, 6).T
Y_test = convert_to_one_hot(Y_test_orig, 6).T
print ("n... | number of training examples = 1080
number of test examples = 120
X_train shape: (1080, 64, 64, 3)
Y_train shape: (1080, 6)
X_test shape: (120, 64, 64, 3)
Y_test shape: (120, 6)
| MIT | Convolutional Neural Networks/Residual_Networks_v2a.ipynb | joyfinder/Deep_Learning_Specialisation |
Run the following cell to train your model on 2 epochs with a batch size of 32. On a CPU it should take you around 5min per epoch. | model.fit(X_train, Y_train, epochs = 2, batch_size = 32) | Epoch 1/2
1080/1080 [==============================] - 265s - loss: 2.5033 - acc: 0.3380
Epoch 2/2
1080/1080 [==============================] - 259s - loss: 1.3300 - acc: 0.6204
| MIT | Convolutional Neural Networks/Residual_Networks_v2a.ipynb | joyfinder/Deep_Learning_Specialisation |
**Expected Output**: ** Epoch 1/2** loss: between 1 and 5, acc: between 0.2 and 0.5, although your results can be different from ours. ** Epoch 2/2** loss: between 1 and 5, acc: between 0.2 and 0.5, you should ... | preds = model.evaluate(X_test, Y_test)
print ("Loss = " + str(preds[0]))
print ("Test Accuracy = " + str(preds[1])) | 120/120 [==============================] - 9s
Loss = 13.2004664103
Test Accuracy = 0.166666667163
| MIT | Convolutional Neural Networks/Residual_Networks_v2a.ipynb | joyfinder/Deep_Learning_Specialisation |
**Expected Output**: **Test Accuracy** between 0.16 and 0.25 For the purpose of this assignment, we've asked you to train the model for just two epochs. You can see that it achieves poor performances. Please go ahead and submit your assignment; to check corre... | model = load_model('ResNet50.h5')
preds = model.evaluate(X_test, Y_test)
print ("Loss = " + str(preds[0]))
print ("Test Accuracy = " + str(preds[1])) | 120/120 [==============================] - 9s
Loss = 0.530178320408
Test Accuracy = 0.866666662693
| MIT | Convolutional Neural Networks/Residual_Networks_v2a.ipynb | joyfinder/Deep_Learning_Specialisation |
ResNet50 is a powerful model for image classification when it is trained for an adequate number of iterations. We hope you can use what you've learnt and apply it to your own classification problem to perform state-of-the-art accuracy.Congratulations on finishing this assignment! You've now implemented a state-of-the-a... | img_path = 'images/my_image.jpg'
img = image.load_img(img_path, target_size=(64, 64))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = x/255.0
print('Input image shape:', x.shape)
my_image = scipy.misc.imread(img_path)
imshow(my_image)
print("class prediction vector [p(0), p(1), p(2), p(3), p(4), p(5)] = "... | Input image shape: (1, 64, 64, 3)
class prediction vector [p(0), p(1), p(2), p(3), p(4), p(5)] =
[[ 3.41876671e-06 2.77412561e-04 9.99522924e-01 1.98842812e-07
1.95619068e-04 4.11686671e-07]]
| MIT | Convolutional Neural Networks/Residual_Networks_v2a.ipynb | joyfinder/Deep_Learning_Specialisation |
You can also print a summary of your model by running the following code. | model.summary() | ____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================================
input_1 (InputLay... | MIT | Convolutional Neural Networks/Residual_Networks_v2a.ipynb | joyfinder/Deep_Learning_Specialisation |
Finally, run the code below to visualize your ResNet50. You can also download a .png picture of your model by going to "File -> Open...-> model.png". | plot_model(model, to_file='model.png')
SVG(model_to_dot(model).create(prog='dot', format='svg')) | _____no_output_____ | MIT | Convolutional Neural Networks/Residual_Networks_v2a.ipynb | joyfinder/Deep_Learning_Specialisation |
Plotting is Back | %matplotlib inline
from massinference.plot import Limits
from massinference.map import KappaMap, ShearMap
import matplotlib.pyplot as plt
limits = Limits(1.8, 1.65, -2.0, -1.9)
plot_config = KappaMap.default().plot(limits=limits)
ShearMap.default().plot(plot_config=plot_config) | _____no_output_____ | MIT | GroupMeeting12_5_16.ipynb | davidthomas5412/PanglossNotebooks |
Rearchitected MassInference Benchmarking Benchmark- 36 square arcmin field- 10 source objects / arcmin- lightcnoe radius of 4 arcmins- no relevance filtering- no smooth kappas- 4 independent samples- no setup/io/etc, timer starts after objects initialized Pangloss ... 214.165 seconds MassInference ... 1.082 seconds ... | import numpy as np
x = np.random.rand(10**8)
%timeit -n 1 -r 1 np.isnan(x)
%timeit -n 1 -r 1 np.isnan(np.sum(x))
%timeit -n 1 -r 1 np.sum(-x)
%timeit -n 1 -r 1 (-np.sum(x)) | 1 loop, best of 1: 6.02 s per loop
1 loop, best of 1: 1.51 s per loop
| MIT | GroupMeeting12_5_16.ipynb | davidthomas5412/PanglossNotebooks |
Table of Contents1 Data2 Model3 Training4 Explore Latent Space | import sys
import yaml
import tensorflow as tf
import numpy as np
import pandas as pd
import functools
from pathlib import Path
from datetime import datetime
from tqdm import tqdm_notebook as tqdm
# Plotting
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation
plt.rcParams['animation.ffmp... | _____no_output_____ | Apache-2.0 | deep learning/GAN/DCGAN.ipynb | sugatoray/data-science-learning |
Data | # load Fashion MNIST dataset
((X_train, y_train), (X_test, y_test)) = tf.keras.datasets.fashion_mnist.load_data()
X_train = preprocess_images(X_train)
X_test = preprocess_images(X_test)
print(X_train[0].shape)
print(X_train[0].max())
print(X_train[0].min())
print(X_train.shape)
assert X_train[0].shape == tuple(confi... | _____no_output_____ | Apache-2.0 | deep learning/GAN/DCGAN.ipynb | sugatoray/data-science-learning |
Model | # instantiate GAN
gan = dcgan.DCGan(IMG_SHAPE, config)
# test generator
generator_out = gan.generator.predict(np.random.randn(BATCH_SIZE, HIDDEN_DIM))
generator_out.shape
# test discriminator
discriminator_out = gan.discriminator.predict(generator_out)
discriminator_out.shape
# test gan
gan.gan.predict(np.random.randn(... | _____no_output_____ | Apache-2.0 | deep learning/GAN/DCGAN.ipynb | sugatoray/data-science-learning |
Training | # setup model directory for checkpoint and tensorboard logs
model_name = "dcgan_celeba"
model_dir = Path.home() / "Documents/models/tf_playground/gan" / model_name
model_dir.mkdir(exist_ok=True, parents=True)
export_dir = model_dir / 'export'
export_dir.mkdir(exist_ok=True)
log_dir = model_dir / "logs" / datetime.now()... | _____no_output_____ | Apache-2.0 | deep learning/GAN/DCGAN.ipynb | sugatoray/data-science-learning |
Explore Latent Space | %matplotlib inline
def gen_image_fun(latent_vectors):
img = gan.generator.predict(latent_vectors)[0].reshape(PLOT_IMG_SHAPE)
return img
img = gen_image_fun(z_s)
render_dir = Path.home() / 'Documents/videos/gan' / "gan_celeba"
nb_samples = 10
nb_transition_frames = 10
nb_frames = min(2000, (nb_samples-1)*nb_tra... | _____no_output_____ | Apache-2.0 | deep learning/GAN/DCGAN.ipynb | sugatoray/data-science-learning |
ReferencesKoGPT3 shares the same structure as KoGPT2. - [KoGPT2-Transformers huggingface 활용 예시](https://github.com/taeminlee/KoGPT2-Transformers) | from transformers import GPT2Tokenizer, PreTrainedTokenizerFast
model_dir = "skt/ko-gpt-trinity-1.2B-v0.5"
# Load the Tokenizer: "Fast" means that the tokenizer code is written in Rust Lang
tokenizer = PreTrainedTokenizerFast.from_pretrained(
model_dir,
bos_token="<s>",
eos_token="</s>",
unk_token="<u... | Generated Sequence | Number 0 : 이 편지는 영국에서 최초로 시작되어 일년에 한바퀴 돌면서 받는 사람에게 행운을 주었고 지금은 당신에게로 옮겨진 이 편지는 이 지구 상의 모든 사람에게 복을 주는 것이 된다. 이 편지는 그 내용이 진실되고 당신이 다른 사람에게 복을 주기를 바라는 마음이 담겨져 있다. 그리고 당신의 친구들은 이 편지를 읽고 당신의 행운을 기원해주며 당신에게 다시 연락한다. 마지막으로 당신의 친구들은 이 편지를 읽을 때마다 복을 받길 기원하며 당신에게 행운을 가져다 줄 것이다. 이 우체통에 넣은 편지는 당신이 한밤중에 받아도 좋을 ... | MIT | inference_without_finetune_kogpt_trinity.ipynb | snoop2head/KoGPT-Joong-2 |
Suport Vector clustering let us learn how to work on svm in sk learn | import pandas as pd
from sklearn.datasets import load_iris
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
#importing necessary libraries
#loading the iris data set from the sklearn library
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris... | _____no_output_____ | BSD-3-Clause | svc/SVC.ipynb | aswathyaa/Acharya-MachineLearning |
new dataframe with one column from each VM | new_df = pd.DataFrame()
for index in range(len(dataframes)):
diter = dataframes[index]
new_df[['net_write_' + diter.dataframeName]] = diter[['net_write']]
print(new_df.shape)
df = new_df
df.describe()
df.index
df.dtypes
df.head() | _____no_output_____ | Apache-2.0 | time_series/materna_dataset/Materna_PCA.ipynb | sanjosh/machine_learning |
Inf columns | df.columns.to_series()[np.isinf(df).any()]
df.index[np.isinf(df).any(1)]
import numpy as np
df.replace([np.inf, -np.inf], np.nan)
| _____no_output_____ | Apache-2.0 | time_series/materna_dataset/Materna_PCA.ipynb | sanjosh/machine_learning |
Null columns | df.isnull().values.any()
df[df.isnull().any(axis=1)]
df = df.interpolate( axis='columns')
df.dropna()
df.shape | _____no_output_____ | Apache-2.0 | time_series/materna_dataset/Materna_PCA.ipynb | sanjosh/machine_learning |
mean throughput over time per VM | ax = df.mean().plot(grid=False)
### mean throughput across VMs at any time
ax = df.T.mean().plot(grid=False)
| _____no_output_____ | Apache-2.0 | time_series/materna_dataset/Materna_PCA.ipynb | sanjosh/machine_learning |
multivariate PCAhttps://www.statsmodels.org/stable/examples/notebooks/generated/pca_fertility_factors.html | import statsmodels.api as sm
from statsmodels.multivariate.pca import PCA
pca_model = PCA(df, standardize=False, demean=True)
fig = pca_model.plot_scree(log_scale=False)
%matplotlib inline
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4))
lines = ax.plot(pca_model.factors.iloc[:,:3], lw=4, alp... | _____no_output_____ | Apache-2.0 | time_series/materna_dataset/Materna_PCA.ipynb | sanjosh/machine_learning |
Linear Regression with Db2 Stored Procedures Contents:* [1. Introduction](Introduction)* [2. Libraries and Modules](Libraries-and-Modules)* [3. Connect to Db2](Connect-to-Db2)* [4. Data exploration](Data-exploration)* [5. Train/Test Split](Train/Test-Split)* [6. Data transformation](Data-transformation-after-Train/Te... | import os
import sys
module_path = os.path.abspath(os.path.join('../lib/'))
if module_path not in sys.path:
sys.path.append(module_path)
import ibm_db
import ibm_db_dbi
# import ibm_db_sa
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from InDBMLModules import col_to_row_organize, print_mult... | _____no_output_____ | Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
3. Connect to Db2 | conn_str = "DATABASE=in_db;" + \
"HOSTNAME=*********************;"+ \
"PROTOCOL=TCPIP;" + \
"PORT=*******;" + \
"UID=***;" + \
"PWD=******************;"
ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=True)
rc = close_connection_to_db(ibm_db_conn, v... | Connected to the database!
Connection is closed.
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
4. Data exploration Create a special schema for this experiment | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
drop_object("LINREG", "SCHEMA", ibm_db_conn, verbose = True)
sql ="create schema LINREG authorization MLP"
stmt = ibm_db.exec_immediate(ibm_db_conn, sql)
print("Schema LINREG was created.")
rc = close_connection_to_db(ibm_db_conn, verbose=False) | Pre-existing SCHEMA LINREG was not found.
Schema LINREG was created.
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Collect statistics on the entire dataset by creating the column properties table | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
drop_object("LINREG.GS_COL_PROP", "TABLE", ibm_db_conn, verbose = True)
sql = """CALL IDAX.COLUMN_PROPERTIES('intable=DATA.GO_SALES, outtable=LINREG.GS_COL_PROP, withstatistics=true, incolumn=ID:id; PURCHASE_AMOUNT:target')"""
stmt = ibm_db.exec_imm... | Pre-existing TABLE LINREG.GS_COL_PROP was not found.
TABLE LINREG.GS_COL_PROP was created.
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
List columns with any nulls | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
sql = "select COLNO, NAME, TYPE,NUMMISSING,NUMMISSING+NUMINVALID+NUMVALID as ALL_VALUES, dec(NUMMISSING,10,2)/(dec(NUMMISSING, 10,2)+dec(NUMINVALID, 10,2)+dec(NUMVALID, 10,2))*100 as NULL_PERCENTAGE from LINREG.GS_COL_PROP where NUMMISSING > 0"
GS_N... | Column properties table fetched successfully!
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Evaluate CONTINIOUS columns using RUNSTATS Plot distribution based on runstats results | numerical_columns = ["AGE"]
plot_histogram (numerical_columns,"DATA","GO_SALES",conn_str) | _____no_output_____ | Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Evaluate NOMINAL columns using RUNSTATS Plot data distribution for nominal columns | nominal_columns = ["GENDER","MARITAL_STATUS","PROFESSION","PRODUCT_LINE","IS_TENT"]
plot_barchart (nominal_columns, "DATA", "GO_SALES", conn_str) | _____no_output_____ | Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Check data skewness using SUMMARY1000 stored procedure | # Create HOUSING_PRICES_SUM1000 table that contains whole dataset feature stats (mean, stdev, freq, etc)
ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
drop_object("LINREG.GO_SALES_SUM1000", "TABLE", ibm_db_conn, verbose = True)
drop_object("LINREG.GO_SALES_SUM1000_CHAR", "TABLE", ibm_db_conn, ... | Pre-existing TABLE LINREG.GO_SALES_SUM1000 was not found.
Pre-existing TABLE LINREG.GO_SALES_SUM1000_CHAR was not found.
Pre-existing TABLE LINREG.GO_SALES_SUM1000_NUM was not found.
SUM1000 tables were created.
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
**Observation:**SKEWNESS on numerical columns is negligible. 5. Train/Test Split | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
drop_object("LINREG.GSTRAIN", "TABLE", ibm_db_conn, verbose = True)
drop_object("LINREG.GSTEST", "TABLE", ibm_db_conn, verbose = True)
sql = "CALL IDAX.SPLIT_DATA('intable = DATA.GO_SALES, id = ID, traintable = LINREG.GSTRAIN, testtable = LINREG.GS... | Pre-existing TABLE LINREG.GSTRAIN was not found.
Pre-existing TABLE LINREG.GSTEST was not found.
Dataset splitting was successful!
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
6. Data transformation Get statistics of the train data to be used for transforming the test data Create the SUMMARY1000 table for training dataset | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
drop_object("LINREG.GSTRAIN_STATS", "TABLE", ibm_db_conn, verbose = True)
drop_object("LINREG.GSTRAIN_STATS_NUM", "TABLE", ibm_db_conn, verbose = True)
drop_object("LINREG.GSTRAIN_STATS_CHAR", "TABLE", ibm_db_conn, verbose = True)
sql = """... | Pre-existing TABLE LINREG.GSTRAIN_STATS was not found.
Pre-existing TABLE LINREG.GSTRAIN_STATS_NUM was not found.
Pre-existing TABLE LINREG.GSTRAIN_STATS_CHAR was not found.
LINREG.GSTRAIN_STATS, LINREG.GSTRAIN_STATS_NUM, and LINREG.GSTRAIN_STATS_CHAR were created
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Null imputation Null impute NUMERICAL columns in TRAINING data with mean | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
sql = """CALL IDAX.IMPUTE_DATA('intable=LINREG.GSTRAIN,method=mean,inColumn=AGE');"""
stmt = ibm_db.exec_immediate(ibm_db_conn, sql)
print("AGE in LINREG.GSTRAIN null imputed successfully!")
rc = close_connection_to_db(ibm_db_conn, verbose=F... | AGE in LINREG.GSTRAIN null imputed successfully!
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Null impute the NOMINAL columns in TRAINING with the most frequent value | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
for column in nominal_columns:
null_impute_most_freq ("LINREG", "GSTRAIN", column, "GSTRAIN_STATS",ibm_db_conn, verbose=True)
rc = close_connection_to_db(ibm_db_conn, verbose=False) | GENDER in LINREG.GSTRAIN null imputed successfully!
MARITAL_STATUS in LINREG.GSTRAIN null imputed successfully!
PROFESSION in LINREG.GSTRAIN null imputed successfully!
PRODUCT_LINE in LINREG.GSTRAIN null imputed successfully!
IS_TENT in LINREG.GSTRAIN null imputed successfully!
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Null impute NUMERICAL column in TEST data with mean | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
for column in numerical_columns:
null_impute_mean("LINREG", "GSTEST", column, "GSTRAIN_STATS",ibm_db_conn, verbose=True)
rc = close_connection_to_db(ibm_db_conn, verbose=False) | AGE in LINREG.GSTEST null imputed successfully!
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Null impute the NOMINAL columns in TEST data with the most frequent value | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
for column in nominal_columns:
null_impute_most_freq ("LINREG", "GSTEST", column, "GSTRAIN_STATS",ibm_db_conn, verbose=True)
rc = close_connection_to_db(ibm_db_conn, verbose=False) | GENDER in LINREG.GSTEST null imputed successfully!
MARITAL_STATUS in LINREG.GSTEST null imputed successfully!
PROFESSION in LINREG.GSTEST null imputed successfully!
PRODUCT_LINE in LINREG.GSTEST null imputed successfully!
IS_TENT in LINREG.GSTEST null imputed successfully!
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Standardize AGE in training data | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
drop_object("LINREG.GSTRAIN_STD", "TABLE", ibm_db_conn, verbose = True)
sql = """CALL IDAX.STD_NORM('intable=LINREG.GSTRAIN,
incolumn="GENDER":L;"AGE":S;"MARITAL_STATUS":L;"PROFESSION":L;"IS_TENT":L;"PRODUCT_LINE":L;"PURCHASE_AMOUNT":L... | Pre-existing TABLE LINREG.GSTRAIN_STD was not found.
LINREG.GSTRAIN_STD was created and AGE column was standardized.
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Standardize AGE in test data | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
drop_object("LINREG.GSTEST_STD", "TABLE", ibm_db_conn, verbose = True)
sql = "CREATE TABLE LINREG.GSTEST_STD AS (SELECT * FROM LINREG.GSTEST) WITH DATA"
stmt = ibm_db.exec_immediate(ibm_db_conn, sql)
print ("Table LINREG.GSTEST_STD was created.... | Pre-existing TABLE LINREG.GSTEST_STD was not found.
Table LINREG.GSTEST_STD was created.
AGE was standardized in test data successfully!
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
7. Train a linear regression model Train the model | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
drop_object("LINREG.GSLINREG", "MODEL", ibm_db_conn, verbose = True)
sql = """CALL IDAX.LINEAR_REGRESSION('model=LINREG.GSLINREG, intable=LINREG.GSTRAIN_STD, id=ID,
target= PURCHASE_AMOUNT, incolumn =GENDER;STD_AGE;MARITAL_STATUS;PROFESSIO... | Pre-existing MODEL LINREG.GSLINREG was not found.
Model trained successfully!
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
8. Predict purchase amount for train and test data Create view GSTEST_INPUT from feature columns in GSTEST_STD | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
drop_object("LINREG.GSTEST_INPUT", "VIEW", ibm_db_conn, verbose = True)
sql = "CREATE VIEW LINREG.GSTEST_INPUT AS (SELECT ID,GENDER,STD_AGE,MARITAL_STATUS,PROFESSION,IS_TENT,PRODUCT_LINE FROM LINREG.GSTEST_STD)"
stmt = ibm_db.exec_immediate(ibm_db_... | Pre-existing VIEW LINREG.GSTEST_INPUT was not found.
VIEW LINREG.GSTEST_INPUT was created successfuly!
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Predict purchase amounts using IDAX.PREDICT_LINEAR_REGRESSION | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
drop_object("LINREG.GSTEST_OUTPUT", "TABLE", ibm_db_conn, verbose = True)
sql = """CALL IDAX.PREDICT_LINEAR_REGRESSION('model=LINREG.GSLINREG, intable=LINREG.GSTEST_INPUT, outtable =LINREG.GSTEST_OUTPUT, id=ID')"""
stmt = ibm_db.exec_immedi... | Pre-existing TABLE LINREG.GSTEST_OUTPUT was not found.
LINREG.GSTEST_OUTPUT was created with test results.
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Create view GSTRAIN_INPUT from feature columns in GSTRAIN_STD | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
drop_object("LINREG.GSTRAIN_INPUT", "VIEW", ibm_db_conn, verbose = True)
sql = "CREATE VIEW LINREG.GSTRAIN_INPUT AS (SELECT ID,GENDER,STD_AGE,MARITAL_STATUS,PROFESSION,IS_TENT,PRODUCT_LINE FROM LINREG.GSTRAIN_STD)"
stmt = ibm_db.exec_immediate(ibm_... | Pre-existing VIEW LINREG.GSTRAIN_INPUT was not found.
VIEW LINREG.GSTRAIN_INPUT was created successfuly!
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Predict purchase amounts using IDAX.PREDICT_LINEAR_REGRESSION | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
drop_object("LINREG.GSTRAIN_OUTPUT", "TABLE", ibm_db_conn, verbose = True)
sql = """CALL IDAX.PREDICT_LINEAR_REGRESSION('model=LINREG.GSLINREG, intable=LINREG.GSTRAIN_INPUT, outtable =LINREG.GSTRAIN_OUTPUT, id=ID')"""
stmt = ibm_db.exec_imm... | Pre-existing TABLE LINREG.GSTRAIN_OUTPUT was not found.
LINREG.GSTEST_OUTPUT was created with train results.
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
9. Evaluate Model Performance Evaluate model performance on TRAINING data | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
print("Training performance: ")
sql = """CALL IDAX.MSE('intable= LINREG.GSTRAIN_STD, id = ID, target = PURCHASE_AMOUNT, resulttable=LINREG.GSTRAIN_OUTPUT, resultid=ID, resulttarget=PURCHASE_AMOUNT')"""
print_multi_result_set(ibm_db_conn, sql)
sql = ... | Training performance:
{'MSE': 98.36862842452432}
{'MAE': 7.5297574998766}
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Evaluate model performance on TEST data | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
print("Test performance: ")
sql = """CALL IDAX.MSE('intable= LINREG.GSTEST_STD, id = ID, target = PURCHASE_AMOUNT, resulttable=LINREG.GSTEST_OUTPUT, resultid=ID, resulttarget=PURCHASE_AMOUNT')"""
print_multi_result_set(ibm_db_conn, sql)
sql = """CAL... | Test performance:
{'MSE': 97.53595615684684}
{'MAE': 7.461251686160011}
| Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
**Observations:*** Mean absolute error on test data is 7.46 -> Model predicts with a fairly good accuracy.* Performance is consistent for Training and Test datasets -> Model is not overfitting the training set. Visually evaluate model performance | ibm_db_conn, ibm_db_dbi_conn = connect_to_db(conn_str, verbose=False)
sql = """select ACT.ID, ACT.PURCHASE_AMOUNT AS ACTUAL, PRED.PURCHASE_AMOUNT AS PREDICTION
from LINREG.GSTEST_STD AS ACT, LINREG.GSTEST_OUTPUT AS PRED
where ACT.ID = PRED.ID"""
GSTEST_ACT_PRED = pd.read_sql(sql,ibm_db_dbi_conn... | _____no_output_____ | Apache-2.0 | In_Db2_Machine_Learning/Building ML Models with Db2/Notebooks/Regression_Demo.ipynb | ibmmichaelschapira/db2-samples |
Copyright 2018 The AdaNet 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 | adanet/examples/tutorials/adanet_objective.ipynb | sararob/adanet |
The AdaNet objective Run in Google Colab View source on GitHub One of key contributions from *AdaNet: Adaptive Structural Learning of NeuralNetworks* [[Cortes et al., ICML 2017](https://arxiv.org/abs/1607.01097)] isdefining an algorithm that aims to directly minimize the DeepBoostgeneralization bound fr... | # If you're running this in Colab, first install the adanet package:
!pip install adanet
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import adanet
import tensorflow as tf
# The random seed to use.
RANDOM_SEED = 42 | _____no_output_____ | Apache-2.0 | adanet/examples/tutorials/adanet_objective.ipynb | sararob/adanet |
Boston Housing datasetIn this example, we will solve a regression task known as the [Boston Housing dataset](https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html) to predict the price of suburban houses in Boston, MA in the 1970s. There are 13 numerical features, the labels are in thousands of dollars, and ... | (x_train, y_train), (x_test, y_test) = (
tf.keras.datasets.boston_housing.load_data())
# Preview the first example from the training data
print('Model inputs: %s \n' % x_train[0])
print('Model output (house price): $%s ' % (y_train[0] * 1000))
| Model inputs: [ 1.23247 0. 8.14 0. 0.538 6.142 91.7
3.9769 4. 307. 21. 396.9 18.72 ]
Model output (house price): $15200.0
| Apache-2.0 | adanet/examples/tutorials/adanet_objective.ipynb | sararob/adanet |
Supply the data in TensorFlowOur first task is to supply the data in TensorFlow. Using thetf.estimator.Estimator convention, we will define a function that returns aninput_fn which returns feature and label Tensors.We will also use the tf.data.Dataset API to feed the data into our models.Also, as a preprocessing step,... | FEATURES_KEY = "x"
def input_fn(partition, training, batch_size):
"""Generate an input function for the Estimator."""
def _input_fn():
if partition == "train":
dataset = tf.data.Dataset.from_tensor_slices(({
FEATURES_KEY: tf.log1p(x_train)
}, tf.log1p(y_train)))
else:
dataset... | _____no_output_____ | Apache-2.0 | adanet/examples/tutorials/adanet_objective.ipynb | sararob/adanet |
Define the subnetwork generatorLet's define a subnetwork generator similar to the one in[[Cortes et al., ICML 2017](https://arxiv.org/abs/1607.01097)] and in`simple_dnn.py` which creates two candidate fully-connected neural networks ateach iteration with the same width, but one an additional hidden layer. To makeour g... | _NUM_LAYERS_KEY = "num_layers"
class _SimpleDNNBuilder(adanet.subnetwork.Builder):
"""Builds a DNN subnetwork for AdaNet."""
def __init__(self, optimizer, layer_size, num_layers, learn_mixture_weights,
seed):
"""Initializes a `_DNNBuilder`.
Args:
optimizer: An `Optimizer` instance f... | _____no_output_____ | Apache-2.0 | adanet/examples/tutorials/adanet_objective.ipynb | sararob/adanet |
Train and evaluateNext we create an `adanet.Estimator` using the `SimpleDNNGenerator` we just defined.In this section we will show the effects of two hyperparamters: **learning mixture weights** and **complexity regularization**.On the righthand side you will be able to play with the hyperparameters of this model. Unt... | #@title AdaNet parameters
LEARNING_RATE = 0.001 #@param {type:"number"}
TRAIN_STEPS = 100000 #@param {type:"integer"}
BATCH_SIZE = 32 #@param {type:"integer"}
LEARN_MIXTURE_WEIGHTS = False #@param {type:"boolean"}
ADANET_LAMBDA = 0 #@param {type:"number"}
BOOSTING_ITERATIONS = 5 #@param {type:"integer"}
def tr... | WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmpBX73lD
INFO:tensorflow:Using config: {'_save_checkpoints_secs': None, '_num_ps_replicas': 0, '_keep_checkpoint_max': 5, '_task_type': 'worker', '_global_id_in_cluster': 0, '_is_chief': True, '_cluster_spec': <tensorflow.python.training.server_lib.Clu... | Apache-2.0 | adanet/examples/tutorials/adanet_objective.ipynb | sararob/adanet |
These hyperparameters preduce a model that achieves **0.0348** MSE on the testset (exact MSE will vary depending on the hardware you're using to train the model). Notice that the ensemble is composed of 5 subnetworks, each one a hiddenlayer deeper than the previous. The most complex subnetwork is made of 5 hiddenlayers... | #@test {"skip": true}
results, _ = train_and_evaluate(learn_mixture_weights=True)
print("Loss:", results["average_loss"])
print("Uniform average loss:", results["average_loss/adanet/uniform_average_ensemble"])
print("Architecture:", ensemble_architecture(results)) | WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmpDexXZd
INFO:tensorflow:Using config: {'_save_checkpoints_secs': None, '_num_ps_replicas': 0, '_keep_checkpoint_max': 5, '_task_type': 'worker', '_global_id_in_cluster': 0, '_is_chief': True, '_cluster_spec': <tensorflow.python.training.server_lib.Clu... | Apache-2.0 | adanet/examples/tutorials/adanet_objective.ipynb | sararob/adanet |
Learning the mixture weights produces a model with **0.0449** MSE, a bit worsethan the uniform average model, which the `adanet.Estimator` always compute as abaseline. The mixture weights were learned without regularization, so theylikely overfit to the training set.Observe that AdaNet learned the same ensemble composi... | #@test {"skip": true}
results, _ = train_and_evaluate(learn_mixture_weights=True, adanet_lambda=.015)
print("Loss:", results["average_loss"])
print("Uniform average loss:", results["average_loss/adanet/uniform_average_ensemble"])
print("Architecture:", ensemble_architecture(results)) | WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmpU33rCk
INFO:tensorflow:Using config: {'_save_checkpoints_secs': None, '_num_ps_replicas': 0, '_keep_checkpoint_max': 5, '_task_type': 'worker', '_global_id_in_cluster': 0, '_is_chief': True, '_cluster_spec': <tensorflow.python.training.server_lib.Clu... | Apache-2.0 | adanet/examples/tutorials/adanet_objective.ipynb | sararob/adanet |
Remote control Jetbot using Virtual gamepad====== | # This cell should only run once.
import os
# set the current working directory. This is required by isaac.
os.chdir("../..")
os.getcwd()
simulation =True
from packages.pyalice import Application, Message, Codelet
# Creates an empty Isaac application
app = Application(name="jetbot_application") | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
The Robot Engine Bridge enables communication between Omniverse and the Isaac SDK. When a REB application is created, a simulation-side Isaac SDK application is started, allowing messages to be sent to, or published from, the REB Components. The simulation Subgraph is loaded into our Isaac application, allowing the exc... | if simulation:
# Loads the simulation_tcp subgraph into the Isaac application, adding all nodes, components,
# edges, and configurations
app.load(filename="apps/jetbot/simulation_tcp.subgraph.json", prefix="simulation")
# Gets a reference to the interface node of the subgraph having a prefix of "simula... | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
The Robot Remote Control component can send commands to the Differential Base to control the Jetbot model. Therefore, we add a node to which a component of type RobotRemoteControl is added. Nodes can be thought of as a container to group related components in an Isaac application. As the RobotRemoteControl component wi... | if simulation:
# Creating a new node in the Isaac application named "robot_remote"
robot_remote_node = app.add("robot_remote")
# Loads the navigation module, allowing components requiring this module to be added to the application
app.load_module("navigation")
# Add the RobotRemoteControl and Fail... | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
To generate a corresponding command, the Robot Remote Control component must receive either JoystickStateProto messages from its "js_state" channel, or messages consisting of a linear and angular velocity over its "ctrl" channel. Here, we add the virtual gamepad subgraph which can be used to generate "JoystickStateProt... | if simulation:
# Loads the virtual_gamepad subgraph into the application
app.load(filename="apps/jetbot/virtual_gamepad.subgraph.json", prefix="virtual_gamepad")
# Finds a reference to the component named "interface", located in the subgraph node of the virtual gamepad
# subgraph. The component named ... | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
The virtual gamepad widget in Sight allows us to use the WASD keys of the keyboard to steer the Jetbot in simulation, thus making the connection between Isaac and Omniverse more concrete. Prior to starting the Isaac application, the REB application is created by opening the jetbot.usd file in Omniverse, navigating to t... | app.start() | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
Open Sight by going to (Your-IP-Address):3000 in your browser (or localhost:3000 if the Isaac SDK is running on your local machine), and control the Jetbot in simulation with the Virtual Gamepad as shown below. | app.stop() | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
Running Inference in Simulation ======Please note the following section requires a training environment built in simulation and a model trained.With the simulation environment and a trained model (the .etlt file generated by following the Object Detection with DetectNetv2 pipeline), we can run inference using data stre... | app.load(filename="packages/detect_net/apps/detect_net_inference.subgraph.json", prefix="detect_net")
# Setting configuration parameters of components used in the detect-net subgraph to allow the trained
# model to be used, and training parameters specified.
inference_component = app.nodes["detect_net.tensor_r_t_infer... | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
With the subgraph loaded and configuration parameters set, we can relay Omniverse's viewport stream, captured by the REB Camera, to the detectnet subgraph, allowing inference to be performed on simulation data. | detect_net_interface = app.nodes["detect_net.subgraph"]["interface"]
if simulation:
# Allows image stream from Omniverse to flow to detect-net
app.connect(simulation_node["output"], "color", detect_net_interface, "image")
app.start() | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
Upon opening the jetbot_inference.usd file in Omniverse, creating the Robot Engine Bridge application, and starting both the simulation and he Isaac application, the performance of the detection model can be verified. | app.stop() | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
Jetbot Autonomously Following Objects in Simulation======Now that objects are being correctly detected in simulation, we need to implement the control logic to move the Jetbot model such that it keeps the desired object both just in front of it and horizontally centered. To accomplish this, we first define a couple hel... | import numpy as np
import json
def get_parsed_detections(detections_msg):
"""Parses and reformats Detections2Proto messages"""
detections_msg_json = detections_msg.json
zipped = zip(detections_msg_json['predictions'], detections_msg_json['boundingBoxes'])
zipped_list = list(zipped)
detections ... | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
With the helper functions in place and detections being made in simulation, we can develop a Python Codelet to control the Jetbot, which will use detections messages to compute the desired motor commands of the Jetbot, and then publish messages containing these commands. Codelets are functionally equivalent to the buil... | # Generates PWM commands to follow desired object
class JetbotControl(Codelet):
def start(self):
self.rx = self.isaac_proto_rx("Detections2Proto", "detections")
self.tx = self.isaac_proto_tx("StateProto", "motor_command")
# Ticks when new detections message is received
self.tic... | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
The created Codelet must be added to the Isaac application, just like a normal component. The configuration parameters are then set and an edge added between the Codelet and the detect-net subgraph so that the detections messages can be used to generate control commands. | # Create a new node, and add the JetbotControl Codelet to the node.
controller_node = app.add("controller")
jetbot_control_component = controller_node.add(JetbotControl)
# Set the configuration parameters of the JetbotControl Codelet
if simulation:
jetbot_control_component.config.image_width = 1280
jetbot_cont... | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
While the added Codelet can generate motor commands compatible with the real Jetbot, in simulation the Jetbot is controlled by sending Segway commands to the REB Differential Base. Segway commands can be generated by providing linear and angular velocities to the “ctrl” channel of the previously created RobotRemoteCont... | def pwm_to_velocity(pwm_command, min_pwm_command):
"""Computes velocity (in [m/s]) of real Jetbot when both motors are set to "pwm_command" based on experimental data"""
command_abs = np.abs(pwm_command)
# min_pwm_command represents the interval of commands sent to the jetbot which do not cause movement:
... | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
A second Codelet can now be created to adapt the PWM commands so that they are able to be used in simulation. With the help of our recently defined “pwm_to_velocity” function, the velocity of each wheel can be calculated. Then, using the dynamics equations of a differential base, linear and angular velocity can be calc... | # Converts PWM commands into linear and angular velocities
class SimulationAdapter(Codelet):
def start(self):
self.rx = self.isaac_proto_rx("StateProto", "motor_command")
self.tx = self.isaac_proto_tx("StateProto", "velocity_command")
self.tick_on_message(self.rx)
def tick(self):
... | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
With the Simulation Adapter Codelet defined, we may now add it to our Isaac application. An edge is added from the Jetbot Control Codelet to the Simulation Adapter, allowing the Adapter to receive PWM commands from the controller. Once the commands are converted into linear and angular velocities, they must be sent to ... | if simulation:
# Create a new node, and add the SimulationAdapter Codelet to the node.
adapter_node = app.add("adapter")
simulation_adapter_component = adapter_node.add(SimulationAdapter)
# Set the configuration parameters of the SimulationAdapter Codelet
simulation_adapter_component.config.min_pwm... | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
Now we’re ready to autonomously follow a ball in simulation. Upon opening the jetbot_follow.usd file in Omniverse, create the Robot Engine Bridge application, and start the Isaac application by running the next cell. | app.start() | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
You'll notice that despite the Jetbot detecting objects, it isn't moving. The reason is that the Robot Remote Control component will only send commands while the deadman switch is pressed for safety reasons. But there aren't any safety concerns in simulation! Lets go ahead and disable that. | if simulation:
robot_remote_control_component.config["disable_deadman_switch"] = True | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
You should now see your Jetbot following balls as they appear before it in simulation. Cool! Tweak the config parameters of the Wheel Velocity Control Generator Codelet to your likening, and let's finish bridging the gap between simulation and reality! | app.stop() | _____no_output_____ | FSFAP | sdk/apps/jetbot/jetbot_notebook.ipynb | antonspivak/isaac_gps |
PyTorch: 사용자 정의 nn Module-------------------------------하나의 은닉층(hidden layer)과 편향(bias)이 없는 완전히 연결된 ReLU 신경망을,유클리드 거리(Euclidean distance) 제곱을 최소화하는 식으로 x로부터 y를 예측하도록학습하겠습니다.이번에는 사용자 정의 Module의 서브클래스로 모델을 정의합니다. 기존 Module의 간단한구성보다 더 복잡한 모델을 원한다면, 이 방법으로 모델을 정의하면 됩니다. | import torch
class TwoLayerNet(torch.nn.Module):
def __init__(self, D_in, H, D_out):
"""
생성자에서 2개의 nn.Linear 모듈을 생성하고, 멤버 변수로 지정합니다.
"""
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
def for... | _____no_output_____ | BSD-3-Clause | docs/_downloads/ee69127c1eacbde4ff2e2aca2e46e8f0/two_layer_net_module.ipynb | jessemin/PyTorch-tutorials-kr |
Read sample data | x_train = pd.read_csv('sample_training_data.csv')
ft_predict = 'cur_pH' # specify which column to predict
all_fts = x_train.columns
model_fts = all_fts
model_fts.drop(ft_predict) | _____no_output_____ | MIT | example/runPairwiseRegression_example.ipynb | philips-labs/pairwise-regression |
Run pairwise regression model | # train model
z_dynamic_range = np.linspace(6.8,7.5,15) # specify the range and binning of key-covariate
model = KeyCovariatePairwiseLR(alpha_blend=20, cov_steps=20, coeff_smooth_z=6, func_smooth_z='sigmoid')
print(ft_predict)
model.fit(x_train[all_fts], 'prev_pH', ft_predict, cov_range_z=z_dynamic_range, include_z_in... | cur_pH
prev_pH
| MIT | example/runPairwiseRegression_example.ipynb | philips-labs/pairwise-regression |
d-sandbox Connecting to JDBCApache Spark™ and Databricks® allow you to connect to a number of data stores using JDBC. In this lesson you:* Read data from a JDBC connection * Parallelize your read operation to leverage distributed computation Audience* Primary Audience: Data Engineers* Additional Audiences:... | %run "./Includes/Classroom-Setup" | _____no_output_____ | MIT | ETL-I/ETL1 04 - Connecting to JDBC.ipynb | vshiv667/Data-Engineering |
-sandboxRun the cell below to confirm you are using the right driver. Each notebook has a default language that appears in upper corner of the screen next to the notebook name, and you can easily switch between languages in a notebook. To change languages, start your cell with `%python`, `%scala`, `%sql`, or `%r`. | %scala
// run this regardless of language type
Class.forName("org.postgresql.Driver") | _____no_output_____ | MIT | ETL-I/ETL1 04 - Connecting to JDBC.ipynb | vshiv667/Data-Engineering |
Define your database connection criteria. In this case, you need the hostname, port, and database name. Access the database `training` via port `5432` of a Postgres server sitting at the endpoint `server1.databricks.training`.Combine the connection criteria into a URL. | jdbcHostname = "server1.databricks.training"
jdbcPort = 5432
jdbcDatabase = "training"
jdbcUrl = f"jdbc:postgresql://{jdbcHostname}:{jdbcPort}/{jdbcDatabase}" | _____no_output_____ | MIT | ETL-I/ETL1 04 - Connecting to JDBC.ipynb | vshiv667/Data-Engineering |
Create a connection properties object with the username and password for the database. | connectionProps = {
"user": "readonly",
"password": "readonly"
} | _____no_output_____ | MIT | ETL-I/ETL1 04 - Connecting to JDBC.ipynb | vshiv667/Data-Engineering |
Read from the database by passing the URL, table name, and connection properties into `spark.read.jdbc()`. | tableName = "training.people_1m"
peopleDF = spark.read.jdbc(url=jdbcUrl, table=tableName, properties=connectionProps)
display(peopleDF) | _____no_output_____ | MIT | ETL-I/ETL1 04 - Connecting to JDBC.ipynb | vshiv667/Data-Engineering |
Exercise 1: Parallelizing JDBC ConnectionsThe command above was executed as a serial read through a single connection to the database. This works well for small data sets; at scale, parallel reads are necessary for optimal performance.See the [Managing Parallelism](https://docs.databricks.com/spark/latest/data-sources... | dfMin=peopleDF.select("id").rdd.min()[0]
dfMax=peopleDF.select("id").rdd.max()[0]
# TEST - Run this cell to test your solution
dbTest("ET1-P-04-01-01", 1, dfMin)
dbTest("ET1-P-04-01-02", 1000000, dfMax)
print("Tests passed!") | _____no_output_____ | MIT | ETL-I/ETL1 04 - Connecting to JDBC.ipynb | vshiv667/Data-Engineering |
-sandbox Step 2: Define the Connection Parameters.Referencing the documentation, define the connection parameters for this read.Use 8 partitions.Assign the results to `peopleDFParallel`. Setting the column for your parallel read introduces unexpected behavior due to a bug in Spark. To make sure Spark uses the capitaliz... | peopleDFParallel = spark.read.jdbc(url=jdbcUrl, table="training.people_1m", column='"id"', lowerBound=1, upperBound=100000, numPartitions=8,properties=connectionProps)
display(peopleDFParallel)
# TEST - Run this cell to test your solution
dbTest("ET1-P-04-02-01", 8, peopleDFParallel.rdd.getNumPartitions())
print("Tes... | _____no_output_____ | MIT | ETL-I/ETL1 04 - Connecting to JDBC.ipynb | vshiv667/Data-Engineering |
Step 3: Compare the Serial and Parallel ReadsCompare the two reads with the `%timeit` function. Display the number of partitions in each DataFrame by running the following: | print("Partitions:", peopleDF.rdd.getNumPartitions())
print("Partitions:", peopleDFParallel.rdd.getNumPartitions()) | _____no_output_____ | MIT | ETL-I/ETL1 04 - Connecting to JDBC.ipynb | vshiv667/Data-Engineering |
Invoke `%timeit` followed by calling a `.describe()`, which computes summary statistics, on both `peopleDF` and `peopleDFParallel`. | %timeit peopleDF.describe()
%timeit peopleDFParallel.describe() | _____no_output_____ | MIT | ETL-I/ETL1 04 - Connecting to JDBC.ipynb | vshiv667/Data-Engineering |
What is the difference between serial and parallel reads? Note that your results vary drastically depending on the cluster and number of partitions you use | #Parallel reads are faster by 3.5 secs on average over 7 runs | _____no_output_____ | MIT | ETL-I/ETL1 04 - Connecting to JDBC.ipynb | vshiv667/Data-Engineering |
Review**Question:** What is JDBC? **Answer:** JDBC stands for Java Database Connectivity, and is a Java API for connecting to databases such as MySQL, Hive, and other data stores.**Question:** How does Spark read from a JDBC connection by default? **Answer:** With a serial read. With additional specifications, Spar... | %run "./Includes/Classroom-Cleanup" | _____no_output_____ | MIT | ETL-I/ETL1 04 - Connecting to JDBC.ipynb | vshiv667/Data-Engineering |
AI for Earth System Science Hackathon 2020 HOLODEC Machine Learning Challenge ProblemMatt Hayman, Aaron Bansemer, David John Gagne, Gabrielle Gantos, Gunther Wallach, Natasha Flyer IntroductionThe properties of the water and ice particles in clouds are critical to many aspects of weather and climate. The size, shape,... | !pip install numpy scipy matplotlib xarray pandas scikit-learn tensorflow netcdf4 h5netcdf tqdm s3fs zarr
# if working on google colab, uncomment and enable save to google drive
# ! pip install -U -q PyDrive
# from google.colab import drive
# drive.mount('/content/gdrive') | _____no_output_____ | MIT | notebooks/holodec.ipynb | carlosenciso/ai4ess-hackathon-2020 |
DataThe datasets consist of synthetically-generated holograms of cloud droplets. Each dataset is in zarr format, and contains a series of hologram images as well as the properties of each particle in the image. The zarr variable names and properties are as follows:| Variable Name | Description | Dimensions | Units/R... | # Module imports
import argparse
import random
import os
from os.path import join, exists
import sys
import s3fs
import yaml
import zarr
import xarray as xr
import numpy as np
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.preprocessing import Standar... | _____no_output_____ | MIT | notebooks/holodec.ipynb | carlosenciso/ai4ess-hackathon-2020 |
Baseline Machine Learning ModelA baseline model for solving this problem uses a ConvNET architecture implemented in Keras. The first three convolution layers consist of 5 x 5 pixel kernels with rectified linear unit (relu) activation followed by a 4 x 4 pixel max pool layer. The first convolution layer has 8 channel... | class Conv2DNeuralNetwork(object):
"""
A Conv2D Neural Network Model that can support arbitrary numbers of layers.
Attributes:
filters: List of number of filters in each Conv2D layer
kernel_sizes: List of kernel sizes in each Conv2D layer
conv2d_activation: Type of activation functi... | _____no_output_____ | MIT | notebooks/holodec.ipynb | carlosenciso/ai4ess-hackathon-2020 |
Z Relative Particle Mass ModelThis neural network is tasked to predict the distribution of particle mass in the z-plane of the instrument. The relative mass is calculated by calculating the volume of each sphere based on the area and dividing by the total mass of all particles. The advantage of this target is that it ... | def calc_z_relative_mass(outputs, holograms, num_z_bins=20, z_bins=None):
"""
Calculate z-relative mass from particle data.
Args:
outputs: (np array) Output data previously specified by output_cols
holograms: (int) Number of holograms
num_z_bins: (int) Number of bins for z_bin... | _____no_output_____ | MIT | notebooks/holodec.ipynb | carlosenciso/ai4ess-hackathon-2020 |
Three particle, z-mass model definition | # conv2d_network definitions for 3 particle z mass solution
IN_COLAB = 'google.colab' in sys.modules
if IN_COLAB:
path_out = "/content/gdrive/My Drive/micro_models/3particle_base"
else:
path_out = "./holodec_models/3particle_base/"
if not exists(path_out):
os.makedirs(path_out)
model_name = "cnn"
filters =... | _____no_output_____ | MIT | notebooks/holodec.ipynb | carlosenciso/ai4ess-hackathon-2020 |
Three Particle MetricsHow well do individual predictions (red) match with the actual particle locations (blue)? | valid_index = 11
bin_size = z_bins[1] - z_bins[0]
plt.figure(figsize=(10, 6))
plt.bar(z_bins / 1000, valid_z_mass_pred[valid_index], bin_size / 1000, color='red', label="Predicted")
plt.bar(z_bins / 1000, valid_z_mass[valid_index], bin_size / 1000, edgecolor='blue', facecolor="none", lw=3, label="True")
plt.ylim(0, 1)
... | _____no_output_____ | MIT | notebooks/holodec.ipynb | carlosenciso/ai4ess-hackathon-2020 |
If the model was completely unbiased, then mean relative mass in each bin should be nearly the same across all validation examples. In this case we see that the CNN preferentially predicts that the mass is closer to the camera, likely due to a combination of particles closer to the camera blocking those farther away al... | plt.bar(z_bins / 1000, valid_z_mass_pred.mean(axis=0), (z_bins[1] - z_bins[0]) / 1000, color='red')
plt.bar(z_bins / 1000, valid_z_mass.mean(axis=0), (z_bins[1]-z_bins[0]) / 1000, edgecolor='blue', facecolor="none", lw=3)
plt.xlabel("z location (mm)", fontsize=16)
plt.ylabel("Mean Relative Mass", fontsize=16)
def ranke... | _____no_output_____ | MIT | notebooks/holodec.ipynb | carlosenciso/ai4ess-hackathon-2020 |
One Particle ModelAn easier problem is predicting the location and properties of synthetic single particles. | # data definitions
path_data = "ncar-aiml-data-commons/holodec/"
num_particles = 1
output_cols_one = ["x", "y", "z", "d"]
scaler_one = MinMaxScaler()
slice_idx = 15000
# load and normalize data (this takes approximately 2 minutes)
train_inputs_scaled_one,\
train_outputs_one,\
scaler_vals_one = load_scaled_datasets(p... | _____no_output_____ | MIT | notebooks/holodec.ipynb | carlosenciso/ai4ess-hackathon-2020 |
One Particle MetricsAn ideal solution to HOLODEC processing would leverage all the advantages of the instrument (unparalleled particle position and size accuracy) but reduce the drawbacks (processing time). For this reason, the major components of the model assessment should include:Mean absolute error in predictions... | # calculate error by output_cols_one
valid_maes_one = np.zeros(len(output_cols_one))
max_errors_one = np.zeros(len(output_cols_one))
for o, output_col in enumerate(output_cols_one):
valid_maes_one[o] = mean_absolute_error(valid_outputs_one[output_col], valid_preds_one[output_col])
max_errors_one[o] = max_error... | _____no_output_____ | MIT | notebooks/holodec.ipynb | carlosenciso/ai4ess-hackathon-2020 |
Hackathon Challenges Monday* Load the data* Create an exploratory visualization of the data* Test two different transformation and scaling methods* Test one dimensionality reduction method* Train a linear model* Train a decision tree ensemble method of your choice | # Monday's code goes here
| _____no_output_____ | MIT | notebooks/holodec.ipynb | carlosenciso/ai4ess-hackathon-2020 |
Tuesday* Train a densely connected neural network* Train a convolutional or recurrent neural network (depends on problem)* Experiment with different architectures | # Tuesday's code goes here
| _____no_output_____ | MIT | notebooks/holodec.ipynb | carlosenciso/ai4ess-hackathon-2020 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.