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
Here you can see that although the finite difference formula is fast to compute the gradients themselves in the analytical case, when it came to the sampling based methods it was far too noisy. More careful techniques must be used to ensure a good gradient can be calculated. Next you will look at a much slower techniqu...
# A smarter differentiation scheme. gradient_safe_sampled_expectation = tfq.layers.SampledExpectation( differentiator=tfq.differentiators.ParameterShift()) with tf.GradientTape() as g: g.watch(values_tensor) imperfect_outputs = gradient_safe_sampled_expectation( my_circuit, operators=pauli_...
_____no_output_____
Apache-2.0
docs/tutorials/gradients.ipynb
HectorIGH/quantum
From the above you can see that certain differentiators are best used for particular research scenarios. In general, the slower sample-based methods that are robust to device noise, etc., are great differentiators when testing or implementing algorithms in a more "real world" setting. Faster methods like finite differe...
pauli_z = cirq.Z(qubit) pauli_z
_____no_output_____
Apache-2.0
docs/tutorials/gradients.ipynb
HectorIGH/quantum
If this observable is used with the same circuit as before, then you have $f_{2}(\alpha) = ⟨Y(\alpha)| Z | Y(\alpha)⟩ = \cos(\pi \alpha)$ and $f_{2}^{'}(\alpha) = -\pi \sin(\pi \alpha)$. Perform a quick check:
test_value = 0. print('Finite difference:', my_grad(pauli_z, test_value)) print('Sin formula: ', -np.pi * np.sin(np.pi * test_value))
_____no_output_____
Apache-2.0
docs/tutorials/gradients.ipynb
HectorIGH/quantum
It's a match (close enough).Now if you define $g(\alpha) = f_{1}(\alpha) + f_{2}(\alpha)$ then $g'(\alpha) = f_{1}^{'}(\alpha) + f^{'}_{2}(\alpha)$. Defining more than one observable in TensorFlow Quantum to use along with a circuit is equivalent to adding on more terms to $g$.This means that the gradient of a particul...
sum_of_outputs = tfq.layers.Expectation( differentiator=tfq.differentiators.ForwardDifference(grid_spacing=0.01)) sum_of_outputs(my_circuit, operators=[pauli_x, pauli_z], symbol_names=['alpha'], symbol_values=[[test_value]])
_____no_output_____
Apache-2.0
docs/tutorials/gradients.ipynb
HectorIGH/quantum
Here you see the first entry is the expectation w.r.t Pauli X, and the second is the expectation w.r.t Pauli Z. Now when you take the gradient:
test_value_tensor = tf.convert_to_tensor([[test_value]]) with tf.GradientTape() as g: g.watch(test_value_tensor) outputs = sum_of_outputs(my_circuit, operators=[pauli_x, pauli_z], symbol_names=['alpha'], symbol_values=test_v...
_____no_output_____
Apache-2.0
docs/tutorials/gradients.ipynb
HectorIGH/quantum
Here you have verified that the sum of the gradients for each observable is indeed the gradient of $\alpha$. This behavior is supported by all TensorFlow Quantum differentiators and plays a crucial role in the compatibility with the rest of TensorFlow. 4. Advanced usageHere you will learn how to define your own custom...
class MyDifferentiator(tfq.differentiators.Differentiator): """A Toy differentiator for <Y^alpha | X |Y^alpha>.""" def __init__(self): pass @tf.function def get_gradient_circuits(self, programs, symbol_names, symbol_values): """Return circuits to compute gradients for given forward pas...
_____no_output_____
Apache-2.0
docs/tutorials/gradients.ipynb
HectorIGH/quantum
This new differentiator can now be used with existing `tfq.layer` objects:
custom_dif = MyDifferentiator() custom_grad_expectation = tfq.layers.Expectation(differentiator=custom_dif) # Now let's get the gradients with finite diff. with tf.GradientTape() as g: g.watch(values_tensor) exact_outputs = expectation_calculation(my_circuit, operato...
_____no_output_____
Apache-2.0
docs/tutorials/gradients.ipynb
HectorIGH/quantum
This new differentiator can now be used to generate differentiable ops.Key Point: A differentiator that has been previously attached to an op must be refreshed before attaching to a new op, because a differentiator may only be attached to one op at a time.
# Create a noisy sample based expectation op. expectation_sampled = tfq.get_sampled_expectation_op( cirq.DensityMatrixSimulator(noise=cirq.depolarize(0.01))) # Make it differentiable with your differentiator: # Remember to refresh the differentiator before attaching the new op custom_dif.refresh() differentiable_o...
_____no_output_____
Apache-2.0
docs/tutorials/gradients.ipynb
HectorIGH/quantum
Now You Code 2: Is That An Email Address?Let's use Python's built-in string functions to write our own function to detect if a string is an email address. The function `isEmail(text)` should return `True` when `text` is an email address, `False` otherwise. For simplicity's sake we will define an email address to be a...
## Step 2: Todo write the function definition for isEmail functiuon ## Step 3: Write some tests, to ensure the function works, for example ## Make sure to test all cases! print("WHEN text=mike@syr.edu We EXPECT isEmail(text) to return True", "ACTUAL", isEmail("mike@syr.edu") ) print("WHEN text=mike@ We EXPECT isEmail(...
_____no_output_____
MIT
content/lessons/07/Now-You-Code/NYC2-Email-Address.ipynb
IST256-classroom/fall2018-learn-python-mafudge
Step 4: Problem Analysis for full ProgramInputs:Outputs:Algorithm (Steps in Program):
## Step 5: todo write code for full problem, using the isEmail function to help you solve the problem
_____no_output_____
MIT
content/lessons/07/Now-You-Code/NYC2-Email-Address.ipynb
IST256-classroom/fall2018-learn-python-mafudge
Example notebook for training a U-net deep learning network to predict tree cover This notebook presents a toy example for training a deep learning architecture for semantic segmentation of satellite images using `eo-learn` and `keras`. The example showcases tree cover prediction over an area in Framce. The ground-tru...
import os import datetime from os import path as op import itertools from eolearn.io import * from eolearn.core import EOTask, EOPatch, LinearWorkflow, FeatureType, SaveToDisk, OverwritePermission from sentinelhub import BBox, CRS, BBoxSplitter, MimeType, ServiceType from tqdm import tqdm_notebook as tqdm import mat...
Using TensorFlow backend.
MIT
examples/tree-cover-keras/tree-cover-keras.ipynb
Gnilliw/eo-learn
1. Set up workflow
# global image request parameters time_interval = ('2017-01-01', '2017-12-31') img_width = 256 img_height = 256 maxcc = 0.2 # get the AOI and split into bboxes crs = CRS.UTM_31N aoi = geopandas.read_file('../../example_data/eastern_france.geojson') aoi = aoi.to_crs(crs=crs.pyproj_crs()) aoi_shape = aoi.geometry.values[...
_____no_output_____
MIT
examples/tree-cover-keras/tree-cover-keras.ipynb
Gnilliw/eo-learn
Test workflow on an example patch and display
idx = 168 example_patch = execute_workflow(idx) example_patch mp = example_patch.data_timeless['MEDIAN_PIXEL'] plt.figure(figsize=(15,15)) plt.imshow(2.5*mp) tc = example_patch.mask_timeless['TREE_COVER'] plt.imshow(tc[...,0], vmin=0, vmax=5, alpha=.5, cmap=tree_cmap) plt.colorbar()
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
MIT
examples/tree-cover-keras/tree-cover-keras.ipynb
Gnilliw/eo-learn
2. Run workflow on all patches
# run over multiple bboxes subset_idx = len(bbox_splitter.bbox_list) x_train_raw = np.empty((subset_idx, img_height, img_width, 3)) y_train_raw = np.empty((subset_idx, img_height, img_width, 1)) pbar = tqdm(total=subset_idx) for idx in range(0, subset_idx): patch = execute_workflow(idx) x_train_raw[idx] = patch...
_____no_output_____
MIT
examples/tree-cover-keras/tree-cover-keras.ipynb
Gnilliw/eo-learn
3. Create training and validation data arrays
# data normalization and augmentation img_mean = np.mean(x_train_raw, axis=(0, 1, 2)) img_std = np.std(x_train_raw, axis=(0, 1, 2)) x_train_mean = x_train_raw - img_mean x_train = x_train_mean - img_std train_gen = ImageDataGenerator( horizontal_flip=True, vertical_flip=True, rotation_range=180) y_train =...
_____no_output_____
MIT
examples/tree-cover-keras/tree-cover-keras.ipynb
Gnilliw/eo-learn
4. Set up U-net model using Keras (tensorflow back-end)
# Model setup #from https://www.kaggle.com/lyakaap/weighing-boundary-pixels-loss-script-by-keras2 # weight: weighted tensor(same shape with mask image) def weighted_bce_loss(y_true, y_pred, weight): # avoiding overflow epsilon = 1e-7 y_pred = K.clip(y_pred, epsilon, 1. - epsilon) logit_y_pred = K.log(y_...
_____no_output_____
MIT
examples/tree-cover-keras/tree-cover-keras.ipynb
Gnilliw/eo-learn
5. Train the model
# Fit the model batch_size = 16 model.fit_generator( train_gen.flow(x_train, y_train, batch_size=batch_size), steps_per_epoch=len(x_train), epochs=20, verbose=1) model.save(op.join('model.h5'))
Epoch 1/20 190/190 [==============================] - 419s 2s/step - loss: 0.9654 - acc: 0.6208 Epoch 2/20 190/190 [==============================] - 394s 2s/step - loss: 0.9242 - acc: 0.6460 Epoch 3/20 190/190 [==============================] - 394s 2s/step - loss: 0.9126 - acc: 0.6502 Epoch 4/20 190/190 [============...
MIT
examples/tree-cover-keras/tree-cover-keras.ipynb
Gnilliw/eo-learn
6. Validate model and show some results
# plot one example (image, label, prediction) idx = 4 p = np.argmax(model.predict(np.array([x_train[idx]])), axis=3) fig = plt.figure(figsize=(12,4)) ax1 = fig.add_subplot(1,3,1) ax1.imshow(x_train_raw[idx]) ax2 = fig.add_subplot(1,3,2) ax2.imshow(y_train_raw[idx][:,:,0]) ax3 = fig.add_subplot(1,3,3) ax3.imshow(p[0]) d...
Normalized confusion matrix [[0.93412552 0. 0. 0. 0.01624412 0.04963036] [0.75458006 0. 0. 0. 0.08682321 0.15859672] [0.73890185 0. 0. 0. 0.1051384 0.15595975] [0.6504189 0. 0. 0. 0.1332155 0.2163656 ] [0.36706531 0. ...
MIT
examples/tree-cover-keras/tree-cover-keras.ipynb
Gnilliw/eo-learn
Measure autophagosome properties area=[]for i in range (0,number_of_objects): area=np.append(area,props[i].area)
experiments = os.listdir(os. getcwd()) for item in experiments: if 'raph' not in item : experiments.remove(item) experiments.remove('.ipynb_checkpoints') #experiments.remove('Statistical_Analysis.ipynb') experiments.remove('Measure_and _Plot.ipynb') experiments.remove('train') experiments.remove('Results') experime...
_____no_output_____
MIT
Measure_and _Plot.ipynb
sourabh-bhide/Analyze_Vesicles
PLOT NUMBER OF OBJECTS
import seaborn as sns for experiment in experiments: experiment_data = results_all[results_all['experiment']==experiment] fig,ax = plt.subplots() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax = sns.boxplot(x="condition", y="number_of_objects", data=experiment_data) ...
_____no_output_____
MIT
Measure_and _Plot.ipynb
sourabh-bhide/Analyze_Vesicles
PLOT SIZE OF OBJECTS/ MEAN_AREA
for experiment in experiments: experiment_data = results_all[results_all['experiment']==experiment] fig,ax = plt.subplots() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax = sns.boxplot(x="condition", y="mean_area", data=experiment_data) ax = sns.swarmplot(x="cond...
_____no_output_____
MIT
Measure_and _Plot.ipynb
sourabh-bhide/Analyze_Vesicles
PLOT POOLED SIZE OF OBJECTS/ MEAN_AREA
output_csv_dir = 'Results/' for experiment in experiments: df=pd.read_csv(output_csv_dir+experiment+'_pooled_cell_sizes.csv', sep=';', decimal=',') df = df.drop(columns=['Unnamed: 0']) df = df.sort_index(axis=1) if '60x' in str(experiment):df=df*0.1111 if '40x' in str(experiment):df=df*0.1...
Graph10_BoiPy__60xWater Graph11_ER__60xWater Graph12_Golgi__60xWater Graph14_Atg8a_Epistase_time_Of_Woud_Healing__40x Graph15_Atg8a_Insulin_Foxo_time_Of_Woud_Healing__40x_and_60x Graph16_Atg8a_Foxo_TM_time_Of_Woud_Healing__40xOil Graph17_Atg8a_time_Of_Woud_Healing__40xOil Graph1_Geraf2__Atg8a__40xOil_rest_of_data Graph...
MIT
Measure_and _Plot.ipynb
sourabh-bhide/Analyze_Vesicles
Инициализация
#@markdown - **Монтирование GoogleDrive** from google.colab import drive drive.mount('GoogleDrive') # #@markdown - **Размонтирование** # !fusermount -u GoogleDrive
_____no_output_____
MIT
notebooks(colab)/Neural_network_models/Supervised_learning_models/CNN_tf_RU.ipynb
jswanglp/MyML
Область кодов
#@title Сверточные нейронные сети { display-mode: "both" } # В программе используется API в TensorFlow для реализации двухслойных сверточных нейронных сетей # coding: utf-8 import tensorflow.examples.tutorials.mnist.input_data as input_data import tensorflow as tf import matplotlib.pyplot as plt import os #@markdown - ...
_____no_output_____
MIT
notebooks(colab)/Neural_network_models/Supervised_learning_models/CNN_tf_RU.ipynb
jswanglp/MyML
Predicting Flight Delays with sklearnIn this notebook, we will be using features we've prepared in PySpark to predict flight delays via regression and classification.
import sys, os, re sys.path.append("lib") import utils import numpy as np import sklearn import iso8601 import datetime print("Imports loaded...")
Imports loaded...
MIT
ch07/Predicting flight delays with sklearn.ipynb
kdiogenes/Agile_Data_Code_2
Load and Inspect our JSON Training Data
# Load and check the size of our training data. May take a minute. print("Original JSON file size: {:,} Bytes".format(os.path.getsize("../data/simple_flight_delay_features.jsonl"))) training_data = utils.read_json_lines_file('../data/simple_flight_delay_features.jsonl') print("Training items: {:,}".format(len(trainin...
Size of training data in RAM: 406,496 Bytes {'ArrDelay': -14.0, 'CRSArrTime': '2015-01-01T10:25:00.000Z', 'CRSDepTime': '2015-01-01T08:55:00.000Z', 'Carrier': 'AA', 'DayOfMonth': 1, 'DayOfWeek': 4, 'DayOfYear': 1, 'DepDelay': -4.0, 'Dest': 'DFW', 'Distance': 731.0, 'FlightDate': '2015-01-01T00:00:00.000Z', 'FlightNum':...
MIT
ch07/Predicting flight delays with sklearn.ipynb
kdiogenes/Agile_Data_Code_2
Sample our Data
# We need to sample our data to fit into RAM training_data = np.random.choice(training_data, 1000000) # 'Sample down to 1MM examples' print("Sampled items: {:,} Bytes".format(len(training_data))) print("Data sampled...")
Sampled items: 1,000,000 Bytes Data sampled...
MIT
ch07/Predicting flight delays with sklearn.ipynb
kdiogenes/Agile_Data_Code_2
Vectorize the Results (y)
# Separate our results from the rest of the data, vectorize and size up results = [record['ArrDelay'] for record in training_data] results_vector = np.array(results) print("Results vectorized size: {:,}".format(sys.getsizeof(results_vector))) # 45,712,160 bytes print("Results vectorized...")
Results vectorized size: 8,000,096 Results vectorized...
MIT
ch07/Predicting flight delays with sklearn.ipynb
kdiogenes/Agile_Data_Code_2
Prepare Training Data
# Remove the two delay fields and the flight date from our training data for item in training_data: item.pop('ArrDelay', None) item.pop('FlightDate', None) print("ArrDelay and FlightDate removed from training data...") # Must convert datetime strings to unix times for item in training_data: if isinstance(item['CR...
CRSArr/DepTime converted to unix time...
MIT
ch07/Predicting flight delays with sklearn.ipynb
kdiogenes/Agile_Data_Code_2
Vectorize Training Data with `DictVectorizer`
# Use DictVectorizer to convert feature dicts to vectors from sklearn.feature_extraction import DictVectorizer print("Sampled dimensions: [{:,}]".format(len(training_data))) vectorizer = DictVectorizer() training_vectors = vectorizer.fit_transform(training_data) print("Size of DictVectorized vectors: {:,} Bytes".forma...
_____no_output_____
MIT
ch07/Predicting flight delays with sklearn.ipynb
kdiogenes/Agile_Data_Code_2
Prepare Experiment by Splitting Data into Train/Test
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( training_vectors, results_vector, test_size=0.1, random_state=43 ) print(X_train.shape, X_test.shape) print(y_train.shape, y_test.shape) print("Test train split performed...")
_____no_output_____
MIT
ch07/Predicting flight delays with sklearn.ipynb
kdiogenes/Agile_Data_Code_2
Train our Model(s) on our Training Data
# Train a regressor from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import median_absolute_error, r2_score print("Regressor library and metrics imported...") regressor = LinearRegression() print("Regressor instantiated...") from sklearn.ensembl...
_____no_output_____
MIT
ch07/Predicting flight delays with sklearn.ipynb
kdiogenes/Agile_Data_Code_2
Predict Using the Test Data
predicted = regressor.predict(X_test) print("Predictions made for X_test...")
_____no_output_____
MIT
ch07/Predicting flight delays with sklearn.ipynb
kdiogenes/Agile_Data_Code_2
Evaluate and Visualize Model Accuracy
from sklearn.metrics import median_absolute_error, r2_score # Median absolute error is the median of all absolute differences between the target and the prediction. # Less is better, more indicates a high error between target and prediction. medae = median_absolute_error(y_test, predicted) print("Median absolute error...
_____no_output_____
MIT
ch07/Predicting flight delays with sklearn.ipynb
kdiogenes/Agile_Data_Code_2
Assignment-1
class BankAccount(object): def __init__(self, initial_balance=0): self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount def overdrawn(self): return self.balance < 0 my_account = BankAccount(15) ...
10
Apache-2.0
Batch-7_Day-6_Assignments.ipynb
Deepika0309/LetsUpgrage-Python-Essentials-
Assignment-2
import math pi = math.pi def volume(r, h): return (1 / 3) * pi * r * r * h def surfacearea(r, s): return pi * r * s + pi * r * r radius = float(5) height = float(12) slat_height = float(13) print( "Volume Of Cone : ", volume(radius, height) ) print( "Surface Area Of Cone : ", surfacearea(r...
Volume Of Cone : 314.15926535897927 Surface Area Of Cone : 282.7433388230814
Apache-2.0
Batch-7_Day-6_Assignments.ipynb
Deepika0309/LetsUpgrage-Python-Essentials-
Praktikum 12 | Pengolahan Citra SharpnessSharpness adalah proses untuk mendapatkan gambar yang lebih tajam. Proses sharpness ini memanfaatkan BSF (Band-Stop Filter) yang merupakan gabungan antara LPF (Low Pass Filter) dan HPF (High Pass Filter). Fadhil Yori Hibatullah | 2103161037 | 2 D3 Teknik Inform...
import imageio import matplotlib.pyplot as plt import numpy as np
_____no_output_____
MIT
Praktikum 12 - Sharpness.ipynb
fadhilyori/pengolahan-citra
Load Image
imgNormal = imageio.imread("gambar4.jpg")
_____no_output_____
MIT
Praktikum 12 - Sharpness.ipynb
fadhilyori/pengolahan-citra
Show Image
plt.imshow(imgNormal) plt.title("Load Image") plt.show()
_____no_output_____
MIT
Praktikum 12 - Sharpness.ipynb
fadhilyori/pengolahan-citra
--------------------- To Grayscale
imgGrayscale = np.zeros((imgNormal.shape[0], imgNormal.shape[1], 3), dtype=np.uint8) for y in range(0, imgNormal.shape[0]): for x in range(0, imgNormal.shape[1]): r = imgNormal[y][x][0] g = imgNormal[y][x][1] b = imgNormal[y][x][2] gr = ( int(r) + int(g) + int(b) ) / 3 imgGr...
_____no_output_____
MIT
Praktikum 12 - Sharpness.ipynb
fadhilyori/pengolahan-citra
--------------------- Sharpness Gray
imgSharpnessGray = np.zeros((imgNormal.shape[0], imgNormal.shape[1], 3), dtype=np.uint8) for y in range(1, imgNormal.shape[0] - 1): for x in range(1, imgNormal.shape[1] - 1): x1 = int(imgGrayscale[y - 1][x - 1][0]) x2 = int(imgGrayscale[y][x - 1][0]) x3 = int(imgGrayscale[y + 1][x - 1][0]) ...
_____no_output_____
MIT
Praktikum 12 - Sharpness.ipynb
fadhilyori/pengolahan-citra
------------------ Sharpness Gray (2:1 LPF:HPF)
imgSharpnessGrayL = np.zeros((imgNormal.shape[0], imgNormal.shape[1], 3), dtype=np.uint8) for y in range(1, imgNormal.shape[0] - 1): for x in range(1, imgNormal.shape[1] - 1): x1 = int(imgGrayscale[y - 1][x - 1][0]) x2 = int(imgGrayscale[y][x - 1][0]) x3 = int(imgGrayscale[y + 1][x - 1][0])...
_____no_output_____
MIT
Praktikum 12 - Sharpness.ipynb
fadhilyori/pengolahan-citra
------------------ Sharpness Gray (1:2 LPF:HPF)
imgSharpnessGrayH = np.zeros((imgNormal.shape[0], imgNormal.shape[1], 3), dtype=np.uint8) for y in range(1, imgNormal.shape[0] - 1): for x in range(1, imgNormal.shape[1] - 1): x1 = int(imgGrayscale[y - 1][x - 1][0]) x2 = int(imgGrayscale[y][x - 1][0]) x3 = int(imgGrayscale[y + 1][x - 1][0])...
_____no_output_____
MIT
Praktikum 12 - Sharpness.ipynb
fadhilyori/pengolahan-citra
Newton's Method for finding a root[Newton's method](https://en.wikipedia.org/wiki/Newton's_method) uses a clever insight to iteratively home in on the root of a function $f$. The central idea is to approximate $f$ by its tangent at some initial position $x_0$:$$y = f'(x_0) (x-x_0) + f(x_0)$$The $x$-intercept of this l...
def newtons_method(f, df, x0, tol=1E-6): x_n = x0 while abs(f(x_n)) > tol: x_n = x_n - f(x_n)/df(x_n) return x_n
_____no_output_____
MIT
day4/Newton-Method.ipynb
devonwt/usrp-sciprog
Minimizing a functionAs the maximum and minimum of a function are defined by $f'(x) = 0$, we can use Newton's method to find extremal points by applying it to the first derivative. Let's try this with a simply function with known minimum:
# define a test function def f(x): return (x-3)**2 - 9 def df(x): return 2*(x-3) def df2(x): return 2. root = newtons_method(f, df, x0=0.1) print ("root {0}, f(root) = {1}".format(root, f(root))) minimum = newtons_method(df, df2, x0=0.1) print ("minimum {0}, f'(minimum) = {1}".format(minimum, df(minimum))...
minimum 3.0, f'(minimum) = 0.0
MIT
day4/Newton-Method.ipynb
devonwt/usrp-sciprog
There is an important qualifier in the statement about fixed points: **a root needs to exist in the vicinity of $x_0$!** Let's see what happens if that's not the case:
def f(x): return (x-3)**2 + 1 newtons_method(f, df, x0=0.1)
_____no_output_____
MIT
day4/Newton-Method.ipynb
devonwt/usrp-sciprog
With a little more defensive programming we can make sure that the function will terminate after a given number of iterations:
def newtons_method2(f, df, x0, tol=1E-6, maxiter=100000): x_n = x0 for _ in range(maxiter): x_n = x_n - f(x_n)/df(x_n) if abs(f(x_n)) < tol: return x_n raise RuntimeError("Failed to find a minimum within {} iterations ".format(maxiter)) newtons_method2(f, df...
_____no_output_____
MIT
day4/Newton-Method.ipynb
devonwt/usrp-sciprog
Random Forest with hyperparameter tuning
import numpy as np import pandas as pd train_data = pd.read_csv('Train_Data.csv') test_data = pd.read_csv('Test_Data.csv') train_data.head() train_data.info() train_data.drop('date', axis=1, inplace=True) train_data.drop('campaign', axis=1, inplace=True) test_data.drop('date', axis=1, inplace=True) test_data.drop('camp...
_____no_output_____
Apache-2.0
WEEK 6 (Project)/baseline.ipynb
prachuryanath/SA-CAIITG
Notebook for calculating Mask Consistency Score for GAN-transformed images
from PIL import Image import cv2 from matplotlib import pyplot as plt import tensorflow as tf import glob, os import numpy as np import matplotlib.image as mpimg #from keras.preprocessing.image import img_to_array, array_to_img
_____no_output_____
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
1. Resize GAN-transformed Dataset to 1024*1024 1.1 Specify Args: Directory, folder name and the new image size
folder = 'A2B_FID' image_size = 1024 dir = '/mnt/robolab/data/Bilddaten/GAN_train_data_sydavis-ai/Powertrain14_Blattfeder/Results/training4_batch4_400trainA_250trainB/samples_testing'
_____no_output_____
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
1.2 Create new Folder "/A2B_FID_1024" in Directory
old_folder = (os.path.join(dir, folder)) new_folder = (os.path.join(dir, folder+'_'+str(image_size))) if not os.path.exists(new_folder): try: os.mkdir(new_folder) except FileExistsError: print('Folder already exists') pass print(os.path.join(old_folder)) print(os.path.join(dir, folder+'...
/mnt/robolab/data/Bilddaten/GAN_train_data_sydavis-ai/Powertrain14_Blattfeder/Results/training4_batch4_400trainA_250trainB/samples_testing/A2B_FID /mnt/robolab/data/Bilddaten/GAN_train_data_sydavis-ai/Powertrain14_Blattfeder/Results/training4_batch4_400trainA_250trainB/samples_testing/A2B_FID_1024
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
1.3 Function for upsampling images of 256-256 or 512-512 to images with size 1024-1024
new_size = image_size width = new_size height = new_size dim = (width, height) #images = glob.glob(os.path.join(new_folder, '*.jpg')) + glob.glob(os.path.join(new_folder, '*.png')) def resize_upsampling(old_folder, new_folder): for image in os.listdir(old_folder): img = cv2.imread(os.path.join(old_folder, ...
_____no_output_____
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
1.4 Run the aforementoined function
resize_upsampling(old_folder, new_folder)
Shape: (256, 256, 3) is now resized to: (1024, 1024, 3) Shape: (256, 256, 3) is now resized to: (1024, 1024, 3) Shape: (256, 256, 3) is now resized to: (1024, 1024, 3) Shape: (256, 256, 3) is now resized to: (1024, 1024, 3) Shape: (256, 256, 3) is now resized to: (1024, 1024, 3) Shape: (256, 256, 3) is now resized to: ...
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
2. Use the annotation Tool Labelme to create polygons in JSON format We than use the JSON files with polygon data to create semantic segmentation mask - no instance segmentation needed, because we do not need to differenciate between distinct features. We use the bash and python skript in this directory to do the mask...
!ls !pwd
augmentation.py interpolation.py __pycache__ data.py labelme2coco.py pylib datasets labelme2voc.py README.md download_dataset.sh labels.txt resize_images_pascalvoc 'FeatureConsistency Score.ipynb' LICENSE test.py FeatureScore mask-score.ipynb tf2gan fid.py mod...
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
Insert the folder path as **input_dir** where the GAN transformed images with corresponding JSON label are located.
input_dir = '/mnt/robolab/data/Bilddaten/GAN_train_data_sydavis-ai/Evaluation/BatchSize/Blattfeder/Batch1' output_dir = input_dir+'_mask' print(output_dir) !python3 labelme2voc.py $input_dir $output_dir --labels labels.txt seg_dir = output_dir+'/SegmentationObjectPNG' print(seg_dir) GAN_mask_images = os.listdir(seg_dir...
['rgb_274321.png', 'rgb_274414.png', 'rgb_273810.png', 'rgb_274350.png', 'rgb_274227.png', 'rgb_274288.png', 'rgb_273684.png', 'rgb_273905.png', 'rgb_273715.png', 'rgb_274513.png', 'rgb_274544.png', 'rgb_274002.png', 'rgb_273747.png', 'rgb_273971.png', 'rgb_273462.png', 'rgb_273582.png', 'rgb_273366.png', 'rgb_274064.p...
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
3. Mask Parameters syntetic Images
mask_Blattfeder = [149, 255, 0] mask_Entluefter = [] mask_Wandlerhalter = [] mask_Getreibeflansch = [] mask_Abdeckung = []
_____no_output_____
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
Resize syn. Masks from 1920-1080 to 1024-1024
def resize(image, size): dim = (size, size) img = cv2.imread(path) img = img img_resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) # tp show as array use display() #display(img_resized) plt.imshow(img_resized) return img_resized
_____no_output_____
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
Check Mask and Color
#img = Image.open(path) #rgb_im = img.convert('RGB') r, g, b = rgb_im.getpixel((1020, 500)) width, height = img.size print(r, g, b) print(rgb_im.getextrema()) print(rgb_im) print(width, height) def readfile(path): #img = Image.open(path) #with only one color channel: img = (Image.open(path).convert('L')) ...
_____no_output_____
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
Read Dataset Folder of Image Masks
def read_imgs(path, size=(1920, 1080), resize=None): """Read images as ndarray. Args: path: A string, path of images. size: A tuple of 2 integers, (heights, widths). resize: A float or None, specifying how the image value should be resized. If None, no...
_____no_output_____
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
Syntetical Image Data
path = r'/mnt/robolab/data/Bilddaten/GAN_train_data_sydavis-ai/Powertrain14_Blattfeder/Instance_280443.png' img_or = readfile(path) img_or_res = resize(img_or, 1024) img_or_res = img_or_res[:,:,1] img_or_res_bin = binarize (img_or_res)
2073600 (1080, 1920) (0, 0, 1920, 1080) <class 'numpy.ndarray'> 255 [[False False False ... False False False] [False False False ... False False False] [False False False ... False False False] ... [False False False ... False False False] [False False False ... False False False] [False False False ... False Fa...
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
GAN Image Data
path_result = '/mnt/robolab/data/Bilddaten/GAN_train_data_sydavis-ai/Powertrain14_Blattfeder/Test_maskScore_results/rgb_280443.png' img_gan = readfile(path_result) img_gan_bin = binarize(img_gan) def loadpolygon(): return
_____no_output_____
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
Since True is regarded as 1 and False is regarded as 0, when multiplied by 255 which is the Max value of uint8, True becomes 255 (white) and False becomes 0 (black)
def binarize(image): #im_gray = np.array(Image.open(path).convert('L')) print(type(image)) print(image[600,600]) thresh = 28 im_bool = image > thresh print(im_bool) print(im_bool[600,600]) print(im_bool.shape) maxval = 255 im_bin = (image > thresh) * maxval print(im...
Ground truth shape: (1024, 1024) Predicted GAN image shape: (1024, 1024) IoU is: 0.7979989122059556 Dice/F1 Score is: 0.8876522747468127
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
Image mask transformation Translate image mask to white RGB(255,255,255), fill convex hull, and compare masks to calculate 'Feature Consistency Score'
for file in glob.glob("*.png"): calculatescore()
_____no_output_____
MIT
Notebook_Archive/FeatureConsistency Score.ipynb
molu1019/CycleGAN-Tensorflow-2
1.2 Bayesian FrameworkWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a prior belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.Secondly, we observe our evidence. To continue our...
%matplotlib inline from IPython.core.pylabtools import figsize import numpy as np from matplotlib import pyplot as plt figsize(11, 9) import scipy.stats as stats dist = stats.beta n_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500] data = stats.bernoulli.rvs(0.5, size=n_trials[-1]) x = np.linspace(0, 1, 100) # For the alr...
_____no_output_____
CC-BY-4.0
cracking-the-data-science-interview-master/cracking-the-data-science-interview-master/EBooks/Bayesian-Methods-for-Hackers/.ipynb_checkpoints/C1-Introduction-checkpoint.ipynb
anushka-DS/DS-Interview-Prep
The posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tig...
figsize(12.5, 4) p = np.linspace(0, 1, 50) plt.plot(p, 2*p/(1+p), color="#348ABD", lw=3) #plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=["#A60628"]) plt.scatter(0.2, 2*(0.2)/1.2, s=140, c="#348ABD") plt.xlim(0, 1) plt.ylim(0, 1) plt.xlabel("Prior, $P(A) = p$") plt.ylabel("Posterior, $P(A|X)$, with $P(A) = p$") plt...
_____no_output_____
CC-BY-4.0
cracking-the-data-science-interview-master/cracking-the-data-science-interview-master/EBooks/Bayesian-Methods-for-Hackers/.ipynb_checkpoints/C1-Introduction-checkpoint.ipynb
anushka-DS/DS-Interview-Prep
We can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realist...
figsize(12.5, 4) colours = ["#348ABD", "#A60628"] prior = [0.20, 0.80] posterior = [1. / 3, 2. / 3] plt.bar([0, .7], prior, alpha=0.70, width=0.25, color=colours[0], label="prior distribution", lw="3", edgecolor=colours[0]) plt.bar([0 + 0.25, .7 + 0.25], posterior, alpha=0.7, width=0.25, color...
_____no_output_____
CC-BY-4.0
cracking-the-data-science-interview-master/cracking-the-data-science-interview-master/EBooks/Bayesian-Methods-for-Hackers/.ipynb_checkpoints/C1-Introduction-checkpoint.ipynb
anushka-DS/DS-Interview-Prep
1.3 Probability DistributionsLet's quickly recall what a probability distribution is: Let $Z$ be some random variable. Then associated with $Z$ is a probability distribution function that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probabil...
figsize(12.5, 4) import scipy.stats as stats a = np.arange(16) poi = stats.poisson lambda_ = [1.5, 4.25] colours = ["#348ABD", "#A60628"] plt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0], label="$\lambda = %.1f$" % lambda_[0], alpha=0.60, edgecolor=colours[0], lw="3") plt.bar(a, poi.pmf(a, lambda_...
_____no_output_____
CC-BY-4.0
cracking-the-data-science-interview-master/cracking-the-data-science-interview-master/EBooks/Bayesian-Methods-for-Hackers/.ipynb_checkpoints/C1-Introduction-checkpoint.ipynb
anushka-DS/DS-Interview-Prep
1.3.2 Continuous CaseInstead of a probability mass function, a continuous random variable has a probability density function. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with ex...
a = np.linspace(0, 4, 100) expo = stats.expon lambda_ = [0.5, 1] for l, c in zip(lambda_, colours): plt.plot(a, expo.pdf(a, scale=1. / l), lw=3, color=c, label="$\lambda = %.1f$" % l) plt.fill_between(a, expo.pdf(a, scale=1. / l), color=c, alpha=.33) plt.legend() plt.ylabel("PDF at $z$") plt.xlab...
_____no_output_____
CC-BY-4.0
cracking-the-data-science-interview-master/cracking-the-data-science-interview-master/EBooks/Bayesian-Methods-for-Hackers/.ipynb_checkpoints/C1-Introduction-checkpoint.ipynb
anushka-DS/DS-Interview-Prep
But what is $\lambda \;$?This question is what motivates statistics. In the real world, $\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\lambda$. Many different methods have been created to ...
figsize(12.5, 3.5) count_data = np.loadtxt("data/txtdata.csv") n_count_data = len(count_data) plt.bar(np.arange(n_count_data), count_data, color="#348ABD") plt.xlabel("Time (days)") plt.ylabel("count of text-msgs received") plt.title("Did the user's texting habits change over time?") plt.xlim(0, n_count_data);
_____no_output_____
CC-BY-4.0
cracking-the-data-science-interview-master/cracking-the-data-science-interview-master/EBooks/Bayesian-Methods-for-Hackers/.ipynb_checkpoints/C1-Introduction-checkpoint.ipynb
anushka-DS/DS-Interview-Prep
Before we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period?How can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of count data. D...
import pymc3 as pm import theano.tensor as tt with pm.Model() as model: alpha = 1.0/count_data.mean() # Recall count_data is the # variable that holds our txt counts lambda_1 = pm.Exponential("lambda_1", alpha) lambda_2 = pm.Exponential("lambda_2", alpha) tau = ...
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters a...
CC-BY-4.0
cracking-the-data-science-interview-master/cracking-the-data-science-interview-master/EBooks/Bayesian-Methods-for-Hackers/.ipynb_checkpoints/C1-Introduction-checkpoint.ipynb
anushka-DS/DS-Interview-Prep
In the code above, we create the PyMC3 variables corresponding to $\lambda_1$ and $\lambda_2$. We assign them to PyMC3's stochastic variables, so-called because they are treated by the back end as random number generators.
with model: idx = np.arange(n_count_data) # Index lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)
_____no_output_____
CC-BY-4.0
cracking-the-data-science-interview-master/cracking-the-data-science-interview-master/EBooks/Bayesian-Methods-for-Hackers/.ipynb_checkpoints/C1-Introduction-checkpoint.ipynb
anushka-DS/DS-Interview-Prep
This code creates a new function lambda_, but really we can think of it as a random variable: the random variable $\lambda$ from above. The switch() function assigns lambda_1 or lambda_2 as the value of lambda_, depending on what side of tau we are on. The values of lambda_ up until tau are lambda_1 and the values aft...
with model: observation = pm.Poisson("obs", lambda_, observed=count_data)
_____no_output_____
CC-BY-4.0
cracking-the-data-science-interview-master/cracking-the-data-science-interview-master/EBooks/Bayesian-Methods-for-Hackers/.ipynb_checkpoints/C1-Introduction-checkpoint.ipynb
anushka-DS/DS-Interview-Prep
The variable observation combines our data, count_data, with our proposed data-generation scheme, given by the variable lambda_, through the observed keyword.The code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a learning step. The machiner...
with model: step = pm.Metropolis() trace = pm.sample(10000, tune=5000,step=step) lambda_1_samples = trace['lambda_1'] lambda_2_samples = trace['lambda_2'] tau_samples = trace['tau'] figsize(12.5, 10) #histogram of the samples: ax = plt.subplot(311) ax.set_autoscaley_on(False) plt.hist(lambda_1_samples, histty...
_____no_output_____
CC-BY-4.0
cracking-the-data-science-interview-master/cracking-the-data-science-interview-master/EBooks/Bayesian-Methods-for-Hackers/.ipynb_checkpoints/C1-Introduction-checkpoint.ipynb
anushka-DS/DS-Interview-Prep
InterpretationRecall that Bayesian methodology returns a distribution. Hence we now have distributions to describe the unknown $\lambda$s and $\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also s...
figsize(12.5, 5) # tau_samples, lambda_1_samples, lambda_2_samples contain # N samples from the corresponding posterior distribution N = tau_samples.shape[0] expected_texts_per_day = np.zeros(n_count_data) for day in range(0, n_count_data): # ix is a bool index of all tau samples corresponding to # the switchpo...
_____no_output_____
CC-BY-4.0
cracking-the-data-science-interview-master/cracking-the-data-science-interview-master/EBooks/Bayesian-Methods-for-Hackers/.ipynb_checkpoints/C1-Introduction-checkpoint.ipynb
anushka-DS/DS-Interview-Prep
Tight Layout guideHow to use tight-layout to fit plots within your figure cleanly.*tight_layout* automatically adjusts subplot params so that thesubplot(s) fits in to the figure area. This is an experimentalfeature and may not work for some cases. It only checks the extentsof ticklabels, axis labels, and titles.An alt...
# sphinx_gallery_thumbnail_number = 7 import matplotlib.pyplot as plt import numpy as np plt.rcParams['savefig.facecolor'] = "0.8" def example_plot(ax, fontsize=12): ax.plot([1, 2]) ax.locator_params(nbins=3) ax.set_xlabel('x-label', fontsize=fontsize) ax.set_ylabel('y-label', fontsize=fontsize) ...
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
To prevent this, the location of axes needs to be adjusted. Forsubplots, this can be done by adjusting the subplot params(`howto-subplots-adjust`). Matplotlib v1.1 introduces a newcommand :func:`~matplotlib.pyplot.tight_layout` that does thisautomatically for you.
fig, ax = plt.subplots() example_plot(ax, fontsize=24) plt.tight_layout()
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
Note that :func:`matplotlib.pyplot.tight_layout` will only adjust thesubplot params when it is called. In order to perform this adjustment eachtime the figure is redrawn, you can call ``fig.set_tight_layout(True)``, or,equivalently, set the ``figure.autolayout`` rcParam to ``True``.When you have multiple subplots, oft...
plt.close('all') fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4)
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
:func:`~matplotlib.pyplot.tight_layout` will also adjust spacing betweensubplots to minimize the overlaps.
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) plt.tight_layout()
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
:func:`~matplotlib.pyplot.tight_layout` can take keyword arguments of*pad*, *w_pad* and *h_pad*. These control the extra padding around thefigure border and between subplots. The pads are specified in fractionof fontsize.
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
:func:`~matplotlib.pyplot.tight_layout` will work even if the sizes ofsubplots are different as far as their grid specification iscompatible. In the example below, *ax1* and *ax2* are subplots of a 2x2grid, while *ax3* is of a 1x2 grid.
plt.close('all') fig = plt.figure() ax1 = plt.subplot(221) ax2 = plt.subplot(223) ax3 = plt.subplot(122) example_plot(ax1) example_plot(ax2) example_plot(ax3) plt.tight_layout()
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
It works with subplots created with:func:`~matplotlib.pyplot.subplot2grid`. In general, subplots createdfrom the gridspec (:doc:`/tutorials/intermediate/gridspec`) will work.
plt.close('all') fig = plt.figure() ax1 = plt.subplot2grid((3, 3), (0, 0)) ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2) ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2) ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) plt.tight...
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
Although not thoroughly tested, it seems to work for subplots withaspect != "auto" (e.g., axes with images).
arr = np.arange(100).reshape((10, 10)) plt.close('all') fig = plt.figure(figsize=(5, 4)) ax = plt.subplot(111) im = ax.imshow(arr, interpolation="none") plt.tight_layout()
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
Caveats======= * :func:`~matplotlib.pyplot.tight_layout` only considers ticklabels, axis labels, and titles. Thus, other artists may be clipped and also may overlap. * It assumes that the extra space needed for ticklabels, axis labels, and titles is independent of original location of axes. This is often true, ...
import matplotlib.gridspec as gridspec plt.close('all') fig = plt.figure() gs1 = gridspec.GridSpec(2, 1) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) example_plot(ax1) example_plot(ax2) gs1.tight_layout(fig)
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
You may provide an optional *rect* parameter, which specifies the bounding boxthat the subplots will be fit inside. The coordinates must be in normalizedfigure coordinates and the default is (0, 0, 1, 1).
fig = plt.figure() gs1 = gridspec.GridSpec(2, 1) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) example_plot(ax1) example_plot(ax2) gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
For example, this can be used for a figure with multiple gridspecs.
fig = plt.figure() gs1 = gridspec.GridSpec(2, 1) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) example_plot(ax1) example_plot(ax2) gs1.tight_layout(fig, rect=[0, 0, 0.5, 1]) gs2 = gridspec.GridSpec(3, 1) for ss in gs2: ax = fig.add_subplot(ss) example_plot(ax) ax.set_title("") ax.set_...
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
While this should be mostly good enough, adjusting top and bottommay require adjustment of hspace also. To update hspace & vspace, wecall :func:`~matplotlib.gridspec.GridSpec.tight_layout` again with updatedrect argument. Note that the rect argument specifies the area including theticklabels, etc. Thus, we will incre...
fig = plt.gcf() gs1 = gridspec.GridSpec(2, 1) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) example_plot(ax1) example_plot(ax2) gs1.tight_layout(fig, rect=[0, 0, 0.5, 1]) gs2 = gridspec.GridSpec(3, 1) for ss in gs2: ax = fig.add_subplot(ss) example_plot(ax) ax.set_title("") ax.set_xla...
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
Legends and Annotations=======================Pre Matplotlib 2.2, legends and annotations were excluded from the boundingbox calculations that decide the layout. Subsequently these artists wereadded to the calculation, but sometimes it is undesirable to include them.For instance in this case it might be good to have t...
fig, ax = plt.subplots(figsize=(4, 3)) lines = ax.plot(range(10), label='A simple plot') ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',) fig.tight_layout() plt.show()
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
However, sometimes this is not desired (quite often when using``fig.savefig('outname.png', bbox_inches='tight')``). In order toremove the legend from the bounding box calculation, we simply set itsbounding ``leg.set_in_layout(False)`` and the legend will be ignored.
fig, ax = plt.subplots(figsize=(4, 3)) lines = ax.plot(range(10), label='B simple plot') leg = ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',) leg.set_in_layout(False) fig.tight_layout() plt.show()
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
Use with AxesGrid1==================While limited, the axes_grid1 toolkit is also supported.
from mpl_toolkits.axes_grid1 import Grid plt.close('all') fig = plt.figure() grid = Grid(fig, rect=111, nrows_ncols=(2, 2), axes_pad=0.25, label_mode='L', ) for ax in grid: example_plot(ax) ax.title.set_visible(False) plt.tight_layout()
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
Colorbar========If you create a colorbar with the :func:`~matplotlib.pyplot.colorbar`command, the created colorbar is an instance of Axes, *not* Subplot, sotight_layout does not work. With Matplotlib v1.1, you may create acolorbar as a subplot using the gridspec.
plt.close('all') arr = np.arange(100).reshape((10, 10)) fig = plt.figure(figsize=(4, 4)) im = plt.imshow(arr, interpolation="none") plt.colorbar(im, use_gridspec=True) plt.tight_layout()
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
Another option is to use AxesGrid1 toolkit toexplicitly create an axes for colorbar.
from mpl_toolkits.axes_grid1 import make_axes_locatable plt.close('all') arr = np.arange(100).reshape((10, 10)) fig = plt.figure(figsize=(4, 4)) im = plt.imshow(arr, interpolation="none") divider = make_axes_locatable(plt.gca()) cax = divider.append_axes("right", "5%", pad="3%") plt.colorbar(im, cax=cax) plt.tight_l...
_____no_output_____
MIT
testing/examples/tight_layout_guide.ipynb
pchaos/quanttesting
Energy Minimization Assignment, PharmSci 175/275 By David Mobley (UCI), Jan. 2018 Adapted with permission from an assignment by M. Scott Shell (UCSB) OverviewIn this assignment, you will begin with a provided template and several functions, as well as a Fortran library, and add additional code to perform a conjugate-g...
import numpy as np import emlib from pos_to_pdb import * #This would allow you to export coordinates if you want, later
_____no_output_____
CC-BY-4.0
uci-pharmsci/assignments/energy_minimization/energy_minimization_assignment.ipynb
matthagy/drug-computing
Important technical note: Unit masses, etc.Note that all of the following code will assume unit atomic masses, such that forces and accelerations are equal -- that is, instead of $F=ma$ we write $F=a$ assuming that $m=1$. We also drop most constants. This is a relatively common trick in physics when you are interested...
def LineSearch(Pos, Dir, dx, EFracTol, Accel = 1.5, MaxInc = 10., MaxIter = 10000): """Performs a line search along direction Dir. Input: Pos: starting positions, (N,3) array Dir: (N,3) array of gradient direction dx: initial step amount, a float EFracTol: fractional e...
_____no_output_____
CC-BY-4.0
uci-pharmsci/assignments/energy_minimization/energy_minimization_assignment.ipynb
matthagy/drug-computing
Step 2: Write a function to assign random initial positions to your atomsWe need a function that can randomly place N atoms in a box with sides of length L. Write a function based on a tool from the numpy 'random' module to do this. Some hints are in order:* NumPy contains a ‘random’ module which is good for obtaining...
a = np.random.random(3) print("a=\n",a) b = np.random.random((2,3)) print("b=\n",b)
a= [ 0.27969529 0.37836589 0.96785443] b= [[ 0.37068791 0.64081204 0.21422213] [ 0.471194 0.28575791 0.54468387]]
CC-BY-4.0
uci-pharmsci/assignments/energy_minimization/energy_minimization_assignment.ipynb
matthagy/drug-computing
* Note that in your function, you want the numbers to run from 0 to L. You might try out what happens if you multiply 'a' and 'b' in the code above by some number.Now, write your function. I've written the doc string and some comments for you, but you have to fill in its inner workings:
def InitPositions(N, L): """Returns an array of initial positions of each atom, placed randomly within a box of dimensions L. Input: N: number of atoms L: box width Output: Pos: (N,3) array of positions """ #### WRITE YOUR CODE HERE #### ## In my code, I can accomplish this function in 1 line ...
_____no_output_____
CC-BY-4.0
uci-pharmsci/assignments/energy_minimization/energy_minimization_assignment.ipynb
matthagy/drug-computing
Step 3: Write the Conjugate Gradient function described belowFill in code for the ConjugateGradient function below based on the discussion in class and below, supplemented by your reading of Leach's book (and other online sources if needed). Some additional guidance and hints are warranted first. Hints for ConjugateGr...
def ConjugateGradient(Pos, dx, EFracTolLS, EFracTolCG): """Performs a conjugate gradient search. Input: Pos: starting positions, (N,3) array dx: initial step amount EFracTolLS: fractional energy tolerance for line search EFracTolCG: fractional energy tolerance for conjugate gradient Output: PEne...
_____no_output_____
CC-BY-4.0
uci-pharmsci/assignments/energy_minimization/energy_minimization_assignment.ipynb
matthagy/drug-computing
Step 4: Energy minimize a variety of clusters, storing energiesWrite code to use the functions you wrote above, plus the emlib module, to energy minimize clusters of various sizes. Loop over clusters from size N=2 to (and including) N=25. For each particle number, do the following:* Perform K (to be specified below in...
import pickle file = open('energies.pickle', "w") pickle.dump( energies, file) file.close() #To load again, use: #file = open("energies.pickle", "r") #energies = pickle.load(file) #file.close()
_____no_output_____
CC-BY-4.0
uci-pharmsci/assignments/energy_minimization/energy_minimization_assignment.ipynb
matthagy/drug-computing
Write your code here:
#Your energy minimization code here #This will be the longest code you write in this assignment
_____no_output_____
CC-BY-4.0
uci-pharmsci/assignments/energy_minimization/energy_minimization_assignment.ipynb
matthagy/drug-computing
Step 5: Graph your findings Plot the minimum and average energies as a function of N for each of K=100, 1000, and 10000. The last case may be fairly time consuming (i.e. several hours) and should be done without output of pdb files for visualization (since this can slow it down).Use matplotlib/PyLab to make these plot...
#Your code for this here
_____no_output_____
CC-BY-4.0
uci-pharmsci/assignments/energy_minimization/energy_minimization_assignment.ipynb
matthagy/drug-computing
Step 6: Compare with what's expectedCompare your results (your minimum energy at each N value) with the known global minimum energies, via a plot and by commenting on the results. These are from ( Leary, J. Global Optimization 11:35 (1997)). Add this curve to your graph. Why might your results be higher?
#Write code here to add these to your graph
_____no_output_____
CC-BY-4.0
uci-pharmsci/assignments/energy_minimization/energy_minimization_assignment.ipynb
matthagy/drug-computing