markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Introduction to Neural Nets This Colab builds a deep neural network to perform more sophisticated linear regression than the earlier Colabs. Learning Objectives: After doing this Colab, you'll know how to do the following: Create a simple deep neural network. Tune the hyperparameters for a simple deep neural network. ...
#@title Run on TensorFlow 2.x %tensorflow_version 2.x from __future__ import absolute_import, division, print_function, unicode_literals
ml/cc/exercises/intro_to_neural_nets.ipynb
google/eng-edu
apache-2.0
Import relevant modules The following hidden code cell imports the necessary code to run the code in the rest of this Colaboratory.
#@title Import relevant modules import numpy as np import pandas as pd import tensorflow as tf from tensorflow.keras import layers from matplotlib import pyplot as plt import seaborn as sns # The following lines adjust the granularity of reporting. pd.options.display.max_rows = 10 pd.options.display.float_format = "{...
ml/cc/exercises/intro_to_neural_nets.ipynb
google/eng-edu
apache-2.0
Load the dataset Like most of the previous Colab exercises, this exercise uses the California Housing Dataset. The following code cell loads the separate .csv files and creates the following two pandas DataFrames: train_df, which contains the training set test_df, which contains the test set
train_df = pd.read_csv("https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv") train_df = train_df.reindex(np.random.permutation(train_df.index)) # shuffle the examples test_df = pd.read_csv("https://download.mlcc.google.com/mledu-datasets/california_housing_test.csv")
ml/cc/exercises/intro_to_neural_nets.ipynb
google/eng-edu
apache-2.0
Normalize values When building a model with multiple features, the values of each feature should cover roughly the same range. The following code cell normalizes datasets by converting each raw value to its Z-score. (For more information about Z-scores, see the Classification exercise.)
#@title Convert raw values to their Z-scores # Calculate the Z-scores of each column in the training set: train_df_mean = train_df.mean() train_df_std = train_df.std() train_df_norm = (train_df - train_df_mean)/train_df_std # Calculate the Z-scores of each column in the test set. test_df_mean = test_df.mean() test_d...
ml/cc/exercises/intro_to_neural_nets.ipynb
google/eng-edu
apache-2.0
Represent data The following code cell creates a feature layer containing three features: latitude X longitude (a feature cross) median_income population This code cell specifies the features that you'll ultimately train the model on and how each of those features will be represented. The transformations (collected i...
# Create an empty list that will eventually hold all created feature columns. feature_columns = [] # We scaled all the columns, including latitude and longitude, into their # Z scores. So, instead of picking a resolution in degrees, we're going # to use resolution_in_Zs. A resolution_in_Zs of 1 corresponds to # a fu...
ml/cc/exercises/intro_to_neural_nets.ipynb
google/eng-edu
apache-2.0
Build a linear regression model as a baseline Before creating a deep neural net, find a baseline loss by running a simple linear regression model that uses the feature layer you just created.
#@title Define the plotting function. def plot_the_loss_curve(epochs, mse): """Plot a curve of loss vs. epoch.""" plt.figure() plt.xlabel("Epoch") plt.ylabel("Mean Squared Error") plt.plot(epochs, mse, label="Loss") plt.legend() plt.ylim([mse.min()*0.95, mse.max() * 1.03]) plt.show() print("Define...
ml/cc/exercises/intro_to_neural_nets.ipynb
google/eng-edu
apache-2.0
Run the following code cell to invoke the the functions defined in the preceding two code cells. (Ignore the warning messages.) Note: Because we've scaled all the input data, including the label, the resulting loss values will be much less than previous models. Note: Depending on the version of TensorFlow, running thi...
# The following variables are the hyperparameters. learning_rate = 0.01 epochs = 15 batch_size = 1000 label_name = "median_house_value" # Establish the model's topography. my_model = create_model(learning_rate, my_feature_layer) # Train the model on the normalized training set. epochs, mse = train_model(my_model, tra...
ml/cc/exercises/intro_to_neural_nets.ipynb
google/eng-edu
apache-2.0
Define a deep neural net model The create_model function defines the topography of the deep neural net, specifying the following: The number of layers in the deep neural net. The number of nodes in each layer. The create_model function also defines the activation function of each layer.
def create_model(my_learning_rate, my_feature_layer): """Create and compile a simple linear regression model.""" # Most simple tf.keras models are sequential. model = tf.keras.models.Sequential() # Add the layer containing the feature columns to the model. model.add(my_feature_layer) # Describe the topogr...
ml/cc/exercises/intro_to_neural_nets.ipynb
google/eng-edu
apache-2.0
Define a training function The train_model function trains the model from the input features and labels. The tf.keras.Model.fit method performs the actual training. The x parameter of the fit method is very flexible, enabling you to pass feature data in a variety of ways. The following implementation passes a Python di...
def train_model(model, dataset, epochs, label_name, batch_size=None): """Train the model by feeding it data.""" # Split the dataset into features and label. features = {name:np.array(value) for name, value in dataset.items()} label = np.array(features.pop(label_name)) history = model.fit(x=fe...
ml/cc/exercises/intro_to_neural_nets.ipynb
google/eng-edu
apache-2.0
Call the functions to build and train a deep neural net Okay, it is time to actually train the deep neural net. If time permits, experiment with the three hyperparameters to see if you can reduce the loss against the test set.
# The following variables are the hyperparameters. learning_rate = 0.01 epochs = 20 batch_size = 1000 # Specify the label label_name = "median_house_value" # Establish the model's topography. my_model = create_model(learning_rate, my_feature_layer) # Train the model on the normalized training set. We're passing the ...
ml/cc/exercises/intro_to_neural_nets.ipynb
google/eng-edu
apache-2.0
Task 1: Compare the two models How did the deep neural net perform against the baseline linear regression model?
#@title Double-click to view a possible answer # Assuming that the linear model converged and # the deep neural net model also converged, please # compare the test set loss for each. # In our experiments, the loss of the deep neural # network model was consistently lower than # that of the linear regression model, ...
ml/cc/exercises/intro_to_neural_nets.ipynb
google/eng-edu
apache-2.0
Task 2: Optimize the deep neural network's topography Experiment with the number of layers of the deep neural network and the number of nodes in each layer. Aim to achieve both of the following goals: Lower the loss against the test set. Minimize the overall number of nodes in the deep neural net. The two goals may...
#@title Double-click to view a possible answer # Many answers are possible. We noticed the # following trends: # * Two layers outperformed one layer, but # three layers did not perform significantly # better than two layers; two layers # outperformed one layer. # In other words, two layers seeme...
ml/cc/exercises/intro_to_neural_nets.ipynb
google/eng-edu
apache-2.0
Task 3: Regularize the deep neural network (if you have enough time) Notice that the model's loss against the test set is much higher than the loss against the training set. In other words, the deep neural network is overfitting to the data in the training set. To reduce overfitting, regularize the model. The course...
#@title Double-click for a possible solution # The following "solution" uses L2 regularization to bring training loss # and test loss closer to each other. Many, many other solutions are possible. def create_model(my_learning_rate, my_feature_layer): """Create and compile a simple linear regression model.""" # ...
ml/cc/exercises/intro_to_neural_nets.ipynb
google/eng-edu
apache-2.0
Then we can start with some imports.
import pandas as pd from sklearn.datasets import fetch_covtype import ray from ray import tune from ray.air import RunConfig from ray.train.xgboost import XGBoostTrainer from ray.tune.tune_config import TuneConfig from ray.tune.tuner import Tuner
doc/source/ray-air/examples/analyze_tuning_results.ipynb
ray-project/ray
apache-2.0
We'll define a utility function to create a Ray Dataset from the Sklearn dataset. We expect the target column to be in the dataframe, so we'll add it to the dataframe manually.
def get_training_data() -> ray.data.Dataset: data_raw = fetch_covtype() df = pd.DataFrame(data_raw["data"], columns=data_raw["feature_names"]) df["target"] = data_raw["target"] return ray.data.from_pandas(df) train_dataset = get_training_data()
doc/source/ray-air/examples/analyze_tuning_results.ipynb
ray-project/ray
apache-2.0
Let's take a look at the schema here:
print(train_dataset)
doc/source/ray-air/examples/analyze_tuning_results.ipynb
ray-project/ray
apache-2.0
Since we'll be training a multiclass prediction model, we have to pass some information to XGBoost. For instance, XGBoost expects us to provide the number of classes, and multiclass-enabled evaluation metrices. For a good overview of commonly used hyperparameters, see our tutorial in the docs.
# XGBoost specific params params = { "tree_method": "approx", "objective": "multi:softmax", "eval_metric": ["mlogloss", "merror"], "num_class": 8, "min_child_weight": 2 }
doc/source/ray-air/examples/analyze_tuning_results.ipynb
ray-project/ray
apache-2.0
With these parameters in place, we'll create a Ray AIR XGBoostTrainer. Note a few things here. First, we pass in a scaling_config to configure the distributed training behavior of each individual XGBoost training job. Here, we want to distribute training across 2 workers. The label_column specifies which columns in the...
trainer = XGBoostTrainer( scaling_config={"num_workers": 2}, label_column="target", params=params, datasets={"train": train_dataset}, num_boost_round=10, )
doc/source/ray-air/examples/analyze_tuning_results.ipynb
ray-project/ray
apache-2.0
We can now create the Tuner with a search space to override some of the default parameters in the XGBoost trainer. Here, we just want to the XGBoost max_depth and min_child_weights parameters. Note that we specifically specified min_child_weight=2 in the default XGBoost trainer - this value will be overwritten during t...
tuner = Tuner( trainer, run_config=RunConfig(verbose=1), param_space={ "params": { "max_depth": tune.randint(2, 8), "min_child_weight": tune.randint(1, 10), }, }, tune_config=TuneConfig(num_samples=8, metric="train-mlogloss", mode="min"), )
doc/source/ray-air/examples/analyze_tuning_results.ipynb
ray-project/ray
apache-2.0
Let's run the tuning. This will take a few minutes to complete.
results = tuner.fit()
doc/source/ray-air/examples/analyze_tuning_results.ipynb
ray-project/ray
apache-2.0
Now that we obtained the results, we can analyze them. For instance, we can fetch the best observed result according to the configured metric and mode and print it:
# This will fetch the best result according to the `metric` and `mode` specified # in the `TuneConfig` above: best_result = results.get_best_result() print("Best result error rate", best_result.metrics["train-merror"])
doc/source/ray-air/examples/analyze_tuning_results.ipynb
ray-project/ray
apache-2.0
For more sophisticated analysis, we can get a pandas dataframe with all trial results:
df = results.get_dataframe() print(df.columns)
doc/source/ray-air/examples/analyze_tuning_results.ipynb
ray-project/ray
apache-2.0
As an example, let's group the results per min_child_weight parameter and fetch the minimal obtained values:
groups = df.groupby("config/params/min_child_weight") mins = groups.min() for min_child_weight, row in mins.iterrows(): print("Min child weight", min_child_weight, "error", row["train-merror"], "logloss", row["train-mlogloss"])
doc/source/ray-air/examples/analyze_tuning_results.ipynb
ray-project/ray
apache-2.0
As you can see in our example run, the min child weight of 2 showed the best prediction accuracy with 0.196929. That's the same as results.get_best_result() gave us! The results.get_dataframe() returns the last reported results per trial. If you want to obtain the best ever observed results, you can pass the filter_met...
df_min_error = results.get_dataframe(filter_metric="train-merror", filter_mode="min") df_min_error["train-merror"]
doc/source/ray-air/examples/analyze_tuning_results.ipynb
ray-project/ray
apache-2.0
Confirm TensorFlow can see the GPU Simply select "GPU" in the Accelerator drop-down in Notebook Settings (either through the Edit menu or the command palette at cmd/ctrl-shift-P).
device_name = tf.test.gpu_device_name() if device_name != '/device:GPU:0': #raise SystemError('GPU device not found') print('GPU device not found') else: print('Found GPU at: {}'.format(device_name)) #GPU count and name !nvidia-smi -L
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Load the Dataset Download and Extract the Dataset
# Download the dataset !curl -O https://selbystorage.s3-us-west-2.amazonaws.com/research/office_2/office_2.tar.gz data_set = 'office_2' tar_file = data_set + '.tar.gz' # Unzip the .tgz file # -x for extract # -v for verbose # -z for gnuzip # -f for file (should come at last just before file name) # -C to extract the...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Parse the CSV File
# Define path to csv file csv_path = data_set + '/interpolated.csv' # Load the CSV file into a pandas dataframe df = pd.read_csv(csv_path, sep=",") # Print the dimensions print("Dataset Dimensions:") print(df.shape) # Print the first 5 lines of the dataframe for review print("\nDataset Summary:") df.head(5)
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Clean and Pre-process the Dataset Remove Unneccessary Columns
# Remove 'index' and 'frame_id' columns df.drop(['index','frame_id'],axis=1,inplace=True) # Verify new dataframe dimensions print("Dataset Dimensions:") print(df.shape) # Print the first 5 lines of the new dataframe for review print("\nDataset Summary:") df.head(5)
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Detect Missing Data
# Detect Missing Values print("Any Missing Values?: {}".format(df.isnull().values.any())) # Total Sum print("\nTotal Number of Missing Values: {}".format(df.isnull().sum().sum())) # Sum Per Column print("\nTotal Number of Missing Values per Column:") print(df.isnull().sum())
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Remove Zero Throttle Values
# Determine if any throttle values are zeroes print("Any 0 throttle values?: {}".format(df['speed'].eq(0).any())) # Determine number of 0 throttle values: print("\nNumber of 0 throttle values: {}".format(df['speed'].eq(0).sum())) # Remove rows with 0 throttle values if df['speed'].eq(0).any(): df = df.query('speed ...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
View Label Statistics
# Steering Command Statistics print("\nSteering Command Statistics:") print(df['angle'].describe()) print("\nThrottle Command Statistics:") # Throttle Command Statistics print(df['speed'].describe())
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
View Histogram of Steering Commands
#@title Select the number of histogram bins num_bins = 25 #@param {type:"slider", min:5, max:50, step:1} hist, bins = np.histogram(df['angle'], num_bins) center = (bins[:-1]+ bins[1:]) * 0.5 plt.bar(center, hist, width=0.05) #plt.plot((np.min(df['angle']), np.max(df['angle'])), (samples_per_bin, samples_per_bin)) # ...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
View a Sample Image
# View a Single Image index = random.randint(0,df.shape[0]-1) img_name = data_set + '/' + df.loc[index,'filename'] angle = df.loc[index,'angle'] center_image = cv2.imread(img_name) center_image_mod = cv2.resize(center_image, (320,180)) center_image_mod = cv2.cvtColor(center_image_mod,cv2.COLOR_RGB2BGR) # Crop the i...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
View Multiple Images
# Number of Images to Display num_images = 4 # Display the images i = 0 for i in range (i,num_images): index = random.randint(0,df.shape[0]-1) image_path = df.loc[index,'filename'] angle = df.loc[index,'angle'] img_name = data_set + '/' + image_path image = cv2.imread(img_name) image = cv2.resi...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Split the Dataset Define an ImageDataGenerator to Augment Images
# Create image data augmentation generator and choose augmentation types datagen = ImageDataGenerator( #rotation_range=20, zoom_range=0.15, #width_shift_range=0.1, #height_shift_range=0.2, ...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
View Image Augmentation Examples
# load the image index = random.randint(0,df.shape[0]-1) img_name = data_set + '/' + df.loc[index,'filename'] original_image = cv2.imread(img_name) original_image = cv2.cvtColor(original_image,cv2.COLOR_RGB2BGR) original_image = cv2.resize(original_image, (320,180)) label = df.loc[index,'angle'] # convert to numpy ar...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Define a Data Generator
def generator(samples, batch_size=32, aug=0): num_samples = len(samples) while 1: # Loop forever so the generator never terminates for offset in range(0, num_samples, batch_size): batch_samples = samples[offset:offset + batch_size] #print(batch_samples) images = []...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Split the Dataset
samples = [] samples = df.values.tolist() sklearn.utils.shuffle(samples) train_samples, validation_samples = train_test_split(samples, test_size=0.2) print("Number of traing samples: ", len(train_samples)) print("Number of validation samples: ", len(validation_samples))
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Define Training and Validation Data Generators
batch_size_value = 32 img_aug = 0 train_generator = generator(train_samples, batch_size=batch_size_value, aug=img_aug) validation_generator = generator( validation_samples, batch_size=batch_size_value, aug=0)
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Compile and Train the Model Build the Model
# Initialize the model model = Sequential() # trim image to only see section with road # (top_crop, bottom_crop), (left_crop, right_crop) model.add(Cropping2D(cropping=((height_min,0), (width_min,0)), input_shape=(180,320,3))) # Preprocess incoming data, centered around zero with small standard deviation model.add(La...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Setup Checkpoints
# checkpoint model_path = './model' !if [ -d $model_path ]; then echo 'Directory Exists'; else mkdir $model_path; fi filepath = model_path + "/weights-improvement-{epoch:02d}-{val_loss:.2f}.hdf5" checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='auto', period=1)
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Setup Early Stopping to Prevent Overfitting
# The patience parameter is the amount of epochs to check for improvement early_stop = EarlyStopping(monitor='val_loss', patience=10)
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Reduce Learning Rate When a Metric has Stopped Improving
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5, min_lr=0.001)
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Setup Tensorboard
# Clear any logs from previous runs !rm -rf ./Graph/ # Launch Tensorboard !pip install -U tensorboardcolab from tensorboardcolab import * tbc = TensorBoardColab() # Configure the Tensorboard Callback tbCallBack = TensorBoard(log_dir='./Graph', histogram_freq=1, writ...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Load Existing Model
load = True #@param {type:"boolean"} if load: # Returns a compiled model identical to the previous one !curl -O https://selbystorage.s3-us-west-2.amazonaws.com/research/office_2/model.h5 !mv model.h5 model/ model_path_full = model_path + '/' + 'model.h5' model = load_model(model_path_full) print("Loaded pr...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Train the Model
# Define step sizes STEP_SIZE_TRAIN = len(train_samples) / batch_size_value STEP_SIZE_VALID = len(validation_samples) / batch_size_value # Define number of epochs n_epoch = 5 # Define callbacks # callbacks_list = [TensorBoardColabCallback(tbc)] # callbacks_list = [TensorBoardColabCallback(tbc), early_stop] # callback...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Save the Model
# Save model model_path_full = model_path + '/' model.save(model_path_full + 'model.h5') with open(model_path_full + 'model.json', 'w') as output_json: output_json.write(model.to_json())
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Evaluate the Model Plot the Training Results
# Plot the training and validation loss for each epoch print('Generating loss chart...') plt.plot(history_object.history['loss']) plt.plot(history_object.history['val_loss']) plt.title('model mean squared error loss') plt.ylabel('mean squared error loss') plt.xlabel('epoch') plt.legend(['training set', 'validation set'...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Print Performance Metrics
scores = model.evaluate_generator(validation_generator, STEP_SIZE_VALID, use_multiprocessing=True) metrics_names = model.metrics_names for i in range(len(model.metrics_names)): print("Metric: {} - {}".format(metrics_names[i],scores[i]))
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Compute Prediction Statistics
# Define image loading function def load_images(dataframe): # initialize images array images = [] for i in dataframe.index.values: name = data_set + '/' + dataframe.loc[i,'filename'] center_image = cv2.imread(name) center_image = cv2.resize(center_image, (320,180)) images.append(center_image...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Plot a Prediction
# Plot the image with the actual and predicted steering angle index = random.randint(0,df_test.shape[0]-1) img_name = data_set + '/' + df_test.loc[index,'filename'] center_image = cv2.imread(img_name) center_image = cv2.cvtColor(center_image,cv2.COLOR_RGB2BGR) center_image_mod = cv2.resize(center_image, (320,180)) #res...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Visualize the Network Show the Model Summary
model.summary()
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Access Individual Layers
# Creating a mapping of layer name ot layer details # We will create a dictionary layers_info which maps a layer name to its charcteristics layers_info = {} for i in model.layers: layers_info[i.name] = i.get_config() # Here the layer_weights dictionary will map every layer_name to its corresponding weights layer_...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Visualize the filters
# Visualize the first filter of each convolution layer layers = model.layers layer_ids = [2,3,4,6,7] #plot the filters fig,ax = plt.subplots(nrows=1,ncols=5) for i in range(5): ax[i].imshow(layers[layer_ids[i]].get_weights()[0][:,:,:,0][:,:,0],cmap='gray') ax[i].set_title('Conv'+str(i+1)) ax[i].set_xticks(...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
Visualize the Saliency Map
!pip install -I scipy==1.2.* !pip install git+https://github.com/raghakot/keras-vis.git -U # import specific functions from keras-vis package from vis.utils import utils from vis.visualization import visualize_saliency, visualize_cam, overlay # View a Single Image index = random.randint(0,df.shape[0]-1) img_name = d...
rover_ml/colab/RC_Car_End_to_End_Image_Regression_with_CNNs_(RGB_camera).ipynb
wilselby/diy_driverless_car_ROS
bsd-2-clause
I like this way of importing libraries, if some libraries are not already installed, the system will exit. There is another room for improvement here, if a library does not exist, it is possile to install it automatically if we run the code as admin or with enough permission The Notifier Class
class Notifier(object): suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] def __init__(self, **kwargs): self.threshold = None self.path = None self.list = None self.email_sender = None self.email_password = None self.gmail_smtp = None self.gmail_smtp_port ...
QuotaWatcher.ipynb
radaniba/QuotaWatcher
gpl-2.0
We init the class as an object containing some features, this object will have a threshold upon which there will be an email triggered to a recipient list. This obect is looking ath the size of each subdirectory in path. You need to create an email addresse and add some variables to your PATH ( will be discussed later)
@property def loggy(self): return self._log
QuotaWatcher.ipynb
radaniba/QuotaWatcher
gpl-2.0
We need to inherhit logging capabilities from the logging class we imported (see later the code of this class). This will allow us to log from within the class itself
@staticmethod def load_recipients_emails(emails_file): recipients = [line.rstrip('\n') for line in open(emails_file) if not line[0].isspace()] return recipients
QuotaWatcher.ipynb
radaniba/QuotaWatcher
gpl-2.0
We need to lad the emails from a file created by the user. Usually I create 2 files, development_list containing only email adresses I will use for testing and production_list containing adresses I want to notify in production
@staticmethod def load_message_content(message_template_file, table): template_file = open(message_template_file, 'rb') template_file_content = template_file.read().replace( "{{table}}", table.get_string()) template_file.close() return template_file_content
QuotaWatcher.ipynb
radaniba/QuotaWatcher
gpl-2.0
Inspired by MVC apps, we load message body from a template, this template will contain a placeholder called {{table}} that will contain the table of subdirectories and their respective sizes
def notify_user(self, email_receivers, table, template): """This method sends an email :rtype : email sent to specified members """ # Create the message input_file = os.path.join( os.path.dirname(__file__), "templates/" + template + ".txt") content = self....
QuotaWatcher.ipynb
radaniba/QuotaWatcher
gpl-2.0
notify_user is the function that will send an email to the users upon request. It loads the message body template and injects the table in it.
@staticmethod def du(path): """disk usage in kilobytes""" # return subprocess.check_output(['du', '-s', # path]).split()[0].decode('utf-8') try: p1 = subprocess.Popen(('ls', '-d', path), stdout=subprocess.PIPE) p2 = subprocess.Popen((os.environ["GNU_PARALL...
QuotaWatcher.ipynb
radaniba/QuotaWatcher
gpl-2.0
This is a wrapper of the famous du command. I use GNU_PARALLEL in case we have a lot of subdirectories and in case we don't want to wait for sequential processing. Note that we could have done this in multithreading as well
def du_h(self, nbytes): if nbytes == 0: return '0 B' i = 0 while nbytes >= 1024 and i < len(self.suffixes) - 1: nbytes /= 1024. i += 1 f = ('%.2f'.format(nbytes)).rstrip('0').rstrip('.') return '%s %s'.format(f, self.suffixes[i])
QuotaWatcher.ipynb
radaniba/QuotaWatcher
gpl-2.0
I didn't want to use the -h flag because we may want to sum up subdirectories sizes or doing other postprocessing, we'd rather keep them in a unified format (unit). For a more human readable format, we can use du_h() method
@staticmethod def list_folders(given_path): user_list = [] for path in os.listdir(given_path): if not os.path.isfile(os.path.join(given_path, path)) and not path.startswith(".") and not path.startswith( "archive"): user_list.append(path) re...
QuotaWatcher.ipynb
radaniba/QuotaWatcher
gpl-2.0
we need at some point to return a list of subdirectories, each will be passed through the same function (du)
def notify(self): global cap_reached self._log.info("Loading recipient emails...") list_of_recievers = self.load_recipients_emails(self.list) paths = self.list_folders(self.path) paths = [self.path + user for user in paths] sizes = [] for size in paths: ...
QuotaWatcher.ipynb
radaniba/QuotaWatcher
gpl-2.0
Finally we create the function that will bring all this protocol together : Read the list of recievers load the path we want to look into for each subdirectory calculate the size of it and append it to a list create a Table to be populated row by row add subdirectories and their sizes Calculate the total of sizes in s...
def arguments(): """Defines the command line arguments for the script.""" main_desc = """Monitors changes in the size of dirs for a given path""" parser = ArgumentParser(description=main_desc) parser.add_argument("path", default=os.path.expanduser('~'), nargs='?', help="The path...
QuotaWatcher.ipynb
radaniba/QuotaWatcher
gpl-2.0
The program takes in account : the path to examine, the list of emails in a file, the subject of the alert, the thresold that will trigger the email (here by defailt 2.5T)
def main(): args = arguments().parse_args() notifier = Notifier() loggy = notifier.loggy # Set parameters loggy.info("Starting QuotaWatcher session...") loggy.info("Setting parameters ...") notifier.list = args.list notifier.threshold = args.threshold notifier.path = args.path ...
QuotaWatcher.ipynb
radaniba/QuotaWatcher
gpl-2.0
Note that in the main we load some environment variable that you should specify in advance. This is up to the user to fill these out, It is always preferable to declare these as environment variable, most of the time these are confidential so we better not show them here, it is always safe to set environment variable f...
import logging import datetime def init_log(): current_time = datetime.datetime.now() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.FileHandler(current_time.isoformat()+'_quotawatcher.log') handler.setLevel(logging.INFO) # create a logging format forma...
QuotaWatcher.ipynb
radaniba/QuotaWatcher
gpl-2.0
To keep track of the information we'll setup a config variable and output them on the screen for bookkeeping.
import os import shutil from datetime import datetime from ioos_tools.ioos import parse_config config = parse_config("config.yaml") # Saves downloaded data into a temporary directory. save_dir = os.path.abspath(config["run_name"]) if os.path.exists(save_dir): shutil.rmtree(save_dir) os.makedirs(save_dir) fmt = ...
notebooks/2018-03-15-ssh-skillscore.ipynb
ioos/notebooks_demos
mit
To interface with the IOOS catalog we will use the Catalogue Service for the Web (CSW) endpoint and python's OWSLib library. The cell below creates the Filter Encoding Specification (FES) with configuration we specified in cell [2]. The filter is composed of: - or to catch any of the standard names; - not some names we...
def make_filter(config): from owslib import fes from ioos_tools.ioos import fes_date_filter kw = dict( wildCard="*", escapeChar="\\", singleChar="?", propertyname="apiso:Subject" ) or_filt = fes.Or( [fes.PropertyIsLike(literal=("*%s*" % val), **kw) for val in config["cf_names"]] ...
notebooks/2018-03-15-ssh-skillscore.ipynb
ioos/notebooks_demos
mit
We need to wrap OWSlib.csw.CatalogueServiceWeb object with a custom function, get_csw_records, to be able to paginate over the results. In the cell below we loop over all the catalogs returns and extract the OPeNDAP endpoints.
from ioos_tools.ioos import get_csw_records, service_urls from owslib.csw import CatalogueServiceWeb dap_urls = [] print(fmt(" Catalog information ")) for endpoint in config["catalogs"]: print("URL: {}".format(endpoint)) try: csw = CatalogueServiceWeb(endpoint, timeout=120) except Exception as e: ...
notebooks/2018-03-15-ssh-skillscore.ipynb
ioos/notebooks_demos
mit
We found 10 dataset endpoints but only 9 of them have the proper metadata for us to identify the OPeNDAP endpoint, those that contain either OPeNDAP:OPeNDAP or urn:x-esri:specification:ServiceType:odp:url scheme. Unfortunately we lost the COAWST model in the process. The next step is to ensure there are no observations...
from ioos_tools.ioos import is_station from timeout_decorator import TimeoutError # Filter out some station endpoints. non_stations = [] for url in dap_urls: try: if not is_station(url): non_stations.append(url) except (IOError, OSError, RuntimeError, TimeoutError) as e: print("Coul...
notebooks/2018-03-15-ssh-skillscore.ipynb
ioos/notebooks_demos
mit
Now we have a nice list of all the models available in the catalog for the domain we specified. We still need to find the observations for the same domain. To accomplish that we will use the pyoos library and search the SOS CO-OPS services using the virtually the same configuration options from the catalog search.
from pyoos.collectors.coops.coops_sos import CoopsSos collector_coops = CoopsSos() collector_coops.set_bbox(config["region"]["bbox"]) collector_coops.end_time = config["date"]["stop"] collector_coops.start_time = config["date"]["start"] collector_coops.variables = [config["sos_name"]] ofrs = collector_coops.server.o...
notebooks/2018-03-15-ssh-skillscore.ipynb
ioos/notebooks_demos
mit
To make it easier to work with the data we extract the time-series as pandas tables and interpolate them to a common 1-hour interval index.
import pandas as pd from ioos_tools.ioos import collector2table data = collector2table( collector=collector_coops, config=config, col="water_surface_height_above_reference_datum (m)", ) df = dict( station_name=[s._metadata.get("station_name") for s in data], station_code=[s._metadata.get("station_...
notebooks/2018-03-15-ssh-skillscore.ipynb
ioos/notebooks_demos
mit
The next cell saves those time-series as CF-compliant netCDF files on disk, to make it easier to access them later.
import iris from ioos_tools.tardis import series2cube attr = dict( featureType="timeSeries", Conventions="CF-1.6", standard_name_vocabulary="CF-1.6", cdm_data_type="Station", comment="Data from http://opendap.co-ops.nos.noaa.gov", ) cubes = iris.cube.CubeList([series2cube(obs, attr=attr) for obs ...
notebooks/2018-03-15-ssh-skillscore.ipynb
ioos/notebooks_demos
mit
We still need to read the model data from the list of endpoints we found. The next cell takes care of that. We use iris, and a set of custom functions from the ioos_tools library, that downloads only the data in the domain we requested.
from ioos_tools.ioos import get_model_name from ioos_tools.tardis import is_model, proc_cube, quick_load_cubes from iris.exceptions import ConstraintMismatchError, CoordinateNotFoundError, MergeError print(fmt(" Models ")) cubes = dict() for k, url in enumerate(dap_urls): print("\n[Reading url {}/{}]: {}".format(k...
notebooks/2018-03-15-ssh-skillscore.ipynb
ioos/notebooks_demos
mit
Now we can match each observation time-series with its closest grid point (0.08 of a degree) on each model. This is a complex and laborious task! If you are running this interactively grab a coffee and sit comfortably :-) Note that we are also saving the model time-series to files that align with the observations we sa...
import iris from ioos_tools.tardis import ( add_station, ensure_timeseries, get_nearest_water, make_tree, ) from iris.pandas import as_series for mod_name, cube in cubes.items(): fname = "{}.nc".format(mod_name) fname = os.path.join(save_dir, fname) print(fmt(" Downloading to file {} ".form...
notebooks/2018-03-15-ssh-skillscore.ipynb
ioos/notebooks_demos
mit
With the matched set of models and observations time-series it is relatively easy to compute skill score metrics on them. In cells [13] to [16] we apply both mean bias and root mean square errors to the time-series.
from ioos_tools.ioos import stations_keys def rename_cols(df, config): cols = stations_keys(config, key="station_name") return df.rename(columns=cols) from ioos_tools.ioos import load_ncs from ioos_tools.skill_score import apply_skill, mean_bias dfs = load_ncs(config) df = apply_skill(dfs, mean_bias, remov...
notebooks/2018-03-15-ssh-skillscore.ipynb
ioos/notebooks_demos
mit
Last but not least we can assemble a GIS map, cells [17-23], with the time-series plot for the observations and models, and the corresponding skill scores.
import folium from ioos_tools.ioos import get_coordinates def make_map(bbox, **kw): line = kw.pop("line", True) zoom_start = kw.pop("zoom_start", 5) lon = (bbox[0] + bbox[2]) / 2 lat = (bbox[1] + bbox[3]) / 2 m = folium.Map( width="100%", height="100%", location=[lat, lon], zoom_start=zoo...
notebooks/2018-03-15-ssh-skillscore.ipynb
ioos/notebooks_demos
mit
原始資料來源的 SQL,這是抽樣過的資料,當中也有一筆資料是修改過的,因為當天 Server 似乎出了一些問題,導至流量大幅下降
sql = """ SELECT date,count(distinct cookie_pta) as uv from TABLE_DATE_RANGE(pixinsight.article_visitor_log_1_100_, TIMESTAMP('2017-01-01'), CURRENT_TIMESTAMP()) where venue = 'pixnet' group by date order by date """ from os import environ # load and plot dataset import pandas as pd from pandas import read_csv from p...
Keras_LSTM2.ipynb
texib/deeplearning_homework
mit
進行 scale to 0-1 ,方便作為 input 及 output (因為 sigmoid 介於 0~1 之間)
from sklearn.preprocessing import scale,MinMaxScaler scaler = MinMaxScaler() x = series.values x = x.reshape([x.shape[0],1]) scaler.fit(x) x_scaled = scaler.transform(x) pyplot.figure() pyplot.plot(x_scaled) pyplot.show()
Keras_LSTM2.ipynb
texib/deeplearning_homework
mit
產生 x,y pair 舉列來說假設將 Step Size 設為 4 天,故一筆 Training Data ,為連續 4 天的流量。再來利用這4天的資料來預測第 5 天的流量 綠色的部是 Training Data(前4天的資料),藍色的部份是需要被預測的部份。示意如下圖 <img align="left" width="50%" src="./imgs/sequence_uv.png" />
#往回看 30 天前的每一筆資料 step_size = 15 print("原始資料長度:{}".format(x_scaled.shape)) def window_stack(a, stepsize=1, width=3): return np.hstack( a[i:1+i-width or None:stepsize] for i in range(0,width) ) import numpy as np train_x = window_stack(x_scaled, stepsize=1, width=step_size) # 最後一筆資料要放棄,因為沒有未來的答案作驗證 train_x = tra...
Keras_LSTM2.ipynb
texib/deeplearning_homework
mit
確認產出來的 Training Data 沒有包含到 Testing Data
train_y.shape train_x[0] train_x[1] train_y[0]
Keras_LSTM2.ipynb
texib/deeplearning_homework
mit
Design Graph
# reshape input to be [samples, time steps, features] trainX = np.reshape(train_x, (train_x.shape[0], step_size, 1)) from keras import Sequential from keras.layers import LSTM,Dense # create and fit the LSTM network model = Sequential() # input_shape(step_size,feature_dim) model.add(LSTM(4, input_shape=(step_size,1), ...
Keras_LSTM2.ipynb
texib/deeplearning_homework
mit
最後30 筆資料不要看
validation_size = 60 val_loss = [] loss = [] for _ in range(400): history = model.fit(trainX[:-1*validation_size], train_y[:-1*validation_size], epochs=1,shuffle=False, validation_data=(trainX[-1*validation_size:], train_y[-1*validation_size:])) los...
Keras_LSTM2.ipynb
texib/deeplearning_homework
mit
看一下 Error Rate 曲線
pyplot.figure() pyplot.plot(loss) pyplot.plot(val_loss) pyplot.show()
Keras_LSTM2.ipynb
texib/deeplearning_homework
mit
看一下曲線擬合效果
predict_y = model.predict(trainX) train_y.shape pyplot.figure() pyplot.plot(scaler.inverse_transform(predict_y)) pyplot.plot(scaler.inverse_transform(train_y)) pyplot.show()
Keras_LSTM2.ipynb
texib/deeplearning_homework
mit
來預測最後 60 天資料預出來的結果
predict_y = model.predict(trainX[-1*validation_size:]) predict_y = scaler.inverse_transform(predict_y) predict_y.shape pyplot.figure() pyplot.plot(x[-1*(validation_size+1):-1]) pyplot.plot(predict_y) pyplot.show()
Keras_LSTM2.ipynb
texib/deeplearning_homework
mit
We need a lot of building blocks from Lasagne to build network
import lasagne from lasagne.utils import floatX from lasagne.layers import InputLayer from lasagne.layers import Conv2DLayer as ConvLayer # can be replaced with dnn layers from lasagne.layers import BatchNormLayer from lasagne.layers import Pool2DLayer as PoolLayer from lasagne.layers import NonlinearityLayer from lasa...
code/Experiments/Lasagne_examples/examples/ResNets/resnet50/ImageNet Pretrained Network (ResNet-50).ipynb
matthijsvk/multimodalSR
mit
Helper modules, some of them will help us to download images and plot them
%matplotlib inline import numpy as np import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = 8, 6 import io import urllib import skimage.transform from IPython.display import Image import pickle
code/Experiments/Lasagne_examples/examples/ResNets/resnet50/ImageNet Pretrained Network (ResNet-50).ipynb
matthijsvk/multimodalSR
mit
Build Lasagne model BatchNormalization issue in caffe Caffe doesn't have correct BN layer as described in https://arxiv.org/pdf/1502.03167.pdf: * it can collect datasets mean ($\hat{\mu}$) and variance ($\hat{\sigma}^2$) * it can't fit $\gamma$ and $\beta$ parameters to scale and shift standardized distribution of fe...
Image(filename='images/head.png', width='40%')
code/Experiments/Lasagne_examples/examples/ResNets/resnet50/ImageNet Pretrained Network (ResNet-50).ipynb
matthijsvk/multimodalSR
mit
We can increase, decrease or keep same dimensionality of data using such blocks. In ResNet-50 only several transformation are used. Keep shape with 1x1 convolution We can apply nonlinearity transformation from (None, 64, 56, 56) to (None, 64, 56, 56) if we apply simple block with following parameters (look at the origi...
Image(filename='images/conv1x1.png', width='40%')
code/Experiments/Lasagne_examples/examples/ResNets/resnet50/ImageNet Pretrained Network (ResNet-50).ipynb
matthijsvk/multimodalSR
mit
Keep shape with 3x3 convolution Also we can apply nonlinearity transformation from (None, 64, 56, 56) to (None, 64, 56, 56) if we apply simple block with following parameters (look at the middle of any residual blocks): * num_filters: same as parent has * filter_size: 3x3 * stride: 1 * pad: 1
Image(filename='images/conv3x3.png', width='40%')
code/Experiments/Lasagne_examples/examples/ResNets/resnet50/ImageNet Pretrained Network (ResNet-50).ipynb
matthijsvk/multimodalSR
mit
Increase shape using number of filters We can nonlinearly increase shape from (None, 64, 56, 56) to (None, 256, 56, 56) if we apply simple block with following parameters (look at the last simple block of any risidual block): * num_filters: four times greater then parent has * filter_size: 1x1 * stride: 1 * pad: 0
Image(filename='images/increase_fn.png', width='40%')
code/Experiments/Lasagne_examples/examples/ResNets/resnet50/ImageNet Pretrained Network (ResNet-50).ipynb
matthijsvk/multimodalSR
mit
Increase shape using number of filters We can nonlinearly decrease shape from (None, 256, 56, 56) to (None, 64, 56, 56) if we apply simple block with following parameters (look at the first simple block of any risidual block without left branch): * num_filters: four times less then parent has * filter_size: 1x1 * st...
Image(filename='images/decrease_fn.png', width='40%')
code/Experiments/Lasagne_examples/examples/ResNets/resnet50/ImageNet Pretrained Network (ResNet-50).ipynb
matthijsvk/multimodalSR
mit
Increase shape using number of filters We can also nonlinearly decrease shape from (None, 256, 56, 56) to (None, 128, 28, 28) if we apply simple block with following parameters (look at the first simple block of any risidual block with left branch): * num_filters: two times less then parent has * filter_size: 1x1 * ...
Image(filename='images/decrease_fnstride.png', width='40%')
code/Experiments/Lasagne_examples/examples/ResNets/resnet50/ImageNet Pretrained Network (ResNet-50).ipynb
matthijsvk/multimodalSR
mit
Following function creates simple block
def build_simple_block(incoming_layer, names, num_filters, filter_size, stride, pad, use_bias=False, nonlin=rectify): """Creates stacked Lasagne layers ConvLayer -> BN -> (ReLu) Parameters: ---------- incoming_layer : instance of Lasagne layer ...
code/Experiments/Lasagne_examples/examples/ResNets/resnet50/ImageNet Pretrained Network (ResNet-50).ipynb
matthijsvk/multimodalSR
mit
Residual blocks ResNet also contains several residual blockes built from simple blocks, each of them have two branches; left branch sometimes contains simple block, sometimes not. Each block ends with Elementwise sum layer followed by ReLu nonlinearity. http://ethereon.github.io/netscope/#/gist/410e7e48fa1e5a368ee7bc...
Image(filename='images/left_branch.png', width='40%') Image(filename='images/no_left_branch.png', width='40%') simple_block_name_pattern = ['res%s_branch%i%s', 'bn%s_branch%i%s', 'res%s_branch%i%s_relu'] def build_residual_block(incoming_layer, ratio_n_filter=1.0, ratio_size=1.0, has_left_branch=False, ...
code/Experiments/Lasagne_examples/examples/ResNets/resnet50/ImageNet Pretrained Network (ResNet-50).ipynb
matthijsvk/multimodalSR
mit
Gathering everighting together Create head of the network (everithing before first residual block)
net = {} net['input'] = InputLayer((None, 3, 224, 224)) sub_net, parent_layer_name = build_simple_block( net['input'], ['conv1', 'bn_conv1', 'conv1_relu'], 64, 7, 3, 2, use_bias=True) net.update(sub_net) net['pool1'] = PoolLayer(net[parent_layer_name], pool_size=3, stride=2, pad=0, mode='max', ignore_border=Fal...
code/Experiments/Lasagne_examples/examples/ResNets/resnet50/ImageNet Pretrained Network (ResNet-50).ipynb
matthijsvk/multimodalSR
mit
Create four groups of residual blocks
block_size = list('abc') parent_layer_name = 'pool1' for c in block_size: if c == 'a': sub_net, parent_layer_name = build_residual_block(net[parent_layer_name], 1, 1, True, 4, ix='2%s' % c) else: sub_net, parent_layer_name = build_residual_block(net[parent_layer_name], 1.0/4, 1, False, 4, ix='2%...
code/Experiments/Lasagne_examples/examples/ResNets/resnet50/ImageNet Pretrained Network (ResNet-50).ipynb
matthijsvk/multimodalSR
mit
Create tail of the network (everighting after last resudual block)
net['pool5'] = PoolLayer(net[parent_layer_name], pool_size=7, stride=1, pad=0, mode='average_exc_pad', ignore_border=False) net['fc1000'] = DenseLayer(net['pool5'], num_units=1000, nonlinearity=None) net['prob'] = NonlinearityLayer(net['fc1000'], nonlinearity=softmax) print 'Total number of l...
code/Experiments/Lasagne_examples/examples/ResNets/resnet50/ImageNet Pretrained Network (ResNet-50).ipynb
matthijsvk/multimodalSR
mit