markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
When all of the runs have finished, you can find the best one based on the performance metric you specified (in this case, the one with the best AUC).
best_run = run.get_best_run_by_primary_metric() best_run_metrics = best_run.get_metrics() parameter_values = best_run.get_details() ['runDefinition']['arguments'] print('Best Run Id: ', best_run.id) print(' -AUC:', best_run_metrics['AUC']) print(' -Accuracy:', best_run_metrics['Accuracy']) print(' -Regularization Rate...
_____no_output_____
MIT
examples/AzureML-Primers/04 - Optimizing Model Training.ipynb
kunZooberg/MLOps
Since we've found the best run, we can register the model it trained.
from azureml.core import Model # Register model best_run.register_model(model_path='outputs/diabetes_model.pkl', model_name='diabetes_model', tags={'Training context':'Hyperdrive'}, properties={'AUC': best_run_metrics['AUC'], 'Accuracy': best_run_metrics['Accuracy']}) # List registered models for model in Model.list(...
_____no_output_____
MIT
examples/AzureML-Primers/04 - Optimizing Model Training.ipynb
kunZooberg/MLOps
Task 3: Use *Auto ML* to Find the Best ModelHyperparameter tuning has helped us find the optimal regularization rate for our logistic regression model, but we might get better results by trying a different algorithm, and by performing some basic feature-engineering, such as scaling numeric feature values. You could ju...
# Create a project folder if it doesn't exist automl_folder = "automl_experiment" if not os.path.exists(automl_folder): os.makedirs(automl_folder) print(automl_folder, 'folder created')
_____no_output_____
MIT
examples/AzureML-Primers/04 - Optimizing Model Training.ipynb
kunZooberg/MLOps
You don't need to create a training script (Auto ML will do that for you), but you do need to load the training data; and when using remote compute, this is best achieved by creating a script containing a **get_data** function.
%%writefile $automl_folder/get_data.py #Write the get_data file. from azureml.core import Run, Workspace, Dataset from sklearn.model_selection import train_test_split import pandas as pd import numpy as np def get_data(): # load the diabetes dataset run = Run.get_context() dataset_name = 'Diabetes Dataset...
_____no_output_____
MIT
examples/AzureML-Primers/04 - Optimizing Model Training.ipynb
kunZooberg/MLOps
Now you're ready to confifure the Auto ML experiment. To do this, you'll need a run configuration that includes the required packages for the experiment environment, and a set of configuration settings that tells Auto ML how many options to try, which metric to use when evaluating models, and so on.> **More Information...
from azureml.core.runconfig import RunConfiguration from azureml.core.conda_dependencies import CondaDependencies from azureml.train.automl import AutoMLConfig import time import logging automl_run_config = RunConfiguration(framework="python") automl_run_config.environment.docker.enabled = True auto_ml_dependencies ...
_____no_output_____
MIT
examples/AzureML-Primers/04 - Optimizing Model Training.ipynb
kunZooberg/MLOps
OK, we're ready to go. Let's start the Auto ML run, which will generate child runs for different algorithms.> **Note**: This will take some time. Progress will be displayed as each child run completes, and then a widget showing the results will be displayed.
from azureml.core.experiment import Experiment from azureml.widgets import RunDetails automl_experiment = Experiment(ws, 'diabetes_automl') automl_run = automl_experiment.submit(automl_config, show_output=True) RunDetails(automl_run).show()
_____no_output_____
MIT
examples/AzureML-Primers/04 - Optimizing Model Training.ipynb
kunZooberg/MLOps
View the output of the experiment in the widget, and click the run that produced the best result to see its details.Then click the link to view the experiment details in the Azure portal and view the overall experiment details before viewing the details for the individual run that produced the best result. There's lots...
best_run, fitted_model = automl_run.get_output() print(best_run) print(fitted_model) best_run_metrics = best_run.get_metrics() for metric_name in best_run_metrics: metric = best_run_metrics[metric_name] print(metric_name, metric)
_____no_output_____
MIT
examples/AzureML-Primers/04 - Optimizing Model Training.ipynb
kunZooberg/MLOps
One of the options you used was to include model *explainability*. This uses a test dataset to evaluate the importance of each feature. You can view this data in the notebook widget or the portal, and you can also retrieve it from the run.
from azureml.train.automl.automlexplainer import retrieve_model_explanation shap_values, expected_values, overall_summary, overall_imp, per_class_summary, per_class_imp = retrieve_model_explanation(best_run) # Overall feature importance (the Feature value is the column index in the training data) print("Feature\tImpo...
_____no_output_____
MIT
examples/AzureML-Primers/04 - Optimizing Model Training.ipynb
kunZooberg/MLOps
Finally, having found the best performing model, you can register it.
# Register model best_run.register_model(model_path='outputs/model.pkl', model_name='diabetes_model', tags={'Training context':'Auto ML'}, properties={'AUC': best_run_metrics['AUC_weighted'], 'Accuracy': best_run_metrics['accuracy']}) # List registered models for model in Model.list(ws): print(model.name, 'version...
_____no_output_____
MIT
examples/AzureML-Primers/04 - Optimizing Model Training.ipynb
kunZooberg/MLOps
Hello,> Welcome to Module-5> In this module, we'll discuss about Character Sets.---- > 1. [a-z] or [A-Z]>> [a-z] represent a single character from the set of lowercase alphabets.>> [A-Z] represent a single character from the set of uppercase alphabets.>> They all react similarly to quantifiers as of a single cha...
import re pattern1 = '[a-z]' pattern2 = '[a-z]+' pattern3 = '[A-Z]' pattern4 = '[a-zA-Z]+' string1 = 'India55' #--------------CODE--------------- def findpattern(pattern, text): if re.search(pattern, text): return re.search(pattern, text) else: return 'Not Found!' print(findpattern(pattern1,...
<re.Match object; span=(1, 2), match='n'> <re.Match object; span=(1, 5), match='ndia'> <re.Match object; span=(0, 1), match='I'> <re.Match object; span=(0, 5), match='India'>
MIT
Python/2. Python Basics (cont.)/1. Regular Expressions (REGEX)/0. Start Learning Here/Regex-Course-Modular/5.Regex_Character_Sets.ipynb
okara83/Becoming-a-Data-Scientist
---- > 2. [0-9]>> [0-9] represent a single character from the set of digits.>> They all react similarly to quantifiers as of a single character in regex.
import re pattern1 = '[0-9]' pattern2 = '[0-9]+' string1 = 'India08112021' #--------------CODE--------------- def findpattern(pattern, text): if re.search(pattern, text): return re.search(pattern, text) else: return 'Not Found!' print(findpattern(pattern1, string1)) print(findpattern(patter...
<re.Match object; span=(5, 6), match='0'> <re.Match object; span=(5, 13), match='08112021'>
MIT
Python/2. Python Basics (cont.)/1. Regular Expressions (REGEX)/0. Start Learning Here/Regex-Course-Modular/5.Regex_Character_Sets.ipynb
okara83/Becoming-a-Data-Scientist
Numpy实现浅层神经网络实践部分将搭建神经网络,包含一个隐藏层,实验将会展现出与Logistic回归的不同之处。实验将使用两层神经网络实现对“花”型图案的分类,如图所示,图中的点包含红点(y=0)和蓝点(y=1)还有点的坐标信息,实验将通过以下步骤完成对两种点的分类,使用Numpy实现。- 输入样本;- 搭建神经网络;- 初始化参数;- 训练,包括前向传播与后向传播(即BP算法);- 得出训练后的参数;- 根据训练所得参数,绘制两类点边界曲线。该实验将使用Python原生库实现两层神经网络的搭建,完成分类。 1 - 引用库首先,载入几个需要用到的库,它们分别是:- numpy:一个python的基本库,用于科学计算- plan...
import numpy as np import sklearn from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets import matplotlib.pyplot as plt %matplotlib inline np.random.seed(1)
_____no_output_____
Apache-2.0
jupyter/4.shallow_neural_network/nn_numpy.ipynb
BaiduOSS/PaddleTutorial
2 - 载入数据并观察纬度载入数据后,输出维度
#载入数据 train_x, train_y, test_x, test_y = load_planar_dataset() #输出维度 shape_X = train_x.shape shape_Y = train_y.shape print ('The shape of X is: ' + str(shape_X)) print ('The shape of Y is: ' + str(shape_Y))
The shape of X is: (2, 320) The shape of Y is: (1, 320)
Apache-2.0
jupyter/4.shallow_neural_network/nn_numpy.ipynb
BaiduOSS/PaddleTutorial
由输出可知每组输入坐标包含两个值,包含一个值,共320组数据(测试集在训练集基础上增加80组数据,共400组)。 3 - 简单逻辑回归实验使用逻辑回归处理该数据,观察分类结果
#训练逻辑回归分类器 clf = sklearn.linear_model.LogisticRegressionCV(); clf.fit(train_x.T, train_y.T); #绘制逻辑回归分类边界 plot_decision_boundary(lambda x: clf.predict(x), train_x, train_y) plt.title("Logistic Regression") #输出准确率 LR_predictions = clf.predict(train_x.T) print ('Accuracy of logistic regression:%d ' % float((np.dot(train_...
/Users/starwe/Desktop/WorkDir/anaconda/lib/python3.6/site-packages/sklearn/utils/validation.py:526: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel(). y = column_or_1d(y, warn=True)
Apache-2.0
jupyter/4.shallow_neural_network/nn_numpy.ipynb
BaiduOSS/PaddleTutorial
可以看出逻辑回归效果并不好,这是因为逻辑回归网络结构只包含输入层和输出层,无法拟合更为复杂的模型,下面尝试神经网络模型。 4 - 神经网络模型下面开始搭建神经网络模型,我们采用两层神经网络实验,隐藏层包含4个节点,使用tanh激活函数;输出层包含一个节点,使用Sigmoid激活函数,结果小于0.5即认为是0,否则认为是1。** 神经网络结构 **下面用代码实现神经网络结构,首先确定神经网络的结构,即获取相关数据维度,并设置隐藏层节点个数(本实验设置4个隐藏层节点),用以初始化参数
#定义各层规模函数 def layer_sizes(X, Y): """ 参数含义: X -- 输入的数据 Y -- 输出值 返回值: n_x -- 输入层节点数 n_h -- 隐藏层节点数 n_y -- 输出层节点数 """ n_x = X.shape[0] #输入层大小(节点数) n_h = 4 n_y = Y.shape[0] #输出层大小(节点数) return (n_x, n_h, n_y)
_____no_output_____
Apache-2.0
jupyter/4.shallow_neural_network/nn_numpy.ipynb
BaiduOSS/PaddleTutorial
** 初始化模型参数 **获取相关维度信息后,开始初始化参数,定义相关函数
# 定义函数:初始化参数 def initialize_parameters(n_x, n_h, n_y): """ 参数: n_x -- 输入层大小 n_h -- 隐藏层大小 n_y -- 输出层大小 返回值: params -- 一个包含所有参数的python字典: W1 -- (隐藏层)权重,维度是 (n_h, n_x) b1 -- (隐藏层)偏移量,维度是 (n_h, 1) W2 -- (输出层)权重,维度是 (n_y, n_h) ...
_____no_output_____
Apache-2.0
jupyter/4.shallow_neural_network/nn_numpy.ipynb
BaiduOSS/PaddleTutorial
** 前向传播与后向传播 **获取输入数据,参数初始化完成后,可以开始前向传播的计算
# 定义函数:前向传播 def forward_propagation(X, parameters): """ 参数: X -- 输入值 parameters -- 一个python字典,包含计算所需全部参数(是initialize_parameters函数的输出) 返回值: A2 -- 模型输出值 cache -- 一个字典,包含 "Z1", "A1", "Z2" and "A2" """ W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] ...
_____no_output_____
Apache-2.0
jupyter/4.shallow_neural_network/nn_numpy.ipynb
BaiduOSS/PaddleTutorial
前向传播最后可得出模型输出值(即代码中的A2),即可计算成本函数cost
# 定义函数:成本函数 def compute_cost(A2, Y, parameters): """ 根据第三章给出的公式计算成本 参数: A2 -- 模型输出值 Y -- 真实值 parameters -- 一个python字典包含参数 W1, b1, W2和b2 返回值: cost -- 成本函数 """ m = Y.shape[1] #样本个数 #计算成本 logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), 1 - Y) ...
_____no_output_____
Apache-2.0
jupyter/4.shallow_neural_network/nn_numpy.ipynb
BaiduOSS/PaddleTutorial
计算了成本函数,可以开始后向传播的计算
# 定义函数:后向传播 def backward_propagation(parameters, cache, X, Y): """ 参数: parameters -- 一个python字典,包含所有参数 cache -- 一个python字典包含"Z1", "A1", "Z2"和"A2". X -- 输入值 Y -- 真实值 返回值: grads -- 一个python字典包含所有参数的梯度 """ m = X.shape[1] #首先从"parameters"获取W1,W2 W1 = parameters[...
_____no_output_____
Apache-2.0
jupyter/4.shallow_neural_network/nn_numpy.ipynb
BaiduOSS/PaddleTutorial
通过后向传播获取梯度后,可以根据梯度下降公式更新参数
def update_parameters(parameters, grads, learning_rate = 1.2): """ 使用梯度更新参数 参数: parameters -- 包含所有参数的python字典 grads -- 包含所有参数梯度的python字典 返回值: parameters -- 包含更新后参数的python """ #从"parameters"中读取全部参数 W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W...
_____no_output_____
Apache-2.0
jupyter/4.shallow_neural_network/nn_numpy.ipynb
BaiduOSS/PaddleTutorial
** 神经网络模型 **前向传播、成本函数计算和后向传播构成一个完整的神经网络,将上述函数组合,构建一个神经网络模型
#定义函数:神经网络模型 def nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False): """ 参数: X -- 输入值 Y -- 真实值 n_h -- 隐藏层大小/节点数 num_iterations -- 训练次数 print_cost -- 设置为True,则每1000次训练打印一次成本函数值 返回值: parameters -- 训练结束,更新后的参数值 """ np.random.seed(3) n_x = layer_sizes(X, Y)[0...
_____no_output_____
Apache-2.0
jupyter/4.shallow_neural_network/nn_numpy.ipynb
BaiduOSS/PaddleTutorial
** 预测 ** 通过上述模型可以训练得出最后的参数,此时需检测其准确率,用训练后的参数预测训练的输出,大于0.5的值视作1,否则视作0
#定义函数:预测 def predict(parameters, X): """ 使用训练所得参数,对每个训练样本进行预测 参数: parameters -- 保安所有参数的python字典 X -- 输入值 返回值: predictions -- 模型预测值向量(红色: 0 / 蓝色: 1) """ #使用训练所得参数进行前向传播计算,并将模型输出值转化为预测值(大于0.5视作1,即True) A2, cache = forward_propagation(X, parameters) predictions =...
_____no_output_____
Apache-2.0
jupyter/4.shallow_neural_network/nn_numpy.ipynb
BaiduOSS/PaddleTutorial
下面对获取的数据进行训练,并输出准确率
#建立神经网络模型 parameters = nn_model(train_x, train_y, n_h = 4, num_iterations = 10000, print_cost=True) #绘制分类边界 plot_decision_boundary(lambda x: predict(parameters, x.T), train_x, train_y) plt.title("Decision Boundary for hidden layer size " + str(4)) predictions = predict(parameters, train_x) # 预测训练集 print('Train Accur...
Cost after iteration 0: 0.693049 Cost after iteration 1000: 0.272304 Cost after iteration 2000: 0.261430 Cost after iteration 3000: 0.260627 Cost after iteration 4000: 0.257842 Cost after iteration 5000: 0.255809 Cost after iteration 6000: 0.254249 Cost after iteration 7000: 0.253019 Cost after iteration 8000: 0.252028...
Apache-2.0
jupyter/4.shallow_neural_network/nn_numpy.ipynb
BaiduOSS/PaddleTutorial
What's this TensorFlow business?You've written a lot of code in this assignment to provide a whole host of neural network functionality. Dropout, Batch Norm, and 2D convolutions are some of the workhorses of deep learning in computer vision. You've also worked hard to make your code efficient and vectorized.For the la...
import os import tensorflow as tf import numpy as np import math import timeit import matplotlib.pyplot as plt %matplotlib inline def load_cifar10(num_training=49000, num_validation=1000, num_test=10000): """ Fetch the CIFAR-10 dataset from the web and perform preprocessing to prepare it for the two-layer ...
0 (64, 32, 32, 3) (64,) 1 (64, 32, 32, 3) (64,) 2 (64, 32, 32, 3) (64,) 3 (64, 32, 32, 3) (64,) 4 (64, 32, 32, 3) (64,) 5 (64, 32, 32, 3) (64,) 6 (64, 32, 32, 3) (64,)
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
You can optionally **use GPU by setting the flag to True below**. It's not neccessary to use a GPU for this assignment; if you are working on Google Cloud then we recommend that you do not use a GPU, as it will be significantly more expensive.
# Set up some global variables USE_GPU = False if USE_GPU: device = '/device:GPU:0' else: device = '/cpu:0' # Constant to control how often we print when training models print_every = 100 print('Using device: ', device)
Using device: /cpu:0
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Part II: Barebones TensorFlowTensorFlow ships with various high-level APIs which make it very convenient to define and train neural networks; we will cover some of these constructs in Part III and Part IV of this notebook. In this section we will start by building a model with basic TensorFlow constructs to help you b...
def flatten(x): """ Input: - TensorFlow Tensor of shape (N, D1, ..., DM) Output: - TensorFlow Tensor of shape (N, D1 * ... * DM) """ N = tf.shape(x)[0] return tf.reshape(x, (N, -1)) def test_flatten(): # Construct concrete values of the input data x using numpy x_np = np...
x_np: [[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]]] x_flat_np: tf.Tensor( [[ 0 1 2 3 4 5 6 7 8 9 10 11] [12 13 14 15 16 17 18 19 20 21 22 23]], shape=(2, 12), dtype=int32)
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Barebones TensorFlow: Define a Two-Layer NetworkWe will now implement our first neural network with TensorFlow: a fully-connected ReLU network with two hidden layers and no biases on the CIFAR10 dataset. For now we will use only low-level TensorFlow operators to define the network; later we will see how to use the hig...
def two_layer_fc(x, params): """ A fully-connected neural network; the architecture is: fully-connected layer -> ReLU -> fully connected layer. Note that we only need to define the forward pass here; TensorFlow will take care of computing the gradients for us. The input to the network will ...
(64, 10)
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Barebones TensorFlow: Three-Layer ConvNetHere you will complete the implementation of the function `three_layer_convnet` which will perform the forward pass of a three-layer convolutional network. The network should have the following architecture:1. A convolutional layer (with bias) with `channel_1` filters, each wit...
def three_layer_convnet(x, params): """ A three-layer convolutional network with the architecture described above. Inputs: - x: A TensorFlow Tensor of shape (N, H, W, 3) giving a minibatch of images - params: A list of TensorFlow Tensors giving the weights and biases for the network; shou...
_____no_output_____
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
After defing the forward pass of the three-layer ConvNet above, run the following cell to test your implementation. Like the two-layer network, we run the graph on a batch of zeros just to make sure the function doesn't crash, and produces outputs of the correct shape.When you run this function, `scores_np` should have...
def three_layer_convnet_test(): with tf.device(device): x = tf.zeros((64, 32, 32, 3)) conv_w1 = tf.zeros((5, 5, 3, 6)) conv_b1 = tf.zeros((6,)) conv_w2 = tf.zeros((3, 3, 6, 9)) conv_b2 = tf.zeros((9,)) fc_w = tf.zeros((32 * 32 * 9, 10)) fc_b = tf.zeros((1...
scores_np has shape: (64, 10)
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Barebones TensorFlow: Training StepWe now define the `training_step` function performs a single training step. This will take three basic steps:1. Compute the loss2. Compute the gradient of the loss with respect to all network weights3. Make a weight update step using (stochastic) gradient descent.We need to use a few...
def training_step(model_fn, x, y, params, learning_rate): with tf.GradientTape() as tape: scores = model_fn(x, params) # Forward pass of the model loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=scores) total_loss = tf.reduce_mean(loss) grad_params = tape.gradi...
_____no_output_____
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Barebones TensorFlow: InitializationWe'll use the following utility method to initialize the weight matrices for our models using Kaiming's normalization method.[1] He et al, *Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification*, ICCV 2015, https://arxiv.org/abs/1502.01852
def create_matrix_with_kaiming_normal(shape): if len(shape) == 2: fan_in, fan_out = shape[0], shape[1] elif len(shape) == 4: fan_in, fan_out = np.prod(shape[:3]), shape[3] return tf.keras.backend.random_normal(shape) * np.sqrt(2.0 / fan_in)
_____no_output_____
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Barebones TensorFlow: Train a Two-Layer NetworkWe are finally ready to use all of the pieces defined above to train a two-layer fully-connected network on CIFAR-10.We just need to define a function to initialize the weights of the model, and call `train_part2`.Defining the weights of the network introduces another imp...
def two_layer_fc_init(): """ Initialize the weights of a two-layer network, for use with the two_layer_network function defined above. You can use the `create_matrix_with_kaiming_normal` helper! Inputs: None Returns: A list of: - w1: TensorFlow tf.Variable giving the weights for t...
Iteration 0, loss = 3.0008 Got 130 / 1000 correct (13.00%) Iteration 100, loss = 1.8573 Got 373 / 1000 correct (37.30%) Iteration 200, loss = 1.4276 Got 407 / 1000 correct (40.70%) Iteration 300, loss = 1.9213 Got 370 / 1000 correct (37.00%) Iteration 400, loss = 1.8742 Got 440 / 1000 correct (44.00%) Iteration 500, lo...
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Barebones TensorFlow: Train a three-layer ConvNetWe will now use TensorFlow to train a three-layer ConvNet on CIFAR-10.You need to implement the `three_layer_convnet_init` function. Recall that the architecture of the network is:1. Convolutional layer (with bias) with 32 5x5 filters, with zero-padding 22. ReLU3. Convo...
def three_layer_convnet_init(): """ Initialize the weights of a Three-Layer ConvNet, for use with the three_layer_convnet function defined above. You can use the `create_matrix_with_kaiming_normal` helper! Inputs: None Returns a list containing: - conv_w1: TensorFlow tf.Variable gi...
Iteration 0, loss = 2.9100 Got 99 / 1000 correct (9.90%) Iteration 100, loss = 1.8889 Got 383 / 1000 correct (38.30%) Iteration 200, loss = 1.5494 Got 416 / 1000 correct (41.60%) Iteration 300, loss = 1.6844 Got 405 / 1000 correct (40.50%) Iteration 400, loss = 1.7709 Got 441 / 1000 correct (44.10%) Iteration 500, loss...
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Part III: Keras Model Subclassing APIImplementing a neural network using the low-level TensorFlow API is a good way to understand how TensorFlow works, but it's a little inconvenient - we had to manually keep track of all Tensors holding learnable parameters. This was fine for a small network, but could quickly become...
class TwoLayerFC(tf.keras.Model): def __init__(self, hidden_size, num_classes): super(TwoLayerFC, self).__init__() initializer = tf.initializers.VarianceScaling(scale=2.0) self.fc1 = tf.keras.layers.Dense(hidden_size, activation='relu', kernel_initi...
(64, 10)
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Keras Model Subclassing API: Three-Layer ConvNetNow it's your turn to implement a three-layer ConvNet using the `tf.keras.Model` API. Your model should have the same architecture used in Part II:1. Convolutional layer with 5 x 5 kernels, with zero-padding of 22. ReLU nonlinearity3. Convolutional layer with 3 x 3 kerne...
class ThreeLayerConvNet(tf.keras.Model): def __init__(self, channel_1, channel_2, num_classes): super(ThreeLayerConvNet, self).__init__() ######################################################################## # TODO: Implement the __init__ method for a three-layer ConvNet. You # ...
_____no_output_____
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Once you complete the implementation of the `ThreeLayerConvNet` above you can run the following to ensure that your implementation does not crash and produces outputs of the expected shape.
def test_ThreeLayerConvNet(): channel_1, channel_2, num_classes = 12, 8, 10 model = ThreeLayerConvNet(channel_1, channel_2, num_classes) with tf.device(device): x = tf.zeros((64, 3, 32, 32)) scores = model(x) print(scores.shape) test_ThreeLayerConvNet()
(64, 10)
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Keras Model Subclassing API: Eager TrainingWhile keras models have a builtin training loop (using the `model.fit`), sometimes you need more customization. Here's an example, of a training loop implemented with eager execution.In particular, notice `tf.GradientTape`. Automatic differentiation is used in the backend for...
def train_part34(model_init_fn, optimizer_init_fn, num_epochs=1, is_training=False): """ Simple training loop for use with models defined using tf.keras. It trains a model for one epoch on the CIFAR-10 training set and periodically checks accuracy on the CIFAR-10 validation set. Inputs: - m...
_____no_output_____
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Keras Model Subclassing API: Train a Two-Layer NetworkWe can now use the tools defined above to train a two-layer network on CIFAR-10. We define the `model_init_fn` and `optimizer_init_fn` that construct the model and optimizer respectively when called. Here we want to train the model using stochastic gradient descent...
hidden_size, num_classes = 4000, 10 learning_rate = 1e-2 def model_init_fn(): return TwoLayerFC(hidden_size, num_classes) def optimizer_init_fn(): return tf.keras.optimizers.SGD(learning_rate=learning_rate) train_part34(model_init_fn, optimizer_init_fn)
Iteration 0, Epoch 1, Loss: 3.164823532104492, Accuracy: 7.8125, Val Loss: 2.628608465194702, Val Accuracy: 12.399999618530273 Iteration 100, Epoch 1, Loss: 2.236602544784546, Accuracy: 28.46534538269043, Val Loss: 1.8742749691009521, Val Accuracy: 40.0 Iteration 200, Epoch 1, Loss: 2.0714330673217773, Accuracy: 32.594...
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Keras Model Subclassing API: Train a Three-Layer ConvNetHere you should use the tools we've defined above to train a three-layer ConvNet on CIFAR-10. Your ConvNet should use 32 filters in the first convolutional layer and 16 filters in the second layer.To train the model you should use gradient descent with Nesterov ...
learning_rate = 3e-3 channel_1, channel_2, num_classes = 32, 16, 10 def model_init_fn(): model = None ############################################################################ # TODO: Complete the implementation of model_fn. # ###############################################...
Iteration 0, Epoch 1, Loss: 2.300231456756592, Accuracy: 4.6875, Val Loss: 2.2966694831848145, Val Accuracy: 13.600000381469727 Iteration 100, Epoch 1, Loss: 1.800517201423645, Accuracy: 35.45792007446289, Val Loss: 1.5509482622146606, Val Accuracy: 45.20000076293945 Iteration 200, Epoch 1, Loss: 1.661733865737915, Acc...
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Part IV: Keras Sequential APIIn Part III we introduced the `tf.keras.Model` API, which allows you to define models with any number of learnable layers and with arbitrary connectivity between layers.However for many models you don't need such flexibility - a lot of models can be expressed as a sequential stack of layer...
learning_rate = 1e-2 def model_init_fn(): input_shape = (32, 32, 3) hidden_layer_size, num_classes = 4000, 10 initializer = tf.initializers.VarianceScaling(scale=2.0) layers = [ tf.keras.layers.Flatten(input_shape=input_shape), tf.keras.layers.Dense(hidden_layer_size, activation='relu',...
_____no_output_____
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Abstracting Away the Training LoopIn the previous examples, we used a customised training loop to train models (e.g. `train_part34`). Writing your own training loop is only required if you need more flexibility and control during training your model. Alternately, you can also use built-in APIs like `tf.keras.Model.fi...
model = model_init_fn() model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=learning_rate), loss='sparse_categorical_crossentropy', metrics=[tf.keras.metrics.sparse_categorical_accuracy]) model.fit(X_train, y_train, batch_size=64, epochs=1, validation_data=(X_val, y_val)) model.eva...
_____no_output_____
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Keras Sequential API: Three-Layer ConvNetHere you should use `tf.keras.Sequential` to reimplement the same three-layer ConvNet architecture used in Part II and Part III. As a reminder, your model should have the following architecture:1. Convolutional layer with 32 5x5 kernels, using zero padding of 22. ReLU nonlinear...
def model_init_fn(): model = None ############################################################################ # TODO: Construct a three-layer ConvNet using tf.keras.Sequential. # ############################################################################ # *****START OF YOUR CODE (DO NOT D...
Iteration 0, Epoch 1, Loss: 2.3726930618286133, Accuracy: 14.0625, Val Loss: 2.371110439300537, Val Accuracy: 10.59999942779541 Iteration 100, Epoch 1, Loss: 2.1053175926208496, Accuracy: 24.42759895324707, Val Loss: 1.9350684881210327, Val Accuracy: 33.599998474121094 Iteration 200, Epoch 1, Loss: 1.98719322681427, Ac...
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
We will also train this model with the built-in training loop APIs provided by TensorFlow.
model = model_init_fn() model.compile(optimizer='sgd', loss='sparse_categorical_crossentropy', metrics=[tf.keras.metrics.sparse_categorical_accuracy]) model.fit(X_train, y_train, batch_size=64, epochs=1, validation_data=(X_val, y_val)) model.evaluate(X_test, y_test)
Train on 49000 samples, validate on 1000 samples 49000/49000 [==============================] - 5s 94us/sample - loss: 1.5918 - sparse_categorical_accuracy: 0.4327 - val_loss: 1.3710 - val_sparse_categorical_accuracy: 0.5150 10000/10000 [==============================] - 1s 73us/sample - loss: 1.3944 - sparse_categoric...
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Part IV: Functional API Demonstration with a Two-Layer Network In the previous section, we saw how we can use `tf.keras.Sequential` to stack layers to quickly build simple models. But this comes at the cost of losing flexibility.Often we will have to write complex models that have non-sequential data flows: a layer c...
def two_layer_fc_functional(input_shape, hidden_size, num_classes): initializer = tf.initializers.VarianceScaling(scale=2.0) inputs = tf.keras.Input(shape=input_shape) flattened_inputs = tf.keras.layers.Flatten()(inputs) fc1_output = tf.keras.layers.Dense(hidden_size, activation='relu', ...
(64, 10)
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Keras Functional API: Train a Two-Layer NetworkYou can now train this two-layer network constructed using the functional API.You don't need to perform any hyperparameter tuning here, but you should see validation accuracies above 40% after training for one epoch.
input_shape = (32, 32, 3) hidden_size, num_classes = 4000, 10 learning_rate = 1e-2 def model_init_fn(): return two_layer_fc_functional(input_shape, hidden_size, num_classes) def optimizer_init_fn(): return tf.keras.optimizers.SGD(learning_rate=learning_rate) train_part34(model_init_fn, optimizer_init_fn)
Iteration 0, Epoch 1, Loss: 3.025775909423828, Accuracy: 3.125, Val Loss: 3.0881335735321045, Val Accuracy: 11.90000057220459 Iteration 100, Epoch 1, Loss: 2.242359161376953, Accuracy: 28.418933868408203, Val Loss: 1.8806251287460327, Val Accuracy: 37.400001525878906 Iteration 200, Epoch 1, Loss: 2.085632085800171, Acc...
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Part V: CIFAR-10 open-ended challengeIn this section you can experiment with whatever ConvNet architecture you'd like on CIFAR-10.You should experiment with architectures, hyperparameters, loss functions, regularization, or anything else you can think of to train a model that achieves **at least 70%** accuracy on the ...
class CustomConvNet(tf.keras.Model): def __init__(self): super(CustomConvNet, self).__init__() ############################################################################ # TODO: Construct a model that performs well on CIFAR-10 # ###################################...
Iteration 0, Epoch 1, Loss: 2.3782572746276855, Accuracy: 10.9375, Val Loss: 2.315579414367676, Val Accuracy: 8.699999809265137 Iteration 700, Epoch 1, Loss: 1.4779174327850342, Accuracy: 46.58746337890625, Val Loss: 1.2174204587936401, Val Accuracy: 57.099998474121094 Iteration 1400, Epoch 2, Loss: 1.08061945438385, A...
Unlicense
Assignment_02/TensorFlow.ipynb
andrewlstewart/CS231n-Convolutional-Neural-Networks-
Trump Tweets at the Internet ArchiveSo Trump's Twitter account is gone. At least at twitter.com. But (fortunately for history) there has probably never been a more heavily archived social media account at the Internet Archive and elsewhere on the web. There are also a plethora of online "archives" like [The Trump Arch...
! pip install wayback
Requirement already satisfied: wayback in /home/ed/.local/share/virtualenvs/notebooks-7Xlq9Gbm/lib/python3.8/site-packages (0.2.5) Requirement already satisfied: requests in /home/ed/.local/share/virtualenvs/notebooks-7Xlq9Gbm/lib/python3.8/site-packages (from wayback) (2.24.0) Requirement already satisfied: urllib3 ...
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
The search() method handles paging through the API results using a resumption token behind the scenes. Lets look at the first 100 results just to see what they look like.
from wayback import WaybackClient wb = WaybackClient() count = 0 for result in wb.search('twitter.com/realDonaldTrump/status/', matchType='prefix'): print(result.url) count += 1 if count > 100: break
https://twitter.com/real…061992042975232
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
So there are some weird URLs in there, that look like the result of buggy automated archive processes that aren't constructing URLs properly?* https://twitter.com/realDonaldTrump/status/%22/SyakibPutera/status/636601131339087872%22* https://twitter.com/realDonaldTrump/status/'+twitter_id+And then we can see lots of res...
import re seen = set() for result in wb.search('twitter.com/realDonaldTrump/status/', matchType='prefix'): if re.search(r'/realDonaldTrump/status/\d+', result.url): if result.url not in seen: print(result.url) seen.add(result.url) if len(seen) > 100: bre...
https://twitter.com/realDonaldTrump/status/0?s=19 https://twitter.com/realDonaldTrump/status/0n/7 http://twitter.com/realDonaldTrump/status/1000061992042975232 https://twitter.com/realDonaldTrump/status/1000061992042975232 https://www.twitter.com/realDonaldTrump/status/1000061992042975232 https://twitter.com/realDonald...
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
This list shows that some tweet URLs can have query strings, which modify the presentation of the tweet in various ways. For example to change the language of the user interface:* https://twitter.com/realDonaldTrump/status/1000114139136606209?lang=en-gbOr to highlight certain information:* https://twitter.com/realDonal...
from urllib.parse import urlparse seen = set() for result in wb.search('twitter.com/realDonaldTrump/status/', matchType='prefix'): uri = urlparse(result.url) m = re.match(r'^/realDonaldTrump/status/(\d+)/?$', uri.path, re.IGNORECASE) if not m: continue tweet_id = m.group(1) i...
https://twitter.com/realDonaldTrump/status/0?s=19 http://twitter.com/realDonaldTrump/status/1000061992042975232 http://twitter.com/realDonaldTrump/status/1000064605903876096 http://twitter.com/realDonaldTrump/status/1000114139136606209 http://twitter.com/realDonaldTrump/status/1000138164923781121 http://twitter.com/rea...
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
It looks like this is actually working pretty good. For completeness we can store a mapping of the tweet id to all the results for that tweet id. This will allow us to track how many tweet have been archiving, while letting us examing how many times that tweet was archived, and what their precise URLs are for playback....
from collections import defaultdict tweets = defaultdict(list) for result in wb.search('twitter.com/realDonaldTrump/status/', matchType='prefix'): uri = urlparse(result.url) m = re.match(r'^/realDonaldTrump/status/(\d{8,})/?$', uri.path, re.IGNORECASE) if not m: continue tweet_i...
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Now we can see the tweet ids. Instead of printing them all out we can just look at the first 100:
list(tweets.keys())[0:100]
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
And we can look at when a given tweet was archived too, irrespective of the various query strings that can be part of it. Here we get all the snapshots for tweet id 1002298565299965953 and print out the times that it was archived, in descending order.
for result in sorted(tweets['1002298565299965953'], key=lambda r: r.timestamp, reverse=True): print(result.timestamp) len(tweets['1002298565299965953'])
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
So this particular URL was archived 252 times! The snapshots start on May 31, 2018 and most of the snapshots are from a few days of that. But there are also a handful of snapshots in 2019 and 2020. Examining [one of the snapshots] shows that it was sent on May 31st at 2:19 PM. It's hard to tell what time zone the displ...
for result in sorted(tweets['1002298565299965953'], key=lambda r: r.timestamp, reverse=True): print(result.url)
https://twitter.com/realDonaldTrump/status/1002298565299965953 https://twitter.com/realdonaldtrump/status/1002298565299965953 https://twitter.com/realDonaldTrump/status/1002298565299965953 https://twitter.com/realDonaldTrump/status/1002298565299965953 https://www.twitter.com/realDonaldTrump/status/1002298565299965953 h...
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
What was the most archived tweet?
sorted(tweets, key=lambda r: len(tweets[r]), reverse=True)[0] len(tweets['1006837823469735936'])
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
So https://twitter.com/realDonaldTrump/status/1006837823469735936 was archived 23,419 times?! It's interesting that the [overview page](https://web.archive.org/web/*/twitter.com/realDonaldTrump/status/1006837823469735936) only says 595 times, because it is looking at that exact URL. Looking at [the content](https://web...
len(tweets)
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
That is *a lot* less than what we should have found. So either there is a problem with my code, or the wayback module isn't paging results properly, or the CDX API isn't functioning properly, or not all of Trumps tweets have been archived?In conversation with [Rob Brackett](https://robbrackett.com/) who is the principa...
import pathlib data = pathlib.Path("data") db_path = data / "trump-tweets.sqlite3" import sqlite3 # only generate the sqlite db if it's not already there if not db_path.is_file(): db = sqlite3.connect(db_path) db.execute( ''' CREATE TABLE tweets ( tweet_id TEXT, u...
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Unfortunately GitHub won't let you upload the 3GB sqlite file--even with git-lfs enabled.
db = sqlite3.connect("data/trump-tweets.sqlite3") db.execute('SELECT COUNT(DISTINCT(tweet_id)) FROM tweets').fetchall()
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
So 65,314 tweets were found. That's quite a bit more than the 59k suggested by the Twitter display and the 56,571 by the Trump Archive. Let's limit to snapshots that had a 200 OK HTTP response. As we saw above it's possible people tried to archive bogus tweet URLs.
db.execute( ''' SELECT COUNT(DISTINCT(tweet_id)) FROM tweets WHERE status_code = 200 ''').fetchall()
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
That seems a lot more like it. So what were the most archived tweet? Let's get the top 10.
cursor = db.execute( ''' SELECT tweet_id, COUNT(*) AS total FROM tweets WHERE status_code = 200 GROUP by tweet_id ORDER BY total DESC LIMIT 10 ''' ) for row in cursor.fetchall(): print(row)
('704834185471598592', 65486) ('704756216157839360', 65353) ('704818842153971712', 65350) ('796315640307060738', 55391) ('796182637622816768', 54854) ('796055597594578944', 54258) ('795733366842806272', 54243) ('796099494442057728', 54230) ('796126077647196160', 54180) ('794259252613414915', 54088)
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
So the most archived URL was archived 56,571 times: https://web.archive.org/web/20200521045242/https://twitter.com/realDonaldTrump/status/704834185471598592The interface indicates it was archived 1,616 times, but remember we factored in alternate forms of the tweet URL. Lets see what those were.
cursor = db.execute( ''' SELECT url, COUNT(*) as total FROM tweets WHERE tweet_id = "704834185471598592" AND status_code = 200 GROUP BY url ORDER BY total DESC ''' ) for row in cursor.fetchall(): print(row)
('https://twitter.com/realDonaldTrump/status/704834185471598592', 1612) ('https://twitter.com/realdonaldtrump/status/704834185471598592?lang=zh-tw', 1359) ('https://twitter.com/realdonaldtrump/status/704834185471598592?lang=vi', 1359) ('https://twitter.com/realdonaldtrump/status/704834185471598592?lang=ur', 1359) ('htt...
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Now that is kind of fascinating. Why would there be 1,349 captures of each of those language specific URLs for this tweet? This seems like some kind of automation? Missing from Trump Archive?So what tweets were found in the Internet Archive that are not in the Trump Archive. To figure this out we can first load in the...
import pandas df = pandas.read_csv('https://drive.google.com/uc?export=download&id=1xRKHaP-QwACMydlDnyFPEaFdtskJuBa6' ) trump_archive = set([str(tweet_id) for tweet_id in df['id']]) len(trump_archive)
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Now we need the tweet ids from our sqlite db. Tweets will return a 200 OK and retweets will 301 Moved Permanently to the original tweet so we will include both here.
cursor = db.execute( ''' SELECT DISTINCT(tweet_id) FROM tweets WHERE status_code in (200, 301) ''' ) wayback = set([r[0] for r in cursor.fetchall()]) len(wayback)
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Now we can see what tweet ids are in the Wayback Machine but not in the Trump Archive.
len(wayback - trump_archive)
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Wow. so 3592 tweets are in the Wayback Machine but not in the Trump Archive?! Let's spot check one of them to see if this is the case. Lets generate the Wayback URLs for the first 25 of these ids. https://web.archive.org/web/{datetime}/{url}
ids = list(wayback - trump_archive)[0:25] cursor = db.execute( ''' SELECT "https://web.archive.org/web/" || STRFTIME('%Y%m%d%H%M%S', timestamp) || "/" || url FROM tweets WHERE tweet_id IN ({}) '''.format(",".join(["?"] * 25)), ids ) for row in cursor.fetchall(): ...
https://web.archive.org/web/20201108045542/https://twitter.com/realDonaldTrump/status/1080839175392321541 https://web.archive.org/web/20200706132436/http://twitter.com/realDonaldTrump/status/1280130505829224448 https://web.archive.org/web/20200706132436/https://twitter.com/realDonaldTrump/status/1280130505829224448 htt...
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
The first 5 of these seem to generate a *Something Went Wrong Page*. Perhaps there were tweets there and the Wayback Machine failed fetch them properly? Or maybe the data is there but failing to play back? It's hard to say with confidence.https://web.archive.org/web/20201108045542/https://twitter.com/realDonaldTrump/st...
import csv out = csv.writer(open('data/trump-tweets-missing-from-archive.csv', 'w')) out.writerow(['tweet_url', 'archive_url']) for tweet_id in wayback - trump_archive: sql = """ SELECT url, STRFTIME('%Y%m%d%H%M%S', timestamp) AS timestamp FROM tweets WHERE tweet_i...
https://twitter.com/realDonaldTrump/status/918240536984801280 https://twitter.com/realDonaldTrump/status/315107115054276608 https://twitter.com/realDonaldTrump/status/455802609589583872 https://twitter.com/realDonaldTrump/status/303870510951981056 https://twitter.com/realdonaldtrump/status/1198672518833430534 https://t...
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Missing from Internet Archive?How about the other angle: are there any tweet ids in the Trump Archive that didn't come back from the CDX API?
len(trump_archive - wayback)
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
It appears yes?
trump_archive - wayback
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Lets examing the first one: 1175115230457802752. Is it in the Trump Archive?https://www.thetrumparchive.com/tweets/1175115230457802752Yes. It looks like a retweet of @FLOTUS: RT @FLOTUS: Welcome to the @WhiteHouse PM Morrison and Mrs. Morrison! 🇺🇸🇦🇺 https://t.co/kYznIkJf9HBut the redirect of the retweet is not i...
import requests for tweet_id in trump_archive - wayback: url = "https://www.thetrumparchive.com/tweets/{}".format(tweet_id) resp = requests.get(url) if resp.status_code == 200: tweet = resp.json() if tweet['isRetweet'] == False: print("id: {}\ndate: {}\n{}\n".format( ...
id: 1237490722317746178 date: 2020-03-10T21:29:14.000Z deleted: True If you like automobils, how can you vote for a Democrat who all want to get rid of cars, as quickly as possible, especially if they are powered by gasoline. Remember also, no more than one car per family. I, on the other hand, have new plants being bu...
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
We can verify by looking in our database for a tweet id like 1281926278845812736:
db.execute('SELECT * FROM tweets WHERE tweet_id = ?', ["1281926278845812736"]).fetchall()
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Sure enough, it looks like Internet Archive wasn't quite quick enough to pick this one up. It's hard to say when the tweet was deleted, but it was archived on 2020-11-15 which was well after when it was sent on 2020-07-11. But this is truly remarkable that the Wayback Machine only seems to be missing three original twe...
sql = \ ''' SELECT STRFTIME('%Y%m%d', timestamp) AS day, COUNT(*) AS "snapshots" FROM tweets GROUP BY day ORDER BY day ASC ''' df = pandas.read_sql_query(sql, db, parse_dates=['day']) df.head()
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Lets fill in the blanks for days where there was no archiving of Trump's tweets.
dates = pandas.date_range(min(df.day), max(df.day)) df = df.set_index('day').reindex(dates).fillna(0) df.head()
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Now we can try a plot!
df.plot( kind='line', title="Archiving Trump's Tweets at the Internet Archive", figsize=(10, 4), legend=False, xlabel='Time', ylabel='Snapshots per Day' )
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Kinda noisy. Maybe it will look better as tweets-per-week?
df = df.resample('W').sum().rename_axis('time') df.plot( kind='line', title="Archiving Trump's Tweets at the Internet Archive", figsize=(10, 4), legend=False, xlabel='Time', ylabel='Snapshots per Week' )
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Trump Archive URLsTo help media organizations update their links to point at snapshots at the Internet Archive I thought it could be useful to create a CSV dataset of the tweet ids and links. It's important to limit to known good tweets (within a particular range) and ones that returned a 200 OK. The latest snapshot w...
import requests_html http = requests_html.AsyncHTMLSession() async def response_ok(url, tries=10): global http try: resp = await http.get(url) await resp.html.arender(timeout=60) match = resp.html.search("Something went wrong") if match: return False return ...
checking https://web.archive.org/web/20201112035441/https://twitter.com/realdonaldtrump/status/1698308935?s=21 checking https://web.archive.org/web/20201112032934/https://twitter.com/realdonaldtrump/status/1698308935 checking https://web.archive.org/web/20201112032721/https://twitter.com/realdonaldtrump/status/16983089...
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Top 10What were the top 10 most archived tweets?
import sqlite3 import pandas db = sqlite3.connect('data/trump-tweets.sqlite3') df = pandas.read_csv('data/trump-archive.csv') def get_text(tweet_id): v = df[df['id'] == tweet_id].text.values if len(v) != 0: return v[0] else: return "???" get_text(1698308935) sql = ''' SELECT tweet_id, ...
* [Thank you Alabama! #Trump2016#SuperTuesday](https://web.archive.org/web/*/https://twitter.com/realDonaldTrump/status/704834185471598592) 65489 * [MAKE AMERICA GREAT AGAIN!](https://web.archive.org/web/*/https://twitter.com/realDonaldTrump/status/704756216157839360) 65360 * [Thank you Georgia!#SuperTuesday #Trump2016...
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
PolitwoopsJust as a last exercise its interesting to see which tweets in Politwoops for Trump are in (or not in the Internet Archive). We saw one of them above when we were analyzing The Trump Twitter Archive.First we need all the politwoops ids. We can use Politwoops API:
import requests politwoops = set() page = 1 while True: url = "https://projects.propublica.org/politwoops/user/realDonaldTrump" data = requests.get(url, params={"format": "json", "page": page}).json() if not data or len(data["tweets"]) == 0: break for tweet in data["tweets"]: politwoop...
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
So it looks like there are 179 tweets in Politwoops that are missing from Wayback Machine? Lets take a look at the URLs to spot check a few.
for tweet_id in wayback_missing: politwoops_url = "https://projects.propublica.org/politwoops/tweet/{}".format(tweet_id) wayback_url = "https://web.archive.org/web/*/http://twitter.com/realDonaldTrump/status/{}".format(tweet_id) print(politwoops_url) print(wayback_url) print()
https://projects.propublica.org/politwoops/tweet/1228437662094196743 https://web.archive.org/web/*/http://twitter.com/realDonaldTrump/status/1228437662094196743 https://projects.propublica.org/politwoops/tweet/1193376950481489921 https://web.archive.org/web/*/http://twitter.com/realDonaldTrump/status/11933769504814899...
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Looking at some of these it becomes clear that politwoops are lumping together realDonaldTrump and POTUS. But we didn't collect Wayback data for POTUS. We can collect the Politwoops data again but filter out the POTUS data.
politwoops = set() page = 1 while True: url = "https://projects.propublica.org/politwoops/user/realDonaldTrump" data = requests.get(url, params={"format": "json", "page": page}).json() if not data or len(data["tweets"]) == 0: break for tweet in data["tweets"]: # make sure the user is re...
_____no_output_____
CC-BY-4.0
Trump Tweets at Internet Archive.ipynb
edsu/notebooks
Stock Sentiment Analysis using News Headlines
import pandas as pd df=pd.read_csv('Data.csv', encoding = "ISO-8859-1") df.head() train = df[df['Date'] < '20150101'] test = df[df['Date'] > '20141231'] # Removing punctuations data=train.iloc[:,2:27] data.replace("[^a-zA-Z]"," ",regex=True, inplace=True) # Renaming column names for ease of access list1= [i for i in r...
_____no_output_____
Apache-2.0
Stock Sentiment Analysis.ipynb
FGpramodgupta/Stock-News-Sentiment-Analysis
Profiling sequential code I profiled the sequential code `count_spacers_with_ED.py` using the `cProfile` Python package. I ran `count_spacers_with_ED.py` with a control file of 100 sequences (*Genome-Pos-3T3-Unsorted_100_seqs.txt*) and an experimental file of 100 sequences (*Genome-Pos-3T3-Bot10_100_seqs.txt*). Each o...
import pstats p = pstats.Stats('100_seq_stats.profile'); #read in profiling stats p.strip_dirs(); #remove the extraneous path from all the module names #sort according to time spent within each function, and then print the statistics for the top 20 functions. p.sort_stats('time').print_stats(20)
Mon Apr 29 16:08:45 2019 100_seq_stats.profile 350132307 function calls (350126604 primitive calls) in 537.388 seconds Ordered by: internal time List reduced from 1999 to 20 due to restriction <20> ncalls tottime percall cumtime percall filename:lineno(function) 3981650 462.315 0.000 ...
MIT
sequential_pipeline/profiling_sequential_code.ipynb
rohuba/PACS
Bayesian Optimization with Scikit-OptimizeIn this notebook, we will perform **Bayesian Optimization** with Gaussian Processes in Parallel, utilizing various CPUs, to speed up the search.This is useful to reduce search times. https://scikit-optimize.github.io/stable/auto_examples/parallel-optimization.htmlexample
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_breast_cancer from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import cross_val_score, train_test_split from skopt import Optimizer # for the optimization from joblib import Par...
_____no_output_____
BSD-3-Clause
Section-10-Scikit-Optimize/06-Parallelization.ipynb
ankitario/hyperparameter-optimization
Define the Hyperparameter SpaceScikit-optimize provides an utility function to create the range of values to examine for each hyperparameters. More details in [skopt.Space](https://scikit-optimize.github.io/stable/modules/generated/skopt.Space.html)
# determine the hyperparameter space param_grid = [ Integer(10, 120, name="n_estimators"), Integer(1, 5, name="max_depth"), Real(0.0001, 0.1, prior='log-uniform', name='learning_rate'), Real(0.001, 0.999, prior='log-uniform', name="min_samples_split"), Categorical(['deviance', 'exponential'], name=...
_____no_output_____
BSD-3-Clause
Section-10-Scikit-Optimize/06-Parallelization.ipynb
ankitario/hyperparameter-optimization
Define the model
# set up the gradient boosting classifier gbm = GradientBoostingClassifier(random_state=0)
_____no_output_____
BSD-3-Clause
Section-10-Scikit-Optimize/06-Parallelization.ipynb
ankitario/hyperparameter-optimization
Define the objective functionThis is the hyperparameter response space, the function we want to minimize.
# We design a function to maximize the accuracy, of a GBM, # with cross-validation # the decorator allows our objective function to receive the parameters as # keyword arguments. This is a requirement for scikit-optimize. @use_named_args(param_grid) def objective(**params): # model with new parameters gb...
_____no_output_____
BSD-3-Clause
Section-10-Scikit-Optimize/06-Parallelization.ipynb
ankitario/hyperparameter-optimization
Optimization with Gaussian Process
# We use the Optimizer optimizer = Optimizer( dimensions = param_grid, # the hyperparameter space base_estimator = "GP", # the surrogate n_initial_points=10, # the number of points to evaluate f(x) to start of acq_func='EI', # the acquisition function random_state=0, n_jobs=4, ) # we will use ...
_____no_output_____
BSD-3-Clause
Section-10-Scikit-Optimize/06-Parallelization.ipynb
ankitario/hyperparameter-optimization
Evaluate convergence of the search
tmp['accuracy'].sort_values(ascending=False).reset_index(drop=True).plot()
_____no_output_____
BSD-3-Clause
Section-10-Scikit-Optimize/06-Parallelization.ipynb
ankitario/hyperparameter-optimization
The trade-off with parallelization, is that we will not optimize the search after each evaluation of f(x), instead after, in this case 4, evaluations of f(x). Thus, we may need to perform more evaluations to find the optima. But, because we do it in parallel, overall, we reduce wall time.
tmp.sort_values(by='accuracy', ascending=True)
_____no_output_____
BSD-3-Clause
Section-10-Scikit-Optimize/06-Parallelization.ipynb
ankitario/hyperparameter-optimization
**Problem 1**Yiyang wants to understand the following question: If he randomly chooses three points on the perimeter of a circle, what is the probability that the triangle made of three points contains the center?(1) Write a pseudocode to estimate the probability.(2) Write a python code and implement it.(3) Give me y...
_____no_output_____
MIT
src/Problem_1.ipynb
JiaminJIAN/20MA573
(2) Write a python code and implement it.
import numpy as np from scipy import stats from scipy.stats import bernoulli def circle(N): p = 0 for i in range(N): x = np.zeros(3) y = np.zeros(3) for j in range(3): x[j] = np.random.uniform(low=-1, high=1) y[j] = np.sqrt(1 - x[j]**2) * (2 * bernoulli.rvs(0.5) - 1) a = (x[0]-x[1])**2 ...
_____no_output_____
MIT
src/Problem_1.ipynb
JiaminJIAN/20MA573
Control FlowGenerally, a program is executed sequentially and once executed it is not repeated again. There may be a situation when you need to execute a piece of code n number of times, or maybe even execute certain piece of code based on a particular condition.. this is where the control flow statements come in.In t...
result = 1 if result == 1: print("Best Match") elif result <= 3: print("Close Enough") else: print("This is Blasphemy!")
Best Match
MIT
notebooks/01-05 Control Flow.ipynb
Mohitsharma44/ucsl17
The logic is very simple.. *`if`* , *`then`* do something; *`else`* do something else. Python adopts the `if`-`else` clause as it is used in many languages.. However the `elif` part is unique to python. `elif` simply is a contraction for `else if`. Loop StatementsThese statements are used when we want to execute a pie...
for i in [0,1,2]: print("{}".format(i))
0 1 2
MIT
notebooks/01-05 Control Flow.ipynb
Mohitsharma44/ucsl17
In `for` loop, we specify the variable we want to use, the `iterator` we want to loop over, and use the `in` (membership) operator to link them together.
i = 2 while i >= 0: print("{}".format(i)) i -= 1
2 1 0
MIT
notebooks/01-05 Control Flow.ipynb
Mohitsharma44/ucsl17
As you can see, they both serve different purposes. For loop is used when you want to run something for fixed amount of times, whereas while loop can theoretically run forever (if you use something like `while True:` .. *dont!* ). One of the most commonly used `iterator` with for loop is the `range` object which is use...
list(range(10))
_____no_output_____
MIT
notebooks/01-05 Control Flow.ipynb
Mohitsharma44/ucsl17
The `range` requires the *stop* argument. It can also accept *start* (at first position) and *step* (at third position) as arguments but if not passed, it creates a sequence of numbers from `0` till `stop - 1`. Remember, the *stop* is not included in the output
# With start and stop list(range(2, 20)) # With start, stop and step list(range(2, 20, 2))
_____no_output_____
MIT
notebooks/01-05 Control Flow.ipynb
Mohitsharma44/ucsl17
When you have an iterator of iterators .. for example a list of lists .. then you can use what is known as nested loops to flatten the list.
# This is not the best way.. but for the sake of completion of # topic, this example is included. arr = [range(3), range(3, 6)] for lists in arr: for elem in lists: print(elem)
0 1 2 3 4 5
MIT
notebooks/01-05 Control Flow.ipynb
Mohitsharma44/ucsl17
Loop Control StatementsLoop control statements change the executing of loop from its normal sequence. Break It terminates the current loop and resumes the execution at the next statement. The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement ...
for i in range(1, 10): if i == 5: print('Condition satisfied') break print(i) # What would happen if this is placed before if condition?
1 2 3 4 Condition satisfied
MIT
notebooks/01-05 Control Flow.ipynb
Mohitsharma44/ucsl17
ContinueContinue statement returns the control to the beginning of the loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.
for i in range(1, 10): if i == 5: print('Condition satisfied') continue print("whatever.. I won't get printed anyways.") print(i)
1 2 3 4 Condition satisfied 6 7 8 9
MIT
notebooks/01-05 Control Flow.ipynb
Mohitsharma44/ucsl17
PassPass is used when a statement is required syntactically but performs a null operation i.e. nothing happens when the statement is executed.
for i in range(1, 10): if i == 5: print('Condition satisfied') pass print(i)
1 2 3 4 Condition satisfied 5 6 7 8 9
MIT
notebooks/01-05 Control Flow.ipynb
Mohitsharma44/ucsl17
As you can see execution of pass statement had no effect on the flow of the code. It wouldn't have mattered if it was not there. It is generally used as a temporary placeholder for an unimplemented logic. For example lets say you have written a function (we'll learn about functions a little later) and want to test the ...
best = 11 for i in range(10): if i >= best: print("Excellent") break else: continue else: print("Couldn't find the best match")
Couldn't find the best match
MIT
notebooks/01-05 Control Flow.ipynb
Mohitsharma44/ucsl17