markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
训练无约束(非单调)的校准线性模型
nomon_linear_estimator = optimize_learning_rates( train_df=law_train_df, val_df=law_val_df, test_df=law_test_df, monotonicity=0, learning_rates=LEARNING_RATES, batch_size=BATCH_SIZE, num_epochs=NUM_EPOCHS, get_input_fn=get_input_fn_law, get_feature_columns_and_configs=get_feature_columns_and_configs_law) plot_model_contour(nomon_linear_estimator, input_df=law_df)
site/zh-cn/lattice/tutorials/shape_constraints_for_ethics.ipynb
tensorflow/docs-l10n
apache-2.0
训练单调的校准线性模型
mon_linear_estimator = optimize_learning_rates( train_df=law_train_df, val_df=law_val_df, test_df=law_test_df, monotonicity=1, learning_rates=LEARNING_RATES, batch_size=BATCH_SIZE, num_epochs=NUM_EPOCHS, get_input_fn=get_input_fn_law, get_feature_columns_and_configs=get_feature_columns_and_configs_law) plot_model_contour(mon_linear_estimator, input_df=law_df)
site/zh-cn/lattice/tutorials/shape_constraints_for_ethics.ipynb
tensorflow/docs-l10n
apache-2.0
训练其他无约束的模型 我们演示了可以将 TFL 校准线性模型训练成在 LSAT 分数和 GPA 上均单调,而不会牺牲过多的准确率。 但是,与其他类型的模型(如深度神经网络 (DNN) 或梯度提升树 (GBT))相比,校准线性模型表现如何?DNN 和 GBT 看起来会有公平合理的输出吗?为了解决这一问题,我们接下来将训练无约束的 DNN 和 GBT。实际上,我们将观察到 DNN 和 GBT 都很容易违反 LSAT 分数和本科生 GPA 中的单调性。 训练无约束的深度神经网络 (DNN) 模型 之前已对此架构进行了优化,可以实现较高的验证准确率。
feature_names = ['ugpa', 'lsat'] dnn_estimator = tf.estimator.DNNClassifier( feature_columns=[ tf.feature_column.numeric_column(feature) for feature in feature_names ], hidden_units=[100, 100], optimizer=tf.keras.optimizers.Adam(learning_rate=0.008), activation_fn=tf.nn.relu) dnn_estimator.train( input_fn=get_input_fn_law( law_train_df, batch_size=BATCH_SIZE, num_epochs=NUM_EPOCHS)) dnn_train_acc = dnn_estimator.evaluate( input_fn=get_input_fn_law(law_train_df, num_epochs=1))['accuracy'] dnn_val_acc = dnn_estimator.evaluate( input_fn=get_input_fn_law(law_val_df, num_epochs=1))['accuracy'] dnn_test_acc = dnn_estimator.evaluate( input_fn=get_input_fn_law(law_test_df, num_epochs=1))['accuracy'] print('accuracies for DNN: train: %f, val: %f, test: %f' % (dnn_train_acc, dnn_val_acc, dnn_test_acc)) plot_model_contour(dnn_estimator, input_df=law_df)
site/zh-cn/lattice/tutorials/shape_constraints_for_ethics.ipynb
tensorflow/docs-l10n
apache-2.0
训练无约束的梯度提升树 (GBT) 模型 之前已对此树形结构进行了优化,可以实现较高的验证准确率。
tree_estimator = tf.estimator.BoostedTreesClassifier( feature_columns=[ tf.feature_column.numeric_column(feature) for feature in feature_names ], n_batches_per_layer=2, n_trees=20, max_depth=4) tree_estimator.train( input_fn=get_input_fn_law( law_train_df, num_epochs=NUM_EPOCHS, batch_size=BATCH_SIZE)) tree_train_acc = tree_estimator.evaluate( input_fn=get_input_fn_law(law_train_df, num_epochs=1))['accuracy'] tree_val_acc = tree_estimator.evaluate( input_fn=get_input_fn_law(law_val_df, num_epochs=1))['accuracy'] tree_test_acc = tree_estimator.evaluate( input_fn=get_input_fn_law(law_test_df, num_epochs=1))['accuracy'] print('accuracies for GBT: train: %f, val: %f, test: %f' % (tree_train_acc, tree_val_acc, tree_test_acc)) plot_model_contour(tree_estimator, input_df=law_df)
site/zh-cn/lattice/tutorials/shape_constraints_for_ethics.ipynb
tensorflow/docs-l10n
apache-2.0
案例研究 2:信用违约 我们将在本教程中考虑的第二个案例研究是预测个人的信用违约概率。我们将使用 UCI 存储库中的 Default of Credit Card Clients 数据集。这些数据收集自 30,000 名中国台湾信用卡用户,并包含一个二元标签,用于标识用户是否在时间窗口内拖欠了付款。特征包括婚姻状况、性别、教育程度以及在 2005 年 4-9 月的每个月中,用户拖欠现有账单的时间有多长。 正如我们在第一个案例研究中所做的那样,我们再次阐明了使用单调性约束来避免不公平的惩罚:使用该模型来确定用户的信用评分时,在其他条件都相同的情况下,如果许多人因较早支付账单而受到惩罚,那么这对他们来说是不公平的。因此,我们应用了单调性约束,使模型不会惩罚提前付款。 加载信用违约数据
# Load data file. credit_file_name = 'credit_default.csv' credit_file_path = os.path.join(DATA_DIR, credit_file_name) credit_df = pd.read_csv(credit_file_path, delimiter=',') # Define label column name. CREDIT_LABEL = 'default'
site/zh-cn/lattice/tutorials/shape_constraints_for_ethics.ipynb
tensorflow/docs-l10n
apache-2.0
将数据划分为训练/验证/测试集
credit_train_df, credit_val_df, credit_test_df = split_dataset(credit_df)
site/zh-cn/lattice/tutorials/shape_constraints_for_ethics.ipynb
tensorflow/docs-l10n
apache-2.0
可视化数据分布 首先,我们可视化数据的分布。我们将为婚姻状况和还款状况不同的人绘制观察到的违约率的平均值和标准误差。还款状态表示一个人已偿还贷款的月数(截至 2005 年 4 月)。
def get_agg_data(df, x_col, y_col, bins=11): xbins = pd.cut(df[x_col], bins=bins) data = df[[x_col, y_col]].groupby(xbins).agg(['mean', 'sem']) return data def plot_2d_means_credit(input_df, x_col, y_col, x_label, y_label): plt.rcParams['font.family'] = ['serif'] _, ax = plt.subplots(nrows=1, ncols=1) plt.setp(ax.spines.values(), color='black', linewidth=1) ax.tick_params( direction='in', length=6, width=1, top=False, right=False, labelsize=18) df_single = get_agg_data(input_df[input_df['MARRIAGE'] == 1], x_col, y_col) df_married = get_agg_data(input_df[input_df['MARRIAGE'] == 2], x_col, y_col) ax.errorbar( df_single[(x_col, 'mean')], df_single[(y_col, 'mean')], xerr=df_single[(x_col, 'sem')], yerr=df_single[(y_col, 'sem')], color='orange', marker='s', capsize=3, capthick=1, label='Single', markersize=10, linestyle='') ax.errorbar( df_married[(x_col, 'mean')], df_married[(y_col, 'mean')], xerr=df_married[(x_col, 'sem')], yerr=df_married[(y_col, 'sem')], color='b', marker='^', capsize=3, capthick=1, label='Married', markersize=10, linestyle='') leg = ax.legend(loc='upper left', fontsize=18, frameon=True, numpoints=1) ax.set_xlabel(x_label, fontsize=18) ax.set_ylabel(y_label, fontsize=18) ax.set_ylim(0, 1.1) ax.set_xlim(-2, 8.5) ax.patch.set_facecolor('white') leg.get_frame().set_edgecolor('black') leg.get_frame().set_facecolor('white') leg.get_frame().set_linewidth(1) plt.show() plot_2d_means_credit(credit_train_df, 'PAY_0', 'default', 'Repayment Status (April)', 'Observed default rate')
site/zh-cn/lattice/tutorials/shape_constraints_for_ethics.ipynb
tensorflow/docs-l10n
apache-2.0
训练校准线性模型以预测信用违约率 接下来,我们将通过 TFL 训练校准线性模型,以预测某人是否会拖欠贷款。两个输入特征将是该人的婚姻状况以及该人截至 4 月已偿还贷款的月数(还款状态)。训练标签将是该人是否拖欠过贷款。 我们首先在没有任何约束的情况下训练校准线性模型。然后,我们在具有单调性约束的情况下训练校准线性模型,并观察模型输出和准确率的差异。 用于配置信用违约数据集特征的辅助函数 下面这些辅助函数专用于信用违约案例研究。
def get_input_fn_credit(input_df, num_epochs, batch_size=None): """Gets TF input_fn for credit default models.""" return tf.compat.v1.estimator.inputs.pandas_input_fn( x=input_df[['MARRIAGE', 'PAY_0']], y=input_df['default'], num_epochs=num_epochs, batch_size=batch_size or len(input_df), shuffle=False) def get_feature_columns_and_configs_credit(monotonicity): """Gets TFL feature configs for credit default models.""" feature_columns = [ tf.feature_column.numeric_column('MARRIAGE'), tf.feature_column.numeric_column('PAY_0'), ] feature_configs = [ tfl.configs.FeatureConfig( name='MARRIAGE', lattice_size=2, pwl_calibration_num_keypoints=3, monotonicity=monotonicity, pwl_calibration_always_monotonic=False), tfl.configs.FeatureConfig( name='PAY_0', lattice_size=2, pwl_calibration_num_keypoints=10, monotonicity=monotonicity, pwl_calibration_always_monotonic=False), ] return feature_columns, feature_configs
site/zh-cn/lattice/tutorials/shape_constraints_for_ethics.ipynb
tensorflow/docs-l10n
apache-2.0
用于可视化训练的模型输出的辅助函数
def plot_predictions_credit(input_df, estimator, x_col, x_label='Repayment Status (April)', y_label='Predicted default probability'): predictions = get_predicted_probabilities( estimator=estimator, input_df=input_df, get_input_fn=get_input_fn_credit) new_df = input_df.copy() new_df.loc[:, 'predictions'] = predictions plot_2d_means_credit(new_df, x_col, 'predictions', x_label, y_label)
site/zh-cn/lattice/tutorials/shape_constraints_for_ethics.ipynb
tensorflow/docs-l10n
apache-2.0
训练无约束(非单调)的校准线性模型
nomon_linear_estimator = optimize_learning_rates( train_df=credit_train_df, val_df=credit_val_df, test_df=credit_test_df, monotonicity=0, learning_rates=LEARNING_RATES, batch_size=BATCH_SIZE, num_epochs=NUM_EPOCHS, get_input_fn=get_input_fn_credit, get_feature_columns_and_configs=get_feature_columns_and_configs_credit) plot_predictions_credit(credit_train_df, nomon_linear_estimator, 'PAY_0')
site/zh-cn/lattice/tutorials/shape_constraints_for_ethics.ipynb
tensorflow/docs-l10n
apache-2.0
训练单调的校准线性模型
mon_linear_estimator = optimize_learning_rates( train_df=credit_train_df, val_df=credit_val_df, test_df=credit_test_df, monotonicity=1, learning_rates=LEARNING_RATES, batch_size=BATCH_SIZE, num_epochs=NUM_EPOCHS, get_input_fn=get_input_fn_credit, get_feature_columns_and_configs=get_feature_columns_and_configs_credit) plot_predictions_credit(credit_train_df, mon_linear_estimator, 'PAY_0')
site/zh-cn/lattice/tutorials/shape_constraints_for_ethics.ipynb
tensorflow/docs-l10n
apache-2.0
As shown above, the error from the model is not normally distributed. The error is skewed to the right, similar to the raw data itself. Additionally, the distribution of error terms is not consistent, it is heteroscadastic. Inspect the Data and Transform The data is skewed to the right. The data is transformed by taking its square root to see if we can obtain a more normal distribution.
plt.hist(actual) plt.show() sqrt_actual = np.sqrt(actual) plt.hist(sqrt_actual) plt.show()
CorrectingForAssumptions.ipynb
Jackie789/JupyterNotebooks
gpl-3.0
That's a little better. Has this helped the multivariate normality? Yes.
# Extract predicted values. predicted = regr.predict(X).ravel() actual = data['Sales'] # Calculate the error, also called the residual. corr_residual = sqrt_actual - predicted plt.hist(corr_residual) plt.title('Residual counts') plt.xlabel('Residual') plt.ylabel('Count') plt.show()
CorrectingForAssumptions.ipynb
Jackie789/JupyterNotebooks
gpl-3.0
Transforming the data into the sqrt of the data lessened the skewness to the right, and allowed the error from the model to be more normally-distributed. Let's see if our transformation helped the problem with heteroscedasticity. Homoscedasticity
plt.scatter(predicted, corr_residual) plt.xlabel('Predicted') plt.ylabel('Residual') plt.axhline(y=0) plt.title('Residual vs. Predicted') plt.show()
CorrectingForAssumptions.ipynb
Jackie789/JupyterNotebooks
gpl-3.0
Import the usual libraries You can load that library with the code cell above:
# import matplotlib and numpy # use "inline" instead of "notebook" for non-interactive # use widget for jupyterlab needs ipympl to be installed import sys if 'google.colab' in sys.modules: %pylab --no-import-all notebook else: %pylab --no-import-all widget from sidpy.io.interface_utils import open_file_dialog from SciFiReaders import DM3Reader import SciFiReaders %load_ext autoreload %autoreload 2 sys.path.insert(0, '../') import pycroscopy as px __notebook__ = 'Image_Registration' __notebook_version__ = '2021_10_04'
jupyter_notebooks/image_registration.ipynb
pycroscopy/pycroscopy
mit
Load an image stack : Please, load an image stack. <br> A stack of images is used to reduce noise, but for an added image the images have to be aligned to compensate for drift and other microscope instabilities. You select here (with the open_file_dialog parameter), whether an open file dialog apears in the code cell below the next one or whether you want to get a list of files (Nion has a weird way of dealing with file names).
if 'google.colab' in sys.modules: from google.colab import drive drive.mount("/content/drive") drive_directory = 'drive/MyDrive/' else: drive_directory = '.' file_widget = open_file_dialog(drive_directory) file_widget
jupyter_notebooks/image_registration.ipynb
pycroscopy/pycroscopy
mit
Plot Image Stack Either we load the selected file in hte widget above above or a file dialog window appears. This is the point the notebook can be repeated with a new file. Either select a file above again (without running the code cell above) or open a file dialog here Note that the open file dialog might not apear in the foreground!
try: main_dataset.h5_dataset.file.close() except: pass dm3_reader = DM3Reader(file_widget.selected) main_dataset = dm3_reader.read() if main_dataset.data_type.name != 'IMAGE_STACK': print(f"Please load an image stack for this notebook, this is an {main_dataset.data_type}") print(main_dataset) main_dataset.dim_0.dimension_type = 'spatial' main_dataset.dim_1.dimension_type = 'spatial' main_dataset.z.dimension_type = 'temporal' main_dataset.plot() # note this needs a view reference for interaction main_dataset._axes frame_dim = [] spatial_dim = [] for i, axis in main_dataset._axes.items(): if axis.dimension_type.name == 'SPATIAL': spatial_dim.append(i) else: frame_dim.append(i) if len(spatial_dim) != 2: print('need two spatial dimensions') if len(frame_dim) != 1: print('need one frame dimensions')
jupyter_notebooks/image_registration.ipynb
pycroscopy/pycroscopy
mit
Complete Registration Takes a while, depending on your computer between 1 and 10 minutes.
## Do all of registration notebook_tags ={'notebook': __notebook__, 'notebook_version': __notebook_version__} non_rigid_registered, rigid_registered_dataset = px.image.complete_registration(main_dataset) non_rigid_registered.plot() non_rigid_registered
jupyter_notebooks/image_registration.ipynb
pycroscopy/pycroscopy
mit
Check Drift
scale_x = (rigid_registered_dataset.x[1]-rigid_registered_dataset.x[0])*1. drift = rigid_registered_dataset.metadata['drift'] x = np.linspace(0,drift.shape[0]-1,drift.shape[0]) polynom_degree = 2 # 1 is linear fit, 2 is parabolic fit, ... line_fit_x = np.polyfit(x, drift[:,0], polynom_degree) poly_x = np.poly1d(line_fit_x) line_fit_y = np.polyfit(x, drift[:,1], polynom_degree) poly_y = np.poly1d(line_fit_y) plt.figure() # plot drift and fit of drift plt.axhline(color = 'gray') plt.plot(x, drift[:,0], label = 'drift x') plt.plot(x, drift[:,1], label = 'drift y') plt.plot(x, poly_x(x), label = 'fit_drift_x') plt.plot(x, poly_y(x), label = 'fit_drift_y') plt.legend(); # set second axis in pico meter ax_pixels = plt.gca() ax_pixels.step(1, 1) ax_pm = ax_pixels.twinx() x_1, x_2 = ax_pixels.get_ylim() ax_pm.set_ylim(x_1*scale_x, x_2*scale_x) # add labels ax_pixels.set_ylabel('drift [pixels]') ax_pm.set_ylabel('drift [nm]') ax_pixels.set_xlabel('image number'); plt.tight_layout()
jupyter_notebooks/image_registration.ipynb
pycroscopy/pycroscopy
mit
Appendix Demon Registration Here we use the Diffeomorphic Demon Non-Rigid Registration as provided by simpleITK. Please Cite: * simpleITK and T. Vercauteren, X. Pennec, A. Perchant and N. Ayache Diffeomorphic Demons Using ITK\'s Finite Difference Solver Hierarchy The Insight Journal, 2007 This Non-Rigid Registration consists of the following steps: determine reference image For this we use the average of the rigid registered stack this averaged stack is then smeared with a Gaussian of sigma 2 pixel to reduce noise under the assumption that high frequency scan distortions cancel out over several images, we, therefore, obtained the center of mass of the atoms. perform the demon registration filter to determine a distortion matrix each single image of a stack is first smeared with a Gaussian of sigma of 2pixels then the deformation matrix is determined for these images the deformation matrix is a matrix where each pixel has a vector ( x, and y value) for the relative shift of this pixel. This deformation matrix is used to transform the image The transformation is performed on the original image. Important, here, is to set the interpolator method, (the image needs to be interpolated because the new pixels are not on an integer grid.) Let's see what the different interpolators do. |Method | RMS contrast | Standard | Mean | |-------|:--------------|:-------------|:-------| |original |0.1965806 |0.07764114 |0.3949583 |Linear |0.20159315 |0.079470366 |0.39421165 |BSpline |0.20162606 |0.0794831 |0.39421043 |Gaussian |0.14310582 |0.056414302 |0.39421389 |Hamming |0.20163293 |0.07948672 |0.39421496 The Gaussian interpolator is the only one seems to smear the signal. We will use the Bspline method a fast and simple method that does not introduce spurious features and does not smear the signal. Full Code of Demon registration
import simpleITK as sitk def DemonReg(cube, verbose = False): """ Diffeomorphic Demon Non-Rigid Registration Usage: DemReg = DemonReg(cube, verbose = False) Input: cube: stack of image after rigid registration and cropping Output: DemReg: stack of images with non-rigid registration Dempends on: simpleITK and numpy Please Cite: http://www.simpleitk.org/SimpleITK/project/parti.html and T. Vercauteren, X. Pennec, A. Perchant and N. Ayache Diffeomorphic Demons Using ITK\'s Finite Difference Solver Hierarchy The Insight Journal, http://hdl.handle.net/1926/510 2007 """ DemReg = np.zeros_like(cube) nimages = cube.shape[0] print(nimages) # create fixed image by summing over rigid registration fixed_np = np.average(current_dataset, axis=0) fixed = sitk.GetImageFromArray(fixed_np) fixed = sitk.DiscreteGaussian(fixed, 2.0) #demons = sitk.SymmetricForcesDemonsRegistrationFilter() demons = sitk.DiffeomorphicDemonsRegistrationFilter() demons.SetNumberOfIterations(200) demons.SetStandardDeviations(1.0) resampler = sitk.ResampleImageFilter() resampler.SetReferenceImage(fixed); resampler.SetInterpolator(sitk.sitkBspline) resampler.SetDefaultPixelValue(0) done = 0 for i in range(nimages): if done < int((i+1)/nimages*50): done = int((i+1)/nimages*50) sys.stdout.write('\r') # progress output : sys.stdout.write("[%-50s] %d%%" % ('*'*done, 2*done)) sys.stdout.flush() moving = sitk.GetImageFromArray(cube[i]) movingf = sitk.DiscreteGaussian(moving, 2.0) displacementField = demons.Execute(fixed,movingf) outTx = sitk.DisplacementFieldTransform( displacementField ) resampler.SetTransform(outTx) out = resampler.Execute(moving) DemReg[i,:,:] = sitk.GetArrayFromImage(out) #print('image ', i) print(':-)') print('You have succesfully completed Diffeomorphic Demons Registration') return DemReg
jupyter_notebooks/image_registration.ipynb
pycroscopy/pycroscopy
mit
2 - Dataset First, let's get the dataset you will work on. The following code will load a "flower" 2-class dataset into variables X and Y.
X, Y = load_planar_dataset()
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Visualize the dataset using matplotlib. The data looks like a "flower" with some red (label y=0) and some blue (y=1) points. Your goal is to build a model to fit this data.
# Visualize the data: plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
You have: - a numpy-array (matrix) X that contains your features (x1, x2) - a numpy-array (vector) Y that contains your labels (red:0, blue:1). Lets first get a better sense of what our data is like. Exercise: How many training examples do you have? In addition, what is the shape of the variables X and Y? Hint: How do you get the shape of a numpy array? (help)
### START CODE HERE ### (≈ 3 lines of code) shape_X = X.shape shape_Y = Y.shape m = Y.flatten().shape # training set size ### END CODE HERE ### print ('The shape of X is: ' + str(shape_X)) print ('The shape of Y is: ' + str(shape_Y)) print ('I have m = %d training examples!' % (m))
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Expected Output: <table style="width:20%"> <tr> <td>**shape of X**</td> <td> (2, 400) </td> </tr> <tr> <td>**shape of Y**</td> <td>(1, 400) </td> </tr> <tr> <td>**m**</td> <td> 400 </td> </tr> </table> 3 - Simple Logistic Regression Before building a full neural network, lets first see how logistic regression performs on this problem. You can use sklearn's built-in functions to do that. Run the code below to train a logistic regression classifier on the dataset.
# Train the logistic regression classifier clf = sklearn.linear_model.LogisticRegressionCV(); clf.fit(X.T, Y.T);
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
You can now plot the decision boundary of these models. Run the code below.
# Plot the decision boundary for logistic regression plot_decision_boundary(lambda x: clf.predict(x), X, Y) plt.title("Logistic Regression") # Print accuracy LR_predictions = clf.predict(X.T) print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) + '% ' + "(percentage of correctly labelled datapoints)")
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Expected Output: <table style="width:20%"> <tr> <td>**Accuracy**</td> <td> 47% </td> </tr> </table> Interpretation: The dataset is not linearly separable, so logistic regression doesn't perform well. Hopefully a neural network will do better. Let's try this now! 4 - Neural Network model Logistic regression did not work well on the "flower dataset". You are going to train a Neural Network with a single hidden layer. Here is our model: <img src="images/classification_kiank.png" style="width:600px;height:300px;"> Mathematically: For one example $x^{(i)}$: $$z^{[1] (i)} = W^{[1]} x^{(i)} + b^{[1] (i)}\tag{1}$$ $$a^{[1] (i)} = \tanh(z^{[1] (i)})\tag{2}$$ $$z^{[2] (i)} = W^{[2]} a^{[1] (i)} + b^{[2] (i)}\tag{3}$$ $$\hat{y}^{(i)} = a^{[2] (i)} = \sigma(z^{ [2] (i)})\tag{4}$$ $$y^{(i)}_{prediction} = \begin{cases} 1 & \mbox{if } a^{2} > 0.5 \ 0 & \mbox{otherwise } \end{cases}\tag{5}$$ Given the predictions on all the examples, you can also compute the cost $J$ as follows: $$J = - \frac{1}{m} \sum\limits_{i = 0}^{m} \large\left(\small y^{(i)}\log\left(a^{[2] (i)}\right) + (1-y^{(i)})\log\left(1- a^{[2] (i)}\right) \large \right) \small \tag{6}$$ Reminder: The general methodology to build a Neural Network is to: 1. Define the neural network structure ( # of input units, # of hidden units, etc). 2. Initialize the model's parameters 3. Loop: - Implement forward propagation - Compute loss - Implement backward propagation to get the gradients - Update parameters (gradient descent) You often build helper functions to compute steps 1-3 and then merge them into one function we call nn_model(). Once you've built nn_model() and learnt the right parameters, you can make predictions on new data. 4.1 - Defining the neural network structure Exercise: Define three variables: - n_x: the size of the input layer - n_h: the size of the hidden layer (set this to 4) - n_y: the size of the output layer Hint: Use shapes of X and Y to find n_x and n_y. Also, hard code the hidden layer size to be 4.
# GRADED FUNCTION: layer_sizes def layer_sizes(X, Y): """ Arguments: X -- input dataset of shape (input size, number of examples) Y -- labels of shape (output size, number of examples) Returns: n_x -- the size of the input layer n_h -- the size of the hidden layer n_y -- the size of the output layer """ ### START CODE HERE ### (≈ 3 lines of code) n_x = X.shape[0] # size of input layer n_h = 4 n_y = Y.shape[0] # size of output layer ### END CODE HERE ### return (n_x, n_h, n_y) X_assess, Y_assess = layer_sizes_test_case() (n_x, n_h, n_y) = layer_sizes(X_assess, Y_assess) print("The size of the input layer is: n_x = " + str(n_x)) print("The size of the hidden layer is: n_h = " + str(n_h)) print("The size of the output layer is: n_y = " + str(n_y))
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Expected Output (these are not the sizes you will use for your network, they are just used to assess the function you've just coded). <table style="width:20%"> <tr> <td>**n_x**</td> <td> 5 </td> </tr> <tr> <td>**n_h**</td> <td> 4 </td> </tr> <tr> <td>**n_y**</td> <td> 2 </td> </tr> </table> 4.2 - Initialize the model's parameters Exercise: Implement the function initialize_parameters(). Instructions: - Make sure your parameters' sizes are right. Refer to the neural network figure above if needed. - You will initialize the weights matrices with random values. - Use: np.random.randn(a,b) * 0.01 to randomly initialize a matrix of shape (a,b). - You will initialize the bias vectors as zeros. - Use: np.zeros((a,b)) to initialize a matrix of shape (a,b) with zeros.
# GRADED FUNCTION: initialize_parameters def initialize_parameters(n_x, n_h, n_y): """ Argument: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: params -- python dictionary containing your parameters: W1 -- weight matrix of shape (n_h, n_x) b1 -- bias vector of shape (n_h, 1) W2 -- weight matrix of shape (n_y, n_h) b2 -- bias vector of shape (n_y, 1) """ np.random.seed(2) # we set up a seed so that your output matches ours although the initialization is random. ### START CODE HERE ### (≈ 4 lines of code) W1 = np.random.randn(n_h, n_x) * 0.01 b1 = np.zeros((n_h, 1)) W2 = np.random.randn(n_y, n_h) * 0.01 b2 = np.zeros((n_y, 1)) ### END CODE HERE ### assert (W1.shape == (n_h, n_x)) assert (b1.shape == (n_h, 1)) assert (W2.shape == (n_y, n_h)) assert (b2.shape == (n_y, 1)) parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} return parameters n_x, n_h, n_y = initialize_parameters_test_case() parameters = initialize_parameters(n_x, n_h, n_y) print("W1 = " + str(parameters["W1"])) print("b1 = " + str(parameters["b1"])) print("W2 = " + str(parameters["W2"])) print("b2 = " + str(parameters["b2"]))
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Expected Output: <table style="width:90%"> <tr> <td>**W1**</td> <td> [[-0.00416758 -0.00056267] [-0.02136196 0.01640271] [-0.01793436 -0.00841747] [ 0.00502881 -0.01245288]] </td> </tr> <tr> <td>**b1**</td> <td> [[ 0.] [ 0.] [ 0.] [ 0.]] </td> </tr> <tr> <td>**W2**</td> <td> [[-0.01057952 -0.00909008 0.00551454 0.02292208]]</td> </tr> <tr> <td>**b2**</td> <td> [[ 0.]] </td> </tr> </table> 4.3 - The Loop Question: Implement forward_propagation(). Instructions: - Look above at the mathematical representation of your classifier. - You can use the function sigmoid(). It is built-in (imported) in the notebook. - You can use the function np.tanh(). It is part of the numpy library. - The steps you have to implement are: 1. Retrieve each parameter from the dictionary "parameters" (which is the output of initialize_parameters()) by using parameters[".."]. 2. Implement Forward Propagation. Compute $Z^{[1]}, A^{[1]}, Z^{[2]}$ and $A^{[2]}$ (the vector of all your predictions on all the examples in the training set). - Values needed in the backpropagation are stored in "cache". The cache will be given as an input to the backpropagation function.
# GRADED FUNCTION: forward_propagation def forward_propagation(X, parameters): """ Argument: X -- input data of size (n_x, m) parameters -- python dictionary containing your parameters (output of initialization function) Returns: A2 -- The sigmoid output of the second activation cache -- a dictionary containing "Z1", "A1", "Z2" and "A2" """ # Retrieve each parameter from the dictionary "parameters" ### START CODE HERE ### (≈ 4 lines of code) W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] ### END CODE HERE ### # Implement Forward Propagation to calculate A2 (probabilities) ### START CODE HERE ### (≈ 4 lines of code) Z1 = np.dot(W1, X) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) ### END CODE HERE ### assert(A2.shape == (1, X.shape[1])) cache = {"Z1": Z1, "A1": A1, "Z2": Z2, "A2": A2} return A2, cache X_assess, parameters = forward_propagation_test_case() A2, cache = forward_propagation(X_assess, parameters) # Note: we use the mean here just to make sure that your output matches ours. print(np.mean(cache['Z1']) ,np.mean(cache['A1']),np.mean(cache['Z2']),np.mean(cache['A2']))
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Expected Output: <table style="width:55%"> <tr> <td> -0.000499755777742 -0.000496963353232 0.000438187450959 0.500109546852 </td> </tr> </table> Now that you have computed $A^{[2]}$ (in the Python variable "A2"), which contains $a^{2}$ for every example, you can compute the cost function as follows: $$J = - \frac{1}{m} \sum\limits_{i = 0}^{m} \large{(} \small y^{(i)}\log\left(a^{[2] (i)}\right) + (1-y^{(i)})\log\left(1- a^{[2] (i)}\right) \large{)} \small\tag{13}$$ Exercise: Implement compute_cost() to compute the value of the cost $J$. Instructions: - There are many ways to implement the cross-entropy loss. To help you, we give you how we would have implemented $- \sum\limits_{i=0}^{m} y^{(i)}\log(a^{2})$: python logprobs = np.multiply(np.log(A2),Y) cost = - np.sum(logprobs) # no need to use a for loop! (you can use either np.multiply() and then np.sum() or directly np.dot()).
# GRADED FUNCTION: compute_cost def compute_cost(A2, Y, parameters): """ Computes the cross-entropy cost given in equation (13) Arguments: A2 -- The sigmoid output of the second activation, of shape (1, number of examples) Y -- "true" labels vector of shape (1, number of examples) parameters -- python dictionary containing your parameters W1, b1, W2 and b2 Returns: cost -- cross-entropy cost given equation (13) """ m = Y.shape[1] # number of example # Retrieve W1 and W2 from parameters ### START CODE HERE ### (≈ 2 lines of code) W1 = parameters["W1"] W2 = parameters["W2"] ### END CODE HERE ### # Compute the cross-entropy cost ### START CODE HERE ### (≈ 2 lines of code) logprobs = np.multiply(Y, np.log(A2)) + np.multiply(np.log(1 - A2), 1 - Y) cost = - 1 / m * np.sum(logprobs) ### END CODE HERE ### cost = np.squeeze(cost) # makes sure cost is the dimension we expect. # E.g., turns [[17]] into 17 assert(isinstance(cost, float)) return cost A2, Y_assess, parameters = compute_cost_test_case() print("cost = " + str(compute_cost(A2, Y_assess, parameters)))
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Expected Output: <table style="width:20%"> <tr> <td>**cost**</td> <td> 0.692919893776 </td> </tr> </table> Using the cache computed during forward propagation, you can now implement backward propagation. Question: Implement the function backward_propagation(). Instructions: Backpropagation is usually the hardest (most mathematical) part in deep learning. To help you, here again is the slide from the lecture on backpropagation. You'll want to use the six equations on the right of this slide, since you are building a vectorized implementation. <img src="images/grad_summary.png" style="width:600px;height:300px;"> <!-- $\frac{\partial \mathcal{J} }{ \partial z_{2}^{(i)} } = \frac{1}{m} (a^{[2](i)} - y^{(i)})$ $\frac{\partial \mathcal{J} }{ \partial W_2 } = \frac{\partial \mathcal{J} }{ \partial z_{2}^{(i)} } a^{[1] (i) T} $ $\frac{\partial \mathcal{J} }{ \partial b_2 } = \sum_i{\frac{\partial \mathcal{J} }{ \partial z_{2}^{(i)}}}$ $\frac{\partial \mathcal{J} }{ \partial z_{1}^{(i)} } = W_2^T \frac{\partial \mathcal{J} }{ \partial z_{2}^{(i)} } * ( 1 - a^{[1] (i) 2}) $ $\frac{\partial \mathcal{J} }{ \partial W_1 } = \frac{\partial \mathcal{J} }{ \partial z_{1}^{(i)} } X^T $ $\frac{\partial \mathcal{J} _i }{ \partial b_1 } = \sum_i{\frac{\partial \mathcal{J} }{ \partial z_{1}^{(i)}}}$ - Note that $*$ denotes elementwise multiplication. - The notation you will use is common in deep learning coding: - dW1 = $\frac{\partial \mathcal{J} }{ \partial W_1 }$ - db1 = $\frac{\partial \mathcal{J} }{ \partial b_1 }$ - dW2 = $\frac{\partial \mathcal{J} }{ \partial W_2 }$ - db2 = $\frac{\partial \mathcal{J} }{ \partial b_2 }$ !--> Tips: To compute dZ1 you'll need to compute $g^{[1]'}(Z^{[1]})$. Since $g^{[1]}(.)$ is the tanh activation function, if $a = g^{[1]}(z)$ then $g^{[1]'}(z) = 1-a^2$. So you can compute $g^{[1]'}(Z^{[1]})$ using (1 - np.power(A1, 2)).
# GRADED FUNCTION: backward_propagation def backward_propagation(parameters, cache, X, Y): """ Implement the backward propagation using the instructions above. Arguments: parameters -- python dictionary containing our parameters cache -- a dictionary containing "Z1", "A1", "Z2" and "A2". X -- input data of shape (2, number of examples) Y -- "true" labels vector of shape (1, number of examples) Returns: grads -- python dictionary containing your gradients with respect to different parameters """ m = X.shape[1] # First, retrieve W1 and W2 from the dictionary "parameters". ### START CODE HERE ### (≈ 2 lines of code) W1 = parameters["W1"] W2 = parameters["W2"] ### END CODE HERE ### # Retrieve also A1 and A2 from dictionary "cache". ### START CODE HERE ### (≈ 2 lines of code) A1 = cache["A1"] A2 = cache["A2"] ### END CODE HERE ### # Backward propagation: calculate dW1, db1, dW2, db2. ### START CODE HERE ### (≈ 6 lines of code, corresponding to 6 equations on slide above) dZ2 = A2 - Y dW2 = 1 / m * np.dot(dZ2, A1.T) db2 = 1 / m * np.sum(dZ2, axis=1, keepdims=True) dZ1 = np.dot(W2.T, dZ2) * (1 - np.power(A1, 2)) dW1 = 1 / m * np.dot(dZ1, X.T) db1 = 1 / m * np.sum(dZ1, axis=1, keepdims=True) ### END CODE HERE ### grads = {"dW1": dW1, "db1": db1, "dW2": dW2, "db2": db2} return grads parameters, cache, X_assess, Y_assess = backward_propagation_test_case() grads = backward_propagation(parameters, cache, X_assess, Y_assess) print ("dW1 = "+ str(grads["dW1"])) print ("db1 = "+ str(grads["db1"])) print ("dW2 = "+ str(grads["dW2"])) print ("db2 = "+ str(grads["db2"]))
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Expected output: <table style="width:80%"> <tr> <td>**dW1**</td> <td> [[ 0.01018708 -0.00708701] [ 0.00873447 -0.0060768 ] [-0.00530847 0.00369379] [-0.02206365 0.01535126]] </td> </tr> <tr> <td>**db1**</td> <td> [[-0.00069728] [-0.00060606] [ 0.000364 ] [ 0.00151207]] </td> </tr> <tr> <td>**dW2**</td> <td> [[ 0.00363613 0.03153604 0.01162914 -0.01318316]] </td> </tr> <tr> <td>**db2**</td> <td> [[ 0.06589489]] </td> </tr> </table> Question: Implement the update rule. Use gradient descent. You have to use (dW1, db1, dW2, db2) in order to update (W1, b1, W2, b2). General gradient descent rule: $ \theta = \theta - \alpha \frac{\partial J }{ \partial \theta }$ where $\alpha$ is the learning rate and $\theta$ represents a parameter. Illustration: The gradient descent algorithm with a good learning rate (converging) and a bad learning rate (diverging). Images courtesy of Adam Harley. <img src="images/sgd.gif" style="width:400;height:400;"> <img src="images/sgd_bad.gif" style="width:400;height:400;">
# GRADED FUNCTION: update_parameters def update_parameters(parameters, grads, learning_rate = 1.2): """ Updates parameters using the gradient descent update rule given above Arguments: parameters -- python dictionary containing your parameters grads -- python dictionary containing your gradients Returns: parameters -- python dictionary containing your updated parameters """ # Retrieve each parameter from the dictionary "parameters" ### START CODE HERE ### (≈ 4 lines of code) W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] ### END CODE HERE ### # Retrieve each gradient from the dictionary "grads" ### START CODE HERE ### (≈ 4 lines of code) dW1 = grads["dW1"] db1 = grads["db1"] dW2 = grads["dW2"] db2 = grads["db2"] ## END CODE HERE ### # Update rule for each parameter ### START CODE HERE ### (≈ 4 lines of code) W1 = W1 - learning_rate * dW1 b1 = b1 - learning_rate * db1 W2 = W2 - learning_rate * dW2 b2 = b2 - learning_rate * db2 ### END CODE HERE ### parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} return parameters parameters, grads = update_parameters_test_case() parameters = update_parameters(parameters, grads) print("W1 = " + str(parameters["W1"])) print("b1 = " + str(parameters["b1"])) print("W2 = " + str(parameters["W2"])) print("b2 = " + str(parameters["b2"]))
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Expected Output: <table style="width:80%"> <tr> <td>**W1**</td> <td> [[-0.00643025 0.01936718] [-0.02410458 0.03978052] [-0.01653973 -0.02096177] [ 0.01046864 -0.05990141]]</td> </tr> <tr> <td>**b1**</td> <td> [[ -1.02420756e-06] [ 1.27373948e-05] [ 8.32996807e-07] [ -3.20136836e-06]]</td> </tr> <tr> <td>**W2**</td> <td> [[-0.01041081 -0.04463285 0.01758031 0.04747113]] </td> </tr> <tr> <td>**b2**</td> <td> [[ 0.00010457]] </td> </tr> </table> 4.4 - Integrate parts 4.1, 4.2 and 4.3 in nn_model() Question: Build your neural network model in nn_model(). Instructions: The neural network model has to use the previous functions in the right order.
# GRADED FUNCTION: nn_model def nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False): """ Arguments: X -- dataset of shape (2, number of examples) Y -- labels of shape (1, number of examples) n_h -- size of the hidden layer num_iterations -- Number of iterations in gradient descent loop print_cost -- if True, print the cost every 1000 iterations Returns: parameters -- parameters learnt by the model. They can then be used to predict. """ np.random.seed(3) n_x = layer_sizes(X, Y)[0] n_y = layer_sizes(X, Y)[2] # Initialize parameters, then retrieve W1, b1, W2, b2. Inputs: "n_x, n_h, n_y". Outputs = "W1, b1, W2, b2, parameters". ### START CODE HERE ### (≈ 5 lines of code) parameters = initialize_parameters(n_x, n_h, n_y) W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] ### END CODE HERE ### # Loop (gradient descent) for i in range(0, num_iterations): ### START CODE HERE ### (≈ 4 lines of code) # Forward propagation. Inputs: "X, parameters". Outputs: "A2, cache". A2, cache = forward_propagation(X, parameters) # Cost function. Inputs: "A2, Y, parameters". Outputs: "cost". cost = compute_cost(A2, Y, parameters) # Backpropagation. Inputs: "parameters, cache, X, Y". Outputs: "grads". grads = backward_propagation(parameters, cache, X, Y) # Gradient descent parameter update. Inputs: "parameters, grads". Outputs: "parameters". parameters = update_parameters(parameters, grads) ### END CODE HERE ### # Print the cost every 1000 iterations if print_cost and i % 1000 == 0: print ("Cost after iteration %i: %f" %(i, cost)) return parameters X_assess, Y_assess = nn_model_test_case() parameters = nn_model(X_assess, Y_assess, 4, num_iterations=10000, print_cost=False) print("W1 = " + str(parameters["W1"])) print("b1 = " + str(parameters["b1"])) print("W2 = " + str(parameters["W2"])) print("b2 = " + str(parameters["b2"]))
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Expected Output: <table style="width:90%"> <tr> <td>**W1**</td> <td> [[-4.18494056 5.33220609] [-7.52989382 1.24306181] [-4.1929459 5.32632331] [ 7.52983719 -1.24309422]]</td> </tr> <tr> <td>**b1**</td> <td> [[ 2.32926819] [ 3.79458998] [ 2.33002577] [-3.79468846]]</td> </tr> <tr> <td>**W2**</td> <td> [[-6033.83672146 -6008.12980822 -6033.10095287 6008.06637269]] </td> </tr> <tr> <td>**b2**</td> <td> [[-52.66607724]] </td> </tr> </table> 4.5 Predictions Question: Use your model to predict by building predict(). Use forward propagation to predict results. Reminder: predictions = $y_{prediction} = \mathbb 1 \text{{activation > 0.5}} = \begin{cases} 1 & \text{if}\ activation > 0.5 \ 0 & \text{otherwise} \end{cases}$ As an example, if you would like to set the entries of a matrix X to 0 and 1 based on a threshold you would do: X_new = (X &gt; threshold)
# GRADED FUNCTION: predict def predict(parameters, X): """ Using the learned parameters, predicts a class for each example in X Arguments: parameters -- python dictionary containing your parameters X -- input data of size (n_x, m) Returns predictions -- vector of predictions of our model (red: 0 / blue: 1) """ # Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as the threshold. ### START CODE HERE ### (≈ 2 lines of code) A2, cache = forward_propagation(X, parameters) predictions = (A2 > 0.5) ### END CODE HERE ### return predictions parameters, X_assess = predict_test_case() predictions = predict(parameters, X_assess) print("predictions mean = " + str(np.mean(predictions)))
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Expected Output: <table style="width:40%"> <tr> <td>**predictions mean**</td> <td> 0.666666666667 </td> </tr> </table> It is time to run the model and see how it performs on a planar dataset. Run the following code to test your model with a single hidden layer of $n_h$ hidden units.
# Build a model with a n_h-dimensional hidden layer parameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True) # Plot the decision boundary plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y) plt.title("Decision Boundary for hidden layer size " + str(4))
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Expected Output: <table style="width:40%"> <tr> <td>**Cost after iteration 9000**</td> <td> 0.218607 </td> </tr> </table>
# Print accuracy predictions = predict(parameters, X) print ('Accuracy: %d' % float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100) + '%')
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Expected Output: <table style="width:15%"> <tr> <td>**Accuracy**</td> <td> 90% </td> </tr> </table> Accuracy is really high compared to Logistic Regression. The model has learnt the leaf patterns of the flower! Neural networks are able to learn even highly non-linear decision boundaries, unlike logistic regression. Now, let's try out several hidden layer sizes. 4.6 - Tuning hidden layer size (optional/ungraded exercise) Run the following code. It may take 1-2 minutes. You will observe different behaviors of the model for various hidden layer sizes.
# This may take about 2 minutes to run plt.figure(figsize=(16, 32)) hidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50] for i, n_h in enumerate(hidden_layer_sizes): plt.subplot(5, 2, i+1) plt.title('Hidden Layer of size %d' % n_h) parameters = nn_model(X, Y, n_h, num_iterations = 5000) plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y) predictions = predict(parameters, X) accuracy = float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100) print ("Accuracy for {} hidden units: {} %".format(n_h, accuracy))
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
Interpretation: - The larger models (with more hidden units) are able to fit the training set better, until eventually the largest models overfit the data. - The best hidden layer size seems to be around n_h = 5. Indeed, a value around here seems to fits the data well without also incurring noticable overfitting. - You will also learn later about regularization, which lets you use very large models (such as n_h = 50) without much overfitting. Optional questions: Note: Remember to submit the assignment but clicking the blue "Submit Assignment" button at the upper-right. Some optional/ungraded questions that you can explore if you wish: - What happens when you change the tanh activation for a sigmoid activation or a ReLU activation? - Play with the learning_rate. What happens? - What if we change the dataset? (See part 5 below!) <font color='blue'> You've learnt to: - Build a complete neural network with a hidden layer - Make a good use of a non-linear unit - Implemented forward propagation and backpropagation, and trained a neural network - See the impact of varying the hidden layer size, including overfitting. Nice work! 5) Performance on other datasets If you want, you can rerun the whole notebook (minus the dataset part) for each of the following datasets.
# Datasets noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure = load_extra_datasets() datasets = {"noisy_circles": noisy_circles, "noisy_moons": noisy_moons, "blobs": blobs, "gaussian_quantiles": gaussian_quantiles} ### START CODE HERE ### (choose your dataset) dataset = "gaussian_quantiles" ### END CODE HERE ### X, Y = datasets[dataset] X, Y = X.T, Y.reshape(1, Y.shape[0]) # make blobs binary if dataset == "blobs": Y = Y%2 # Visualize the data plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);
course_1/week_3/assignment_1/planar_data_classification_with_one_hidden_layer_v1.ipynb
ImAlexisSaez/deep-learning-specialization-coursera
mit
We want to add these comits to a REBOUND simulation(s). The first thing to do is set the units, which have to be consistent throughout. Here we have a table in AU and days, so we'll use the gaussian gravitational constant (AU, days, solar masses).
sim = rebound.Simulation() k = 0.01720209895 # Gaussian constant sim.G = k**2
ipython_examples/HyperbolicOrbits.ipynb
dtamayo/rebound
gpl-3.0
We also set the simulation time to the epoch at which the elements are valid:
sim.t = epoch_of_elements
ipython_examples/HyperbolicOrbits.ipynb
dtamayo/rebound
gpl-3.0
We then add the giant planets in our Solar System to the simulation. You could for example query JPL HORIZONS for the states of the planets at each comet's corresponding epoch of observation (see Horizons.ipynb). Here we set up toy masses and orbits for Jupiter & Saturn:
sim.add(m=1.) # Sun sim.add(m=1.e-3, a=5.) # Jupiter sim.add(m=3.e-4, a=10.) # Saturn
ipython_examples/HyperbolicOrbits.ipynb
dtamayo/rebound
gpl-3.0
Let's write a function that takes a comet from the table and adds it to our simulation:
def addOrbit(sim, comet_elem): tracklet_id, e, q, inc, Omega, argperi, t_peri, epoch_of_observation = comet_elem sim.add(primary=sim.particles[0], a = q/(1.-e), e = e, inc = inc*np.pi/180., # have to convert to radians Omega = Omega*np.pi/180., omega = argperi*np.pi/180., T = t_peri # time of pericenter passage )
ipython_examples/HyperbolicOrbits.ipynb
dtamayo/rebound
gpl-3.0
By default, REBOUND adds and outputs particles in Jacobi orbital elements. Typically orbital elements for comets are heliocentric. Mixing the two will give you relative errors in elements, positions etc. of order the mass ratio of Jupiter to the Sun ($\sim 0.001$) which is why we pass the additional primary=sim.particles[0] argument to the add() function. If this level of accuracy doesn't matters to you, you can ignore the primary argument. We can now set up the first comet and quickly plot to see what the system looks like:
addOrbit(sim, comets[0]) %matplotlib inline fig = rebound.OrbitPlot(sim, trails=True)
ipython_examples/HyperbolicOrbits.ipynb
dtamayo/rebound
gpl-3.0
Now we just integrate until whatever final time we’re interested in. Here it's the epoch at which we observe the comet, which is the last column in our table:
tfinal = comets[0][-1] sim.integrate(tfinal) fig = rebound.OrbitPlot(sim, trails=True)
ipython_examples/HyperbolicOrbits.ipynb
dtamayo/rebound
gpl-3.0
REBOUND automatically find out if you want to integrate forward or backward in time. For fun, let's add all the coments to a simulation:
sim = rebound.Simulation() sim.G = k**2 sim.t = epoch_of_elements sim.add(m=1.) # Sun sim.add(m=1.e-3, a=5.) # Jupiter sim.add(m=3.e-4, a=10.) # Saturn for comet in comets: addOrbit(sim, comet) fig = rebound.OrbitPlot(sim, trails=True)
ipython_examples/HyperbolicOrbits.ipynb
dtamayo/rebound
gpl-3.0
1. Data preparation You are going to read the graph from an adjacency list saved in earlier exercises.
call_adjmatrix = pd.read_csv('./call.adjmatrix', index_col=0) call_graph = nx.from_numpy_matrix(call_adjmatrix.as_matrix()) # Display call graph object. plt.figure(figsize=(10,10)) plt.axis('off') pos = graphviz_layout(call_graph, prog='dot') nx.draw_networkx(call_graph, pos=pos, node_color='#11DD11', with_labels=False) _ = plt.axis('off')
module_4/M4_NB3_NetworkClustering.ipynb
getsmarter/bda
mit
2. Hierarchical clustering This notebook makes use of a hierarchical clustering algorithm, as implemented in Scipy. The following example uses the average distance measure. Since the graph is weighted, you can also use the single linkage inter-cluster distance measure (see exercises).
def create_hc(G, linkage='average'): """ Creates hierarchical cluster of graph G from distance matrix """ path_length=nx.all_pairs_shortest_path_length(G) distances=np.zeros((G.order(),G.order())) for u,p in dict(path_length).items(): for v,d in p.items(): distances[list(G.nodes)[u]][list(G.nodes)[v]] = d distances[list(G.nodes)[v]][list(G.nodes)[u]] = d if u==v: distances[list(G.nodes)[u]][list(G.nodes)[u]]=0 # Create hierarchical cluster (HC). Y=distance.squareform(distances) if linkage == 'max': # Creates HC using farthest point linkage. Z=hierarchy.complete(Y) if linkage == 'single': # Creates HC using closest point linkage. Z=hierarchy.single(Y) if linkage == 'average': # Creates HC using average point linkage. Z=hierarchy.average(Y) return Z def get_cluster_membership(Z, maxclust): ''' Assigns cluster membership by specifying cluster size. ''' hc_out=list(hierarchy.fcluster(Z,maxclust, criterion='maxclust')) # Map cluster values to a dictionary variable. cluster_membership = {} i = 0 for i in range(len(hc_out)): cluster_membership[i]=hc_out[i] return cluster_membership
module_4/M4_NB3_NetworkClustering.ipynb
getsmarter/bda
mit
Below is a demonstration of hierarchical clustering when applied to the call graph.
# Perform hierarchical clustering using 'average' linkage. Z = create_hc(call_graph, linkage='average')
module_4/M4_NB3_NetworkClustering.ipynb
getsmarter/bda
mit
The dendrogram corresponding to the partitioned graph is obtained as follows:
hierarchy.dendrogram(Z) plt.show()
module_4/M4_NB3_NetworkClustering.ipynb
getsmarter/bda
mit
You will notice that the full dendrogram is unwieldy, and difficult to use or read. Fortunately, the dendrogram method has a feature that allows one to only show the lastp merged clusters, where $p$ is the desired number of last p merged clusters.
plt.title('Hierarchical Clustering Dendrogram (pruned)') plt.xlabel('sample index (or leaf size)') plt.ylabel('distance') hierarchy.dendrogram( Z, truncate_mode='lastp', # show only the last p merged clusters p=10, # show only the last p merged clusters show_leaf_counts=True, # numbers in brackets are counts for each leaf leaf_rotation=90, leaf_font_size=12) plt.show()
module_4/M4_NB3_NetworkClustering.ipynb
getsmarter/bda
mit
This dendrogram can help explain what happens as a result of the agglomerative method of hierarchical clustering. Starting at the bottom-most level, each node is assigned its own cluster. The closest pair of nodes (according to a distance function) are then merged into a new cluster. The distance matrix is recomputed, treating the merged cluster as an individual node. This process is repeated until the entire network has been merged into a single, large cluster, which the top level in the dendrogram above represents. You can now understand why this method is agglomerative. The linkage function is used to determine the distance between a cluster and a node, or between two clusters, using the following possibilities: Single: Merge two clusters with the smallest minimum pairwise distance. Average: Merge two clusters with the smallest average pairwise distance. Maximum or complete: Merge the two clusters with the smallest maximum pairwise distance. Now, you can finally retrieve the clusters, based on the analysis of the dendrogram. In this post-processing, there are different ways of determining $k$, the number of clusters to partition the data into. Scipy's hierarchical flat clustering function - "hierarchy.fcluster()" - is used to assign cluster membership by specifying a distance threshold, or the number of clusters required. In the function definition (above), you have been provided with a utility function, "get_cluster_membership()", which does the latter. Selecting the number of clusters $k$ is, in general, an ill-posed problem. Different interpretations are possible, depending on the nature of the problem, the scale of the distribution of points in a data set, and the required clustering resolution. In agglomerative clustering, as used in the example above, you can get zero error for the objective function by considering each data point as its own cluster. Hence, the selection of $k$ invariably involves a trade-off maximum compression of the data (using a single cluster), and maximum accuracy by assigning each data point to its own cluster. The selection of an optimal $k$ can be done using automated techniques or manually. Here, identification of an appropriate cluster is ideally done manually as this has the advantages of gaining some insights into your data as well as providing an opportunity to perform sanity checks. To select the cluster size, look for a large shift in the distance metric. In our example with dendrograms plots shown above, say a case has been made for an ideal cutoff of 3.5. The number of clusters is then simply the number of intersections of a horizontal line (with height of 3.5) with the vertical lines of the dendrogram. Therefore, 3 clusters would be obtained in this case as shown below.
fancy_dendrogram( Z, truncate_mode='lastp', p=12, leaf_rotation=90., leaf_font_size=12.0, show_contracted=False, annotate_above=10, max_d=3.5) plt.show() opt_clust = 3 opt_clust
module_4/M4_NB3_NetworkClustering.ipynb
getsmarter/bda
mit
You can now assign the data to these "opt_clust" clusters.
cluster_assignments = get_cluster_membership(Z, maxclust=opt_clust)
module_4/M4_NB3_NetworkClustering.ipynb
getsmarter/bda
mit
The partitioned graph, corresponding to the dendrogram above, can now be visualized.
clust = list(set(cluster_assignments.values())) clust cluster_centers = sorted(set(cluster_assignments.values())) freq = [list(cluster_assignments.values()).count(x) for x in cluster_centers] # Creata a DataFrame object containing list of cluster centers and number of objects in each cluster df = pd.DataFrame({'cluster_centres':cluster_centers, 'number_of_objects':freq}) df.head(10)
module_4/M4_NB3_NetworkClustering.ipynb
getsmarter/bda
mit
<br> <div class="alert alert-info"> <b>Exercise 1 Start.</b> </div> Instructions How many clusters are obtained after the final step of a generic agglomerative clustering algorithm (before post-processing)? Note: Post-processing involves determining the optimal clusters for the problem at hand. Based on your answer above, would you consider agglomerative clustering a top-down approach, or a bottom-up approach? Which of the three linkage functions (i.e. single, average, or maximum or complete) do you think is likely to be most sensitive to outliers? Hint: Look at this single-link and complete-link clustering resource. Your markdown answer here. <br> <div class="alert alert-info"> <b>Exercise 1 End.</b> </div> Exercise complete: <br> <div class="alert alert-info"> <b>Exercise 2 [Advanced] Start.</b> </div> Instructions In this exercise, you will investigate the structural properties of the clusters generated from above. Assign the values from your "cluster_assignments" to a Pandas DataFrame named "df1", with the column name "cluster_label". Hint: The variable "cluster_assignments" is of type dict. You will need to get the values component of this dict, not the keys. Add a field called "participantID" to "df1", and assign to this the index values from the previously-loaded "call_adjmatrix" DataFrame. Load the DataFrame containing the centrality measures that you saved in Notebook 1 of this module, into "df2". Perform an inner join by merging "df1" and "df2" on the field "participantID". Assign the result of this join to variable "df3". Perform a groupby on "df3" (using "cluster_label" field), and then evaluate the mean of the four centrality measures (using the "agg()" method). Assign the aggregation result to "df4". Review "df4", and plot its barplot. Merge clusters which share the same mean values for a centrality measure into a single cluster. Assign the smallest value of the labels in the set to the merged cluster. Note:<br> Combine clusters such that, given a cluster with centrality measures $[x1, x2, x3, x4]$, and another cluster with centrality measures $[z1, z2, z3, z4]$, the following holds true:<br> $x1 = z1$ <br> $x2 = z2$ <br> $x3 = z3$ <br> $x4 = z4$<br> Print the size of each cluster, in descending order, after performing the cluster merging in the preceding step.
# Your code here.
module_4/M4_NB3_NetworkClustering.ipynb
getsmarter/bda
mit
<br> <div class="alert alert-info"> <b>Exercise 2 [Advanced] End.</b> </div> Exercise complete: This is a good time to "Save and Checkpoint". 3. Community detection Community detection is an important component in the analysis of large and complex networks. Identifying these subgraph structures helps in understanding organizational and functional characteristics of the underlying physical networks. In this section, you will study a few approaches that are widely used in community detection using graph representations. 3.1 The Louvain modularity-maximization approach The Louvain method is one of the most widely-used methods for detecting communities in large networks. It was developed by a team of researchers at the Université catholique de Louvain. The method can unveil hierarchies of communities, and allows you to zoom within communities in order to discover sub-communities, sub-sub-communities, and so forth. The modularity QQ quantifies how good a "community" or partition is, and is defined as follows: $$Q_c =\frac{1}{2m}\sum {(ij)} \left [ A{ij}-\frac{k_ik_j}{2m} \right] \delta(c_i, c_j)$$ The higher the $Q_c$ of a community is, the better the partition is. The Louvain method is a greedy optimization method that attempts to optimize the "modularity" of a partition of the network via two steps: Locally optimize the modularity to identify "small" communities. Aggregate nodes belonging to the same community, and create a new network with aggregated nodes as individual nodes. Steps 1 and 2 are then repeated until a maximum of modularity produces a hierarchy of communities. 3.2 Spectral graph partitioning Spectral graph partitioning and clustering is based on the spectrum — the eigenvalues and associated eigenvectors — of the Laplacian matrix that corresponds to a given graph. The approach is mathematically complex, but involves performing a $k$-means clustering, on a spectral projection of the graph, with $k$=2 (using an adjacency matrix as the affinity). A schematic illustration of the process is depicted in the figure below. Optional: You can read more about spectral graph processing. Now, apply spectral graph partitioning to your call graph, and visualize the resulting community structure. You can read more about Scikit-Learn, and the Spectral Clustering function utilized in this section. Spectral graph partitioning needs input in the form of the number of clusters sought (default setting is 8). There are various approaches one can take to optimize the final number of clusters, depending on problem domain knowledge. Below you will use a value of $k=9$.
# Create the spectral partition using the spectral clustering function from Scikit-Learn. spectral_partition = spc(call_adjmatrix.as_matrix(), 9, assign_labels='discretize') pos = graphviz_layout(call_graph, prog='dot') nx.draw_networkx_nodes(call_graph, pos, cmap=plt.cm.RdYlBu, node_color=spectral_partition) nx.draw_networkx_edges(call_graph, pos, alpha=0.5) plt.axis('off') plt.show() print(spectral_partition)
module_4/M4_NB3_NetworkClustering.ipynb
getsmarter/bda
mit
<br> <div class="alert alert-info"> <b>Exercise 3 [Advanced] Start.</b> </div> Instructions Compute the size of each the clusters obtained using the spectral graph partitioning method.
# Your code here.
module_4/M4_NB3_NetworkClustering.ipynb
getsmarter/bda
mit
Household class Below is a rough draft of the household class. It only has one component: constructor: class constructor, which "initializes" or "creates" the household when we call Household(). This is in the init method.
class Household(object): """ Household class, which encapsulates the entire behavior of a household. """ def __init__(self, model, household_id, adopted=False, threshold=1): """ Constructor for HH class. By default, * not adopted * threshold = 1 Must "link" the Household to their "parent" Model object. """ # Set model link and ID self.model = model self.household_id = household_id # Set HH parameters. self.adopted = adopted self.threshold = threshold def __repr__(self): ''' Return string representation. ''' skip_none = True repr_string = type(self).__name__ + " [" except_list = "model" elements = [e for e in dir(self) if str(e) not in except_list] for e in elements: # Make sure we only display "public" fields; skip anything private (_*), that is a method/function, or that is a module. if not e.startswith("_") and eval('type(self.{0}).__name__'.format(e)) not in ['DataFrame', 'function', 'method', 'builtin_function_or_method', 'module', 'instancemethod']: value = eval("self." + e) if value != None and skip_none == True: repr_string += "{0}={1}, ".format(e, value) # Clean up trailing space and comma. return repr_string.strip(" ").strip(",") + "]"
samples/cscs530-w2015-midterm-sample1.ipynb
mjbommar/cscs-530-w2016
bsd-2-clause
Model class Below, we will define our model class. This can be broken up as follows: - constructor: class constructor, which "initializes" or "creates" the model when we call Model(). This is in the init method. - setup_network: sets up graph - setup_households: sets up households - get_neighborhood: defines a function to get a list of connected nodes - step_adopt_decision: method to step through household decision - step: main step method
class Model(object): """ Model class, which encapsulates the entire behavior of a single "run" in network model. """ def __init__(self, network, alpha, HH_adopted, HH_not_adopted): """ Class constructor. """ # Set our model parameters self.network = network self.alpha = alpha self.HH_adopted = HH_adopted self.HH_not_adopted = HH_not_adopted # Set our state variables self.t = 0 self.households = [] # Setup our history variables. self.history_adopted = [] self.history_not_adopted = [] self.percent_adopted = 0 # Call our setup methods self.setup_network() self.setup_household() def setup_network(self): """ Method to setup network. """ ## need to flesh this out. will network be an input given from wrapper? ## what do I need to do to set up network? g = network def setup_households(self): """ Method to setup households. """ num_households = nx.nodes(g) # Create all households. for i in xrange(self.num_households): self.households.append(Household(model=self, household_id=i, adopted=False, threshold=stats.truncnorm.rvs((0 - alpha) / 0.5, (alpha) / 0.5, loc=alpha, scale=0.5,size=1) def get_neighborhood(self, x): """ Get a list of connected nodes. """ neighbors = [] for i in g.neighbors(x): neighbors.append(i) return neighbors def step_adopt_decision(self): """ Model a household evaluating their connections and making an adopt/not adopt decision """ will_adopt = [] for i in HH_not_adopted: adopt_count = 0 for j in get_neighborhood(i): if j.adopted: adopt_count+=1 if adopt_count >= i.threshold: will_adopt.append(i) def step(self): """ Model step function. """ # Adoption decision self.step_adopt_decision() # Increment steps and track history. self.t += 1 self.HH_adopted.append(will_adopt) self.HH_not_adopted.remove(will_adopt) self.history_adopted.append(self.HH_adopted) self.history_not_adopted.append(self.HH_not_adopted) self.percent_adopted = len(HH_adopted)/len(households) def __repr__(self): ''' Return string representation. ''' skip_none = True repr_string = type(self).__name__ + " [" elements = dir(self) for e in elements: # Make sure we only display "public" fields; skip anything private (_*), that is a method/function, or that is a module. e_type = eval('type(self.{0}).__name__'.format(e)) if not e.startswith("_") and e_type not in ['DataFrame', 'function', 'method', 'builtin_function_or_method', 'module', 'instancemethod']: value = eval("self." + e) if value != None and skip_none == True: if e_type in ['list', 'set', 'tuple']: repr_string += "\n\n\t{0}={1},\n\n".format(e, value) elif e_type in ['ndarray']: repr_string += "\n\n\t{0}=\t\n{1},\n\n".format(e, value) else: repr_string += "{0}={1}, ".format(e, value) # Clean up trailing space and comma. return repr_string.strip(" ").strip(",") + "]"
samples/cscs530-w2015-midterm-sample1.ipynb
mjbommar/cscs-530-w2016
bsd-2-clause
Wrapper with parameter sweep Below is the code which wrappers around the model. It does the following: - Loops through all villages we wish to examine - Pulls network data from a csv and puts in the appropriate format - Loops through all possible pairs of nodes within each village - Sweeps through alpha and number of steps parameters - Runs 2000 samples
## cycle through villages: ## (need to create village list where each item points to a different csv file) num_samples = 2000 for fn in village_list: village = np.genfromtxt(fn, delimiter=",") network = from_numpy_matrix(village) for HH_adopted in itertools.combinations(nx.nodes(network),2): HH_not_adopted = [node for node in nx.nodes(network) if node not in HH_adopted] for alpha in [1,2,3]: for num_steps in [3,4,5,6]: for n in xrange(num_samples): m = Model(network, alpha, HH_adopted, HH_not_adopted) for t in xrange(num_steps): m.step() ## I need to collect adoption rate at each final step and average over all samples ## I am not sure where to fit this in ## I also need to write a function which determines optimal seed pairing ####### #######
samples/cscs530-w2015-midterm-sample1.ipynb
mjbommar/cscs-530-w2016
bsd-2-clause
Suppose we want to study the environmental temperature for plankton drifting around a peninsula. We have a dataset with surface ocean velocities and the corresponding sea surface temperature stored in netcdf files in the folder "Peninsula_data". Besides the velocity fields, we load the temperature field using extra_fields={'T': 'T'}. The particles are released on the left hand side of the domain.
# Velocity and temperature fields fieldset = FieldSet.from_parcels("Peninsula_data/peninsula", extra_fields={'T': 'T'}, allow_time_extrapolation=True) # Particle locations and initial time npart = 10 # number of particles to be released lon = 3e3 * np.ones(npart) lat = np.linspace(3e3 , 45e3, npart, dtype=np.float32) time = np.arange(0, npart) * delta(hours=2).total_seconds() # release each particle two hours later # Plot temperature field and initial particle locations T_data = xr.open_dataset("Peninsula_data/peninsulaT.nc") plt.figure() ax = plt.axes() T_contour = ax.contourf(T_data.x.values, T_data.y.values, T_data.T.values[0,0], cmap=plt.cm.inferno) ax.scatter(lon, lat, c='w') plt.colorbar(T_contour, label='T [$^{\circ} C$]') plt.show()
parcels/examples/tutorial_sampling.ipynb
OceanPARCELS/parcels
mit
To sample the temperature field, we need to create a new class of particles where temperature is a Variable. As an argument for the Variable class, we need to provide the initial values for the particles. The easiest option is to access fieldset.T, but this option has some drawbacks.
class SampleParticle(JITParticle): # Define a new particle class temperature = Variable('temperature', initial=fieldset.T) # Variable 'temperature' initialised by sampling the temperature pset = ParticleSet(fieldset=fieldset, pclass=SampleParticle, lon=lon, lat=lat, time=time)
parcels/examples/tutorial_sampling.ipynb
OceanPARCELS/parcels
mit
Using fieldset.T leads to the WARNING displayed above because Variable accesses the fieldset in the slower SciPy mode. Another problem can occur when using the repeatdt argument instead of time: <a id='repeatdt_error'></a>
repeatdt = delta(hours=3) pset = ParticleSet(fieldset=fieldset, pclass=SampleParticle, lon=lon, lat=lat, repeatdt=repeatdt)
parcels/examples/tutorial_sampling.ipynb
OceanPARCELS/parcels
mit
Since the initial time is not defined, the Variable class does not know at what time to access the temperature field. The solution to this initialisation problem is to leave the initial value zero and sample the initial condition in JIT mode with the sampling Kernel:
class SampleParticleInitZero(JITParticle): # Define a new particle class temperature = Variable('temperature', initial=0) # Variable 'temperature' initially zero pset = ParticleSet(fieldset=fieldset, pclass=SampleParticleInitZero, lon=lon, lat=lat, time=time) def SampleT(particle, fieldset, time): particle.temperature = fieldset.T[time, particle.depth, particle.lat, particle.lon] sample_kernel = pset.Kernel(SampleT) # Casting the SampleT function to a kernel.
parcels/examples/tutorial_sampling.ipynb
OceanPARCELS/parcels
mit
To sample the initial values we can execute the Sample kernel over the entire particleset with dt = 0 so that time does not increase
pset.execute(sample_kernel, dt=0) # by only executing the sample kernel we record the initial temperature of the particles output_file = pset.ParticleFile(name="InitZero.nc", outputdt=delta(hours=1)) pset.execute(AdvectionRK4 + sample_kernel, runtime=delta(hours=30), dt=delta(minutes=5), output_file=output_file) output_file.export() # export the trajectory data to a netcdf file output_file.close()
parcels/examples/tutorial_sampling.ipynb
OceanPARCELS/parcels
mit
The particle dataset now contains the particle trajectories and the corresponding environmental temperature
Particle_data = xr.open_dataset("InitZero.nc") plt.figure() ax = plt.axes() ax.set_ylabel('Y') ax.set_xlabel('X') ax.set_ylim(1000, 49000) ax.set_xlim(1000, 99000) ax.plot(Particle_data.lon.transpose(), Particle_data.lat.transpose(), c='k', zorder=1) T_scatter = ax.scatter(Particle_data.lon, Particle_data.lat, c=Particle_data.temperature, cmap=plt.cm.inferno, norm=mpl.colors.Normalize(vmin=0., vmax=20.), edgecolor='k', zorder=2) plt.colorbar(T_scatter, label='T [$^{\circ} C$]') plt.show()
parcels/examples/tutorial_sampling.ipynb
OceanPARCELS/parcels
mit
Sampling initial values In some simulations only the particles initial value within the field is of interest: the variable does not need to be known along the entire trajectory. To reduce computing we can specify the to_write argument to the temperature Variable. This argument can have three values: True, False or 'once'. It determines whether to write the Variable to the output file. If we want to know only the initial value, we can enter 'once' and only the first value will be written to the output file.
class SampleParticleOnce(JITParticle): # Define a new particle class temperature = Variable('temperature', initial=0, to_write='once') # Variable 'temperature' pset = ParticleSet(fieldset=fieldset, pclass=SampleParticleOnce, lon=lon, lat=lat, time=time) pset.execute(sample_kernel, dt=0) # by only executing the sample kernel we record the initial temperature of the particles output_file = pset.ParticleFile(name="WriteOnce.nc", outputdt=delta(hours=1)) pset.execute(AdvectionRK4, runtime=delta(hours=24), dt=delta(minutes=5), output_file=output_file) output_file.close()
parcels/examples/tutorial_sampling.ipynb
OceanPARCELS/parcels
mit
Since all the particles are released at the same x-position and the temperature field is invariant in the y-direction, all particles have an initial temperature of 0.4$^\circ$C
Particle_data = xr.open_dataset("WriteOnce.nc") plt.figure() ax = plt.axes() ax.set_ylabel('Y') ax.set_xlabel('X') ax.set_ylim(1000, 49000) ax.set_xlim(1000, 99000) ax.plot(Particle_data.lon.transpose(), Particle_data.lat.transpose(), c='k', zorder=1) T_scatter = ax.scatter(Particle_data.lon, Particle_data.lat, c=np.tile(Particle_data.temperature, (Particle_data.lon.shape[1], 1)).T, cmap=plt.cm.inferno, norm=mpl.colors.Normalize(vmin=0., vmax=1.), edgecolor='k', zorder=2) plt.colorbar(T_scatter, label='Initial T [$^{\circ} C$]') plt.show()
parcels/examples/tutorial_sampling.ipynb
OceanPARCELS/parcels
mit
Sampling with repeatdt Some experiments require large sets of particles to be released repeatedly on the same locations. The particleset object has the option repeatdt for this, but when you want to sample the initial values this introduces some problems as we have seen here. For more advanced control over the repeated release of particles, you can manually write a for-loop using the function particleset.add(). Note that this for-loop is very similar to the one that repeatdt would execute under the hood in particleset.execute(). Adding particles to the particleset during the simulation reduces the memory used compared to specifying the delayed particle release times upfront, which improves the computational speed. In the loop, we want to initialise new particles and sample their initial temperature. If we want to write both the initialised particles with the sampled temperature and the older particles that have already been advected, we have to make sure both sets of particles find themselves at the same moment in time. The initial conditions must be written to the output file before advecting them, because during advection the particle.time will increase. We do not specify the outputdt argument for the output_file and instead write the data with output_file.write(pset, time) on each iteration. A new particleset is initialised whenever time is a multiple of repeatdt. Because the particles are advected after being written, the last displacement must be written once more after the loop.
outputdt = delta(hours=1).total_seconds() # write the particle data every hour repeatdt = delta(hours=6).total_seconds() # release each set of particles six hours later runtime = delta(hours=24).total_seconds() pset = ParticleSet(fieldset=fieldset, pclass=SampleParticleInitZero, lon=[], lat=[], time=[]) # Using SampleParticleInitZero kernels = AdvectionRK4 + sample_kernel output_file = pset.ParticleFile(name="RepeatLoop.nc") # Do not specify the outputdt yet, so we can manually write the output for time in np.arange(0, runtime, outputdt): if np.isclose(np.fmod(time, repeatdt), 0): # time is a multiple of repeatdt pset_init = ParticleSet(fieldset=fieldset, pclass=SampleParticleInitZero, lon=lon, lat=lat, time=time) pset_init.execute(sample_kernel, dt=0) # record the initial temperature of the particles pset.add(pset_init) # add the newly released particles to the total particleset output_file.write(pset,time) # write the initialised particles and the advected particles pset.execute(kernels, runtime=outputdt, dt=delta(minutes=5)) print('Length of pset at time %d: %d' % (time, len(pset))) output_file.write(pset, time+outputdt) output_file.close()
parcels/examples/tutorial_sampling.ipynb
OceanPARCELS/parcels
mit
In each iteration of the loop, spanning six hours, we have added ten particles.
Particle_data = xr.open_dataset("RepeatLoop.nc") print(Particle_data.time[:,0].values / np.timedelta64(1, 'h')) # The initial hour at which each particle is released assert np.allclose(Particle_data.time[:,0].values / np.timedelta64(1, 'h'), [int(k/10)*6 for k in range(40)])
parcels/examples/tutorial_sampling.ipynb
OceanPARCELS/parcels
mit
Let's check if the initial temperatures were sampled correctly for all particles
print(Particle_data.temperature[:,0].values) assert np.allclose(Particle_data.temperature[:,0].values, Particle_data.temperature[:,0].values[0])
parcels/examples/tutorial_sampling.ipynb
OceanPARCELS/parcels
mit
And see if the sampling of the temperature field is done correctly along the trajectories
Release0 = Particle_data.where(Particle_data.time[:,0]==np.timedelta64(0, 's')) # the particles released at t = 0 plt.figure() ax = plt.axes() ax.set_ylabel('Y') ax.set_xlabel('X') ax.set_ylim(1000, 49000) ax.set_xlim(1000, 99000) ax.plot(Release0.lon.transpose(), Release0.lat.transpose(), c='k', zorder=1) T_scatter = ax.scatter(Release0.lon, Release0.lat, c=Release0.temperature, cmap=plt.cm.inferno, norm=mpl.colors.Normalize(vmin=0., vmax=20.), edgecolor='k', zorder=2) plt.colorbar(T_scatter, label='T [$^{\circ} C$]') plt.show()
parcels/examples/tutorial_sampling.ipynb
OceanPARCELS/parcels
mit
Compute degree-days First we compute heating degree-days for different base temperatures. More information on the computation of degree-days can be found in this demo.
%matplotlib inline # resample weather data to daily values and compute degree-days dfw = dfw.resample('D').mean() dfw_HDD = og.library.weather.compute_degree_days(ts=dfw['temperature'], heating_base_temperatures=range(8, 18, 2), cooling_base_temperatures=range(16, 26, 2)).bfill() # resample the gas consumption to daily values and add the weather data and the degree-days df_day = df.resample('D').sum()/1000. # kWh/day df_day = pd.concat([df_day, dfw, dfw_HDD], axis=1).loc['2016']
notebooks/Multi-variable Linear Regression Demo.ipynb
opengridcc/opengrid
apache-2.0
Create a monthly model for the gas consumption
# resample to monthly data and plot df_month = df_day.resample('MS').sum() # create the model mvlr = og.MultiVarLinReg(df_month, endog='313b') print(mvlr.fit.summary()) mvlr.plot()
notebooks/Multi-variable Linear Regression Demo.ipynb
opengridcc/opengrid
apache-2.0
<br>
# Import Titanic data (local CSV) titanic = h2o.import_file("kaggle_titanic.csv") titanic.head(5) # Convert 'Survived' and 'Pclass' to categorical values titanic['Survived'] = titanic['Survived'].asfactor() titanic['Pclass'] = titanic['Pclass'].asfactor() # Define features (or predictors) manually features = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'] # Split the H2O data frame into training/test sets # so we can evaluate out-of-bag performance titanic_split = titanic.split_frame(ratios = [0.8], seed = 1234) titanic_train = titanic_split[0] # using 80% for training titanic_test = titanic_split[1] # using the rest 20% for out-of-bag evaluation titanic_train.shape titanic_test.shape
introduction_to_machine_learning/py_04b_classification_ensembles.ipynb
woobe/h2o_tutorials
mit
<br> Define Search Criteria for Random Grid Search
# define the criteria for random grid search search_criteria = {'strategy': "RandomDiscrete", 'max_models': 9, 'seed': 1234}
introduction_to_machine_learning/py_04b_classification_ensembles.ipynb
woobe/h2o_tutorials
mit
<br> Step 1: Build GBM Models using Random Grid Search and Extract the Best Model
# define the range of hyper-parameters for GBM grid search # 27 combinations in total hyper_params = {'sample_rate': [0.7, 0.8, 0.9], 'col_sample_rate': [0.7, 0.8, 0.9], 'max_depth': [3, 5, 7]} # Set up GBM grid search # Add a seed for reproducibility gbm_rand_grid = H2OGridSearch( H2OGradientBoostingEstimator( model_id = 'gbm_rand_grid', seed = 1234, ntrees = 10000, nfolds = 5, fold_assignment = "Modulo", # needed for stacked ensembles keep_cross_validation_predictions = True, # needed for stacked ensembles stopping_metric = 'mse', stopping_rounds = 15, score_tree_interval = 1), search_criteria = search_criteria, # full grid search hyper_params = hyper_params) # Use .train() to start the grid search gbm_rand_grid.train(x = features, y = 'Survived', training_frame = titanic_train) # Sort and show the grid search results gbm_rand_grid_sorted = gbm_rand_grid.get_grid(sort_by='auc', decreasing=True) print(gbm_rand_grid_sorted) # Extract the best model from random grid search best_gbm_model_id = gbm_rand_grid_sorted.model_ids[0] best_gbm_from_rand_grid = h2o.get_model(best_gbm_model_id) best_gbm_from_rand_grid.summary()
introduction_to_machine_learning/py_04b_classification_ensembles.ipynb
woobe/h2o_tutorials
mit
<br> Step 2: Build DRF Models using Random Grid Search and Extract the Best Model
# define the range of hyper-parameters for DRF grid search # 27 combinations in total hyper_params = {'sample_rate': [0.5, 0.6, 0.7], 'col_sample_rate_per_tree': [0.7, 0.8, 0.9], 'max_depth': [3, 5, 7]} # Set up DRF grid search # Add a seed for reproducibility drf_rand_grid = H2OGridSearch( H2ORandomForestEstimator( model_id = 'drf_rand_grid', seed = 1234, ntrees = 200, nfolds = 5, fold_assignment = "Modulo", # needed for stacked ensembles keep_cross_validation_predictions = True), # needed for stacked ensembles search_criteria = search_criteria, # full grid search hyper_params = hyper_params) # Use .train() to start the grid search drf_rand_grid.train(x = features, y = 'Survived', training_frame = titanic_train) # Sort and show the grid search results drf_rand_grid_sorted = drf_rand_grid.get_grid(sort_by='auc', decreasing=True) print(drf_rand_grid_sorted) # Extract the best model from random grid search best_drf_model_id = drf_rand_grid_sorted.model_ids[0] best_drf_from_rand_grid = h2o.get_model(best_drf_model_id) best_drf_from_rand_grid.summary()
introduction_to_machine_learning/py_04b_classification_ensembles.ipynb
woobe/h2o_tutorials
mit
<br> Model Stacking
# Define a list of models to be stacked # i.e. best model from each grid all_ids = [best_gbm_model_id, best_drf_model_id] # Set up Stacked Ensemble ensemble = H2OStackedEnsembleEstimator(model_id = "my_ensemble", base_models = all_ids) # use .train to start model stacking # GLM as the default metalearner ensemble.train(x = features, y = 'Survived', training_frame = titanic_train)
introduction_to_machine_learning/py_04b_classification_ensembles.ipynb
woobe/h2o_tutorials
mit
<br> Comparison of Model Performance on Test Data
print('Best GBM model from Grid (AUC) : ', best_gbm_from_rand_grid.model_performance(titanic_test).auc()) print('Best DRF model from Grid (AUC) : ', best_drf_from_rand_grid.model_performance(titanic_test).auc()) print('Stacked Ensembles (AUC) : ', ensemble.model_performance(titanic_test).auc())
introduction_to_machine_learning/py_04b_classification_ensembles.ipynb
woobe/h2o_tutorials
mit
NOTE: You may ignore specific incompatibility errors and warnings. These components and issues do not impact your ability to complete the lab. Download .whl file for tensorflow-transform. We will pass this file to Beam Pipeline Options so it is installed on the DataFlow workers
!pip download tensorflow-transform==0.15.0 --no-deps
notebooks/feature_engineering/solutions/5_tftransform_taxifare.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
<b>Restart the kernel</b> (click on the reload button above).
%%bash pip freeze | grep -e 'flow\|beam' import shutil import tensorflow as tf import tensorflow_transform as tft print(tf.__version__) import os PROJECT = !gcloud config get-value project PROJECT = PROJECT[0] BUCKET = PROJECT REGION = "us-central1" os.environ["PROJECT"] = PROJECT os.environ["BUCKET"] = BUCKET os.environ["REGION"] = REGION %%bash gcloud config set project $PROJECT gcloud config set compute/region $REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb -l ${REGION} gs://${BUCKET} fi
notebooks/feature_engineering/solutions/5_tftransform_taxifare.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Input source: BigQuery Get data from BigQuery but defer the majority of filtering etc. to Beam. Note that the dayofweek column is now strings.
from google.cloud import bigquery def create_query(phase, EVERY_N): """Creates a query with the proper splits. Args: phase: int, 1=train, 2=valid. EVERY_N: int, take an example EVERY_N rows. Returns: Query string with the proper splits. """ base_query = """ WITH daynames AS (SELECT ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'] AS daysofweek) SELECT (tolls_amount + fare_amount) AS fare_amount, daysofweek[ORDINAL(EXTRACT(DAYOFWEEK FROM pickup_datetime))] AS dayofweek, EXTRACT(HOUR FROM pickup_datetime) AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count AS passengers, 'notneeded' AS key FROM `nyc-tlc.yellow.trips`, daynames WHERE trip_distance > 0 AND fare_amount > 0 """ if EVERY_N is None: if phase < 2: # training query = """{} AND ABS(MOD(FARM_FINGERPRINT(CAST (pickup_datetime AS STRING), 4)) < 2""".format( base_query ) else: query = """{} AND ABS(MOD(FARM_FINGERPRINT(CAST( pickup_datetime AS STRING), 4)) = {}""".format( base_query, phase ) else: query = """{} AND ABS(MOD(FARM_FINGERPRINT(CAST( pickup_datetime AS STRING)), {})) = {}""".format( base_query, EVERY_N, phase ) return query query = create_query(2, 100000)
notebooks/feature_engineering/solutions/5_tftransform_taxifare.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Let's pull this query down into a Pandas DataFrame and take a look at some of the statistics.
df_valid = bigquery.Client().query(query).to_dataframe() display(df_valid.head()) df_valid.describe()
notebooks/feature_engineering/solutions/5_tftransform_taxifare.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Create ML dataset using tf.transform and Dataflow Let's use Cloud Dataflow to read in the BigQuery data and write it out as TFRecord files. Along the way, let's use tf.transform to do scaling and transforming. Using tf.transform allows us to save the metadata to ensure that the appropriate transformations get carried out during prediction as well. transformed_data is type pcollection.
import datetime import apache_beam as beam import tensorflow as tf import tensorflow_metadata as tfmd import tensorflow_transform as tft from tensorflow_transform.beam import impl as beam_impl def is_valid(inputs): """Check to make sure the inputs are valid. Args: inputs: dict, dictionary of TableRow data from BigQuery. Returns: True if the inputs are valid and False if they are not. """ try: pickup_longitude = inputs["pickuplon"] dropoff_longitude = inputs["dropofflon"] pickup_latitude = inputs["pickuplat"] dropoff_latitude = inputs["dropofflat"] hourofday = inputs["hourofday"] dayofweek = inputs["dayofweek"] passenger_count = inputs["passengers"] fare_amount = inputs["fare_amount"] return ( fare_amount >= 2.5 and pickup_longitude > -78 and pickup_longitude < -70 and dropoff_longitude > -78 and dropoff_longitude < -70 and pickup_latitude > 37 and pickup_latitude < 45 and dropoff_latitude > 37 and dropoff_latitude < 45 and passenger_count > 0 ) except: return False def preprocess_tft(inputs): """Preproccess the features and add engineered features with tf transform. Args: dict, dictionary of TableRow data from BigQuery. Returns: Dictionary of preprocessed data after scaling and feature engineering. """ import datetime print(inputs) result = {} result["fare_amount"] = tf.identity(inputs["fare_amount"]) # build a vocabulary result["dayofweek"] = tft.string_to_int(inputs["dayofweek"]) result["hourofday"] = tf.identity(inputs["hourofday"]) # pass through # scaling numeric values result["pickuplon"] = tft.scale_to_0_1(inputs["pickuplon"]) result["pickuplat"] = tft.scale_to_0_1(inputs["pickuplat"]) result["dropofflon"] = tft.scale_to_0_1(inputs["dropofflon"]) result["dropofflat"] = tft.scale_to_0_1(inputs["dropofflat"]) result["passengers"] = tf.cast(inputs["passengers"], tf.float32) # a cast # arbitrary TF func result["key"] = tf.as_string(tf.ones_like(inputs["passengers"])) # engineered features latdiff = inputs["pickuplat"] - inputs["dropofflat"] londiff = inputs["pickuplon"] - inputs["dropofflon"] # Scale our engineered features latdiff and londiff between 0 and 1 result["latdiff"] = tft.scale_to_0_1(latdiff) result["londiff"] = tft.scale_to_0_1(londiff) dist = tf.sqrt(latdiff * latdiff + londiff * londiff) result["euclidean"] = tft.scale_to_0_1(dist) return result def preprocess(in_test_mode): """Sets up preprocess pipeline. Args: in_test_mode: bool, False to launch DataFlow job, True to run locally. """ import os import os.path import tempfile from apache_beam.io import tfrecordio from tensorflow_transform.beam import tft_beam_io from tensorflow_transform.beam.tft_beam_io import transform_fn_io from tensorflow_transform.coders import example_proto_coder from tensorflow_transform.tf_metadata import ( dataset_metadata, dataset_schema, ) job_name = "preprocess-taxi-features" + "-" job_name += datetime.datetime.now().strftime("%y%m%d-%H%M%S") if in_test_mode: import shutil print("Launching local job ... hang on") OUTPUT_DIR = "./preproc_tft" shutil.rmtree(OUTPUT_DIR, ignore_errors=True) EVERY_N = 100000 else: print(f"Launching Dataflow job {job_name} ... hang on") OUTPUT_DIR = f"gs://{BUCKET}/taxifare/preproc_tft/" import subprocess subprocess.call(f"gsutil rm -r {OUTPUT_DIR}".split()) EVERY_N = 10000 options = { "staging_location": os.path.join(OUTPUT_DIR, "tmp", "staging"), "temp_location": os.path.join(OUTPUT_DIR, "tmp"), "job_name": job_name, "project": PROJECT, "num_workers": 1, "max_num_workers": 1, "teardown_policy": "TEARDOWN_ALWAYS", "no_save_main_session": True, "direct_num_workers": 1, "extra_packages": ["tensorflow-transform-0.15.0.tar.gz"], } opts = beam.pipeline.PipelineOptions(flags=[], **options) if in_test_mode: RUNNER = "DirectRunner" else: RUNNER = "DataflowRunner" # Set up raw data metadata raw_data_schema = { colname: dataset_schema.ColumnSchema( tf.string, [], dataset_schema.FixedColumnRepresentation() ) for colname in "dayofweek,key".split(",") } raw_data_schema.update( { colname: dataset_schema.ColumnSchema( tf.float32, [], dataset_schema.FixedColumnRepresentation() ) for colname in "fare_amount,pickuplon,pickuplat,dropofflon,dropofflat".split( "," ) } ) raw_data_schema.update( { colname: dataset_schema.ColumnSchema( tf.int64, [], dataset_schema.FixedColumnRepresentation() ) for colname in "hourofday,passengers".split(",") } ) raw_data_metadata = dataset_metadata.DatasetMetadata( dataset_schema.Schema(raw_data_schema) ) # Run Beam with beam.Pipeline(RUNNER, options=opts) as p: with beam_impl.Context(temp_dir=os.path.join(OUTPUT_DIR, "tmp")): # Save the raw data metadata ( raw_data_metadata | "WriteInputMetadata" >> tft_beam_io.WriteMetadata( os.path.join(OUTPUT_DIR, "metadata/rawdata_metadata"), pipeline=p, ) ) # Read training data from bigquery and filter rows raw_data = ( p | "train_read" >> beam.io.Read( beam.io.BigQuerySource( query=create_query(1, EVERY_N), use_standard_sql=True ) ) | "train_filter" >> beam.Filter(is_valid) ) raw_dataset = (raw_data, raw_data_metadata) # Analyze and transform training data ( transformed_dataset, transform_fn, ) = raw_dataset | beam_impl.AnalyzeAndTransformDataset( preprocess_tft ) transformed_data, transformed_metadata = transformed_dataset # Save transformed train data to disk in efficient tfrecord format transformed_data | "WriteTrainData" >> tfrecordio.WriteToTFRecord( os.path.join(OUTPUT_DIR, "train"), file_name_suffix=".gz", coder=example_proto_coder.ExampleProtoCoder( transformed_metadata.schema ), ) # Read eval data from bigquery and filter rows raw_test_data = ( p | "eval_read" >> beam.io.Read( beam.io.BigQuerySource( query=create_query(2, EVERY_N), use_standard_sql=True ) ) | "eval_filter" >> beam.Filter(is_valid) ) raw_test_dataset = (raw_test_data, raw_data_metadata) # Transform eval data transformed_test_dataset = ( raw_test_dataset, transform_fn, ) | beam_impl.TransformDataset() transformed_test_data, _ = transformed_test_dataset # Save transformed train data to disk in efficient tfrecord format ( transformed_test_data | "WriteTestData" >> tfrecordio.WriteToTFRecord( os.path.join(OUTPUT_DIR, "eval"), file_name_suffix=".gz", coder=example_proto_coder.ExampleProtoCoder( transformed_metadata.schema ), ) ) # Save transformation function to disk for use at serving time ( transform_fn | "WriteTransformFn" >> transform_fn_io.WriteTransformFn( os.path.join(OUTPUT_DIR, "metadata") ) ) # Change to True to run locally preprocess(in_test_mode=False)
notebooks/feature_engineering/solutions/5_tftransform_taxifare.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
This will take 10-15 minutes. You cannot go on in this lab until your DataFlow job has succesfully completed.
%%bash # ls preproc_tft gsutil ls gs://${BUCKET}/taxifare/preproc_tft/
notebooks/feature_engineering/solutions/5_tftransform_taxifare.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Train off preprocessed data Now that we have our data ready and verified it is in the correct location we can train our taxifare model locally.
%%bash rm -r ./taxi_trained export PYTHONPATH=${PYTHONPATH}:$PWD python3 -m tft_trainer.task \ --train_data_path="gs://${BUCKET}/taxifare/preproc_tft/train*" \ --eval_data_path="gs://${BUCKET}/taxifare/preproc_tft/eval*" \ --output_dir=./taxi_trained \ !ls $PWD/taxi_trained/export/exporter
notebooks/feature_engineering/solutions/5_tftransform_taxifare.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Now let's create fake data in JSON format and use it to serve a prediction with gcloud ai-platform local predict
%%writefile /tmp/test.json {"dayofweek":0, "hourofday":17, "pickuplon": -73.885262, "pickuplat": 40.773008, "dropofflon": -73.987232, "dropofflat": 40.732403, "passengers": 2.0} %%bash sudo find "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/command_lib/ml_engine" -name '*.pyc' -delete %%bash model_dir=$(ls $PWD/taxi_trained/export/exporter/) gcloud ai-platform local predict \ --model-dir=./taxi_trained/export/exporter/${model_dir} \ --json-instances=/tmp/test.json
notebooks/feature_engineering/solutions/5_tftransform_taxifare.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Remarks The crucial step (<i>cf.</i> <b>Quick Sort</b>) that determines whether we have best case or worst case performance is the choice of the pivot – if we are really lucky we will get a value that cuts down the list the algorithm needs to search very substantially at each step.<br/><br/> The algorithm is divide-and-conquer and each iteration makes the sub-problem substantially smaller. In <b>Quick Sort</b>, both partitions are sorted recursively and provided that the pivot, at each stage, divides the list up into equal parts, we achieve $O(n $log$ n)$ complexity.<br/><br/> However, in the <b>Selection</b> algorithm we know which partition to search, so we only deal with one of them on each recursive call and as a result it is even more efficient. Hence, it can be shown that its complexity is $O(n)$. 4.2 Searching for patterns It often happens that we need to search through a string of characters to find an occurrence (if there is one) of a given pattern, e.g. genetics and DNA searches, keyword searches. Basic string search Algorithm: StringMatch We are representing the sequence to be searched simply as a string of characters, referred to as the search string $S$, a shorter sequence is the target string $T$ and we are trying to find where the first occurrence of $T$ is, if it is present in $S$. Initial Insight Repeatedly shift $T$ one place along $S$ and then compare the characters of $T$ with those of $S$. Do this until a match of $T$ in $S$ is found, or the end of $S$ is reached. Specification <table> <tr> <th>Name:</th> <td><b>StringMatch</b></td> </tr> <tr> <th>Inputs:</th> <td>A search string $S = (s_1, s_2, s_3, ..., s_n)$<br/>A target string $T = (t_1, t_2, t_3, ..., t_m)$</td> </tr> <tr> <th>Outputs:</th> <td>An integer $x$</td> </tr> <tr> <th>Preconditions:</th> <td>$m\le n$, $m>0$ and $n>0$</td> </tr> <tr> <th>Postcondition:</th> <td>If there is an occurrence of $T$ in $S$, $x$ is the start position of the first occurrence of $T$ in $S$; otherwise $x = -1$</td> </tr> </table> Code
def basicStringSearch(searchString, target): searchIndex = 0 lenT = len(target) lenS = len(searchString) while searchIndex + lenT <= lenS: targetIndex = 0 while targetIndex < lenT and target[targetIndex] == searchString[ targetIndex + searchIndex]: targetIndex += 1 if targetIndex == lenT: return searchIndex searchIndex += 1 return -1 # Test Code for target, index in [('per', 0), ('lta', 14), ('ad', 10), ('astra', -1)]: print(basicStringSearch('per ardua ad alta', target)==index)
Notebook/M269 Unit 4 Notes -- Search.ipynb
BoasWhip/Black
mit
Remarks It becomes immediately apparent when implement that this algorithm would consist of two nested loops leading to complexity $O(mn) > O(m^2)$.<br/><br/> We know that if the character in $S$ following the failed comparison with $T$ is not in $T$ then there is no need to slide along one place to do another comparison. We should slide to the next point beyond it. This gives us the basis for an improved algorithm. Quick search Initial Insight For each character in $T$ calculate the number of positions to shift $T$ if a comparison fails, according to where (if at all) that character appears in $T$.<br/><br/> Repeatedly compare the characters of $T$ with those of $S$. If a comparison fails, examine the next character along in $S$ and shift $T$ by the calculated shift distance for that character.<br/><br/> Do this until an occurrence of $T$ in $S$ is found, or the end of $S$ is reached. Remarks An important point to note first of all is that the part of the algorithm calculating the shifts depends entirely on an analysis of the target string $T$ – there is no need to examine the search string $S$ at all because for any character in $S$ that is not in $T$, the shift is a fixed distance.<br/><br/> The database is called a <b>shift table</b> and it stores a <b>shift distance</b> for each character in the domain of $S$ – e.g. for each character of the alphabet, or say, all upper and lower case plus punctuation.<br/><br/> The <b>shift distance</b> is calculated according to the following rules: <ol> <li>If the character does not appear in T, the shift distance is one more than the length of T.</li> <li>If the character does appear in T, the shift distance is the first position at which it appears, counting from right to left and starting at 1. (Hence when a character appears more than once in $T$ keeps the lowest position.)</li> </ol> Suppose $S = $'GGGGGAGGCGGCGGT'. Then for target string $T = $'TCCACC', we have: <table> <tr> <th>G</th> <th>A</th> <th>C</th> <th>T</th> </tr> <tr> <td>7</td> <td>3</td> <td>1</td> <td>6</td> </tr> </table> and if $T = $'TGGCG', we have: <table> <tr> <th>G</th> <th>A</th> <th>C</th> <th>T</th> </tr> <tr> <td>1</td> <td>6</td> <td>2</td> <td>5</td> </tr> </table> <br/> Once the shift table has been computed, the search part of the quick search algorithm is similar to the basic string search algorithm, except that at the end of each failed attempt we look at the next character along in $S$ that is beyond $T$ and use this to look up in the shift table how many steps to slide $T$.<br/> We implement the <b>shift table</b> as a dictionary in Python: Code
def buildShiftTable(target, alphabet): shiftTable = {} for character in alphabet: shiftTable[character] = len(target) + 1 for i in range(len(target)): char = target[i] shift = len(target) - i shiftTable[char] = shift return shiftTable def quickSearch (searchString, target, alphabet): shiftTable = buildShiftTable(target, alphabet) searchIndex = 0 while searchIndex + len(target) <= len(searchString): targetIndex = 0 # Compares the strings while targetIndex < len(target) and target[targetIndex] == searchString[searchIndex + targetIndex]: targetIndex = targetIndex + 1 # Return index if target found if targetIndex == len(target): return searchIndex # Continue search with new shivt value or exit if searchIndex + len(target) < len(searchString): next = searchString[searchIndex + len(target)] shift = shiftTable[next] searchIndex = searchIndex + shift else: return -1 return -1
Notebook/M269 Unit 4 Notes -- Search.ipynb
BoasWhip/Black
mit
Tests
theAlphabet = {'G', 'A', 'C', 'T'} stringToSearch = 'ATGAATACCCACCTTACAGAAACCTGGGAAAAGGCAATAAATATTATAAAAGGTGAACTTACAGAAGTAA' for thetarget in ['ACAG', 'AAGTAA', 'CCCC']: print(quickSearch(stringToSearch, thetarget, theAlphabet))
Notebook/M269 Unit 4 Notes -- Search.ipynb
BoasWhip/Black
mit
Remarks The basic brute-force algorithm we wrote first will work fine with relatively short search strings but, as with all algorithms, inputs of huge size may overwhelm it. For example, DNA strings can be billions of bases long, so algorithmic efficiency can be vital. We noted already that the complexity of the basic string search can be as bad as O(nm) in the worst case.<br/><br/> As for the quick search algorithm, research has shown that its average-case performance is good but, unfortunately, its worst case behaviour is still O(mn).<br/><br/> Knuth–Morris–Pratt (KMP) Better algorithms have been developed. One of the best-known efficient search algorithms is the <b>Knuth–Morris–Pratt (KMP)</b> algorithm. A full description of the precise details of the KMP algorithm is beyond the scope of this text. Algorithm: Knuth–Morris–Pratt (KMP) The <b>KMP</b> algorithm is in two parts: <ol> <li>Build a table of the lengths of prefix matches up to every character in the target string, $T$.</li> <li>Move along the search string, $S$, using the information in the table to do the shifting and compare.</li> </ol> Once the prefix table has been built, the actual search in the second step proceeds like the other string-searching algorithms above, but when a mismatch is detected the algorithm uses the prefix table to decide how to shift $T$. The problem is to know if these prefix matches exist and – if they do – how long the matching substrings are.</br> The prefix will then be aligned as shown in Figure 4.17 and comparison can continue at the next character in S. If you want to take the trouble, you can verify that the final table will be:
prefixTable = [0, 1, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 1, 2]
Notebook/M269 Unit 4 Notes -- Search.ipynb
BoasWhip/Black
mit
Code
# Helper function for kmpSearch() def buildPrefixTable(target): #The first line of code just builds a list that has len(target) #items all of which are given the default value 0 prefixTable = [0] * len(target) q = 0 for p in range(1, len(target)): while q > 0 and target[q] != target[p]: q = prefixTable[q - 1] if target[q] == target[p]: q = q + 1 prefixTable[p] = q return prefixTable def kmpSearch(searchString, target): n = len(searchString) m = len(target) prefixTable = buildPrefixTable(target) q = 0 for i in range(n): while q > 0 and target[q] != searchString[i]: q = prefixTable[q - 1] if target[q] == searchString[i]: q = q + 1 if q == m: return i - m + 1 return -1
Notebook/M269 Unit 4 Notes -- Search.ipynb
BoasWhip/Black
mit
Tests
stringToSearch = 'ATGAATACCCACCTTACAGAAACCTGGGAAAAGGCAATAAATATTATAAAAGGTGAACTTACAGAAGTAA' for thetarget in ['ACAG', 'AAGTAA', 'CCCC']: print(kmpSearch(stringToSearch, thetarget))
Notebook/M269 Unit 4 Notes -- Search.ipynb
BoasWhip/Black
mit
Remarks What about the complexity of the KMP algorithm? Computing the prefix table takes significant effort but in fact there is an efficient algorithm for doing it. Overall, the KMP algorithm has complexity $O(m + n)$. Since $n$ is usually enormously larger than $m$ (think of searching a DNA string of billions of bases), $m$ is usually dominated by $n$, so this means that KMP has effective complexity $O(n)$. Other Algorithms String search is an immensely important application in modern computing, and at least 30 efficient algorithms have been developed for the task. Many of these depend on the principle embodied in the quick search and KMP algorithms – shifting the target string an appropriate distance along the search string at each step, based on information in a table. The <b>Boyer–Moore</b> algorithm, for example, combines elements of both these two algorithms. This algorithm is widely used in practical applications. There are also string-search algorithms that work in entirely different ways from the examples we have looked at. Generally, these are beyond the scope of this text, but some are based on hashing functions, which we now move on to discuss next. 4.3 Hashing and Hash Tables Hashing We have seen how we are able to make improvements in search algorithms by taking advantage of information about where items are stored in the collection with respect to one another. For example, by knowing that a list was ordered, we could search in logarithmic time using a binary search. In this section we will attempt to go one step further by building a data structure that can be searched in $O(1)$ time. This concept is referred to as <b>hashing</b>. In order to do this, we will need to know even more about where the items might be when we go to look for them in the collection. If every item is where it should be, then the search can use a single comparison to discover the presence of an item. A hash table is a collection of items which are stored in such a way as to make it easy to find them later. Each position of the hash table, often called a slot, can hold an item and is named by an integer value starting at 0. Below is a hash table of size $m=11$ implemented in Python as a list with empty slots intialized with a default <b>None</b> value: <img src="http://interactivepython.org/courselib/static/pythonds/_images/hashtable.png"> The mapping between an item and the slot where that item belongs in the hash table is called the <b>hash function</b>. The hash function will take any item in the collection and return an integer in the range of slot names, between $0$ and $m-1$. Our first hash function, sometimes referred to as the <b>remainder method</b>, simply takes an item and divides it by the table size, returning the remainder as its hash value:
set_of_integers = [54, 26, 93, 17, 77, 31] hash_function = lambda x: [y % 11 for y in x] hash_vals = hash_function(set_of_integers) hash_vals
Notebook/M269 Unit 4 Notes -- Search.ipynb
BoasWhip/Black
mit
Once the hash values have been computed, we can insert each item into the hash table at the designated position: <img src="http://interactivepython.org/courselib/static/pythonds/_images/hashtable2.png"> Now when we want to search for an item, we simply use the hash function to compute the slot name for the item and then check the hash table to see if it is present. This searching operation is $O(1)$, since a constant amount of time is required to compute the hash value and then index the hash table at that location. If everything is where it should be, we have found a constant time search algorithm. It immediately becomes apparent that this technique is going to work only if each item maps to a unique location in the hash table. When two or more items would need to be in the same slot. This is referred to as a <b>collision</b> (it may also be called a “clash”). Clearly, collisions create a problem for the hashing technique. We will discuss them in detail later. Hash Functions Given a collection of items, a hash function that maps each item into a unique slot is referred to as a <b>perfect hash function</b>. If we know the items and the collection will never change, then it is possible to construct a perfect hash function (refer to the exercises for more about perfect hash functions). Unfortunately, given an arbitrary collection of items, there is no systematic way to construct a perfect hash function. Luckily, we do not need the hash function to be perfect to still gain performance efficiency. One way to always have a perfect hash function is to increase the size of the hash table so that each possible value in the item range can be accommodated. This guarantees that each item will have a unique slot. Although this is practical for small numbers of items, it is not feasible when the number of possible items is large. For example, if the items were nine-digit Social Security numbers, this method would require almost one billion slots. If we only want to store data for a class of 25 students, we will be wasting an enormous amount of memory. Our goal is to create a hash function that minimizes the number of collisions, is easy to compute, and evenly distributes the items in the hash table. There are a number of common ways to extend the simple remainder method. We will consider a few of them here. The <b>folding method</b> for constructing hash functions begins by dividing the item into equal-size pieces (the last piece may not be of equal size). These pieces are then added together to give the resulting hash value. For example, if our item was the phone number $436-555-4601$, we would take the digits and divide them into groups of $2$ and sum them; that is $43+65+55+46+01=210$. If we assume our hash table has $11$ slots, then we need to perform the extra step of dividing by $11$ and keeping the remainder. In this case $210 % 11210 % 11 = 1$, so the phone number $436-555-4601$ hashes to slot $1$. (Some folding methods go one step further and reverse every other piece before the addition. For the above example, we get $43+56+55+64+01=219$ which gives $219 % 11=10219 % 11=10$.)
word = 4365554601 word = str(word) step = 2 slots = 11 folds = [int(word[n: n+2]) for n in range(0, len(word), step)] print(folds) print(sum(folds)) print(sum(folds)%slots)
Notebook/M269 Unit 4 Notes -- Search.ipynb
BoasWhip/Black
mit
Another numerical technique for constructing a hash function is called the <b>mid-square method</b>. We first square the item, and then extract <i>some portion</i> of the resulting digits. For example, if the item were $44$, we would first compute $44^2=1,936$. By extracting the middle two digits, $93$, and performing the remainder step, we get remainder of $5$ on division by $11$.
set_of_integers = [54, 26, 93, 17, 77, 31] hash_function = lambda x: [int(str(y**2)[1:-1])%11 for y in x] hash_vals = hash_function(set_of_integers) hash_vals
Notebook/M269 Unit 4 Notes -- Search.ipynb
BoasWhip/Black
mit
We can also create hash functions for character-based items such as strings. The word “cat” can be thought of as a sequence of ordinal values. Summing these (unicode values), summing and then taking the remainder from division by $11$:
word = 'cat' sum([ord(l) for l in word]) % 11
Notebook/M269 Unit 4 Notes -- Search.ipynb
BoasWhip/Black
mit
To avoid conflicts from anagram, we could weights:
sum([(ord(word[x]) * (x + 1)) for x in range(len(word))]) % 11
Notebook/M269 Unit 4 Notes -- Search.ipynb
BoasWhip/Black
mit
You may be able to think of a number of additional ways to compute hash values for items in a collection. The important thing to remember is that the hash function has to be efficient so that it does not become the dominant part of the storage and search process. If the hash function is too complex, then it becomes more work to compute the slot name than it would be to simply do a basic sequential or binary search as described earlier. This would quickly defeat the purpose of hashing. Collision Resolution If the hash function is perfect, collisions never occur. However, since this is often not possible. When two items hash to the same slot, we must have a systematic method for placing the second item in the hash table. This process is called <b>collision resolution</b>. One method for resolving collisions looks into the hash table and tries to find another open slot to hold the item that caused the collision. A simple way to do this is to start at the original hash value position and then move in a sequential manner through the slots until we encounter the first slot that is empty. Note that we may need to go back to the first slot (circularly) to cover the entire hash table. This collision resolution process is referred to as <b>open addressing</b> in that it tries to find the next open slot or address in the hash table. By systematically visiting each slot one at a time, we are performing an open addressing technique called <b>linear probing</b>. Using the hash values from the remainder method example, when add $44$ and $55$ say: <img src="http://interactivepython.org/courselib/static/pythonds/_images/clustering.png"> Once we have built a hash table using open addressing and linear probing, it is essential that we utilize the same methods to search for items. we are henced forced to do sequential search to find $44$ and $55$. So, a disadvantage to linear probing is the tendency for <b>clustering</b>; items become clustered in the table. This means that if many collisions occur at the same hash value, a number of surrounding slots will be filled by the linear probing resolution. This will have an impact on other items that are being inserted, as we saw when we tried to add the item 20 above. A cluster of values hashing to 0 had to be skipped to finally find an open position. One way to deal with clustering is to extend the linear probing technique so that instead of looking sequentially for the next open slot, we skip slots, thereby more evenly distributing the items that have caused collisions. This will potentially reduce the clustering that occurs, e.g. with a “plus 3” probe. This means that once a collision occurs, we will look at every third slot until we find one that is empty. The general name for this process of looking for another slot after a collision is <b>rehashing</b>. With simple linear probing, in general, $rehash(pos)=(pos+skip)$%$sizeoftable$. It is important to note that the size of the “skip” must be such that all the slots in the table will eventually be visited. Otherwise, part of the table will be unused. To ensure this, it is often suggested that the table size be a prime number. This is the reason we have been using $11$ in our examples. A variation of the linear probing idea is called <b>quadratic probing</b>. Instead of using a constant “skip” value, we use a rehash function that increments the hash value by 1, 3, 5, 7, 9, and so on. This means that if the first hash value is $h$, the successive values are $h+1$, $h+4$, $h+9$, $h+16$, and so on. In other words, quadratic probing uses a skip consisting of successive <i>perfect squares</i>: <img src="http://interactivepython.org/courselib/static/pythonds/_images/linearprobing2.png"> An alternative method for handling the collision problem is to allow each slot to hold a reference to a collection (or chain) of items. <b>Chaining</b> allows many items to exist at the same location in the hash table. When collisions happen, the item is still placed in the proper slot of the hash table. As more and more items hash to the same location, the difficulty of searching for the item in the collection increases: <img src="http://interactivepython.org/courselib/static/pythonds/_images/chaining.png"> When we want to search for an item, we use the hash function to generate the slot where it should reside. Since each slot holds a collection, we use a searching technique to decide whether the item is present. The advantage is that on the average there are likely to be many fewer items in each slot, so the search is perhaps more efficient.
set_of_integers = [123456, 431941, 789012, 60375] print(set_of_integers) set_of_integers = [((int(str(x)[0:2]) + int(str(x)[2:4]) + int(str(x)[4:])) % 80) -1 for x in set_of_integers] print(set_of_integers)
Notebook/M269 Unit 4 Notes -- Search.ipynb
BoasWhip/Black
mit
Using default legends
from cartoframes.viz import default_legend Map([ Layer('countries', legends=default_legend('Countries')), Layer('global_power_plants', legends=default_legend('Global Power Plants')), Layer('world_rivers', legends=default_legend('World Rivers')) ])
docs/examples/data_visualization/layers/add_multiple_layers.ipynb
CartoDB/cartoframes
bsd-3-clause
Adding a Layer Selector
from cartoframes.viz import default_legend Map([ Layer('countries', title='Countries', legends=default_legend()), Layer('global_power_plants', title='Global Power Plants', legends=default_legend()), Layer('world_rivers', title='World Rivers', legends=default_legend()) ], layer_selector=True)
docs/examples/data_visualization/layers/add_multiple_layers.ipynb
CartoDB/cartoframes
bsd-3-clause