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
And show it in the notebook
ipyd.Image(url='multiple.gif?{}'.format(np.random.rand()), height=500, width=500)
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
What we're seeing is the training process over time. We feed in our `xs`, which consist of the pixel values of each of our 100 images, it goes through the neural network, and out come predicted color values for every possible input value. We visualize it above as a gif by seeing how at each iteration the network has ...
final = gifs[-1] final_gif = [np.clip(((m * 127.5) + 127.5), 0, 255).astype(np.uint8) for m in final] gif.build_gif(final_gif, saveto='final.gif') ipyd.Image(url='final.gif?{}'.format(np.random.rand()), height=200, width=200)
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Part Four - Open Exploration (Extra Credit)I now what you to explore what other possible manipulations of the network and/or dataset you could imagine. Perhaps a process that does the reverse, tries to guess where a given color should be painted? What if it was only taught a certain palette, and had to reason about ...
# Train a network to produce something, storing every few # iterations in the variable gifs, then export the training # over time as a gif. ... gif.build_gif(montage_gifs, saveto='explore.gif') ipyd.Image(url='explore.gif?{}'.format(np.random.rand()), height=500, width=500)
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Assignment SubmissionAfter you've completed the notebook, create a zip file of the current directory using the code below. This code will make sure you have included this completed ipython notebook and the following files named exactly as: session-2/ session-2.ipynb single.gif multiple.gif fina...
utils.build_submission('session-2.zip', ('reference.png', 'single.gif', 'multiple.gif', 'final.gif', 'session-2.ipynb'), ('explore.gif'))
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Cols to drop
# CUST_ID,ONEOFF_PURCHASES Cust.info() Cust.drop(["CUST_ID","ONEOFF_PURCHASES"], axis=1, inplace=True) Cust.info() Cust.TENURE.unique() #Handling Outliers - Method2 def outlier_capping(x): x = x.clip(upper=x.quantile(0.99), lower=x.quantile(0.01)) return x Cust=Cust.apply(lambda x: outlier_capping(x)) #Handlin...
_____no_output_____
MIT
CustSeg.ipynb
pranjalAI/Segmentation-of-Credit-Card-Customers
Standardrizing data - To put data on the same scale
sc=StandardScaler() Cust_scaled=sc.fit_transform(Cust) pd.DataFrame(Cust_scaled).shape
_____no_output_____
MIT
CustSeg.ipynb
pranjalAI/Segmentation-of-Credit-Card-Customers
Applyting PCA
pc = PCA(n_components=16) pc.fit(Cust_scaled) pc.explained_variance_ #Eigen values sum(pc.explained_variance_) #The amount of variance that each PC explains var= pc.explained_variance_ratio_ var #Cumulative Variance explains var1=np.cumsum(np.round(pc.explained_variance_ratio_, decimals=4)*100) var1
_____no_output_____
MIT
CustSeg.ipynb
pranjalAI/Segmentation-of-Credit-Card-Customers
number of components have choosen as 6 based on cumulative variacne is explaining >75 % and individual component explaining >0.8 variance
pc_final=PCA(n_components=6).fit(Cust_scaled) pc_final.explained_variance_ reduced_cr=pc_final.transform(Cust_scaled) dimensions = pd.DataFrame(reduced_cr) dimensions dimensions.columns = ["C1", "C2", "C3", "C4", "C5", "C6"] dimensions.head()
_____no_output_____
MIT
CustSeg.ipynb
pranjalAI/Segmentation-of-Credit-Card-Customers
Factor Loading MatrixLoadings=Eigenvectors * sqrt(Eigenvalues)loadings are the covariances/correlations between the original variables and the unit-scaled components.
Loadings = pd.DataFrame((pc_final.components_.T * np.sqrt(pc_final.explained_variance_)).T,columns=Cust.columns).T Loadings.to_csv("Loadings.csv")
_____no_output_____
MIT
CustSeg.ipynb
pranjalAI/Segmentation-of-Credit-Card-Customers
Clustering
#selected the list variables from PCA based on factor loading matrics list_var = ['PURCHASES_TRX','INSTALLMENTS_PURCHASES','PURCHASES_INSTALLMENTS_FREQUENCY','MINIMUM_PAYMENTS','BALANCE','CREDIT_LIMIT','CASH_ADVANCE','PRC_FULL_PAYMENT','ONEOFF_PURCHASES_FREQUENCY'] Cust_scaled1=pd.DataFrame(Cust_scaled, columns=Cust.co...
_____no_output_____
MIT
CustSeg.ipynb
pranjalAI/Segmentation-of-Credit-Card-Customers
Segmentation
km_3=KMeans(n_clusters=3,random_state=123) km_3.fit(Cust_scaled2) print(km_3.labels_) km_3.cluster_centers_ km_4=KMeans(n_clusters=4,random_state=123).fit(Cust_scaled2) #km_5.labels_a km_5=KMeans(n_clusters=5,random_state=123).fit(Cust_scaled2) #km_5.labels_ km_6=KMeans(n_clusters=6,random_state=123).fit(Cust_scaled2...
_____no_output_____
MIT
CustSeg.ipynb
pranjalAI/Segmentation-of-Credit-Card-Customers
Choosing number clusters using Silhouette Coefficient
# calculate SC for K=6 from sklearn import metrics metrics.silhouette_score(Cust_scaled2, km_3.labels_) # calculate SC for K=3 through K=9 k_range = range(3, 13) scores = [] for k in k_range: km = KMeans(n_clusters=k, random_state=123) km.fit(Cust_scaled2) scores.append(metrics.silhouette_score(Cust_scaled2...
_____no_output_____
MIT
CustSeg.ipynb
pranjalAI/Segmentation-of-Credit-Card-Customers
Segment Distribution
Cust.cluster_3.value_counts()*100/sum(Cust.cluster_3.value_counts()) pd.Series.sort_index(Cust.cluster_3.value_counts())
_____no_output_____
MIT
CustSeg.ipynb
pranjalAI/Segmentation-of-Credit-Card-Customers
Profiling
size=pd.concat([pd.Series(Cust.cluster_3.size), pd.Series.sort_index(Cust.cluster_3.value_counts()), pd.Series.sort_index(Cust.cluster_4.value_counts()), pd.Series.sort_index(Cust.cluster_5.value_counts()), pd.Series.sort_index(Cust.cluster_6.value_counts()), pd.Series.sort_index(Cust.cluster_7.va...
_____no_output_____
MIT
CustSeg.ipynb
pranjalAI/Segmentation-of-Credit-Card-Customers
Copyright 2020 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Writing a training loop from scratch View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Setup
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import numpy as np
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
IntroductionKeras provides default training and evaluation loops, `fit()` and `evaluate()`.Their usage is covered in the guide[Training & evaluation with the built-in methods](https://www.tensorflow.org/guide/keras/train_and_evaluate/).If you want to customize the learning algorithm of your model while still leveragin...
inputs = keras.Input(shape=(784,), name="digits") x1 = layers.Dense(64, activation="relu")(inputs) x2 = layers.Dense(64, activation="relu")(x1) outputs = layers.Dense(10, name="predictions")(x2) model = keras.Model(inputs=inputs, outputs=outputs)
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Let's train it using mini-batch gradient with a custom training loop.First, we're going to need an optimizer, a loss function, and a dataset:
# Instantiate an optimizer. optimizer = keras.optimizers.SGD(learning_rate=1e-3) # Instantiate a loss function. loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) # Prepare the training dataset. batch_size = 64 (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() x_train = np.res...
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Here's our training loop:- We open a `for` loop that iterates over epochs- For each epoch, we open a `for` loop that iterates over the dataset, in batches- For each batch, we open a `GradientTape()` scope- Inside this scope, we call the model (forward pass) and compute the loss- Outside the scope, we retrieve the gradi...
epochs = 2 for epoch in range(epochs): print("\nStart of epoch %d" % (epoch,)) # Iterate over the batches of the dataset. for step, (x_batch_train, y_batch_train) in enumerate(train_dataset): # Open a GradientTape to record the operations run # during the forward pass, which enables auto-d...
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Low-level handling of metricsLet's add metrics monitoring to this basic loop.You can readily reuse the built-in metrics (or custom ones you wrote) in such trainingloops written from scratch. Here's the flow:- Instantiate the metric at the start of the loop- Call `metric.update_state()` after each batch- Call `metric.r...
# Get model inputs = keras.Input(shape=(784,), name="digits") x = layers.Dense(64, activation="relu", name="dense_1")(inputs) x = layers.Dense(64, activation="relu", name="dense_2")(x) outputs = layers.Dense(10, name="predictions")(x) model = keras.Model(inputs=inputs, outputs=outputs) # Instantiate an optimizer to tr...
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Here's our training & evaluation loop:
import time epochs = 2 for epoch in range(epochs): print("\nStart of epoch %d" % (epoch,)) start_time = time.time() # Iterate over the batches of the dataset. for step, (x_batch_train, y_batch_train) in enumerate(train_dataset): with tf.GradientTape() as tape: logits = model(x_batc...
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Speeding-up your training step with `tf.function`The default runtime in TensorFlow 2.0 is[eager execution](https://www.tensorflow.org/guide/eager). As such, our training loopabove executes eagerly.This is great for debugging, but graph compilation has a definite performanceadvantage. Describing your computation as a s...
@tf.function def train_step(x, y): with tf.GradientTape() as tape: logits = model(x, training=True) loss_value = loss_fn(y, logits) grads = tape.gradient(loss_value, model.trainable_weights) optimizer.apply_gradients(zip(grads, model.trainable_weights)) train_acc_metric.update_state(y, l...
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Let's do the same with the evaluation step:
@tf.function def test_step(x, y): val_logits = model(x, training=False) val_acc_metric.update_state(y, val_logits)
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Now, let's re-run our training loop with this compiled training step:
import time epochs = 2 for epoch in range(epochs): print("\nStart of epoch %d" % (epoch,)) start_time = time.time() # Iterate over the batches of the dataset. for step, (x_batch_train, y_batch_train) in enumerate(train_dataset): loss_value = train_step(x_batch_train, y_batch_train) # ...
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Much faster, isn't it? Low-level handling of losses tracked by the modelLayers & models recursively track any losses created during the forward passby layers that call `self.add_loss(value)`. The resulting list of scalar lossvalues are available via the property `model.losses`at the end of the forward pass.If you want...
class ActivityRegularizationLayer(layers.Layer): def call(self, inputs): self.add_loss(1e-2 * tf.reduce_sum(inputs)) return inputs
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Let's build a really simple model that uses it:
inputs = keras.Input(shape=(784,), name="digits") x = layers.Dense(64, activation="relu")(inputs) # Insert activity regularization as a layer x = ActivityRegularizationLayer()(x) x = layers.Dense(64, activation="relu")(x) outputs = layers.Dense(10, name="predictions")(x) model = keras.Model(inputs=inputs, outputs=outp...
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Here's what our training step should look like now:
@tf.function def train_step(x, y): with tf.GradientTape() as tape: logits = model(x, training=True) loss_value = loss_fn(y, logits) # Add any extra losses created during the forward pass. loss_value += sum(model.losses) grads = tape.gradient(loss_value, model.trainable_weights) ...
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
SummaryNow you know everything there is to know about using built-in training loops andwriting your own from scratch.To conclude, here's a simple end-to-end example that ties together everythingyou've learned in this guide: a DCGAN trained on MNIST digits. End-to-end example: a GAN training loop from scratchYou may b...
discriminator = keras.Sequential( [ keras.Input(shape=(28, 28, 1)), layers.Conv2D(64, (3, 3), strides=(2, 2), padding="same"), layers.LeakyReLU(alpha=0.2), layers.Conv2D(128, (3, 3), strides=(2, 2), padding="same"), layers.LeakyReLU(alpha=0.2), layers.GlobalMaxPooling...
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Then let's create a generator network,that turns latent vectors into outputs of shape `(28, 28, 1)` (representingMNIST digits):
latent_dim = 128 generator = keras.Sequential( [ keras.Input(shape=(latent_dim,)), # We want to generate 128 coefficients to reshape into a 7x7x128 map layers.Dense(7 * 7 * 128), layers.LeakyReLU(alpha=0.2), layers.Reshape((7, 7, 128)), layers.Conv2DTranspose(128, (4...
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Here's the key bit: the training loop. As you can see it is quite straightforward. Thetraining step function only takes 17 lines.
# Instantiate one optimizer for the discriminator and another for the generator. d_optimizer = keras.optimizers.Adam(learning_rate=0.0003) g_optimizer = keras.optimizers.Adam(learning_rate=0.0004) # Instantiate a loss function. loss_fn = keras.losses.BinaryCrossentropy(from_logits=True) @tf.function def train_step(r...
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Let's train our GAN, by repeatedly calling `train_step` on batches of images.Since our discriminator and generator are convnets, you're going to want torun this code on a GPU.
import os # Prepare the dataset. We use both the training & test MNIST digits. batch_size = 64 (x_train, _), (x_test, _) = keras.datasets.mnist.load_data() all_digits = np.concatenate([x_train, x_test]) all_digits = all_digits.astype("float32") / 255.0 all_digits = np.reshape(all_digits, (-1, 28, 28, 1)) dataset = tf....
_____no_output_____
Apache-2.0
site/en-snapshot/guide/keras/writing_a_training_loop_from_scratch.ipynb
masa-ita/docs-l10n
Title
# SERVIÇO FLORESTAL BRASILEIRO # Sistema Nacional de Informações Florestais # Incêndios Florestais
_____no_output_____
MIT
SNIF/.ipynb_checkpoints/SNIF_Focos de calor_xlsx-checkpoint.ipynb
geanclm/LabHacker
Import libs
import pandas as pd
_____no_output_____
MIT
SNIF/.ipynb_checkpoints/SNIF_Focos de calor_xlsx-checkpoint.ipynb
geanclm/LabHacker
Import data
# fonte: https://snif.florestal.gov.br/pt-br/incendios-florestais df = pd.read_excel('focos_calor_1998_2019.xlsx') df.shape df.info() df df[df['Número']==df['Número'].max()]
_____no_output_____
MIT
SNIF/.ipynb_checkpoints/SNIF_Focos de calor_xlsx-checkpoint.ipynb
geanclm/LabHacker
使用scikit_learn中的kNN
from sklearn.neighbors import KNeighborsClassifier kNN_classifier = KNeighborsClassifier(n_neighbors=6) kNN_classifier.fit(X_train, y_train) kNN_classifier.predict(x) y_predict = kNN_classifier.predict(x) y_predict[0]
_____no_output_____
Apache-2.0
data-science/scikit-learn/02/02 kNN-in-Scikit-Learn.ipynb
le3t/ko-repo
重新整理我们的kNN的代码
%run ../kNN/kNN.py knn_clf = KNNClassifier(k=6) knn_clf.fit(X_train, y_train) y_predict = knn_clf.predict(x) y_predict y_predict[0]
_____no_output_____
Apache-2.0
data-science/scikit-learn/02/02 kNN-in-Scikit-Learn.ipynb
le3t/ko-repo
Week 3: Improve MNIST with ConvolutionsIn the videos you looked at how you would improve Fashion MNIST using Convolutions. For this exercise see if you can improve MNIST to 99.5% accuracy or more by adding only a single convolutional layer and a single MaxPooling 2D layer to the model from the assignment of the previ...
import os import numpy as np import tensorflow as tf from tensorflow import keras
_____no_output_____
Apache-2.0
C1/W3/assignment/C1W3_Assignment.ipynb
druvdub/Tensorflow-Specialization
Begin by loading the data. A couple of things to notice:- The file `mnist.npz` is already included in the current workspace under the `data` directory. By default the `load_data` from Keras accepts a path relative to `~/.keras/datasets` but in this case it is stored somewhere else, as a result of this, you need to spec...
# Load the data # Get current working directory current_dir = os.getcwd() # Append data/mnist.npz to the previous path to get the full path data_path = os.path.join(current_dir, "data/mnist.npz") # Get only training set (training_images, training_labels), _ = tf.keras.datasets.mnist.load_data(path=data_path)
_____no_output_____
Apache-2.0
C1/W3/assignment/C1W3_Assignment.ipynb
druvdub/Tensorflow-Specialization
One important step when dealing with image data is to preprocess the data. During the preprocess step you can apply transformations to the dataset that will be fed into your convolutional neural network.Here you will apply two transformations to the data:- Reshape the data so that it has an extra dimension. The reason ...
# GRADED FUNCTION: reshape_and_normalize def reshape_and_normalize(images): ### START CODE HERE # Reshape the images to add an extra dimension images = np.reshape(images, images.shape + (1,)) # Normalize pixel values images = np.divide(images,255) ### END CODE HERE return i...
_____no_output_____
Apache-2.0
C1/W3/assignment/C1W3_Assignment.ipynb
druvdub/Tensorflow-Specialization
Test your function with the next cell:
# Reload the images in case you run this cell multiple times (training_images, _), _ = tf.keras.datasets.mnist.load_data(path=data_path) # Apply your function training_images = reshape_and_normalize(training_images) print(f"Maximum pixel value after normalization: {np.max(training_images)}\n") print(f"Shape of train...
Maximum pixel value after normalization: 1.0 Shape of training set after reshaping: (60000, 28, 28, 1) Shape of one image after reshaping: (28, 28, 1)
Apache-2.0
C1/W3/assignment/C1W3_Assignment.ipynb
druvdub/Tensorflow-Specialization
**Expected Output:**```Maximum pixel value after normalization: 1.0Shape of training set after reshaping: (60000, 28, 28, 1)Shape of one image after reshaping: (28, 28, 1)``` Now complete the callback that will ensure that training will stop after an accuracy of 99.5% is reached:
# GRADED CLASS: myCallback ### START CODE HERE # Remember to inherit from the correct class class myCallback(tf.keras.callbacks.Callback): # Define the method that checks the accuracy at the end of each epoch def on_epoch_end(self, epoch, logs={}): # check accuracy if logs.get('accuracy') >= 0....
_____no_output_____
Apache-2.0
C1/W3/assignment/C1W3_Assignment.ipynb
druvdub/Tensorflow-Specialization
Finally, complete the `convolutional_model` function below. This function should return your convolutional neural network:
# GRADED FUNCTION: convolutional_model def convolutional_model(): ### START CODE HERE # Define the model, it should have 5 layers: # - A Conv2D layer with 32 filters, a kernel_size of 3x3, ReLU activation function # and an input shape that matches that of every image in the training set # - A Ma...
Epoch 1/10 1875/1875 [==============================] - 36s 19ms/step - loss: 0.1522 - accuracy: 0.9548 Epoch 2/10 1875/1875 [==============================] - 35s 19ms/step - loss: 0.0529 - accuracy: 0.9840 Epoch 3/10 1875/1875 [==============================] - 35s 19ms/step - loss: 0.0327 - accuracy: 0.9897 Epoch 4/...
Apache-2.0
C1/W3/assignment/C1W3_Assignment.ipynb
druvdub/Tensorflow-Specialization
If you see the message that you defined in your callback printed out after less than 10 epochs it means your callback worked as expected. You can also double check by running the following cell:
print(f"Your model was trained for {len(history.epoch)} epochs")
Your model was trained for 5 epochs
Apache-2.0
C1/W3/assignment/C1W3_Assignment.ipynb
druvdub/Tensorflow-Specialization
Data and TrainingThe **augmented** cough audio dataset of the [Project Coswara](https://coswara.iisc.ac.in/about) was used to train the deep CNN model.The preprocessing steps and CNN architecture is as shown below. The training code is concealed on Github to protect the exact hyperparameters and maintain performance i...
import ibm_boto3 from ibm_botocore.client import Config # @hidden_cell # The following code contains the credentials for a file in your IBM Cloud Object Storage. # You might want to remove those credentials before you share your notebook. credentials_2 = { 'IAM_SERVICE_ID': <>, 'IBM_API_KEY_ID': <>, 'ENDPO...
_____no_output_____
MIT
ML model/model-deploy.ipynb
darshkaushik/cough-it
Set up Watson Machine Learning Client and Deployment space
from ibm_watson_machine_learning import APIClient wml_credentials = { "apikey" : <>, "url" : <> } client = APIClient( wml_credentials ) space_guid = <> client.set.default_space(space_guid)
_____no_output_____
MIT
ML model/model-deploy.ipynb
darshkaushik/cough-it
Store the model
sofware_spec_uid = client.software_specifications.get_id_by_name("default_py3.8") metadata = { client.repository.ModelMetaNames.NAME: "cough-it model", client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: sofware_spec_uid, client.repository.ModelMetaNames.TYPE: "tensorflow_2.4" } published_model = client.re...
_____no_output_____
MIT
ML model/model-deploy.ipynb
darshkaushik/cough-it
Create a deployment
dep_metadata = { client.deployments.ConfigurationMetaNames.NAME: "Deployment of external Keras model", client.deployments.ConfigurationMetaNames.ONLINE: {} } created_deployment = client.deployments.create(published_model_uid, meta_props=dep_metadata) deployment_uid = client.deployments.get_uid(created_deploym...
_____no_output_____
MIT
ML model/model-deploy.ipynb
darshkaushik/cough-it
Joy Ride - Part 3: Parallel ParkingIn this section you will write a function that implements the correct sequence of steps required to parallel park a vehicle.NOTE: for this segment the vehicle's maximum speed has been set to just over 4 mph. This should make parking a little easier.![](https://upload.wikimedia.org/wi...
# SETUP CELL %%HTML <link rel="stylesheet" type="text/css" href="buttonStyle.css"> <button id="launcher">Load Car Simulator </button> <button id="restart">Restart Connection</button> <script src="setupLauncher.js"></script><div id="simulator_frame"></sim> <script src="kernelRestart.js"></script> # CODE CELL # Before/...
running CONNECTED ('172.18.0.1', 50088) connected
MIT
ParallelParking.ipynb
ianleongg/Joy-Ride-Parallel-Parking
Submitting this Project!Your parallel park function is "correct" when:1. Your car doesn't hit any other cars.2. Your car stops completely inside of the right lane.Once you've got it working, it's time to submit. Submit by pressing the `SUBMIT` button at the lower right corner of this page.
# CODE CELL # Before/After running any code changes make sure to click the button "Restart Connection" above first. # Also make sure to click Reset in the simulator to refresh the connection. # You need to wait for the Kernel Ready message. car_parameters = {"throttle": 0, "steer": 0, "brake": 0} def control(pos_x,...
_____no_output_____
MIT
ParallelParking.ipynb
ianleongg/Joy-Ride-Parallel-Parking
The Basics of NumPy Arrays **Python- Numpy Practice Session-S4 : Save a Copy in local drive and Work** Data manipulation in Python is nearly synonymous with NumPy array manipulation: even newer tools like Pandas ([Chapter 3](03.00-Introduction-to-Pandas.ipynb)) are built around the NumPy array.This section will prese...
import numpy as np np.random.seed(0) # seed for reproducibility x1 = np.random.randint(10, size=6) # One-dimensional array x2 = np.random.randint(10, size=(3, 4)) # Two-dimensional array x3 = np.random.randint(10, size=(3, 4, 5)) # Three-dimensional array
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Each array has attributes ``ndim`` (the number of dimensions), ``shape`` (the size of each dimension), and ``size`` (the total size of the array):
print("x3 ndim: ", x3.ndim) print("x3 shape:", x3.shape) print("x3 size: ", x3.size)
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Another useful attribute is the ``dtype``, the data type of the array (which we discussed previously in [Understanding Data Types in Python](02.01-Understanding-Data-Types.ipynb)):
print("dtype:", x3.dtype)
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Other attributes include ``itemsize``, which lists the size (in bytes) of each array element, and ``nbytes``, which lists the total size (in bytes) of the array:
print("itemsize:", x3.itemsize, "bytes") print("nbytes:", x3.nbytes, "bytes")
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
In general, we expect that ``nbytes`` is equal to ``itemsize`` times ``size``. Array Indexing: Accessing Single Elements If you are familiar with Python's standard list indexing, indexing in NumPy will feel quite familiar.In a one-dimensional array, the $i^{th}$ value (counting from zero) can be accessed by specifying...
x1 x1[0] x1[4]
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
To index from the end of the array, you can use negative indices:
x1[-1] x1[-2]
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
In a multi-dimensional array, items can be accessed using a comma-separated tuple of indices:
x2 x2[0, 0] x2[2, 0] x2[2, -1]
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Values can also be modified using any of the above index notation:
x2[0, 0] = 12 x2
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Keep in mind that, unlike Python lists, NumPy arrays have a fixed type.This means, for example, that if you attempt to insert a floating-point value to an integer array, the value will be silently truncated. Don't be caught unaware by this behavior!
x1[0] = 3.14159 # this will be truncated! x1
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Array Slicing: Accessing Subarrays Just as we can use square brackets to access individual array elements, we can also use them to access subarrays with the *slice* notation, marked by the colon (``:``) character.The NumPy slicing syntax follows that of the standard Python list; to access a slice of an array ``x``, us...
x = np.arange(10) x x[:5] # first five elements x[5:] # elements after index 5 x[4:7] # middle sub-array x[::2] # every other element x[1::2] # every other element, starting at index 1
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
A potentially confusing case is when the ``step`` value is negative.In this case, the defaults for ``start`` and ``stop`` are swapped.This becomes a convenient way to reverse an array:
x[::-1] # all elements, reversed x[5::-2] # reversed every other from index 5
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Multi-dimensional subarraysMulti-dimensional slices work in the same way, with multiple slices separated by commas.For example:
x2 x2[:2, :3] # two rows, three columns x2[:3, ::2] # all rows, every other column
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Finally, subarray dimensions can even be reversed together:
x2[::-1, ::-1]
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Accessing array rows and columnsOne commonly needed routine is accessing of single rows or columns of an array.This can be done by combining indexing and slicing, using an empty slice marked by a single colon (``:``):
print(x2[:, 0]) # first column of x2 print(x2[0, :]) # first row of x2
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
In the case of row access, the empty slice can be omitted for a more compact syntax:
print(x2[0]) # equivalent to x2[0, :]
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Subarrays as no-copy viewsOne important–and extremely useful–thing to know about array slices is that they return *views* rather than *copies* of the array data.This is one area in which NumPy array slicing differs from Python list slicing: in lists, slices will be copies.Consider our two-dimensional array from before...
print(x2)
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Let's extract a $2 \times 2$ subarray from this:
x2_sub = x2[:2, :2] print(x2_sub)
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Now if we modify this subarray, we'll see that the original array is changed! Observe:
x2_sub[0, 0] = 99 print(x2_sub) print(x2)
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
This default behavior is actually quite useful: it means that when we work with large datasets, we can access and process pieces of these datasets without the need to copy the underlying data buffer. Creating copies of arraysDespite the nice features of array views, it is sometimes useful to instead explicitly copy th...
x2_sub_copy = x2[:2, :2].copy() print(x2_sub_copy)
[[3 5] [7 6]]
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
If we now modify this subarray, the original array is not touched:
x2_sub_copy[0, 0] = 42 print(x2_sub_copy) print(x2)
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Reshaping of ArraysAnother useful type of operation is reshaping of arrays.The most flexible way of doing this is with the ``reshape`` method.For example, if you want to put the numbers 1 through 9 in a $3 \times 3$ grid, you can do the following:
grid = np.arange(1, 10).reshape((3, 3)) print(grid)
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Note that for this to work, the size of the initial array must match the size of the reshaped array. Where possible, the ``reshape`` method will use a no-copy view of the initial array, but with non-contiguous memory buffers this is not always the case.Another common reshaping pattern is the conversion of a one-dimensi...
x = np.array([1, 2, 3]) # row vector via reshape x.reshape((1, 3)) # row vector via newaxis x[np.newaxis, :] # column vector via reshape x.reshape((3, 1)) # column vector via newaxis x[:, np.newaxis]
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
We will see this type of transformation often throughout the remainder of the book. Array Concatenation and SplittingAll of the preceding routines worked on single arrays. It's also possible to combine multiple arrays into one, and to conversely split a single array into multiple arrays. We'll take a look at those ope...
x = np.array([1, 2, 3]) y = np.array([3, 2, 1]) np.concatenate([x, y])
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
You can also concatenate more than two arrays at once:
z = [99, 99, 99] print(np.concatenate([x, y, z]))
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
It can also be used for two-dimensional arrays:
grid = np.array([[1, 2, 3], [4, 5, 6]]) # concatenate along the first axis np.concatenate([grid, grid]) # concatenate along the second axis (zero-indexed) np.concatenate([grid, grid], axis=1)
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
For working with arrays of mixed dimensions, it can be clearer to use the ``np.vstack`` (vertical stack) and ``np.hstack`` (horizontal stack) functions:
x = np.array([1, 2, 3]) grid = np.array([[9, 8, 7], [6, 5, 4]]) # vertically stack the arrays np.vstack([x, grid]) # horizontally stack the arrays y = np.array([[99], [99]]) np.hstack([grid, y])
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Similary, ``np.dstack`` will stack arrays along the third axis. Splitting of arraysThe opposite of concatenation is splitting, which is implemented by the functions ``np.split``, ``np.hsplit``, and ``np.vsplit``. For each of these, we can pass a list of indices giving the split points:
x = [1, 2, 3, 99, 99, 3, 2, 1] x1, x2, x3 = np.split(x, [3, 5]) print(x1, x2, x3)
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Notice that *N* split-points, leads to *N + 1* subarrays.The related functions ``np.hsplit`` and ``np.vsplit`` are similar:
grid = np.arange(16).reshape((4, 4)) grid upper, lower = np.vsplit(grid, [2]) print(upper) print(lower) left, right = np.hsplit(grid, [2]) print(left) print(right)
_____no_output_____
MIT
OOP/Practice Sessions/Python_S4_Basics_Of_NumPy_Arrays.ipynb
siddhantdixit/OOP-ClassWork
Scraping and Parsing: EAD XML Finding Aids from the Library of Congress
import os from urllib.request import urlopen from bs4 import BeautifulSoup import subprocess ## Creating a directory called 'LOC_Metadata' and setting it as our current working directory !mkdir /sharedfolder/LOC_Metadata os.chdir('/sharedfolder/LOC_Metadata') ## To make this notebook self-contained, we'll download a ...
_____no_output_____
CC0-1.0
Week-06_Scraping-and-Parsing-XML.ipynb
pcda17/pcda
Dependencies
import warnings, glob from tensorflow.keras import Sequential, Model from cassava_scripts import * seed = 0 seed_everything(seed) warnings.filterwarnings('ignore')
_____no_output_____
MIT
Model backlog/Models/Inference/162-cassava-leaf-inf-effnetb4-dcr-04-380x380.ipynb
dimitreOliveira/Cassava-Leaf-Disease-Classification
Hardware configuration
# TPU or GPU detection # Detect hardware, return appropriate distribution strategy strategy, tpu = set_up_strategy() AUTO = tf.data.experimental.AUTOTUNE REPLICAS = strategy.num_replicas_in_sync print(f'REPLICAS: {REPLICAS}')
REPLICAS: 1
MIT
Model backlog/Models/Inference/162-cassava-leaf-inf-effnetb4-dcr-04-380x380.ipynb
dimitreOliveira/Cassava-Leaf-Disease-Classification
Model parameters
BATCH_SIZE = 8 * REPLICAS HEIGHT = 380 WIDTH = 380 CHANNELS = 3 N_CLASSES = 5 TTA_STEPS = 0 # Do TTA if > 0
_____no_output_____
MIT
Model backlog/Models/Inference/162-cassava-leaf-inf-effnetb4-dcr-04-380x380.ipynb
dimitreOliveira/Cassava-Leaf-Disease-Classification
Augmentation
def data_augment(image, label): p_spatial = tf.random.uniform([], 0, 1.0, dtype=tf.float32) # Flips image = tf.image.random_flip_left_right(image) image = tf.image.random_flip_up_down(image) if p_spatial > .75: image = tf.image.transpose(image) return image, label
_____no_output_____
MIT
Model backlog/Models/Inference/162-cassava-leaf-inf-effnetb4-dcr-04-380x380.ipynb
dimitreOliveira/Cassava-Leaf-Disease-Classification
Auxiliary functions
# Datasets utility functions def resize_image(image, label): image = tf.image.resize(image, [HEIGHT, WIDTH]) image = tf.reshape(image, [HEIGHT, WIDTH, CHANNELS]) return image, label def process_path(file_path): name = get_name(file_path) img = tf.io.read_file(file_path) img = decode_image(img) ...
_____no_output_____
MIT
Model backlog/Models/Inference/162-cassava-leaf-inf-effnetb4-dcr-04-380x380.ipynb
dimitreOliveira/Cassava-Leaf-Disease-Classification
Load data
database_base_path = '/kaggle/input/cassava-leaf-disease-classification/' submission = pd.read_csv(f'{database_base_path}sample_submission.csv') display(submission.head()) TEST_FILENAMES = tf.io.gfile.glob(f'{database_base_path}test_tfrecords/ld_test*.tfrec') NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES) print(f'...
Models to predict: /kaggle/input/162-cassava-leaf-effnetb4-dcr-04-380x380/model_0.h5
MIT
Model backlog/Models/Inference/162-cassava-leaf-inf-effnetb4-dcr-04-380x380.ipynb
dimitreOliveira/Cassava-Leaf-Disease-Classification
Model
def model_fn(input_shape, N_CLASSES): inputs = L.Input(shape=input_shape, name='input_image') base_model = tf.keras.applications.EfficientNetB4(input_tensor=inputs, include_top=False, drop_connect_rate=...
Model: "model" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== input_im...
MIT
Model backlog/Models/Inference/162-cassava-leaf-inf-effnetb4-dcr-04-380x380.ipynb
dimitreOliveira/Cassava-Leaf-Disease-Classification
Test set predictions
files_path = f'{database_base_path}test_images/' test_size = len(os.listdir(files_path)) test_preds = np.zeros((test_size, N_CLASSES)) for model_path in model_path_list: print(model_path) K.clear_session() model.load_weights(model_path) if TTA_STEPS > 0: test_ds = get_dataset(files_path, tta=...
_____no_output_____
MIT
Model backlog/Models/Inference/162-cassava-leaf-inf-effnetb4-dcr-04-380x380.ipynb
dimitreOliveira/Cassava-Leaf-Disease-Classification
String Criando uma String Para criar uma string em python você pode usar aspas simples ou duplas
# Uma única palavra 'Olá' # uma frase 'isto é uma string em pyton' # usando aspas duplas "teste aspa duplas" # combinação "podemos utilizas as duas aspas ou uma no 'python'"
_____no_output_____
MIT
02-Variaveis_Tipo_Estrutura_Dados/03-Strings.ipynb
alineAssuncao/Python_Fundamentos_Analise_Dados
Imprimindo uma String
print ('imprimindo uma String') print ('testando \nString \nem \nPython') print ('\n')
MIT
02-Variaveis_Tipo_Estrutura_Dados/03-Strings.ipynb
alineAssuncao/Python_Fundamentos_Analise_Dados
Indexando Strings
# Atribuindo uma string s = 'Data Science Academy' print (s) # primeiro elemento da string s[0] s[1] s[2]
_____no_output_____
MIT
02-Variaveis_Tipo_Estrutura_Dados/03-Strings.ipynb
alineAssuncao/Python_Fundamentos_Analise_Dados
Podemos usar : para executar um slicing que faz a leitura de tudo até um ponto designado
# retorna os elementos sa string, começando em uma posição s[1:] # a string continua inalterada s # retorna tudo até uma posição anterior da informada s[:3] # retorna uma determinada cadeia de caracter s[2:6] s[:] # indexação negativa para ler de trás para frente # busca apenas a posição informada s[-2] # retorna tudo...
_____no_output_____
MIT
02-Variaveis_Tipo_Estrutura_Dados/03-Strings.ipynb
alineAssuncao/Python_Fundamentos_Analise_Dados
Podemos usar a notação de índice e fatiar a string em pedaços especificos
s[::1] s[::2] s[::-1]
_____no_output_____
MIT
02-Variaveis_Tipo_Estrutura_Dados/03-Strings.ipynb
alineAssuncao/Python_Fundamentos_Analise_Dados
Propriedades de string
s # Alterando um caracter (não permite a alteração - imutaveis) s[0] = 'x' # concatenando strings s + ' é a melhor' print (s) s = s + ' é a melhor' print(s) # podemos usar o símbolo de multiplicação para criar repetição letra = 'W' letra * 3
_____no_output_____
MIT
02-Variaveis_Tipo_Estrutura_Dados/03-Strings.ipynb
alineAssuncao/Python_Fundamentos_Analise_Dados
Funções Built-in de strings
s # upper case s.upper() #lower case s.lower() # dividir uma string por espaços em branco(padrão) s.split() # dividindo com um elemento especifico s.split('y')
_____no_output_____
MIT
02-Variaveis_Tipo_Estrutura_Dados/03-Strings.ipynb
alineAssuncao/Python_Fundamentos_Analise_Dados
Funções de string
s = 'olá! Seja bem vindo ao universo Python' s.capitalize() s.count('a') s.find('p') s.center(20, 'z') s.isalnum() s.islower() s.isspace() s.endswith('o') s.partition('!')
_____no_output_____
MIT
02-Variaveis_Tipo_Estrutura_Dados/03-Strings.ipynb
alineAssuncao/Python_Fundamentos_Analise_Dados
Comparando Strings
print ("Python" == "R") print ("Python" == "Python")
True
MIT
02-Variaveis_Tipo_Estrutura_Dados/03-Strings.ipynb
alineAssuncao/Python_Fundamentos_Analise_Dados
This notebook deals with banks of cylinders in a cross flow. Cylinder banks are common heat exchangers where the cylinders may be heated by electricity or a fluid may be flowing within the cylinder to cool or heat the flow around the cylinders. The advantage of cylinder banks is the increase mixing in the fluid, thus t...
import numpy as np from Libraries import thermodynamics as thermo from Libraries import HT_external_convection as extconv T_i = 25 #C T_o = 75 #C T_s = 100 #C V_i = 5 #m/s L = 1 #m D = 10e-3 #mm N_L = 14 S_T = S_L = 15e-3 #m # ?extconv.BankofTubes bank = extconv.BankofTubes('aligned','air',T_i,T_s,T_o,"C",V_i,D,S_L,S...
The number of rows required to reach T_o=75 C is 15.26
CC-BY-3.0
HT-banks_of_tubes.ipynb
CarlGriffinsteed/UVM-ME144-Heat-Transfer
If the outlet temperature can be slightly below $75^\circ\mathrm{C}$, then the number of rows is 15.If the outlet temperature has to be at least $75^\circ\mathrm{C}$, then the number of rows is 16.
N_L = 15 bank = extconv.BankofTubes('aligned','air',T_i,T_s,T_o,"C",V_i,D,S_L,S_T,N_L) N_T = 14 bank.temperature_outlet_tube_banks(N_T,N_L) print("With N_L=%.0f, T_o=%.2f" %(bank.N_L,bank.T_o)) print("Re=%.0f, P_L = %.2f" %(bank.Re,bank.S_T/bank.D)) bank.pressure_drop(N_L,3.2,1) print("Pressure drop is %.2f Pa" %(bank....
With N_L=15, T_o=74.54 Re=9052, P_L = 1.50 Pressure drop is 6401.70
CC-BY-3.0
HT-banks_of_tubes.ipynb
CarlGriffinsteed/UVM-ME144-Heat-Transfer
Problem 2A preheater involves the use of condensing steam at $100^\circ\text{C}$ on the inside of a bank of tubes to heat air that enters at $1 \text{ atm}$ and $25^\circ\text{C}$. The air moves at $5\text{ m/s}$ in cross flow over the tubes. Each tube is $1\text{ m}$ long and has an outside diameter of $10 \text{ mm}...
N_L = N_T = 14 # T_o = 50. # bank = extconv.BankofTubes('aligned','air',T_i,T_s,T_o,"C",V_i,D,S_L,S_T,N_L) # bank.temperature_outlet_tube_banks(N_T,N_L) # print(bank.T_o) # print(bank.Re) # print(bank.Nu) T_o = 72.6 bank = extconv.BankofTubes('aligned','air',T_i,T_s,T_o,"C",V_i,D,S_L,S_T,N_L) bank.temperature_outlet_tu...
72.60620496012206 9080.451003545966 73.95776478607291 59665.2457253688
CC-BY-3.0
HT-banks_of_tubes.ipynb
CarlGriffinsteed/UVM-ME144-Heat-Transfer
Problem 3 An air duct heater consists of an aligned array of electrical heating elements in which the longitudinal and transverse pitches are $S_L=S_T= 24\text{ mm}$. There are 3 rows of elements in the flow direction ($N_L=3$) and 4 elements per row ($N_T=4$). Atmospheric air with an upstream velocity of $12\text{ m/s...
_____no_output_____
CC-BY-3.0
HT-banks_of_tubes.ipynb
CarlGriffinsteed/UVM-ME144-Heat-Transfer
Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License. Training Pipeline - Custom Script_**Training many models using a custom script**_----This notebook demonstrates how to create a pipeline that trains and registers many models using a custom script. We utilize the [ParallelRunStep]...
#!pip install --upgrade azureml-sdk # !pip install azureml-pipeline-steps
_____no_output_____
MIT
Custom_Script/02_CustomScript_Training_Pipeline.ipynb
ben-chin-unify/solution-accelerator-many-models