hexsha
stringlengths 40
40
| size
int64 6
14.9M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 6
260
| max_stars_repo_name
stringlengths 6
119
| max_stars_repo_head_hexsha
stringlengths 40
41
| max_stars_repo_licenses
list | max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 6
260
| max_issues_repo_name
stringlengths 6
119
| max_issues_repo_head_hexsha
stringlengths 40
41
| max_issues_repo_licenses
list | max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 6
260
| max_forks_repo_name
stringlengths 6
119
| max_forks_repo_head_hexsha
stringlengths 40
41
| max_forks_repo_licenses
list | max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2
1.04M
| max_line_length
int64 2
11.2M
| alphanum_fraction
float64 0
1
| cells
list | cell_types
list | cell_type_groups
list |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4aa6751e4aeb48dda2b1d1236aeea87cbcc55832
| 98,834 |
ipynb
|
Jupyter Notebook
|
Course2-Customising_your_models_with_Tensorflow_2/week4_subclassing_custom_training.ipynb
|
mella30/Probabilistic-Deep-Learning-with-TensorFlow-2
|
e9748316547d7f433632f4735990306d6e15da72
|
[
"MIT"
] | null | null | null |
Course2-Customising_your_models_with_Tensorflow_2/week4_subclassing_custom_training.ipynb
|
mella30/Probabilistic-Deep-Learning-with-TensorFlow-2
|
e9748316547d7f433632f4735990306d6e15da72
|
[
"MIT"
] | null | null | null |
Course2-Customising_your_models_with_Tensorflow_2/week4_subclassing_custom_training.ipynb
|
mella30/Probabilistic-Deep-Learning-with-TensorFlow-2
|
e9748316547d7f433632f4735990306d6e15da72
|
[
"MIT"
] | null | null | null | 58.550948 | 28,290 | 0.688468 |
[
[
[
"<a href=\"https://colab.research.google.com/github/mella30/Deep-Learning-with-Tensorflow-2/blob/main/Course2-Customising_your_models_with_Tensorflow_2/week4_subclassing_custom_training.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nprint(tf.__version__)",
"2.5.0\n"
]
],
[
[
"# Model subclassing and custom training loops",
"_____no_output_____"
],
[
" ## Coding tutorials\n #### [1. Model subclassing](#coding_tutorial_1)\n #### [2. Custom layers](#coding_tutorial_2)\n #### [3. Automatic differentiation](#coding_tutorial_3)\n #### [4. Custom training loops](#coding_tutorial_4)\n #### [5. tf.function decorator](#coding_tutorial_5)",
"_____no_output_____"
],
[
"***\n<a id=\"coding_tutorial_1\"></a>\n## Model subclassing",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, Dropout, Softmax, concatenate",
"_____no_output_____"
]
],
[
[
"#### Create a simple model using the model subclassing API",
"_____no_output_____"
]
],
[
[
"# Build the model\n# One branch has only the dense one layer, the other has the dense two, a dense three layers sequentially.\n# Then the outputs of both branches can be concatenated by just writing concatenate. \n\nclass MyModel(Model):\n\n def __init__(self):\n super(MyModel, self).__init__()\n\n self.dense_1 = Dense(64, activation='relu')\n self.dense_2 = Dense(10)\n self.dense_3 = Dense(5)\n self.softmax = Softmax()\n\n def call(self, inputs, training=True):\n x = self.dense_1(inputs)\n y1 = self.dense_2(inputs)\n y2 = self.dense_3(y1)\n concat = concatenate([x,y2])\n return self.softmax(concat)",
"_____no_output_____"
],
[
"# Print the model summary\n\nmodel = MyModel()\nmodel(tf.random.uniform([1,10]))\nmodel.summary()",
"Model: \"my_model\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense (Dense) multiple 704 \n_________________________________________________________________\ndense_1 (Dense) multiple 110 \n_________________________________________________________________\ndense_2 (Dense) multiple 55 \n_________________________________________________________________\nsoftmax (Softmax) multiple 0 \n=================================================================\nTotal params: 869\nTrainable params: 869\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"***\n<a id=\"coding_tutorial_2\"></a>\n## Custom layers",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Layer, Softmax",
"_____no_output_____"
]
],
[
[
"#### Create custom layers",
"_____no_output_____"
]
],
[
[
"# Create a custom layer\n\nclass MyLayer(Layer):\n\n def __init__(self, units, input_dim):\n super(MyLayer, self).__init__()\n self.w = self.add_weight(shape=(input_dim, units),\n initializer='random_normal')\n self.b = self.add_weight(shape=(units,),\n initializer='zeros')\n \n def call(self, inputs):\n return tf.matmul(inputs, self.w)+self.b\n\ndense_layer = MyLayer(3,5)\nx = tf.ones((1,5))\nprint(dense_layer(x))\nprint(dense_layer.weights)",
"tf.Tensor([[-0.03462956 0.27807447 -0.0415416 ]], shape=(1, 3), dtype=float32)\n[<tf.Variable 'Variable:0' shape=(5, 3) dtype=float32, numpy=\narray([[ 0.05272692, 0.07202636, 0.07036196],\n [-0.01977646, 0.14034642, 0.03701119],\n [-0.04026626, -0.04271299, -0.1432971 ],\n [-0.07335179, 0.08981531, -0.00660157],\n [ 0.04603803, 0.01859936, 0.00098393]], dtype=float32)>, <tf.Variable 'Variable:0' shape=(3,) dtype=float32, numpy=array([0., 0., 0.], dtype=float32)>]\n"
],
[
"# Specify trainable weights (to freeze parts of the layers weights) \n\nclass MyLayerNontrainable(Layer):\n\n def __init__(self, units, input_dim):\n super(MyLayerNontrainable, self).__init__()\n self.w = self.add_weight(shape=(input_dim, units),\n initializer='random_normal',\n trainable=False)\n self.b = self.add_weight(shape=(units,),\n initializer='zeros',\n trainable=False)\n \n def call(self, inputs):\n return tf.matmul(inputs, self.w)+self.b\n\ndense_layer_nontrainable = MyLayerNontrainable(3,5)",
"_____no_output_____"
],
[
"print('trainable weights:', len(dense_layer_nontrainable.trainable_weights))\nprint('non-trainable weights:', len(dense_layer_nontrainable.non_trainable_weights))",
"trainable weights: 0\nnon-trainable weights: 2\n"
],
[
"# Create a custom layer to accumulate means of output values\n# \n\nclass MyLayerMean(Layer):\n\n def __init__(self, units, input_dim):\n super(MyLayerMean, self).__init__()\n self.w = self.add_weight(shape=(input_dim, units),\n initializer='random_normal')\n self.b = self.add_weight(shape=(units,),\n initializer='zeros')\n # accumulate means of output values everytime it is called\n self.sum_activation = tf.Variable(initial_value=tf.zeros((units,)),\n trainable=False)\n # counts the number of times the layer has been called\n self.number_call = tf.Variable(initial_value=0,\n trainable=False)\n \n def call(self, inputs):\n # activation of the outputs\n activations = tf.matmul(inputs, self.w)+self.b\n # update values (sum and number of calls, will keep their values across calls) \n self.sum_activation.assign_add(tf.reduce_sum(activations, axis=0))\n self.number_call.assign_add(inputs.shape[0])\n return activations, self.sum_activation / tf.cast(self.number_call, tf.float32)\n\ndense_layer_mean = MyLayerMean(3,5)",
"_____no_output_____"
],
[
"# Test the layer\n\ny, activation_means = dense_layer_mean(tf.ones((1, 5)))\nprint(activation_means.numpy())\n\n# nothing changes because weights and bias are not updated\ny, activation_means = dense_layer_mean(tf.ones((1, 5)))\nprint(activation_means.numpy())\n# Accumulating the mean or variance of the activations can be really useful e.g. for analyzing the propagation of signals in the network. ",
"[0.05410447 0.08467079 0.06959186]\n[0.05410447 0.08467079 0.06959186]\n"
],
[
"# Create a Dropout layer as a custom layer\n\nclass MyDropout(Layer):\n\n def __init__(self, rate):\n super(MyDropout, self).__init__()\n self.rate = rate\n \n def call(self, inputs):\n # Define forward pass for dropout layer\n return tf.nn.dropout(inputs, rate=self.rate)",
"_____no_output_____"
]
],
[
[
"#### Implement the custom layers into a model",
"_____no_output_____"
]
],
[
[
"# Build the model using custom layers with the model subclassing API\n\nclass MyModel(Model):\n\n def __init__(self, units_1, input_dim_1, units_2, units_3):\n super(MyModel, self).__init__()\n # Define layers\n self.layer_1 = MyLayer(units_1, input_dim_1)\n self.dropout_1 = MyDropout(0.5)\n self.layer_2 = MyLayer(units_2, units_1)\n self.dropout_2 = MyDropout(0.5)\n self.layer_3 = MyLayer(units_3, units_2)\n self.softmax = Softmax()\n \n def call(self, inputs):\n # Define forward pass\n x = self.layer_1(inputs)\n x = tf.nn.relu(x) # call activations here, otherwise the layers will be linear\n x = self.dropout_1(x)\n x = self.layer_2(x)\n x = tf.nn.relu(x)\n x = self.dropout_2(x)\n x = self.layer_3(x)\n\n return self.softmax(x)",
"_____no_output_____"
],
[
"# Instantiate a model object\n\nmodel = MyModel(64,10000,64,46)\nprint(model(tf.ones((1, 10000))))\nmodel.summary()",
"tf.Tensor(\n[[0.05454328 0.03436927 0.01711915 0.00422174 0.01680824 0.01881411\n 0.00889291 0.02258453 0.00444886 0.00678244 0.00503646 0.01405701\n 0.01003517 0.00785683 0.008182 0.01316038 0.02942613 0.07519828\n 0.013987 0.00851373 0.03548283 0.00565946 0.00386675 0.01540067\n 0.00643616 0.00304706 0.00739376 0.00267 0.01084765 0.04675708\n 0.00984404 0.02394733 0.00348202 0.0373905 0.00611185 0.00754119\n 0.07485764 0.0198659 0.02637891 0.02605296 0.06726679 0.00403698\n 0.02178637 0.01637157 0.09099672 0.05247034]], shape=(1, 46), dtype=float32)\nModel: \"my_model\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nmy_layer_1 (MyLayer) multiple 640064 \n_________________________________________________________________\nmy_dropout (MyDropout) multiple 0 \n_________________________________________________________________\nmy_layer_2 (MyLayer) multiple 4160 \n_________________________________________________________________\nmy_dropout_1 (MyDropout) multiple 0 \n_________________________________________________________________\nmy_layer_3 (MyLayer) multiple 2990 \n_________________________________________________________________\nsoftmax (Softmax) multiple 0 \n=================================================================\nTotal params: 647,214\nTrainable params: 647,214\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"***\n<a id=\"coding_tutorial_3\"></a>\n## Automatic differentiation",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"#### Create synthetic data",
"_____no_output_____"
]
],
[
[
"# Create data from a noise contaminated linear model\n\ndef MakeNoisyData(m, b, n=20):\n x = tf.random.uniform(shape=(n,))\n noise = tf.random.normal(shape=(len(x),), stddev=0.1)\n y = m * x + b + noise\n return x, y\n\nm=1\nb=2\nx_train, y_train = MakeNoisyData(m,b)\nplt.plot(x_train, y_train, 'b.')",
"_____no_output_____"
]
],
[
[
"#### Define a linear regression model",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.layers import Layer",
"_____no_output_____"
],
[
"# Build a custom layer for the linear regression model\n\nclass LinearLayer(Layer):\n\n def __init__(self):\n super(LinearLayer, self).__init__()\n self.m = self.add_weight(shape=(1,),\n initializer='random_normal')\n self.b = self.add_weight(shape=(1,),\n initializer='zeros')\n \n def call(self, inputs):\n return self.m*inputs+self.b\n\nlinear_regression = LinearLayer()\n\nprint(linear_regression(x_train))\nprint(linear_regression.weights)",
"tf.Tensor(\n[0.06933199 0.023721 0.07912418 0.03079096 0.04425802 0.01021458\n 0.04513784 0.0005613 0.06225901 0.06271388 0.00839703 0.03471534\n 0.02714759 0.06329098 0.08046802 0.05948634 0.03361373 0.01292873\n 0.05710317 0.05492993], shape=(20,), dtype=float32)\n[<tf.Variable 'Variable:0' shape=(1,) dtype=float32, numpy=array([0.08147576], dtype=float32)>, <tf.Variable 'Variable:0' shape=(1,) dtype=float32, numpy=array([0.], dtype=float32)>]\n"
]
],
[
[
"#### Define the loss function",
"_____no_output_____"
]
],
[
[
"# Define the mean squared error loss function\n\ndef SquaredError(y_pred, y_true):\n return tf.reduce_mean(tf.square(y_pred - y_true)) \n\nstarting_loss = SquaredError(linear_regression(x_train), y_train)\nprint(\"Starting loss\", starting_loss.numpy())",
"Starting loss 6.1552916\n"
]
],
[
[
"#### Train and plot the model",
"_____no_output_____"
]
],
[
[
"# Implement a gradient descent training loop for the linear regression model\n\nlearning_rate = 0.05\nsteps = 25\n\nfor i in range(steps):\n with tf.GradientTape() as tape:\n predictions = linear_regression(x_train)\n loss = SquaredError(predictions, y_train)\n\n gradients = tape.gradient(loss, linear_regression.trainable_variables)\n\n linear_regression.m.assign_sub(learning_rate * gradients[0])\n linear_regression.b.assign_sub(learning_rate * gradients[0])\n\n print(\"Step %d, Loss %f\" % (i, loss.numpy()))",
"Step 0, Loss 6.155292\nStep 1, Loss 5.140264\nStep 2, Loss 4.295762\nStep 3, Loss 3.592967\nStep 4, Loss 3.007949\nStep 5, Loss 2.520832\nStep 6, Loss 2.115104\nStep 7, Loss 1.777052\nStep 8, Loss 1.495284\nStep 9, Loss 1.260334\nStep 10, Loss 1.064337\nStep 11, Loss 0.900758\nStep 12, Loss 0.764163\nStep 13, Loss 0.650038\nStep 14, Loss 0.554628\nStep 15, Loss 0.474813\nStep 16, Loss 0.407995\nStep 17, Loss 0.352016\nStep 18, Loss 0.305078\nStep 19, Loss 0.265688\nStep 20, Loss 0.232598\nStep 21, Loss 0.204775\nStep 22, Loss 0.181353\nStep 23, Loss 0.161614\nStep 24, Loss 0.144958\n"
],
[
"# Plot the learned regression model\n\nprint(\"m:{}, trained m:{}\".format(m,linear_regression.m.numpy()))\nprint(\"b:{}, trained b:{}\".format(b,linear_regression.b.numpy()))\n\nplt.plot(x_train, y_train, 'b.')\n\nx_linear_regression=np.linspace(min(x_train), max(x_train),50)\nplt.plot(x_linear_regression, linear_regression.m*x_linear_regression+linear_regression.b, 'r.')",
"m:1, trained m:[1.4811265]\nb:2, trained b:[1.3996508]\n"
]
],
[
[
"***\n<a id=\"coding_tutorial_4\"></a>\n## Custom training loops",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport time",
"_____no_output_____"
]
],
[
[
"#### Build the model",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Layer, Softmax",
"_____no_output_____"
],
[
"# Define the custom layers and model\n\nclass MyLayer(Layer):\n\n def __init__(self, units):\n super(MyLayer, self).__init__()\n self.units = units # number of layer units (weights)\n\n # add build method to the MyLayer class to avoid setting the input shape until the layer is called (flexible shapes)\n # name the layer parts for simplify usage\n def build(self, input_shape):\n # layer weights\n self.w = self.add_weight(shape=(input_shape[-1], self.units),\n initializer='random_normal',\n name='kernel')\n # layer bias\n self.b = self.add_weight(shape=(self.units,),\n initializer='zeros',\n name='bias')\n \n def call(self, inputs):\n return tf.matmul(inputs, self.w)+self.b\n\nclass MyDropout(Layer):\n\n def __init__(self, rate):\n super(MyDropout, self).__init__()\n self.rate = rate\n \n def call(self, inputs):\n # Define forward pass for dropout layer\n return tf.nn.dropout(inputs, rate=self.rate)\n\nclass MyModel(Model):\n\n def __init__(self, units_1, units_2, units_3):\n super(MyModel, self).__init__()\n # Define layers\n self.layer_1 = MyLayer(units_1)\n self.dropout_1 = MyDropout(0.5)\n self.layer_2 = MyLayer(units_2)\n self.dropout_2 = MyDropout(0.5)\n self.layer_3 = MyLayer(units_3)\n self.softmax = Softmax()\n \n def call(self, inputs):\n # Define forward pass\n x = self.layer_1(inputs)\n x = tf.nn.relu(x) # call activations here, otherwise the layers will be linear\n x = self.dropout_1(x)\n x = self.layer_2(x)\n x = tf.nn.relu(x)\n x = self.dropout_2(x)\n x = self.layer_3(x)\n\n return self.softmax(x)",
"_____no_output_____"
],
[
"# Instantiate a model object\n\nmodel = MyModel(64,64,46)\nprint(model(tf.ones((1, 10000))))\nmodel.summary() # is the exact same as above",
"tf.Tensor(\n[[0.02469273 0.02422069 0.02116902 0.03153074 0.04185418 0.02650914\n 0.02331334 0.01793654 0.01791891 0.01802885 0.02326367 0.02021981\n 0.01426613 0.02719969 0.0274377 0.01693712 0.01283608 0.01822274\n 0.02904254 0.02264908 0.02145478 0.0146747 0.01371288 0.02708716\n 0.02050998 0.02386188 0.01340397 0.0286968 0.02174951 0.02303861\n 0.01563685 0.02124431 0.02675487 0.0135526 0.03268624 0.0201091\n 0.02344291 0.02400806 0.01627981 0.01386968 0.02272227 0.0246389\n 0.0211106 0.02249501 0.01746694 0.01654291]], shape=(1, 46), dtype=float32)\nModel: \"my_model_6\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nmy_layer_16 (MyLayer) multiple 640064 \n_________________________________________________________________\nmy_dropout_10 (MyDropout) multiple 0 \n_________________________________________________________________\nmy_layer_17 (MyLayer) multiple 4160 \n_________________________________________________________________\nmy_dropout_11 (MyDropout) multiple 0 \n_________________________________________________________________\nmy_layer_18 (MyLayer) multiple 2990 \n_________________________________________________________________\nsoftmax_5 (Softmax) multiple 0 \n=================================================================\nTotal params: 647,214\nTrainable params: 647,214\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"#### Load the reuters dataset and define the class_names ",
"_____no_output_____"
]
],
[
[
"# Load the dataset\n\nfrom tensorflow.keras.datasets import reuters\n\n(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)\n\nclass_names = ['cocoa','grain','veg-oil','earn','acq','wheat','copper','housing','money-supply',\n 'coffee','sugar','trade','reserves','ship','cotton','carcass','crude','nat-gas',\n 'cpi','money-fx','interest','gnp','meal-feed','alum','oilseed','gold','tin',\n 'strategic-metal','livestock','retail','ipi','iron-steel','rubber','heat','jobs',\n 'lei','bop','zinc','orange','pet-chem','dlr','gas','silver','wpi','hog','lead']",
"/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/datasets/reuters.py:143: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray\n x_train, y_train = np.array(xs[:idx]), np.array(labels[:idx])\n/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/datasets/reuters.py:144: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray\n x_test, y_test = np.array(xs[idx:]), np.array(labels[idx:])\n"
],
[
"# Print the class of the first sample\n\nprint(\"Label: {}\".format(class_names[train_labels[0]]))",
"Label: earn\n"
]
],
[
[
"#### Get the dataset word index",
"_____no_output_____"
]
],
[
[
"# Load the Reuters word index\n\nword_to_index = reuters.get_word_index()\n\ninvert_word_index = dict([(value, key) for (key, value) in word_to_index.items()])\ntext_news = ' '.join([invert_word_index.get(i - 3, '?') for i in train_data[0]])",
"_____no_output_____"
],
[
"# Print the first data example sentence\n\nprint(text_news)",
"? ? ? said as a result of its december acquisition of space co it expects earnings per share in 1987 of 1 15 to 1 30 dlrs per share up from 70 cts in 1986 the company said pretax net should rise to nine to 10 mln dlrs from six mln dlrs in 1986 and rental operation revenues to 19 to 22 mln dlrs from 12 5 mln dlrs it said cash flow per share this year should be 2 50 to three dlrs reuter 3\n"
]
],
[
[
"#### Preprocess the data",
"_____no_output_____"
]
],
[
[
"# Define a function that encodes the data into a 'bag of words' representation\n\ndef bag_of_words(text_samples, elements=10000):\n output = np.zeros((len(text_samples), elements))\n for i, word in enumerate(text_samples):\n output[i, word] = 1.\n return output\n\nx_train = bag_of_words(train_data)\nx_test = bag_of_words(test_data)\n\nprint(\"Shape of x_train:\", x_train.shape)\nprint(\"Shape of x_test:\", x_test.shape)",
"Shape of x_train: (8982, 10000)\nShape of x_test: (2246, 10000)\n"
]
],
[
[
"#### Define the loss function and optimizer\n\n",
"_____no_output_____"
]
],
[
[
"# Define the categorical cross entropy loss and Adam optimizer\n\nloss_object = tf.keras.losses.SparseCategoricalCrossentropy()\n\ndef loss(model, x, y, wd):\n kernel_variables = []\n for l in model.layers:\n for w in l.weights:\n if 'kernel' in w.name:\n kernel_variables.append(w)\n # weight decay penalty as regulizer\n wd_penalty = wd * tf.reduce_sum([tf.reduce_sum(tf.square(k)) for k in kernel_variables])\n y_ = model(x)\n return loss_object(y_true=y, y_pred=y_) + wd_penalty\n\noptimizer = tf.keras.optimizers.Adam(learning_rate=0.001)",
"_____no_output_____"
]
],
[
[
"#### Train the model",
"_____no_output_____"
]
],
[
[
"# Define a function to compute the forward and backward pass\n\ndef grad(model, inputs, targets, wd):\n with tf.GradientTape() as tape:\n loss_value = loss(model, inputs, targets, wd)\n return loss_value, tape.gradient(loss_value, model.trainable_variables)",
"_____no_output_____"
],
[
"# Implement the training loop\n\nfrom tensorflow.keras.utils import to_categorical\n\nstart_time = time.time()\n\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, train_labels))\ntrain_dataset = train_dataset.batch(32)\n\n# keep results for plotting\ntrain_loss_results = []\ntrain_accuracy_results = []\n\nnum_epochs = 10\nweight_decay = 0.005\n\nfor epoch in range(num_epochs):\n epoch_avg_loss = tf.keras.metrics.Mean()\n epoch_accuracy = tf.keras.metrics.CategoricalAccuracy()\n\n # training loop\n for x, y in train_dataset:\n # optimize model\n loss_value, grads = grad(model, x, y, weight_decay)\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\n # compute current loss\n epoch_avg_loss(loss_value)\n epoch_accuracy(to_categorical(y), model(x))\n\n # end epoch\n train_loss_results.append(epoch_avg_loss.result())\n train_accuracy_results.append(epoch_accuracy.result())\n print(\"Epoch {:03d}: Loss: {:.3f}, Accuracy: {:.3%}\".format(epoch, epoch_avg_loss.result(), epoch_accuracy.result()))\n \nprint(\"Duration :{:.3f}\".format(time.time() - start_time))",
"Epoch 000: Loss: 3.318, Accuracy: 47.996%\nEpoch 001: Loss: 1.934, Accuracy: 59.575%\nEpoch 002: Loss: 1.839, Accuracy: 65.153%\nEpoch 003: Loss: 1.792, Accuracy: 68.203%\nEpoch 004: Loss: 1.756, Accuracy: 69.016%\nEpoch 005: Loss: 1.749, Accuracy: 69.773%\nEpoch 006: Loss: 1.724, Accuracy: 70.252%\nEpoch 007: Loss: 1.716, Accuracy: 70.296%\nEpoch 008: Loss: 1.700, Accuracy: 70.842%\nEpoch 009: Loss: 1.705, Accuracy: 70.875%\nDuration :94.792\n"
]
],
[
[
"#### Evaluate the model",
"_____no_output_____"
]
],
[
[
"# Create a Dataset object for the test set\n\ntest_dataset = tf.data.Dataset.from_tensor_slices((x_test, test_labels))\ntest_dataset = test_dataset.batch(32)",
"_____no_output_____"
],
[
"# Collect average loss and accuracy\n\nepoch_loss_avg = tf.keras.metrics.Mean()\nepoch_accuracy = tf.keras.metrics.CategoricalAccuracy()",
"_____no_output_____"
],
[
"# Loop over the test set and print scores\n\nfrom tensorflow.keras.utils import to_categorical\n\nfor x, y in test_dataset:\n # Optimize the model\n loss_value = loss(model, x, y, weight_decay) \n # Compute current loss\n epoch_loss_avg(loss_value) \n # Compare predicted label to actual label\n epoch_accuracy(to_categorical(y), model(x))\n\nprint(\"Test loss: {:.3f}\".format(epoch_loss_avg.result().numpy()))\nprint(\"Test accuracy: {:.3%}\".format(epoch_accuracy.result().numpy()))",
"Test loss: 1.840\nTest accuracy: 67.720%\n"
]
],
[
[
"#### Plot the learning curves",
"_____no_output_____"
]
],
[
[
"# Plot the training loss and accuracy\n\nfig, axes = plt.subplots(2, sharex=True, figsize=(12, 8))\nfig.suptitle('Training Metrics')\n\naxes[0].set_ylabel(\"Loss\", fontsize=14)\naxes[0].plot(train_loss_results)\n\naxes[1].set_ylabel(\"Accuracy\", fontsize=14)\naxes[1].set_xlabel(\"Epoch\", fontsize=14)\naxes[1].plot(train_accuracy_results)\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### Predict from the model",
"_____no_output_____"
]
],
[
[
"# Get the model prediction for an example input\n\npredicted_label = np.argmax(model(x_train[np.newaxis,0]),axis=1)[0]\nprint(\"Prediction: {}\".format(class_names[predicted_label]))\nprint(\" Label: {}\".format(class_names[train_labels[0]]))",
"Prediction: earn\n Label: earn\n"
]
],
[
[
"***\n<a id=\"coding_tutorial_5\"></a>\n## tf.function decorator",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Layer, Softmax\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.datasets import reuters\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time",
"_____no_output_____"
]
],
[
[
"#### Build the model",
"_____no_output_____"
]
],
[
[
"# Initialize a new model\n\nmodel = MyModel(64,64,46)\nprint(model(tf.ones((1, 10000))))\nmodel.summary() # is the exact same as above",
"tf.Tensor(\n[[0.0157793 0.01995642 0.01371924 0.00754535 0.02380487 0.02748704\n 0.06976582 0.00746593 0.00269733 0.00413884 0.00738348 0.00837831\n 0.00287195 0.01909052 0.01206377 0.02009192 0.01970806 0.00673163\n 0.00998205 0.02283304 0.05091274 0.01791169 0.00705515 0.02257455\n 0.00492392 0.01206135 0.11640094 0.00563481 0.03504296 0.00844257\n 0.01600087 0.00273831 0.00950017 0.02514022 0.0172752 0.02607905\n 0.01926632 0.09308005 0.04465098 0.01275241 0.00660244 0.0181314\n 0.0119268 0.08133545 0.00903711 0.00402766]], shape=(1, 46), dtype=float32)\nModel: \"my_model_7\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nmy_layer_19 (MyLayer) multiple 640064 \n_________________________________________________________________\nmy_dropout_12 (MyDropout) multiple 0 \n_________________________________________________________________\nmy_layer_20 (MyLayer) multiple 4160 \n_________________________________________________________________\nmy_dropout_13 (MyDropout) multiple 0 \n_________________________________________________________________\nmy_layer_21 (MyLayer) multiple 2990 \n_________________________________________________________________\nsoftmax_6 (Softmax) multiple 0 \n=================================================================\nTotal params: 647,214\nTrainable params: 647,214\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"#### Redefine the grad function using the @tf.function decorator",
"_____no_output_____"
]
],
[
[
"# Use the @tf.function decorator\n\[email protected]\ndef grad(model, inputs, targets, wd):\n with tf.GradientTape() as tape:\n loss_value = loss(model, inputs, targets, wd)\n return loss_value, tape.gradient(loss_value, model.trainable_variables)",
"_____no_output_____"
]
],
[
[
"#### Train the model",
"_____no_output_____"
]
],
[
[
"# Re-run the training loop\n\nfrom tensorflow.keras.utils import to_categorical\n\nstart_time = time.time()\n\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, train_labels))\ntrain_dataset = train_dataset.batch(32)\n\n# keep results for plotting\ntrain_loss_results = []\ntrain_accuracy_results = []\n\nnum_epochs = 10\nweight_decay = 0.005\n\nfor epoch in range(num_epochs):\n epoch_avg_loss = tf.keras.metrics.Mean()\n epoch_accuracy = tf.keras.metrics.CategoricalAccuracy()\n\n # training loop\n for x, y in train_dataset:\n # optimize model\n loss_value, grads = grad(model, x, y, weight_decay)\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\n # compute current loss\n epoch_avg_loss(loss_value)\n epoch_accuracy(to_categorical(y), model(x))\n\n # end epoch\n train_loss_results.append(epoch_avg_loss.result())\n train_accuracy_results.append(epoch_accuracy.result())\n print(\"Epoch {:03d}: Loss: {:.3f}, Accuracy: {:.3%}\".format(epoch, epoch_avg_loss.result(), epoch_accuracy.result()))\n \nprint(\"Duration :{:.3f}\".format(time.time() - start_time))",
"Epoch 000: Loss: 2.436, Accuracy: 57.059%\nEpoch 001: Loss: 1.915, Accuracy: 65.264%\nEpoch 002: Loss: 1.843, Accuracy: 67.624%\nEpoch 003: Loss: 1.782, Accuracy: 68.314%\nEpoch 004: Loss: 1.775, Accuracy: 68.904%\nEpoch 005: Loss: 1.747, Accuracy: 69.183%\nEpoch 006: Loss: 1.722, Accuracy: 70.018%\nEpoch 007: Loss: 1.721, Accuracy: 70.341%\nEpoch 008: Loss: 1.707, Accuracy: 70.040%\nEpoch 009: Loss: 1.712, Accuracy: 70.430%\nDuration :79.994\n"
]
],
[
[
"#### Print the autograph code",
"_____no_output_____"
]
],
[
[
"# Use tf.autograph.to_code to see the generated code\n\nprint(tf.autograph.to_code(grad.python_function))",
"def tf__grad(model, inputs, targets, wd):\n with ag__.FunctionScope('grad', 'fscope', ag__.ConversionOptions(recursive=True, user_requested=True, optional_features=(), internal_convert_user_code=True)) as fscope:\n do_return = False\n retval_ = ag__.UndefinedReturnValue()\n with ag__.ld(tf).GradientTape() as tape:\n loss_value = ag__.converted_call(ag__.ld(loss), (ag__.ld(model), ag__.ld(inputs), ag__.ld(targets), ag__.ld(wd)), None, fscope)\n try:\n do_return = True\n retval_ = (ag__.ld(loss_value), ag__.converted_call(ag__.ld(tape).gradient, (ag__.ld(loss_value), ag__.ld(model).trainable_variables), None, fscope))\n except:\n do_return = False\n raise\n return fscope.ret(retval_, do_return)\n\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aa67cf19d0d7ce2213c5188b10798c320066a11
| 186,829 |
ipynb
|
Jupyter Notebook
|
Code/Lab/UN_demography.ipynb
|
ljsun88/data_bootcamp_nyu
|
abc2486060672e19f5e4a71342cb8ca05155db83
|
[
"MIT"
] | 74 |
2015-01-14T22:51:39.000Z
|
2021-01-31T17:23:58.000Z
|
Code/Lab/UN_demography.ipynb
|
ljsun88/data_bootcamp_nyu
|
abc2486060672e19f5e4a71342cb8ca05155db83
|
[
"MIT"
] | 13 |
2015-03-18T20:24:40.000Z
|
2016-05-06T13:44:33.000Z
|
Code/Lab/UN_demography.ipynb
|
ljsun88/data_bootcamp_nyu
|
abc2486060672e19f5e4a71342cb8ca05155db83
|
[
"MIT"
] | 60 |
2015-03-24T00:05:50.000Z
|
2021-05-12T15:15:32.000Z
| 125.557124 | 34,958 | 0.832906 |
[
[
[
"# Data Bootcamp: Demography\n\nWe love demography, specifically the dynamics of population growth and decline. You can drill down seemingly without end, as this [terrific graphic](http://www.bloomberg.com/graphics/dataview/how-americans-die/) about causes of death suggests. \n\nWe take a look here at the UN's [population data](http://esa.un.org/unpd/wpp/Download/Standard/Population/): the age distribution of the population, life expectancy, fertility (the word we use for births), and mortality (deaths). Explore the website, it's filled with interesting data. There are other sources that cover longer time periods, and for some countries you can get detailed data on specific things (causes of death, for example). \n\nWe use a number of countries as examples, but Japan and China are the most striking. The code is written so that the country is easily changed. \n\nThis IPython notebook was created by Dave Backus, Chase Coleman, and Spencer Lyon for the NYU Stern course [Data Bootcamp](http://databootcamp.nyuecon.com/). ",
"_____no_output_____"
],
[
"## Preliminaries\n\nImport statements and a date check for future reference. ",
"_____no_output_____"
]
],
[
[
"# import packages \nimport pandas as pd # data management\nimport matplotlib.pyplot as plt # graphics \nimport matplotlib as mpl # graphics parameters\nimport numpy as np # numerical calculations \n\n# IPython command, puts plots in notebook \n%matplotlib inline\n\n# check Python version \nimport datetime as dt \nimport sys\nprint('Today is', dt.date.today())\nprint('What version of Python are we running? \\n', sys.version, sep='') ",
"Today is 2016-03-23\nWhat version of Python are we running? \n3.5.1 |Anaconda 2.5.0 (64-bit)| (default, Jan 29 2016, 15:01:46) [MSC v.1900 64 bit (AMD64)]\n"
]
],
[
[
"## Population by age \n\nWe have both \"estimates\" of the past (1950-2015) and \"projections\" of the future (out to 2100). Here we focus on the latter, specifically what the UN refers to as the medium variant: their middle of the road projection. It gives us a sense of how Japan's population might change over the next century. \n\nIt takes a few seconds to read the data. \n\nWhat are the numbers? Thousands of people in various 5-year age categories. ",
"_____no_output_____"
]
],
[
[
"url1 = 'http://esa.un.org/unpd/wpp/DVD/Files/'\nurl2 = '1_Indicators%20(Standard)/EXCEL_FILES/1_Population/'\nurl3 = 'WPP2015_POP_F07_1_POPULATION_BY_AGE_BOTH_SEXES.XLS'\nurl = url1 + url2 + url3 \n\ncols = [2, 5] + list(range(6,28))\n#est = pd.read_excel(url, sheetname=0, skiprows=16, parse_cols=cols, na_values=['…'])\nprj = pd.read_excel(url, sheetname=1, skiprows=16, parse_cols=cols, na_values=['…'])\n\nprj.head(3)[list(range(6))]",
"_____no_output_____"
],
[
"# rename some variables \npop = prj \nnames = list(pop) \npop = pop.rename(columns={names[0]: 'Country', \n names[1]: 'Year'}) \n# select country and years \ncountry = ['Japan']\nyears = [2015, 2055, 2095]\npop = pop[pop['Country'].isin(country) & pop['Year'].isin(years)]\npop = pop.drop(['Country'], axis=1)\n\n# set index = Year \n# divide by 1000 to convert numbers from thousands to millions\npop = pop.set_index('Year')/1000\n\npop.head()[list(range(8))]",
"_____no_output_____"
],
[
"# transpose (T) so that index = age \npop = pop.T\npop.head(3)",
"_____no_output_____"
],
[
"ax = pop.plot(kind='bar', \n color='blue', \n alpha=0.5, subplots=True, sharey=True, figsize=(8,6))\n\nfor axnum in range(len(ax)): \n ax[axnum].set_title('')\n ax[axnum].set_ylabel('Millions')\n \nax[0].set_title('Population by age', fontsize=14, loc='left') ",
"_____no_output_____"
]
],
[
[
"**Exercise.** What do you see here? What else would you like to know? ",
"_____no_output_____"
],
[
"**Exercise.** Adapt the preceeding code to do the same thing for China. Or some other country that sparks your interest. ",
"_____no_output_____"
],
[
"## Fertility: aka birth rates\n\nWe might wonder, why is the population falling in Japan? Other countries? Well, one reason is that birth rates are falling. Demographers call this fertility. Here we look at the fertility using the same [UN source](http://esa.un.org/unpd/wpp/Download/Standard/Fertility/) as the previous example. We look at two variables: total fertility and fertility by age of mother. In both cases we explore the numbers to date, but the same files contain projections of future fertility. ",
"_____no_output_____"
]
],
[
[
"# fertility overall \nuft = 'http://esa.un.org/unpd/wpp/DVD/Files/'\nuft += '1_Indicators%20(Standard)/EXCEL_FILES/'\nuft += '2_Fertility/WPP2015_FERT_F04_TOTAL_FERTILITY.XLS'\n\ncols = [2] + list(range(5,18))\nftot = pd.read_excel(uft, sheetname=0, skiprows=16, parse_cols=cols, na_values=['…'])\n\nftot.head(3)[list(range(6))]",
"_____no_output_____"
],
[
"# rename some variables \nnames = list(ftot)\nf = ftot.rename(columns={names[0]: 'Country'}) \n\n# select countries \ncountries = ['China', 'Japan', 'Germany', 'United States of America']\nf = f[f['Country'].isin(countries)]\n\n# shape\nf = f.set_index('Country').T \nf = f.rename(columns={'United States of America': 'United States'})\nf.tail(3)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots()\nf.plot(ax=ax, kind='line', alpha=0.5, lw=3, figsize=(6.5, 4))\nax.set_title('Fertility (births per woman, lifetime)', fontsize=14, loc='left')\nax.legend(loc='best', fontsize=10, handlelength=2, labelspacing=0.15)\nax.set_ylim(ymin=0)\nax.hlines(2.1, -1, 13, linestyles='dashed')\nax.text(8.5, 2.4, 'Replacement = 2.1')",
"_____no_output_____"
]
],
[
[
"**Exercise.** What do you see here? What else would you like to know? ",
"_____no_output_____"
],
[
"**Exercise.** Add Canada to the figure. How does it compare to the others? What other countries would you be interested in?",
"_____no_output_____"
],
[
"## Life expectancy \n\nOne of the bottom line summary numbers for mortality is life expectancy: if mortaility rates fall, people live longer, on average. Here we look at life expectancy at birth. There are also numbers for life expectancy given than you live to some specific age; for example, life expectancy given that you survive to age 60. ",
"_____no_output_____"
]
],
[
[
"# life expectancy at birth, both sexes \nule = 'http://esa.un.org/unpd/wpp/DVD/Files/1_Indicators%20(Standard)/EXCEL_FILES/3_Mortality/'\nule += 'WPP2015_MORT_F07_1_LIFE_EXPECTANCY_0_BOTH_SEXES.XLS'\n\ncols = [2] + list(range(5,34))\nle = pd.read_excel(ule, sheetname=0, skiprows=16, parse_cols=cols, na_values=['…'])\n\nle.head(3)[list(range(10))]",
"_____no_output_____"
],
[
"# rename some variables \noldname = list(le)[0]\nl = le.rename(columns={oldname: 'Country'}) \nl.head(3)[list(range(8))]",
"_____no_output_____"
],
[
"# select countries \ncountries = ['China', 'Japan', 'Germany', 'United States of America']\nl = l[l['Country'].isin(countries)]\n\n# shape\nl = l.set_index('Country').T \nl = l.rename(columns={'United States of America': 'United States'})\nl.tail()",
"_____no_output_____"
],
[
"fig, ax = plt.subplots()\nl.plot(ax=ax, kind='line', alpha=0.5, lw=3, figsize=(6, 8), grid=True)\nax.set_title('Life expectancy at birth', fontsize=14, loc='left')\nax.set_ylabel('Life expectancy in years')\nax.legend(loc='best', fontsize=10, handlelength=2, labelspacing=0.15)\nax.set_ylim(ymin=0)",
"_____no_output_____"
]
],
[
[
"**Exercise.** What other countries would you like to see? Can you add them? The code below generates a list. ",
"_____no_output_____"
]
],
[
[
"countries = le.rename(columns={oldname: 'Country'})['Country']",
"_____no_output_____"
]
],
[
[
"**Exercise.** Why do you think the US is falling behind? What would you look at to verify your conjecture?",
"_____no_output_____"
],
[
"## Mortality: aka death rates \n\nAnother thing that affects the age distribution of the population is the mortality rate: if mortality rates fall people live longer, on average. Here we look at how mortality rates have changed over the past 60+ years. Roughly speaking, people live an extra five years every generation. Which is a lot. Some of you will live to be a hundred. (Look at the 100+ agen category over time for Japan.) \n\nThe experts look at mortality rates by age. The UN has a [whole page](http://esa.un.org/unpd/wpp/Download/Standard/Mortality/) devoted to mortality numbers. We take 5-year mortality rates from the Abridged Life Table. \n\nThe numbers are percentages of people in a given age group who die over a 5-year period. 0.1 means that 90 percent of an age group is still alive in five years. ",
"_____no_output_____"
]
],
[
[
"# mortality overall \nurl = 'http://esa.un.org/unpd/wpp/DVD/Files/'\nurl += '1_Indicators%20(Standard)/EXCEL_FILES/3_Mortality/'\nurl += 'WPP2015_MORT_F17_1_ABRIDGED_LIFE_TABLE_BOTH_SEXES.XLS'\n\ncols = [2, 5, 6, 7, 9]\nmort = pd.read_excel(url, sheetname=0, skiprows=16, parse_cols=cols, na_values=['…'])\nmort.tail(3)",
"_____no_output_____"
],
[
"# change names \nnames = list(mort)\nm = mort.rename(columns={names[0]: 'Country', names[2]: 'Age', names[3]: 'Interval', names[4]: 'Mortality'})\nm.head(3)",
"_____no_output_____"
]
],
[
[
"**Comment.** At this point, we need to pivot the data. That's not something we've done before, so take it as simply something we can do easily if we have to. We're going to do this twice to produce different graphs: \n\n* Compare countries for the same period. \n* Compare different periods for the same country. ",
"_____no_output_____"
]
],
[
[
"# compare countries for most recent period\ncountries = ['China', 'Japan', 'Germany', 'United States of America']\nmt = m[m['Country'].isin(countries) & m['Interval'].isin([5]) & m['Period'].isin(['2010-2015'])] \nprint('Dimensions:', mt.shape) \n\nmp = mt.pivot(index='Age', columns='Country', values='Mortality') \nmp.head(3)",
"Dimensions: (64, 5)\n"
],
[
"fig, ax = plt.subplots()\nmp.plot(ax=ax, kind='line', alpha=0.5, linewidth=3, \n# logy=True, \n figsize=(6, 4))\nax.set_title('Mortality by age', fontsize=14, loc='left')\nax.set_ylabel('Mortality Rate (log scale)')\nax.legend(loc='best', fontsize=10, handlelength=2, labelspacing=0.15)",
"_____no_output_____"
]
],
[
[
"**Exercises.**\n\n* What country's old people have the lowest mortality?\n* What do you see here for the US? Why is our life expectancy shorter?\n* What other countries would you like to see? Can you adapt the code to show them? \n* Anything else cross your mind? ",
"_____no_output_____"
]
],
[
[
"# compare periods for the one country -- countries[0] is China \nmt = m[m['Country'].isin([countries[0]]) & m['Interval'].isin([5])] \nprint('Dimensions:', mt.shape) \n\nmp = mt.pivot(index='Age', columns='Period', values='Mortality') \nmp = mp[[0, 6, 12]]\nmp.head(3)",
"Dimensions: (208, 5)\n"
],
[
"fig, ax = plt.subplots()\nmp.plot(ax=ax, kind='line', alpha=0.5, linewidth=3, \n# logy=True, \n figsize=(6, 4))\nax.set_title('Mortality over time', fontsize=14, loc='left')\nax.set_ylabel('Mortality Rate (log scale)')\nax.legend(loc='best', fontsize=10, handlelength=2, labelspacing=0.15)",
"_____no_output_____"
]
],
[
[
"**Exercise.** What do you see? What else would you like to know? ",
"_____no_output_____"
],
[
"**Exercise.** Repeat this graph for the United States? How does it compare?",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
4aa6a60301c01fe3595b4c132ee84523123854e0
| 930,898 |
ipynb
|
Jupyter Notebook
|
courses/machine_learning/deepdive/supplemental_gradient_boosting/c_boosted_trees_model_understanding.ipynb
|
Glairly/introduction_to_tensorflow
|
aa0a44d9c428a6eb86d1f79d73f54c0861b6358d
|
[
"Apache-2.0"
] | 2 |
2022-01-06T11:52:57.000Z
|
2022-01-09T01:53:56.000Z
|
courses/machine_learning/deepdive/supplemental_gradient_boosting/c_boosted_trees_model_understanding.ipynb
|
Glairly/introduction_to_tensorflow
|
aa0a44d9c428a6eb86d1f79d73f54c0861b6358d
|
[
"Apache-2.0"
] | null | null | null |
courses/machine_learning/deepdive/supplemental_gradient_boosting/c_boosted_trees_model_understanding.ipynb
|
Glairly/introduction_to_tensorflow
|
aa0a44d9c428a6eb86d1f79d73f54c0861b6358d
|
[
"Apache-2.0"
] | null | null | null | 741.160828 | 235,577 | 0.946183 |
[
[
[
"# Model understanding and interpretability",
"_____no_output_____"
],
[
"In this colab, we will \n- Will learn how to interpret model results and reason about the features\n- Visualize the model results\n",
"_____no_output_____"
]
],
[
[
"import time\n\n# We will use some np and pandas for dealing with input data.\nimport numpy as np\nimport pandas as pd\n# And of course, we need tensorflow.\nimport tensorflow as tf\n\nfrom matplotlib import pyplot as plt\nfrom IPython.display import clear_output",
"_____no_output_____"
],
[
"tf.__version__",
"_____no_output_____"
]
],
[
[
"Below we demonstrate both *local* and *global* model interpretability for gradient boosted trees. \n\nLocal interpretability refers to an understanding of a model’s predictions at the individual example level, while global interpretability refers to an understanding of the model as a whole.\n\nFor local interpretability, we show how to create and visualize per-instance contributions using the technique outlined in [Palczewska et al](https://arxiv.org/pdf/1312.1121.pdf) and by Saabas in [Interpreting Random Forests](http://blog.datadive.net/interpreting-random-forests/) (this method is also available in scikit-learn for Random Forests in the [`treeinterpreter`](https://github.com/andosa/treeinterpreter) package). To distinguish this from feature importances, we refer to these values as directional feature contributions (DFCs).\n\nFor global interpretability we show how to retrieve and visualize gain-based feature importances, [permutation feature importances](https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf) and also show aggregated DFCs.",
"_____no_output_____"
],
[
"# Setup\n## Load dataset\nWe will be using the titanic dataset, where the goal is to predict passenger survival given characteristiscs such as gender, age, class, etc.",
"_____no_output_____"
]
],
[
[
"tf.logging.set_verbosity(tf.logging.ERROR)\ntf.set_random_seed(123)\n\n# Load dataset.\ndftrain = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/train.csv')\ndfeval = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/eval.csv')\ny_train = dftrain.pop('survived')\ny_eval = dfeval.pop('survived')\n\n# Feature columns.\nfcol = tf.feature_column\nCATEGORICAL_COLUMNS = ['sex', 'n_siblings_spouses', 'parch', 'class', 'deck',\n 'embark_town', 'alone']\nNUMERIC_COLUMNS = ['age', 'fare']\n\ndef one_hot_cat_column(feature_name, vocab):\n return fcol.indicator_column(\n fcol.categorical_column_with_vocabulary_list(feature_name,\n vocab))\nfc = []\nfor feature_name in CATEGORICAL_COLUMNS:\n # Need to one-hot encode categorical features.\n vocabulary = dftrain[feature_name].unique()\n fc.append(one_hot_cat_column(feature_name, vocabulary))\n\nfor feature_name in NUMERIC_COLUMNS:\n fc.append(fcol.numeric_column(feature_name,\n dtype=tf.float32))\n\n# Input functions.\ndef make_input_fn(X, y, n_epochs=None):\n def input_fn():\n dataset = tf.data.Dataset.from_tensor_slices((X.to_dict(orient='list'), y))\n # For training, cycle thru dataset as many times as need (n_epochs=None).\n dataset = (dataset\n .repeat(n_epochs)\n .batch(len(y))) # Use entire dataset since this is such a small dataset.\n return dataset\n return input_fn\n\n# Training and evaluation input functions.\ntrain_input_fn = make_input_fn(dftrain, y_train)\neval_input_fn = make_input_fn(dfeval, y_eval, n_epochs=1)",
"_____no_output_____"
]
],
[
[
"# Interpret model",
"_____no_output_____"
],
[
"## Local interpretability\nOutput directional feature contributions (DFCs) to explain individual predictions, using the approach outlined in [Palczewska et al](https://arxiv.org/pdf/1312.1121.pdf) and by Saabas in [Interpreting Random Forests](http://blog.datadive.net/interpreting-random-forests/). The DFCs are generated with:\n\n`pred_dicts = list(est.experimental_predict_with_explanations(pred_input_fn))`",
"_____no_output_____"
]
],
[
[
"params = {\n 'n_trees': 50,\n 'max_depth': 3,\n 'n_batches_per_layer': 1,\n # You must enable center_bias = True to get DFCs. This will force the model to\n # make an initial prediction before using any features (e.g. use the mean of\n # the training labels for regression or log odds for classification when\n # using cross entropy loss).\n 'center_bias': True\n}\n\nest = tf.estimator.BoostedTreesClassifier(fc, **params)\n# Train model.\nest.train(train_input_fn)\n\n# Evaluation.\nresults = est.evaluate(eval_input_fn)\nclear_output()\npd.Series(results).to_frame()",
"_____no_output_____"
]
],
[
[
"## Local interpretability\nNext you will output the directional feature contributions (DFCs) to explain individual predictions using the approach outlined in [Palczewska et al](https://arxiv.org/pdf/1312.1121.pdf) and by Saabas in [Interpreting Random Forests](http://blog.datadive.net/interpreting-random-forests/) (this method is also available in scikit-learn for Random Forests in the [`treeinterpreter`](https://github.com/andosa/treeinterpreter) package). The DFCs are generated with:\n\n`pred_dicts = list(est.experimental_predict_with_explanations(pred_input_fn))`\n\n(Note: The method is named experimental as we may modify the API before dropping the experimental prefix.)",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport seaborn as sns\nsns_colors = sns.color_palette('colorblind')",
"_____no_output_____"
],
[
"pred_dicts = list(est.experimental_predict_with_explanations(eval_input_fn))",
"_____no_output_____"
],
[
"def clean_feature_names(df):\n \"\"\"Boilerplate code to cleans up feature names -- this is unneed in TF 2.0\"\"\"\n df.columns = [v.split(':')[0].split('_indi')[0] for v in df.columns.tolist()]\n df = df.T.groupby(level=0).sum().T\n return df\n\n# Create DFC Pandas dataframe.\nlabels = y_eval.values\nprobs = pd.Series([pred['probabilities'][1] for pred in pred_dicts])\ndf_dfc = pd.DataFrame([pred['dfc'] for pred in pred_dicts])\ndf_dfc.columns = est._names_for_feature_id\ndf_dfc = clean_feature_names(df_dfc)\ndf_dfc.describe()",
"_____no_output_____"
],
[
"# Sum of DFCs + bias == probabality.\nbias = pred_dicts[0]['bias']\ndfc_prob = df_dfc.sum(axis=1) + bias\nnp.testing.assert_almost_equal(dfc_prob.values,\n probs.values)",
"_____no_output_____"
]
],
[
[
"Plot results",
"_____no_output_____"
]
],
[
[
"import seaborn as sns # Make plotting nicer.\nsns_colors = sns.color_palette('colorblind')\n\ndef plot_dfcs(example_id):\n label, prob = labels[ID], probs[ID]\n example = df_dfc.iloc[ID] # Choose ith example from evaluation set.\n TOP_N = 8 # View top 8 features.\n sorted_ix = example.abs().sort_values()[-TOP_N:].index\n ax = example[sorted_ix].plot(kind='barh', color='g', figsize=(10,5))\n ax.grid(False, axis='y')\n\n plt.title('Feature contributions for example {}\\n pred: {:1.2f}; label: {}'.format(ID, prob, label))\n plt.xlabel('Contribution to predicted probability')\nID = 102\nplot_dfcs(ID)",
"_____no_output_____"
]
],
[
[
"**??? ** How would you explain the above plot in plain english?",
"_____no_output_____"
],
[
"### Prettier plotting\nColor codes based on directionality and adds feature values on figure. Please do not worry about the details of the plotting code :)",
"_____no_output_____"
]
],
[
[
"def plot_example_pretty(example):\n \"\"\"Boilerplate code for better plotting :)\"\"\"\n \n def _get_color(value):\n \"\"\"To make positive DFCs plot green, negative DFCs plot red.\"\"\"\n green, red = sns.color_palette()[2:4]\n if value >= 0: return green\n return red\n\n\n def _add_feature_values(feature_values, ax):\n \"\"\"Display feature's values on left of plot.\"\"\"\n x_coord = ax.get_xlim()[0]\n OFFSET = 0.15\n for y_coord, (feat_name, feat_val) in enumerate(feature_values.items()):\n t = plt.text(x_coord, y_coord - OFFSET, '{}'.format(feat_val), size=12)\n t.set_bbox(dict(facecolor='white', alpha=0.5))\n from matplotlib.font_manager import FontProperties\n font = FontProperties()\n font.set_weight('bold')\n t = plt.text(x_coord, y_coord + 1 - OFFSET, 'feature\\nvalue',\n fontproperties=font, size=12)\n\n\n TOP_N = 8 # View top 8 features.\n sorted_ix = example.abs().sort_values()[-TOP_N:].index # Sort by magnitude.\n example = example[sorted_ix]\n colors = example.map(_get_color).tolist()\n ax = example.to_frame().plot(kind='barh',\n color=[colors],\n legend=None,\n alpha=0.75,\n figsize=(10,6))\n ax.grid(False, axis='y')\n ax.set_yticklabels(ax.get_yticklabels(), size=14)\n _add_feature_values(dfeval.iloc[ID].loc[sorted_ix], ax)\n ax.set_title('Feature contributions for example {}\\n pred: {:1.2f}; label: {}'.format(ID, probs[ID], labels[ID]))\n ax.set_xlabel('Contribution to predicted probability', size=14)\n plt.show()\n return ax",
"_____no_output_____"
],
[
"# Plot results.\nID = 102\nexample = df_dfc.iloc[ID] # Choose ith example from evaluation set.\nax = plot_example_pretty(example)",
"_____no_output_____"
]
],
[
[
"## Global feature importances\n\n1. Gain-based feature importances using `est.experimental_feature_importances`\n2. Aggregate DFCs using `est.experimental_predict_with_explanations`\n3. Permutation importances\n\nGain-based feature importances measure the loss change when splitting on a particular feature, while permutation feature importances are computed by evaluating model performance on the evaluation set by shuffling each feature one-by-one and attributing the change in model performance to the shuffled feature.\n\nIn general, permutation feature importance are preferred to gain-based feature importance, though both methods can be unreliable in situations where potential predictor variables vary in their scale of measurement or their number of categories and when features are correlated ([source](https://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-9-307)). Check out [this article](http://explained.ai/rf-importance/index.html) for an in-depth overview and great discussion on different feature importance types.\n\n## 1. Gain-based feature importances",
"_____no_output_____"
]
],
[
[
"features, importances = est.experimental_feature_importances(normalize=True)\ndf_imp = pd.DataFrame(importances, columns=['importances'], index=features)\n# For plotting purposes. This is not needed in TF 2.0.\ndf_imp = clean_feature_names(df_imp.T).T.sort_values('importances', ascending=False)\n\n# Visualize importances.\nN = 8\nax = df_imp.iloc[0:N][::-1]\\\n .plot(kind='barh',\n color=sns_colors[0],\n title='Gain feature importances',\n figsize=(10, 6))\nax.grid(False, axis='y')\n\nplt.tight_layout()",
"_____no_output_____"
]
],
[
[
"**???** What does the x axis represent? -- A. It represents relative importance. Specifically, the average reduction in loss that occurs when a split occurs on that feature.",
"_____no_output_____"
],
[
"**???** Can we completely trust these results and the magnitudes? -- A. The results can be misleading because variables are correlated.",
"_____no_output_____"
],
[
"### 2. Average absolute DFCs\nWe can also average the absolute values of DFCs to understand impact at a global level.",
"_____no_output_____"
]
],
[
[
"# Plot.\ndfc_mean = df_dfc.abs().mean()\nsorted_ix = dfc_mean.abs().sort_values()[-8:].index # Average and sort by absolute.\nax = dfc_mean[sorted_ix].plot(kind='barh',\n color=sns_colors[1],\n title='Mean |directional feature contributions|',\n figsize=(10, 6))\nax.grid(False, axis='y')",
"_____no_output_____"
]
],
[
[
"We can also see how DFCs vary as a feature value varies.",
"_____no_output_____"
]
],
[
[
"age = pd.Series(df_dfc.age.values, index=dfeval.age.values).sort_index()\nsns.jointplot(age.index.values, age.values);",
"_____no_output_____"
]
],
[
[
"# Visualizing the model's prediction surface",
"_____no_output_____"
],
[
"Lets first simulate/create training data using the following formula:\n\n\n$z=x* e^{-x^2 - y^2}$\n\n\nWhere $z$ is the dependent variable we are trying to predict and $x$ and $y$ are the features.",
"_____no_output_____"
]
],
[
[
"from numpy.random import uniform, seed\nfrom matplotlib.mlab import griddata\n\n# Create fake data\nseed(0)\nnpts = 5000\nx = uniform(-2, 2, npts)\ny = uniform(-2, 2, npts)\nz = x*np.exp(-x**2 - y**2)",
"_____no_output_____"
],
[
"# Prep data for training.\ndf = pd.DataFrame({'x': x, 'y': y, 'z': z})\n\nxi = np.linspace(-2.0, 2.0, 200),\nyi = np.linspace(-2.1, 2.1, 210),\nxi,yi = np.meshgrid(xi, yi)\n\ndf_predict = pd.DataFrame({\n 'x' : xi.flatten(),\n 'y' : yi.flatten(),\n})\npredict_shape = xi.shape",
"_____no_output_____"
],
[
"def plot_contour(x, y, z, **kwargs):\n # Grid the data.\n plt.figure(figsize=(10, 8))\n # Contour the gridded data, plotting dots at the nonuniform data points.\n CS = plt.contour(x, y, z, 15, linewidths=0.5, colors='k')\n CS = plt.contourf(x, y, z, 15,\n vmax=abs(zi).max(), vmin=-abs(zi).max(), cmap='RdBu_r')\n plt.colorbar() # Draw colorbar.\n # Plot data points.\n plt.xlim(-2, 2)\n plt.ylim(-2, 2)",
"_____no_output_____"
]
],
[
[
"We can visualize our function:",
"_____no_output_____"
]
],
[
[
"zi = griddata(x, y, z, xi, yi, interp='linear')\nplot_contour(xi, yi, zi)\nplt.scatter(df.x, df.y, marker='.')\nplt.title('Contour on training data')\nplt.show()",
"/usr/local/lib/python2.7/dist-packages/ipykernel_launcher.py:1: MatplotlibDeprecationWarning: The griddata function was deprecated in version 2.2. Use scipy.interpolate.griddata instead.\n \"\"\"Entry point for launching an IPython kernel.\n"
],
[
"def predict(est):\n \"\"\"Predictions from a given estimator.\"\"\"\n predict_input_fn = lambda: tf.data.Dataset.from_tensors(dict(df_predict))\n preds = np.array([p['predictions'][0] for p in est.predict(predict_input_fn)])\n return preds.reshape(predict_shape)",
"_____no_output_____"
]
],
[
[
"First let's try to fit a linear model to the data.",
"_____no_output_____"
]
],
[
[
"fc = [tf.feature_column.numeric_column('x'),\n tf.feature_column.numeric_column('y')]\n\ntrain_input_fn = make_input_fn(df, df.z)\nest = tf.estimator.LinearRegressor(fc)\nest.train(train_input_fn, max_steps=500);",
"_____no_output_____"
],
[
"plot_contour(xi, yi, predict(est))",
"_____no_output_____"
]
],
[
[
"Not very good at all...",
"_____no_output_____"
],
[
"**???** Why is the linear model not performing well for this problem? Can you think of how to improve it just using a linear model?",
"_____no_output_____"
],
[
"Next let's try to fit a GBDT model to it and try to understand what the model does",
"_____no_output_____"
]
],
[
[
"for n_trees in [1,2,3,10,30,50,100,200]:\n est = tf.estimator.BoostedTreesRegressor(fc,\n n_batches_per_layer=1,\n max_depth=4,\n n_trees=n_trees)\n est.train(train_input_fn)\n plot_contour(xi, yi, predict(est))\n plt.text(-1.8, 2.1, '# trees: {}'.format(n_trees), color='w', backgroundcolor='black', size=20)",
"_____no_output_____"
]
],
[
[
"Copyright 2019 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aa6b2e0b7eb80e72c7a142332fc73754c361cf1
| 744,053 |
ipynb
|
Jupyter Notebook
|
code/EDA.ipynb
|
luajunan/DSA3101-Assignment1
|
b7722c43fff087218f1e6e1a31bf557f68869bf9
|
[
"MIT"
] | 1 |
2021-11-23T01:57:37.000Z
|
2021-11-23T01:57:37.000Z
|
code/EDA.ipynb
|
luajunan/DSA3101-Assignment1
|
b7722c43fff087218f1e6e1a31bf557f68869bf9
|
[
"MIT"
] | null | null | null |
code/EDA.ipynb
|
luajunan/DSA3101-Assignment1
|
b7722c43fff087218f1e6e1a31bf557f68869bf9
|
[
"MIT"
] | null | null | null | 744,053 | 744,053 | 0.932154 |
[
[
[
"#**Exploratory Data Analysis**",
"_____no_output_____"
],
[
"### Setting Up Environment",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.style as style\nimport seaborn as sns\nfrom scipy.stats import pointbiserialr\nfrom scipy.stats import pearsonr\nfrom scipy.stats import chi2_contingency\nfrom sklearn.impute import SimpleImputer\nplt.rcParams[\"figure.figsize\"] = (15,8)",
"_____no_output_____"
],
[
"application_data_raw = pd.read_csv('application_data.csv', encoding = 'unicode_escape')",
"_____no_output_____"
],
[
"application_data_raw.info()\n#application_data_raw.describe()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 307511 entries, 0 to 307510\nColumns: 122 entries, SK_ID_CURR to AMT_REQ_CREDIT_BUREAU_YEAR\ndtypes: float64(65), int64(41), object(16)\nmemory usage: 286.2+ MB\n"
],
[
"df = application_data_raw.copy()",
"_____no_output_____"
]
],
[
[
"### Data Cleaning",
"_____no_output_____"
]
],
[
[
"# drop the customer id column\ndf = df.drop(columns=['SK_ID_CURR'])\n\n# remove invalid values in gender column\ndf['CODE_GENDER'] = df['CODE_GENDER'].replace(\"XNA\", None)\n\n# drop columns filled >25% with null values\nnum_missing_values = df.isnull().sum()\nnulldf = round(num_missing_values/len(df)*100, 2)\ncols_to_keep = nulldf[nulldf<=0.25].index.to_list()\ndf = df.loc[:, cols_to_keep] # 61 of 121 attributes were removed due to null values.\n\n\n# impute remaining columns with null values\nnum_missing_values = df.isnull().sum()\nmissing_cols = num_missing_values[num_missing_values>0].index.tolist()\n\nfor col in missing_cols:\n imp_mean = SimpleImputer(strategy='most_frequent')\n imp_mean.fit(df[[col]])\n df[col] = imp_mean.transform(df[[col]]).ravel()\n",
"_____no_output_____"
],
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 307511 entries, 0 to 307510\nData columns (total 59 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 TARGET 307511 non-null int64 \n 1 NAME_CONTRACT_TYPE 307511 non-null object \n 2 CODE_GENDER 307511 non-null object \n 3 FLAG_OWN_CAR 307511 non-null object \n 4 FLAG_OWN_REALTY 307511 non-null object \n 5 CNT_CHILDREN 307511 non-null int64 \n 6 AMT_INCOME_TOTAL 307511 non-null float64\n 7 AMT_CREDIT 307511 non-null float64\n 8 AMT_ANNUITY 307511 non-null float64\n 9 AMT_GOODS_PRICE 307511 non-null float64\n 10 NAME_INCOME_TYPE 307511 non-null object \n 11 NAME_EDUCATION_TYPE 307511 non-null object \n 12 NAME_FAMILY_STATUS 307511 non-null object \n 13 NAME_HOUSING_TYPE 307511 non-null object \n 14 REGION_POPULATION_RELATIVE 307511 non-null float64\n 15 DAYS_BIRTH 307511 non-null int64 \n 16 DAYS_EMPLOYED 307511 non-null int64 \n 17 DAYS_REGISTRATION 307511 non-null float64\n 18 DAYS_ID_PUBLISH 307511 non-null int64 \n 19 FLAG_MOBIL 307511 non-null int64 \n 20 FLAG_EMP_PHONE 307511 non-null int64 \n 21 FLAG_WORK_PHONE 307511 non-null int64 \n 22 FLAG_CONT_MOBILE 307511 non-null int64 \n 23 FLAG_PHONE 307511 non-null int64 \n 24 FLAG_EMAIL 307511 non-null int64 \n 25 CNT_FAM_MEMBERS 307511 non-null float64\n 26 REGION_RATING_CLIENT 307511 non-null int64 \n 27 REGION_RATING_CLIENT_W_CITY 307511 non-null int64 \n 28 WEEKDAY_APPR_PROCESS_START 307511 non-null object \n 29 HOUR_APPR_PROCESS_START 307511 non-null int64 \n 30 REG_REGION_NOT_LIVE_REGION 307511 non-null int64 \n 31 REG_REGION_NOT_WORK_REGION 307511 non-null int64 \n 32 LIVE_REGION_NOT_WORK_REGION 307511 non-null int64 \n 33 REG_CITY_NOT_LIVE_CITY 307511 non-null int64 \n 34 REG_CITY_NOT_WORK_CITY 307511 non-null int64 \n 35 LIVE_CITY_NOT_WORK_CITY 307511 non-null int64 \n 36 ORGANIZATION_TYPE 307511 non-null object \n 37 EXT_SOURCE_2 307511 non-null float64\n 38 DAYS_LAST_PHONE_CHANGE 307511 non-null float64\n 39 FLAG_DOCUMENT_2 307511 non-null int64 \n 40 FLAG_DOCUMENT_3 307511 non-null int64 \n 41 FLAG_DOCUMENT_4 307511 non-null int64 \n 42 FLAG_DOCUMENT_5 307511 non-null int64 \n 43 FLAG_DOCUMENT_6 307511 non-null int64 \n 44 FLAG_DOCUMENT_7 307511 non-null int64 \n 45 FLAG_DOCUMENT_8 307511 non-null int64 \n 46 FLAG_DOCUMENT_9 307511 non-null int64 \n 47 FLAG_DOCUMENT_10 307511 non-null int64 \n 48 FLAG_DOCUMENT_11 307511 non-null int64 \n 49 FLAG_DOCUMENT_12 307511 non-null int64 \n 50 FLAG_DOCUMENT_13 307511 non-null int64 \n 51 FLAG_DOCUMENT_14 307511 non-null int64 \n 52 FLAG_DOCUMENT_15 307511 non-null int64 \n 53 FLAG_DOCUMENT_16 307511 non-null int64 \n 54 FLAG_DOCUMENT_17 307511 non-null int64 \n 55 FLAG_DOCUMENT_18 307511 non-null int64 \n 56 FLAG_DOCUMENT_19 307511 non-null int64 \n 57 FLAG_DOCUMENT_20 307511 non-null int64 \n 58 FLAG_DOCUMENT_21 307511 non-null int64 \ndtypes: float64(9), int64(40), object(10)\nmemory usage: 138.4+ MB\n"
]
],
[
[
"### Data Preprocessing",
"_____no_output_____"
]
],
[
[
"continuous_vars = ['CNT_CHILDREN', 'AMT_INCOME_TOTAL', 'AMT_CREDIT', 'AMT_ANNUITY', 'AMT_GOODS_PRICE', 'REGION_POPULATION_RELATIVE', \n 'DAYS_REGISTRATION', 'DAYS_ID_PUBLISH', 'CNT_FAM_MEMBERS', 'REGION_RATING_CLIENT', 'REGION_RATING_CLIENT_W_CITY', \n 'HOUR_APPR_PROCESS_START', 'EXT_SOURCE_2', 'DAYS_LAST_PHONE_CHANGE', 'YEARS_BIRTH', 'YEARS_EMPLOYED']\n\n\n#categorical_variables = df.select_dtypes(include=[\"category\"]).columns.tolist()\n#len(categorical_variables)\n\ncategorical_vars = ['NAME_CONTRACT_TYPE', 'CODE_GENDER', 'FLAG_OWN_CAR', 'FLAG_OWN_REALTY', 'NAME_INCOME_TYPE','NAME_EDUCATION_TYPE', \n 'NAME_FAMILY_STATUS', 'NAME_HOUSING_TYPE', 'FLAG_MOBIL', 'FLAG_EMP_PHONE', 'FLAG_WORK_PHONE', 'FLAG_CONT_MOBILE', 'FLAG_PHONE', \n 'FLAG_EMAIL', 'WEEKDAY_APPR_PROCESS_START', 'REG_REGION_NOT_LIVE_REGION','REG_REGION_NOT_WORK_REGION', \n 'LIVE_REGION_NOT_WORK_REGION', 'REG_CITY_NOT_LIVE_CITY', 'REG_CITY_NOT_WORK_CITY', 'LIVE_CITY_NOT_WORK_CITY', \n 'ORGANIZATION_TYPE', 'FLAG_DOCUMENT_2', 'FLAG_DOCUMENT_3', 'FLAG_DOCUMENT_4', 'FLAG_DOCUMENT_5', 'FLAG_DOCUMENT_6', \n 'FLAG_DOCUMENT_7', 'FLAG_DOCUMENT_8', 'FLAG_DOCUMENT_9', 'FLAG_DOCUMENT_10', 'FLAG_DOCUMENT_11', 'FLAG_DOCUMENT_12', \n 'FLAG_DOCUMENT_13', 'FLAG_DOCUMENT_14', 'FLAG_DOCUMENT_15', 'FLAG_DOCUMENT_16', 'FLAG_DOCUMENT_17', 'FLAG_DOCUMENT_18',\n 'FLAG_DOCUMENT_19', 'FLAG_DOCUMENT_20', 'FLAG_DOCUMENT_21']",
"_____no_output_____"
],
[
"# plot to see distribution of categorical variables\nn_cols = 4\nfig, axes = plt.subplots(nrows=int(np.ceil(len(categorical_vars)/n_cols)), \n ncols=n_cols, \n figsize=(15,45))\n\nfor i in range(len(categorical_vars)):\n var = categorical_vars[i]\n dist = df[var].value_counts()\n labels = dist.index\n counts = dist.values\n ax = axes.flatten()[i]\n ax.bar(labels, counts)\n ax.tick_params(axis='x', labelrotation = 90)\n ax.title.set_text(var)\n\n\nplt.tight_layout() \nplt.show()\n# This gives us an idea about which features may already be more useful",
"_____no_output_____"
],
[
"# Remove all FLAG_DOCUMENT features except for FLAG_DOCUMENT_3 as most did not submit, insignificant on model\nvars_to_drop = []\nvars_to_drop = [\"FLAG_DOCUMENT_2\"]\nvars_to_drop += [\"FLAG_DOCUMENT_{}\".format(i) for i in range(4,22)]",
"_____no_output_____"
],
[
"# Unit conversions\ndf['AMT_INCOME_TOTAL'] = df['AMT_INCOME_TOTAL']/100000 # yearly income to be expressed in hundred thousands\n\ndf['YEARS_BIRTH'] = round((df['DAYS_BIRTH']*-1)/365).astype('int64') # days of birth changed to years of birth\n\ndf['YEARS_EMPLOYED'] = round((df['DAYS_EMPLOYED']*-1)/365).astype('int64') # days employed change to years employed\ndf.loc[df['YEARS_EMPLOYED']<0, 'YEARS_EMPLOYED'] = 0\n\ndf = df.drop(columns=['DAYS_BIRTH', 'DAYS_EMPLOYED'])",
"_____no_output_____"
],
[
"# Encoding categorical variables\ndef encode_cat(df, var_list):\n for var in var_list:\n df[var] = df[var].astype('category')\n d = dict(zip(df[var], df[var].cat.codes))\n df[var] = df[var].map(d)\n print(var+\" Category Codes\")\n print(d)\n return df\n\nalready_coded = ['FLAG_MOBIL', 'FLAG_EMP_PHONE', 'FLAG_WORK_PHONE', 'FLAG_CONT_MOBILE', 'FLAG_PHONE', 'FLAG_EMAIL', 'REG_REGION_NOT_LIVE_REGION', \n 'REG_REGION_NOT_WORK_REGION', 'LIVE_REGION_NOT_WORK_REGION', 'REG_CITY_NOT_LIVE_CITY', 'REG_CITY_NOT_WORK_CITY', \n 'LIVE_CITY_NOT_WORK_CITY', 'FLAG_DOCUMENT_2', 'FLAG_DOCUMENT_3', 'FLAG_DOCUMENT_4', 'FLAG_DOCUMENT_5', 'FLAG_DOCUMENT_6', \n 'FLAG_DOCUMENT_7', 'FLAG_DOCUMENT_8', 'FLAG_DOCUMENT_9', 'FLAG_DOCUMENT_10', 'FLAG_DOCUMENT_11', 'FLAG_DOCUMENT_12', \n 'FLAG_DOCUMENT_13', 'FLAG_DOCUMENT_14', 'FLAG_DOCUMENT_15', 'FLAG_DOCUMENT_16', 'FLAG_DOCUMENT_17', 'FLAG_DOCUMENT_18',\n 'FLAG_DOCUMENT_19', 'FLAG_DOCUMENT_20', 'FLAG_DOCUMENT_21']\n\nvars_to_encode = ['NAME_CONTRACT_TYPE', 'CODE_GENDER', 'FLAG_OWN_CAR', 'FLAG_OWN_REALTY', 'NAME_INCOME_TYPE','NAME_EDUCATION_TYPE', \n 'NAME_FAMILY_STATUS', 'NAME_HOUSING_TYPE', 'WEEKDAY_APPR_PROCESS_START', 'ORGANIZATION_TYPE']\n\nfor var in already_coded:\n df[var] = df[var].astype('category')\n\ndf = encode_cat(df, vars_to_encode)",
"NAME_CONTRACT_TYPE Category Codes\n{'Cash loans': 0, 'Revolving loans': 1}\nCODE_GENDER Category Codes\n{'M': 1, 'F': 0}\nFLAG_OWN_CAR Category Codes\n{'N': 0, 'Y': 1}\nFLAG_OWN_REALTY Category Codes\n{'Y': 1, 'N': 0}\nNAME_INCOME_TYPE Category Codes\n{'Working': 7, 'State servant': 4, 'Commercial associate': 1, 'Pensioner': 3, 'Unemployed': 6, 'Student': 5, 'Businessman': 0, 'Maternity leave': 2}\nNAME_EDUCATION_TYPE Category Codes\n{'Secondary / secondary special': 4, 'Higher education': 1, 'Incomplete higher': 2, 'Lower secondary': 3, 'Academic degree': 0}\nNAME_FAMILY_STATUS Category Codes\n{'Single / not married': 3, 'Married': 1, 'Civil marriage': 0, 'Widow': 5, 'Separated': 2, 'Unknown': 4}\nNAME_HOUSING_TYPE Category Codes\n{'House / apartment': 1, 'Rented apartment': 4, 'With parents': 5, 'Municipal apartment': 2, 'Office apartment': 3, 'Co-op apartment': 0}\nWEEKDAY_APPR_PROCESS_START Category Codes\n{'WEDNESDAY': 6, 'MONDAY': 1, 'THURSDAY': 4, 'SUNDAY': 3, 'SATURDAY': 2, 'FRIDAY': 0, 'TUESDAY': 5}\nORGANIZATION_TYPE Category Codes\n{'Business Entity Type 3': 5, 'School': 39, 'Government': 11, 'Religion': 37, 'Other': 33, 'XNA': 57, 'Electricity': 9, 'Medicine': 30, 'Business Entity Type 2': 4, 'Self-employed': 42, 'Transport: type 2': 53, 'Construction': 7, 'Housing': 13, 'Kindergarten': 28, 'Trade: type 7': 51, 'Industry: type 11': 16, 'Military': 31, 'Services': 43, 'Security Ministries': 41, 'Transport: type 4': 55, 'Industry: type 1': 14, 'Emergency': 10, 'Security': 40, 'Trade: type 2': 46, 'University': 56, 'Transport: type 3': 54, 'Police': 34, 'Business Entity Type 1': 3, 'Postal': 35, 'Industry: type 4': 21, 'Agriculture': 1, 'Restaurant': 38, 'Culture': 8, 'Hotel': 12, 'Industry: type 7': 24, 'Trade: type 3': 47, 'Industry: type 3': 20, 'Bank': 2, 'Industry: type 9': 26, 'Insurance': 27, 'Trade: type 6': 50, 'Industry: type 2': 19, 'Transport: type 1': 52, 'Industry: type 12': 17, 'Mobile': 32, 'Trade: type 1': 45, 'Industry: type 5': 22, 'Industry: type 10': 15, 'Legal Services': 29, 'Advertising': 0, 'Trade: type 5': 49, 'Cleaning': 6, 'Industry: type 13': 18, 'Trade: type 4': 48, 'Telecom': 44, 'Industry: type 8': 25, 'Realtor': 36, 'Industry: type 6': 23}\n"
],
[
"# removing rows with all 0\ndf = df[df.T.any()]",
"_____no_output_____"
],
[
"df.describe()",
"_____no_output_____"
]
],
[
[
"### Checking for correlations between variables",
"_____no_output_____"
]
],
[
[
"X = df.iloc[:, 1:]",
"_____no_output_____"
],
[
"# getting correlation matrix of continuous and categorical variables\ncont = ['TARGET'] + continuous_vars\ncat = ['TARGET'] + categorical_vars\n\ncont_df = df.loc[:, cont]\ncat_df = df.loc[:, cat]\n\ncont_corr = cont_df.corr()\ncat_corr = cat_df.corr()",
"_____no_output_____"
],
[
"plt.figure(figsize=(10,10));\nsns.heatmap(cont_corr, \n xticklabels = cont_corr.columns, \n yticklabels = cont_corr.columns, \n cmap=\"PiYG\", \n linewidth = 1);",
"_____no_output_____"
],
[
"# Find Point biserial correlation\nfor cat_var in categorical_vars:\n for cont_var in continuous_vars:\n data_cat = df[cat_var].to_numpy()\n data_cont = df[cont_var].to_numpy()\n \n corr, p_val = pointbiserialr(x=data_cat, y=data_cont)\n if np.abs(corr) >= 0.8:\n print(f'Categorical variable: {cat_var}, Continuous variable: {cont_var}, correlation: {corr}')\n",
"_____no_output_____"
],
[
"# Find Pearson correlation\ntotal_len = len(continuous_vars)\nfor idx1 in range(total_len-1):\n for idx2 in range(idx1+1, total_len):\n cont_var1 = continuous_vars[idx1]\n cont_var2 = continuous_vars[idx2]\n data_cont1 = X[cont_var1].to_numpy()\n data_cont2 = X[cont_var2].to_numpy()\n corr, p_val = pearsonr(x=data_cont1, y=data_cont2)\n if np.abs(corr) >= 0.8:\n print(f' Continuous var 1: {cont_var1}, Continuous var 2: {cont_var2}, correlation: {corr}')",
" Continuous var 1: CNT_CHILDREN, Continuous var 2: CNT_FAM_MEMBERS, correlation: 0.8791602361715272\n Continuous var 1: AMT_CREDIT, Continuous var 2: AMT_GOODS_PRICE, correlation: 0.9867342920601158\n Continuous var 1: REGION_RATING_CLIENT, Continuous var 2: REGION_RATING_CLIENT_W_CITY, correlation: 0.9508422141645037\n"
],
[
"sns.scatterplot(data=X, x='CNT_CHILDREN',y='CNT_FAM_MEMBERS');",
"_____no_output_____"
],
[
"# Find Cramer's V correlation\ntotal_len = len(categorical_vars)\nfor idx1 in range(total_len-1):\n for idx2 in range(idx1+1, total_len):\n cat_var1 = categorical_vars[idx1]\n cat_var2 = categorical_vars[idx2] \n c_matrix = pd.crosstab(X[cat_var1], X[cat_var2])\n\n \"\"\" calculate Cramers V statistic for categorial-categorial association.\n uses correction from Bergsma and Wicher, \n Journal of the Korean Statistical Society 42 (2013): 323-328\n \"\"\"\n chi2 = chi2_contingency(c_matrix)[0]\n n = c_matrix.sum().sum()\n phi2 = chi2/n\n r,k = c_matrix.shape\n phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1))\n rcorr = r-((r-1)**2)/(n-1)\n kcorr = k-((k-1)**2)/(n-1)\n corr = np.sqrt(phi2corr/min((kcorr-1),(rcorr-1)))\n if corr >= 0.8:\n print(f'categorical variable 1 {cat_var1}, categorical variable 2: {cat_var2}, correlation: {corr}')",
"categorical variable 1 NAME_INCOME_TYPE, categorical variable 2: FLAG_EMP_PHONE, correlation: 0.9997491034472517\ncategorical variable 1 FLAG_EMP_PHONE, categorical variable 2: ORGANIZATION_TYPE, correlation: 0.9997768111172551\ncategorical variable 1 REG_REGION_NOT_WORK_REGION, categorical variable 2: LIVE_REGION_NOT_WORK_REGION, correlation: 0.8605887876340311\ncategorical variable 1 REG_CITY_NOT_WORK_CITY, categorical variable 2: LIVE_CITY_NOT_WORK_CITY, correlation: 0.8255640362699692\n"
],
[
"corr, p_val = pearsonr(x=df['REGION_RATING_CLIENT_W_CITY'], y=df['REGION_RATING_CLIENT'])\nprint(corr)\n# High collinearity of 0.95 between variables suggests that one of it should be removed, we shall remove the REGION_RATING_CLIENT_W_CITY.",
"0.9508422141645037\n"
],
[
"# Drop highly correlated variables\nvars_to_drop += ['CNT_FAM_MEMBERS', 'REG_REGION_NOT_WORK_REGION', 'REG_CITY_NOT_WORK_CITY', 'AMT_GOODS_PRICE', 'REGION_RATING_CLIENT_W_CITY']\nfeatures_to_keep = [x for x in df.columns if x not in vars_to_drop]",
"_____no_output_____"
],
[
"features_to_keep",
"_____no_output_____"
],
[
"new_df = df.loc[:, features_to_keep]\nnew_df",
"_____no_output_____"
],
[
"# Checking correlation of X continuous columns vs TARGET column\nplt.figure(figsize=(10,10))\ndf_corr = new_df.corr()\nax = sns.heatmap(df_corr,\n xticklabels=df_corr.columns,\n yticklabels=df_corr.columns,\n annot = True,\n cmap =\"RdYlGn\")\n# No particular feature found to be significantly correlated with the target",
"_____no_output_____"
],
[
"# REGION_RATING_CLIENT and REGION_POPULATION_RELATIVE have multicollinearity\nfeatures_to_keep.remove('REGION_POPULATION_RELATIVE')",
"_____no_output_____"
],
[
"features_to_keep\n# These are our final list of features",
"_____no_output_____"
]
],
[
[
"###Plots",
"_____no_output_____"
]
],
[
[
"ax1 = sns.boxplot(y='AMT_CREDIT', x= 'TARGET', data=new_df)\nax1.set_title(\"Target by amount credit of the loan\", fontsize=20);",
"_____no_output_____"
]
],
[
[
"The amount credit of an individual does not seem to have a siginifcant effect on whether a person finds it difficult to pay. But they are crucial for our business reccomendations so we keep them.",
"_____no_output_____"
]
],
[
[
"ax2 = sns.barplot(x='CNT_CHILDREN', y= 'TARGET', data=new_df)\nax2.set_title(\"Target by number of children\", fontsize=20);",
"_____no_output_____"
]
],
[
[
"From these plots, we can see that number of children has quite a significant effect on whether one defaults or not, with an increasing number of children proving more difficulty to return the loan.",
"_____no_output_____"
]
],
[
[
"ax3 = sns.barplot(x='NAME_FAMILY_STATUS', y= 'TARGET', data=new_df);\nax3.set_title(\"Target by family status\", fontsize=20);\nplt.xticks(np.arange(6), ['Civil marriage', 'Married', 'Separated', 'Single / not married',\n 'Unknown', 'Widow'], rotation=20);",
"_____no_output_____"
]
],
[
[
"\nWidows have the lowest likelihood of finding it difficult to pay, a possible target for our reccomendation strategy.",
"_____no_output_____"
]
],
[
[
"new_df['YEARS_BIRTH_CAT'] = pd.cut(df.YEARS_BIRTH, bins= [21, 25, 35, 45, 55, 69], labels= [\"25 and below\", \"26-35\", \"36-45\", \"46-55\", \"Above 55\"])\n\nax4 = sns.barplot(x='YEARS_BIRTH_CAT', y= 'TARGET', data=new_df);\nax4.set_title(\"Target by age\", fontsize=20);\n",
"_____no_output_____"
]
],
[
[
"Analysis of age groups on ability to pay shows clear trend that the older you are, the better able you are to pay your loans. We will use this to craft our reccomendations.",
"_____no_output_____"
]
],
[
[
"ax5 = sns.barplot(y='TARGET', x= 'NAME_INCOME_TYPE', data=new_df);\nax5.set_title(\"Target by income type\", fontsize=20);\nplt.xticks(np.arange(0, 8),['Businessman', 'Commercial associate', 'Maternity leave', 'Pensioner',\n 'State servant', 'Student', 'Unemployed', 'Working'], rotation=20);",
"_____no_output_____"
],
[
"ax6 = sns.barplot(x='NAME_EDUCATION_TYPE', y= 'TARGET', data=new_df);\nax6.set_title(\"Target by education type\", fontsize=20);\nplt.xticks(np.arange(5), ['Academic Degree', 'Higher education', 'Incomplete higher', 'Lower secondary', 'Secondary / secondary special'], rotation=20);",
"_____no_output_____"
],
[
"ax7 = sns.barplot(x='ORGANIZATION_TYPE', y= 'TARGET', data=new_df);\nax7.set_title(\"Target by organization type\", fontsize=20);\nplt.xticks(np.arange(58), ['Unknown','Advertising','Agriculture', 'Bank', 'Business Entity Type 1', 'Business Entity Type 2', \n'Business Entity Type 3', 'Cleaning', 'Construction', 'Culture', 'Electricity', 'Emergency', 'Government', 'Hotel', 'Housing', 'Industry: type 1', 'Industry: type 10', 'Industry: type 11', 'Industry: type 12', 'Industry: type 13', 'Industry: type 2', 'Industry: type 3', 'Industry: type 4', 'Industry: type 5', 'Industry: type 6', 'Industry: type 7', 'Industry: type 8', 'Industry: type 9', 'Insurance', 'Kindergarten', 'Legal Services', 'Medicine', 'Military', 'Mobile', 'Other', 'Police', 'Postal', 'Realtor', 'Religion', 'Restaurant', 'School', 'Security', 'Security Ministries', 'Self-employed', 'Services', 'Telecom', 'Trade: type 1', 'Trade: type 2', 'Trade: type 3', 'Trade: type 4', 'Trade: type 5', 'Trade: type 6', 'Trade: type 7', 'Transport: type 1', 'Transport: type 2', 'Transport: type 3', 'Transport: type 4','University'], rotation=90);",
"_____no_output_____"
],
[
"ax8 = sns.barplot(x='NAME_CONTRACT_TYPE', y= 'TARGET', data=new_df);\nax8.set_title(\"Target by contract type\", fontsize=20);\nplt.xticks(np.arange(2), ['Cash Loan', 'Revolving Loan']);",
"_____no_output_____"
]
],
[
[
"People who get revolving loans are more likely to pay back their loans than cash loans, perhaps due to the revolving loans being of a lower amount, and also its higher interest rate and recurring nature.",
"_____no_output_____"
]
],
[
[
"ax9 = sns.barplot(x='CODE_GENDER', y= 'TARGET', data=new_df);\nax9.set_title(\"Target by gender\", fontsize=20);\nplt.xticks(np.arange(2), ['Female', 'Male']);",
"_____no_output_____"
]
],
[
[
"Males find it harder to pay back their loans than females in general.\n\n\n",
"_____no_output_____"
]
],
[
[
"# Splitting Credit into bins of 10k\nnew_df['Credit_Category'] = pd.cut(new_df.AMT_CREDIT, bins= [0, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000, 4.050000e+06], labels= [\"0-100k\", \"100-200k\", \"200-300k\", \"300-400k\", \"400-500k\", \"500-600k\", \"600-700k\", \"700-800k\", \"800-900k\",\"900-1 million\", \"Above 1 million\"])\nsetorder= new_df.groupby('Credit_Category')['TARGET'].mean().sort_values(ascending=False)\nax10 = sns.barplot(x='Credit_Category', y= 'TARGET', data=new_df, order = setorder.index);\nax10.set_title(\"Target by Credit Category\", fontsize=20);\nplt.show()\n\n\n\n#No. of people who default\nprint(new_df.loc[new_df[\"TARGET\"]==0, 'Credit_Category',].value_counts().sort_index())\n\n#No. of people who repayed\nprint(new_df.loc[new_df[\"TARGET\"]==1, 'Credit_Category',].value_counts().sort_index())\n\nnew_df['Credit_Category'].value_counts().sort_index()\n# This will be useful for our first recommendation\n\n\n#temp = new_df[\"Credit_Category\"].value_counts()\n#df1 = pd.DataFrame({\"Credit_Category\": temp.index,'Number of contracts': temp.values})\n\n## Calculate the percentage of target=1 per category value\n#cat_perc = new_df[[\"Credit_Category\", 'TARGET']].groupby([\"Credit_Category\"],as_index=False).mean()\n#cat_perc[\"TARGET\"] = cat_perc[\"TARGET\"]*100\n#cat_perc.sort_values(by='TARGET', ascending=False, inplace=True)\n\n#fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12,6))\n \n#s = sns.countplot(ax=ax1, \n# x = \"Credit_Category\", \n# data=new_df,\n# hue =\"TARGET\",\n# order=cat_perc[\"Credit_Category\"],\n# palette=['g','r'])\n \n\n#ax1.set_title(\"Credit Category\", fontdict={'fontsize' : 10, 'fontweight' : 3, 'color' : 'Blue'}) \n#ax1.legend(['Repayer','Defaulter'])\n \n## If the plot is not readable, use the log scale.\n##if ylog:\n## ax1.set_yscale('log')\n## ax1.set_ylabel(\"Count (log)\",fontdict={'fontsize' : 10, 'fontweight' : 3, 'color' : 'Blue'}) \n \n#s.set_xticklabels(s.get_xticklabels(),rotation=90)\n \n#s = sns.barplot(ax=ax2, x = \"Credit_Category\", y='TARGET', order=cat_perc[\"Credit_Category\"], data=cat_perc, palette='Set2')\n \n#s.set_xticklabels(s.get_xticklabels(),rotation=90)\n#plt.ylabel('Percent of Defaulters [%]', fontsize=10)\n#plt.tick_params(axis='both', which='major', labelsize=10)\n#ax2.set_title(\"Credit Category\" + \" Defaulter %\", fontdict={'fontsize' : 15, 'fontweight' : 5, 'color' : 'Blue'}) \n\n#plt.show();\n",
"_____no_output_____"
],
[
"new_df.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 307511 entries, 0 to 307510\nData columns (total 37 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 TARGET 307511 non-null int64 \n 1 NAME_CONTRACT_TYPE 307511 non-null category\n 2 CODE_GENDER 307511 non-null category\n 3 FLAG_OWN_CAR 307511 non-null category\n 4 FLAG_OWN_REALTY 307511 non-null category\n 5 CNT_CHILDREN 307511 non-null int64 \n 6 AMT_INCOME_TOTAL 307511 non-null float64 \n 7 AMT_CREDIT 307511 non-null float64 \n 8 AMT_ANNUITY 307511 non-null float64 \n 9 NAME_INCOME_TYPE 307511 non-null category\n 10 NAME_EDUCATION_TYPE 307511 non-null category\n 11 NAME_FAMILY_STATUS 307511 non-null category\n 12 NAME_HOUSING_TYPE 307511 non-null category\n 13 REGION_POPULATION_RELATIVE 307511 non-null float64 \n 14 DAYS_REGISTRATION 307511 non-null float64 \n 15 DAYS_ID_PUBLISH 307511 non-null int64 \n 16 FLAG_MOBIL 307511 non-null category\n 17 FLAG_EMP_PHONE 307511 non-null category\n 18 FLAG_WORK_PHONE 307511 non-null category\n 19 FLAG_CONT_MOBILE 307511 non-null category\n 20 FLAG_PHONE 307511 non-null category\n 21 FLAG_EMAIL 307511 non-null category\n 22 REGION_RATING_CLIENT 307511 non-null int64 \n 23 WEEKDAY_APPR_PROCESS_START 307511 non-null category\n 24 HOUR_APPR_PROCESS_START 307511 non-null int64 \n 25 REG_REGION_NOT_LIVE_REGION 307511 non-null category\n 26 LIVE_REGION_NOT_WORK_REGION 307511 non-null category\n 27 REG_CITY_NOT_LIVE_CITY 307511 non-null category\n 28 LIVE_CITY_NOT_WORK_CITY 307511 non-null category\n 29 ORGANIZATION_TYPE 307511 non-null category\n 30 EXT_SOURCE_2 307511 non-null float64 \n 31 DAYS_LAST_PHONE_CHANGE 307511 non-null float64 \n 32 FLAG_DOCUMENT_3 307511 non-null category\n 33 YEARS_BIRTH 307511 non-null int64 \n 34 YEARS_EMPLOYED 307511 non-null int64 \n 35 YEARS_BIRTH_CAT 306851 non-null category\n 36 Credit_Category 307511 non-null category\ndtypes: category(23), float64(7), int64(7)\nmemory usage: 51.9 MB\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4aa6b2fb9d2e256d9496e62b8cad179372b30538
| 224,879 |
ipynb
|
Jupyter Notebook
|
Titanic Model.ipynb
|
mongzkey/Titanic-Model
|
85a3964eedbcc0f85e4c3548f32f760bd4f4f633
|
[
"MIT"
] | null | null | null |
Titanic Model.ipynb
|
mongzkey/Titanic-Model
|
85a3964eedbcc0f85e4c3548f32f760bd4f4f633
|
[
"MIT"
] | null | null | null |
Titanic Model.ipynb
|
mongzkey/Titanic-Model
|
85a3964eedbcc0f85e4c3548f32f760bd4f4f633
|
[
"MIT"
] | null | null | null | 91.975051 | 61,652 | 0.760582 |
[
[
[
"### PROBLEM DEFINITION\n\n### Knowing from a training set of samples listing passengers who survived or did not survive the Titanic disaster, Can our model determine based on a given test dataset not containing the survival information, if these passengers in the test dataset survived or not.",
"_____no_output_____"
],
[
"## BackGround\n\n\n### - On April 15, 1912, during her maiden voyage, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. Translated 32% survival rate.\n\n### -One of the reasons that the shipwreck led to such loss of life was that there were not enough lifeboats for the passengers and crew.\n\n### -Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class.",
"_____no_output_____"
],
[
"# Import Libraries",
"_____no_output_____"
]
],
[
[
"#Data Wrangling and Visualization \nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\nimport warnings\n%matplotlib inline\nwarnings.filterwarnings('ignore')\npd.set_option('display.max_columns', 100)\n\n#machine learning\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.tree import DecisionTreeClassifier\n\n",
"_____no_output_____"
]
],
[
[
"#### Acquire The DataSets",
"_____no_output_____"
]
],
[
[
"test_df=pd.read_csv('./kaggle-titanic-master/input/test.csv')\ntrain_df=pd.read_csv('./kaggle-titanic-master/input/train.csv')",
"_____no_output_____"
]
],
[
[
"## DATA ANALYSIS",
"_____no_output_____"
]
],
[
[
"train_df.head()",
"_____no_output_____"
]
],
[
[
"### Data Dictionary\n\n* Survived: 0 = No, 1 = Yes\n* pclass: Ticket class 1 = 1st, 2 = 2nd, 3 = 3rd\n* sibsp: # of siblings / spouses aboard the Titanic\n* parch: # of parents / children aboard the Titanic\n* ticket: Ticket number\n* cabin: Cabin number\n* embarked: Port of Embarkation C = Cherbourg, Q = Queenstown, S = Southampton",
"_____no_output_____"
]
],
[
[
"train_df.shape",
"_____no_output_____"
],
[
"test_df.shape",
"_____no_output_____"
],
[
"test_df.head()",
"_____no_output_____"
],
[
"train_df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 891 entries, 0 to 890\nData columns (total 12 columns):\nPassengerId 891 non-null int64\nSurvived 891 non-null int64\nPclass 891 non-null int64\nName 891 non-null object\nSex 891 non-null object\nAge 714 non-null float64\nSibSp 891 non-null int64\nParch 891 non-null int64\nTicket 891 non-null object\nFare 891 non-null float64\nCabin 204 non-null object\nEmbarked 889 non-null object\ndtypes: float64(2), int64(5), object(5)\nmemory usage: 83.6+ KB\n"
]
],
[
[
"##### Age,cabin and embarked have missing values",
"_____no_output_____"
]
],
[
[
"test_df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 418 entries, 0 to 417\nData columns (total 11 columns):\nPassengerId 418 non-null int64\nPclass 418 non-null int64\nName 418 non-null object\nSex 418 non-null object\nAge 332 non-null float64\nSibSp 418 non-null int64\nParch 418 non-null int64\nTicket 418 non-null object\nFare 417 non-null float64\nCabin 91 non-null object\nEmbarked 418 non-null object\ndtypes: float64(2), int64(4), object(5)\nmemory usage: 36.0+ KB\n"
]
],
[
[
"##### Age,Fare and Cabin have missing values",
"_____no_output_____"
]
],
[
[
"train_df.isnull()",
"_____no_output_____"
],
[
"train_df.describe()",
"_____no_output_____"
],
[
"print(train_df.describe(include=['O']))\ntest_df.describe(include=['O'])",
" Name Sex Ticket Cabin Embarked\ncount 891 891 891 204 889\nunique 891 2 681 147 3\ntop Bourke, Miss. Mary male CA. 2343 G6 S\nfreq 1 577 7 4 644\n"
]
],
[
[
"### Visualization",
"_____no_output_____"
]
],
[
[
"def bar_chart(feature):\n survived = train_df[train_df['Survived']==1][feature].value_counts()\n dead = train_df[train_df['Survived']==0][feature].value_counts()\n df = pd.DataFrame([survived,dead])\n df.index = ['Survived','Dead']\n df.plot(kind='bar', figsize=(10,5))",
"_____no_output_____"
],
[
"bar_chart('Sex')",
"_____no_output_____"
],
[
"bar_chart('Pclass')",
"_____no_output_____"
],
[
"bar_chart('SibSp')",
"_____no_output_____"
],
[
"bar_chart('Parch')",
"_____no_output_____"
],
[
"bar_chart('Embarked')",
"_____no_output_____"
]
],
[
[
"### DATA WRANGLING",
"_____no_output_____"
],
[
"Correlation Anaysis",
"_____no_output_____"
]
],
[
[
"sns.heatmap(train_df.corr(), annot=True, cmap='RdYlGn', linewidth=0.4)",
"_____no_output_____"
],
[
"def impute(feature):\n dfs=[train_df,test_df]\n for df in dfs:\n df[feature][df[feature].isnull()]=np.random.normal(df[feature].mean(),df[feature].std())\ndef Drop_feature(feature):\n dfs=[train_df,test_df]\n for df in dfs:\n df.drop(feature,axis=1,inplace=True)",
"_____no_output_____"
]
],
[
[
"Utility Functions to impute and drop features",
"_____no_output_____"
]
],
[
[
"train_df.describe()",
"_____no_output_____"
]
],
[
[
"Decription of the numerical features",
"_____no_output_____"
]
],
[
[
"train_df.describe(include ='O')",
"_____no_output_____"
]
],
[
[
"Description of the object features",
"_____no_output_____"
]
],
[
[
"impute('Fare')\nimpute('Age')\nDrop_feature('Name')\nDrop_feature('Cabin')\nDrop_feature('Ticket')\n",
"_____no_output_____"
],
[
"dfs=[train_df,test_df]\n\nGender={\"male\":0 ,\"female\":1}\nTowns={\"S\":1, \"Q\":2 ,\"C\":3}\nfor df in dfs:\n df.Age=df.Age.astype(int)\n df[\"Sex\"]=df[\"Sex\"].map(Gender)\n df[\"Embarked\"]=df[\"Embarked\"].map(Towns)\n df.loc[df['Age']<=15,'Age']=0\n df.loc[(df['Age']>15) & (df.Age<=30),'Age']=1\n df.loc[(df['Age']>30) & (df.Age<=45),'Age']=2\n df.loc[(df['Age']>45) & (df.Age<=60),'Age']=3\n df.loc[df['Age']>45,'Age']=4\n",
"_____no_output_____"
]
],
[
[
"Transform Categorical features to discrete feature",
"_____no_output_____"
]
],
[
[
"impute('Embarked')",
"_____no_output_____"
],
[
"sns.heatmap(train_df.corr(), annot=True, cmap='RdYlGn', linewidth=0.4)",
"_____no_output_____"
],
[
"corr_ds=train_df.corr()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4aa6bc8ee026f24de97adf6c83ecbcbbef069d69
| 534,639 |
ipynb
|
Jupyter Notebook
|
notebooks/2_data_understanding (2.1).ipynb
|
dunfrey/BCG-GAMMA-Challenge-2021
|
cd8c20ca67c7de47fca8d03175289866a015f6f9
|
[
"MIT"
] | 2 |
2021-07-05T20:14:14.000Z
|
2021-07-06T10:53:31.000Z
|
notebooks/2_data_understanding (2.1).ipynb
|
dunfrey/BCG-GAMMA-Challenge-2021
|
cd8c20ca67c7de47fca8d03175289866a015f6f9
|
[
"MIT"
] | null | null | null |
notebooks/2_data_understanding (2.1).ipynb
|
dunfrey/BCG-GAMMA-Challenge-2021
|
cd8c20ca67c7de47fca8d03175289866a015f6f9
|
[
"MIT"
] | 1 |
2021-07-04T07:22:52.000Z
|
2021-07-04T07:22:52.000Z
| 87.530943 | 77,724 | 0.672624 |
[
[
[
"import warnings\nimport sys\nsys.path.insert(0, '../src')",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"from felix_ml_tools import macgyver as mg",
"_____no_output_____"
],
[
"from preprocess import *",
"_____no_output_____"
],
[
"from sklearn.linear_model import LassoCV, Lasso",
"_____no_output_____"
],
[
"warnings.filterwarnings('ignore')\n\npd.set_option(\"max_columns\", None)\npd.set_option(\"max_rows\", None)\npd.set_option('display.float_format', lambda x: '%.3f' % x)\n%matplotlib inline ",
"_____no_output_____"
],
[
"# todas as UFs do Nordeste\nUFs_NORDESTE = ['AL', 'BA', 'CE', 'MA', 'PB', 'PE', 'PI', 'RN', 'SE']\nUFs_NORDESTE_NAMES = ['Alagoas', 'Bahia', 'Ceará', 'Maranhão', 'Paraíba', 'Pernambuco', 'Piauí', 'Rio Grande do Norte', 'Sergipe']",
"_____no_output_____"
]
],
[
[
"# Intro",
"_____no_output_____"
],
[
"Ingesting some base data",
"_____no_output_____"
],
[
"-----------\n## Compreender os índices do CRAS",
"_____no_output_____"
]
],
[
[
"idcras = pd.read_excel(\n '../../dataset/GAMMAChallenge21Dados/6. Assistencia Social/IDCRAS.xlsx',\n sheet_name = 'dados'\n)",
"_____no_output_____"
],
[
"inspect(idcras);",
"shape: (64215, 10)\ncolumns: ['ano', 'id_cras', 'cod_ibge', 'uf', 'nome_municipio', 'ind_hora_func', 'ind_estru_fisic', 'ind_servi', 'ind_rh', 'id_cras.1']\n"
],
[
"idcras = generates_normalized_column(idcras, \n column_to_normalize='nome_municipio', \n column_normalized='nome_municipio_norm')",
"_____no_output_____"
],
[
"idcras = keep_last_date(idcras, column_dates='ano')",
"_____no_output_____"
],
[
"columns_to_keep = ['uf', 'nome_municipio', 'nome_municipio_norm', 'cod_ibge', 'ind_estru_fisic', 'ind_servi', 'ind_rh', 'id_cras.1']",
"_____no_output_____"
],
[
"idcras = idcras[columns_to_keep]",
"_____no_output_____"
],
[
"# há cidades com mais de um nucleo CRAS\nidcras = (idcras[idcras['uf'].isin(UFs_NORDESTE)]\n .groupby(['uf', 'nome_municipio', 'nome_municipio_norm', 'cod_ibge'])[\n ['ind_estru_fisic', 'ind_servi', 'ind_rh', 'id_cras.1']\n ]\n .mean())",
"_____no_output_____"
]
],
[
[
"Como são os índices médios das unidades públicas CRAS para estados e municipios?",
"_____no_output_____"
]
],
[
[
"idcras_cities = (\n idcras.groupby(['nome_municipio', \n 'nome_municipio_norm', \n 'cod_ibge'])[['ind_estru_fisic', \n 'ind_servi', 'ind_rh', \n 'id_cras.1']]\n .mean()\n .reset_index()\n)\n\ninspect(idcras_cities);",
"shape: (1793, 7)\ncolumns: ['nome_municipio', 'nome_municipio_norm', 'cod_ibge', 'ind_estru_fisic', 'ind_servi', 'ind_rh', 'id_cras.1']\n"
],
[
"idcras_states = (\n idcras.groupby(['uf'])[['ind_estru_fisic', \n 'ind_servi', \n 'ind_rh', \n 'id_cras.1']]\n .mean()\n .sort_values('uf')\n .reset_index()\n)\n\ninspect(idcras_states);",
"shape: (9, 5)\ncolumns: ['uf', 'ind_estru_fisic', 'ind_servi', 'ind_rh', 'id_cras.1']\n"
]
],
[
[
"-----------\n### Registros CRAS RMA",
"_____no_output_____"
]
],
[
[
"## Bloco I – Famílias em acompanhamento pelo PAIF\nA. Volume de famílias em acompanhamento pelo PAIF\nA.1. Total de famílias em acompanhamento pelo PAIF\nA.2. Novas famílias inseridas no acompanhamento do PAIF no mês de referência\n\nB. Perfil de famílias inseridas em acompanhamento no PAIF, no mês\nB.1. Famílias em situação de extrema pobreza\nB.2. Famílias beneficiárias do Programa Bolsa Família\nB.3. Famílias beneficiárias do Programa Bolsa Família, em descumprimento de condicionalidades\nB.4. Famílias com membros beneficiários do BPC\nB.5. Famílias com crianças/adolescentes em situação de trabalho infantil\nB.6. Famílias com crianças e adolescentes em Serviço de Acolhimento\n\n## Bloco II – Atendimentos individualizados realizados no CRAS\nC. Volume de atendimentos individualizados realizados no CRAS\nC.1. Total de atendimentos individualizados realizados, no mês\nC.2. Famílias encaminhadas para inclusão no Cadastro Único\nC.3. Famílias encaminhadas para atualização cadastral no Cadastro Único\nC.4. Indivíduos encaminhados para acesso ao BPC\nC.5. Famílias encaminhadas para o CREAS\nC.6. Visitas domiciliares\n\n## Bloco III - Atendimentos coletivos realizados no CRAS\nD. Volume dos Serviços de Convivência e Fortalecimentos de Vínculos\nD.1. Famílias participando regularmente de grupos no âmbito do PAIF\nD.2. Crianças de 0 a 6 anos em Serviços de Convivência e Fortalecimentos de Vínculos\nD.3. Crianças/ adolescentes de 7 a 14 anos em Serv. de Convivência e Fortalecimento de Vínculos\nD.4. Adolescentes de 15 a 17 anos em Serviços de Convivência e Fortalecimentos de Vínculos\nD.5. Idosos em Serviços de Convivência e Fortalecimentos de Vínculos para idosos\nD.6. Pessoas que participaram de palestras, oficinas e outras atividades coletivas de caráter não continuado\nD.7. Pessoas com deficiência, participando dos Serviços de Convivência ou dos grupos do PAIF",
"_____no_output_____"
]
],
[
[
"cras_rma = pd.read_excel(\n '../../dataset/GAMMAChallenge21Dados/6. Assistencia Social/RMA.xlsx',\n sheet_name = 'dados_CRAS'\n)",
"_____no_output_____"
],
[
"cras_rma = generates_normalized_column(cras_rma, \n column_to_normalize='nome_municipio', \n column_normalized='nome_municipio_norm')",
"_____no_output_____"
],
[
"cras_rma = keep_last_date(cras_rma, column_dates='ano')",
"_____no_output_____"
],
[
"inspect(cras_rma);",
"shape: (93517, 32)\ncolumns: ['ano', 'mes_referencia', 'regiao', 'uf', 'cod_ibge', 'nome_municipio', 'porte_municipio', 'nome_unidade', 'numero_cras', 'endereco_cras', 'a1', 'a2', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'nome_municipio_norm']\n"
],
[
"cras_rma_states = cras_rma[cras_rma['uf'].isin(UFs_NORDESTE)]\ncras_rma_states_grouped = (\n cras_rma_states\n .groupby(['uf', 'nome_municipio_norm'])\n [['cod_ibge', 'a1', 'a2', 'b1', 'b2', 'b3', 'b5', 'b6', 'c1', 'c6', 'd1', 'd4']]\n .mean()\n .fillna(0)\n .astype(int)\n)",
"_____no_output_____"
],
[
"registry_cras_rma_states_grouped = (\n cras_rma_states_grouped.groupby(['uf'])[['a1', 'a2', 'b1', 'b2', 'b3', 'b5', 'b6', 'c1', 'c6', 'd1', 'd4']]\n .mean()\n .sort_values('uf')\n)",
"_____no_output_____"
],
[
"registry_cras_rma_states_grouped = (\n registry_cras_rma_states_grouped\n .rename(columns = {\n 'a1': 'a1 Total de famílias em acompanhamento pelo PAIF', \n 'a2': 'a2 Novas famílias inseridas no acompanhamento do PAIF no mês de referência',\n 'b1': 'b1 PAIF Famílias em situação de extrema pobreza',\n 'b2': 'b2 PAIF Famílias beneficiárias do Programa Bolsa Família',\n 'b3': 'b3 PAIF Famílias beneficiárias do Programa Bolsa Família, em descumprimento de condicionalidades',\n 'b5': 'b5 PAIF Famílias com crianças/adolescentes em situação de trabalho infantil',\n 'b6': 'b6 PAIF Famílias com crianças e adolescentes em Serviço de Acolhimento',\n 'c1': 'c1 Total de atendimentos individualizados realizados, no mês',\n 'c6': 'c6 Visitas domiciliares',\n 'd1': 'd1 Famílias participando regularmente de grupos no âmbito do PAIF',\n 'd4': 'd4 Adolescentes de 15 a 17 anos em Serviços de Convivência e Fortalecimentos de Vínculos'\n }, \n inplace = False)\n)",
"_____no_output_____"
],
[
"registry_cras_rma_states_grouped",
"_____no_output_____"
]
],
[
[
"## Target Population",
"_____no_output_____"
]
],
[
[
"Ingest dataset to define target population",
"_____no_output_____"
]
],
[
[
"sim_pf_homcidios = pd.read_parquet('../../dataset/handled/sim_pf_homcidios.parquet')",
"_____no_output_____"
],
[
"sim_pf_homcidios = sim_pf_homcidios[sim_pf_homcidios['uf'].isin(UFs_NORDESTE)]",
"_____no_output_____"
],
[
"ibge_municipio_pib = pd.read_parquet('../../dataset/handled/ibge_municipio_pib.parquet')",
"_____no_output_____"
],
[
"ibge_estados = pd.read_excel(\n '../../dataset/GAMMAChallenge21Dados/3. Atlas de Desenvolvimento Humano/Atlas 2013_municipal, estadual e Brasil.xlsx',\n sheet_name = 'UF 91-00-10'\n)",
"_____no_output_____"
],
[
"ibge_estados = keep_last_date(ibge_estados, 'ANO')",
"_____no_output_____"
],
[
"ibge_estados = ibge_estados[ibge_estados.UFN.isin(UFs_NORDESTE_NAMES)]",
"_____no_output_____"
],
[
"inspect(ibge_estados);",
"shape: (9, 235)\ncolumns: ['ANO', 'UF', 'UFN', 'ESPVIDA', 'FECTOT', 'MORT1', 'MORT5', 'RAZDEP', 'SOBRE40', 'SOBRE60', 'T_ENV', 'E_ANOSESTUDO', 'T_ANALF11A14', 'T_ANALF15A17', 'T_ANALF15M', 'T_ANALF18A24', 'T_ANALF18M', 'T_ANALF25A29', 'T_ANALF25M', 'T_ATRASO_0_BASICO', 'T_ATRASO_0_FUND', 'T_ATRASO_0_MED', 'T_ATRASO_1_BASICO', 'T_ATRASO_1_FUND', 'T_ATRASO_1_MED', 'T_ATRASO_2_BASICO', 'T_ATRASO_2_FUND', 'T_ATRASO_2_MED', 'T_FBBAS', 'T_FBFUND', 'T_FBMED', 'T_FBPRE', 'T_FBSUPER', 'T_FLBAS', 'T_FLFUND', 'T_FLMED', 'T_FLPRE', 'T_FLSUPER', 'T_FREQ0A3', 'T_FREQ11A14', 'T_FREQ15A17', 'T_FREQ18A24', 'T_FREQ25A29', 'T_FREQ4A5', 'T_FREQ4A6', 'T_FREQ5A6', 'T_FREQ6', 'T_FREQ6A14', 'T_FREQ6A17', 'T_FREQFUND1517', 'T_FREQFUND1824', 'T_FREQFUND45', 'T_FREQMED1824', 'T_FREQMED614', 'T_FREQSUPER1517', 'T_FUND11A13', 'T_FUND12A14', 'T_FUND15A17', 'T_FUND16A18', 'T_FUND18A24', 'T_FUND18M', 'T_FUND25M', 'T_MED18A20', 'T_MED18A24', 'T_MED18M', 'T_MED19A21', 'T_MED25M', 'T_SUPER25M', 'CORTE1', 'CORTE2', 'CORTE3', 'CORTE4', 'CORTE9', 'GINI', 'PIND', 'PINDCRI', 'PMPOB', 'PMPOBCRI', 'PPOB', 'PPOBCRI', 'PREN10RICOS', 'PREN20', 'PREN20RICOS', 'PREN40', 'PREN60', 'PREN80', 'PRENTRAB', 'R1040', 'R2040', 'RDPC', 'RDPC1', 'RDPC10', 'RDPC2', 'RDPC3', 'RDPC4', 'RDPC5', 'RDPCT', 'RIND', 'RMPOB', 'RPOB', 'THEIL', 'CPR', 'EMP', 'P_AGRO', 'P_COM', 'P_CONSTR', 'P_EXTR', 'P_FORMAL', 'P_FUND', 'P_MED', 'P_SERV', 'P_SIUP', 'P_SUPER', 'P_TRANSF', 'REN0', 'REN1', 'REN2', 'REN3', 'REN5', 'RENOCUP', 'T_ATIV', 'T_ATIV1014', 'T_ATIV1517', 'T_ATIV1824', 'T_ATIV18M', 'T_ATIV2529', 'T_DES', 'T_DES1014', 'T_DES1517', 'T_DES1824', 'T_DES18M', 'T_DES2529', 'THEILtrab', 'TRABCC', 'TRABPUB', 'TRABSC', 'T_AGUA', 'T_BANAGUA', 'T_DENS', 'T_LIXO', 'T_LUZ', 'AGUA_ESGOTO', 'PAREDE', 'T_CRIFUNDIN_TODOS', 'T_FORA4A5', 'T_FORA6A14', 'T_FUNDIN_TODOS', 'T_FUNDIN_TODOS_MMEIO', 'T_FUNDIN18MINF', 'T_M10A14CF', 'T_M15A17CF', 'T_MULCHEFEFIF014', 'T_NESTUDA_NTRAB_MMEIO', 'T_OCUPDESLOC_1', 'T_RMAXIDOSO', 'T_SLUZ', 'HOMEM0A4', 'HOMEM10A14', 'HOMEM15A19', 'HOMEM20A24', 'HOMEM25A29', 'HOMEM30A34', 'HOMEM35A39', 'HOMEM40A44', 'HOMEM45A49', 'HOMEM50A54', 'HOMEM55A59', 'HOMEM5A9', 'HOMEM60A64', 'HOMEM65A69', 'HOMEM70A74', 'HOMEM75A79', 'HOMEMTOT', 'HOMENS80', 'MULH0A4', 'MULH10A14', 'MULH15A19', 'MULH20A24', 'MULH25A29', 'MULH30A34', 'MULH35A39', 'MULH40A44', 'MULH45A49', 'MULH50A54', 'MULH55A59', 'MULH5A9', 'MULH60A64', 'MULH65A69', 'MULH70A74', 'MULH75A79', 'MULHER80', 'MULHERTOT', 'PEA', 'PEA1014', 'PEA1517', 'PEA18M', 'peso1', 'PESO1114', 'PESO1113', 'PESO1214', 'peso13', 'PESO15', 'peso1517', 'PESO1524', 'PESO1618', 'PESO18', 'Peso1820', 'PESO1824', 'Peso1921', 'PESO25', 'peso4', 'peso5', 'peso6', 'PESO610', 'Peso617', 'PESO65', 'PESOM1014', 'PESOM1517', 'PESOM15M', 'PESOM25M', 'pesoRUR', 'pesotot', 'pesourb', 'PIA', 'PIA1014', 'PIA1517', 'PIA18M', 'POP', 'POPT', 'I_ESCOLARIDADE', 'I_FREQ_PROP', 'IDHM', 'IDHM_E', 'IDHM_L', 'IDHM_R']\n"
],
[
"mortes_estados_norm = dict()\n\nfor estado in ibge_estados.UFN.sort_values().to_list():\n \n mortes_estados_norm[estado] = (\n (sim_pf_homcidios[sim_pf_homcidios.nomeUf == estado]\n .groupby('uf')['uf']\n .count()\n .values[0]) / (ibge_estados[ibge_estados.UFN == estado]\n .POP\n .values[0])*1000\n )\n \nmortes_estados_norm = pd.DataFrame.from_dict(mortes_estados_norm, orient='index', columns=['mortes_norm'])",
"_____no_output_____"
],
[
"mortes_estados_norm['mortes_norm']",
"_____no_output_____"
],
[
"homicidios_municipios = sim_pf_homcidios.groupby(['uf','municipioCodigo','nomeMunicipioNorm'])[['contador']].count().astype(int).reset_index()",
"_____no_output_____"
],
[
"inspect(homicidios_municipios);",
"shape: (1563, 4)\ncolumns: ['uf', 'municipioCodigo', 'nomeMunicipioNorm', 'contador']\n"
],
[
"ibge_municipio_populacao_estimada = pd.read_parquet('../../dataset/handled/ibge_municipio_populacao_estimada.parquet')",
"_____no_output_____"
],
[
"ibge_municipio_populacao_estimada = generates_normalized_column(ibge_municipio_populacao_estimada, 'nomeMunicipio', 'nome_municipio_norm')",
"_____no_output_____"
],
[
"inspect(ibge_municipio_populacao_estimada);",
"shape: (5570, 9)\ncolumns: ['uf', 'ufCodigo', 'nomeMunicipio', 'municipioCodigo', 'populacaoEstimada', 'ano', 'municipioCodigo6d', 'faixaPopulacaoEstimada', 'nome_municipio_norm']\n"
],
[
"cras_rma_municipios = cras_rma.groupby(['uf','cod_ibge','nome_municipio_norm'])[[ \n 'a1', 'a2', \n 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', \n 'c1', 'c2', 'c3', 'c4', 'c5', 'c6',\n 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7'\n ]].mean().fillna(0).astype(int).reset_index()",
"_____no_output_____"
],
[
"inspect(cras_rma_municipios);",
"shape: (5525, 24)\ncolumns: ['uf', 'cod_ibge', 'nome_municipio_norm', 'a1', 'a2', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7']\n"
],
[
"list_pop = list()\nlist_mortes_norm = list()\n\nfor cod in cras_rma_municipios.cod_ibge:\n populacao = ibge_municipio_populacao_estimada[ibge_municipio_populacao_estimada['municipioCodigo'].str.contains(str(cod))]['populacaoEstimada'].astype(int).values[0]\n list_pop.append(populacao)\n if homicidios_municipios[(homicidios_municipios['municipioCodigo'].str.contains(str(cod)))&(ibge_municipio_populacao_estimada['faixaPopulacaoEstimada'] == '0:10000')].any().any():\n mortes = homicidios_municipios[(homicidios_municipios['municipioCodigo'].str.contains(str(cod)))]['contador'].astype(int).values[0]\n mortes /= populacao\n mortes *= 10000\n else:\n mortes = None\n list_mortes_norm.append(mortes)",
"_____no_output_____"
]
],
[
[
"## Hypothesis",
"_____no_output_____"
],
[
"### Hypothesis 2",
"_____no_output_____"
]
],
[
[
"2. A disponibilização de serviços públicos de assistência social ajuda a minimizar os níveis de violência nas cidades",
"_____no_output_____"
]
],
[
[
"plot_grouped_df(sim_pf_homcidios.groupby('uf')['uf'], \n xlabel='Quantidade de Homicidios', \n ylabel='UF',\n figsize=(17,3))\n\nmortes_estados_norm.plot(kind='bar',\n figsize=(17,3),\n rot=0, \n grid=True).set_ylabel(\"Quantidade de Homicidios Normalizado\")",
"_____no_output_____"
],
[
"registry_cras_rma_states_grouped['mortes'] = mortes_estados_norm['mortes_norm'].values\nregistry_cras_rma_states_grouped",
"_____no_output_____"
]
],
[
[
"#### (2.1) Estados com CRAS suportam moradores com dificuldade",
"_____no_output_____"
]
],
[
[
"registry_cras_rma_states_grouped.plot(kind='bar', \n title='Registro de Atividades - CRAS',\n figsize=(17,5), \n ylabel='Registros',\n xlabel='UF',\n rot=0, \n grid=True)",
"_____no_output_____"
]
],
[
[
"Feature Importance using LASSO",
"_____no_output_____"
]
],
[
[
"X = registry_cras_rma_states_grouped.iloc[:,:-1]\ny = registry_cras_rma_states_grouped.iloc[:,-1:]",
"_____no_output_____"
],
[
"reg = LassoCV()\nreg.fit(X, y)\nprint(\"Melhor valor de alpha usando LassoCV: %f\" % reg.alpha_)\nprint(\"Melhor score usando LassoCV: %f\" % reg.score(X,y))\ncoef = pd.Series(reg.coef_, index = X.columns)",
"Melhor valor de alpha usando LassoCV: 3.350955\nMelhor score usando LassoCV: 0.562815\n"
],
[
"print(\"LASSO manteve \" + str(sum(coef != 0)) + \" variaveis, e elimina \" + str(sum(coef == 0)) + \" variaveis\")",
"LASSO manteve 3 variaveis, e elimina 8 variaveis\n"
],
[
"imp_coef = coef.sort_values()\nimport matplotlib\nmatplotlib.rcParams['figure.figsize'] = (5, 5)\nimp_coef.plot(kind = \"barh\")\nplt.title(\"Feature importance usando LASSO\")",
"_____no_output_____"
],
[
"trabalhos_cras_estados_totfam = (\n registry_cras_rma_states_grouped[['a1 Total de famílias em acompanhamento pelo PAIF',\n 'c1 Total de atendimentos individualizados realizados, no mês']]\n)\n\ntrabalhos_cras_estados_extpobres = (\n registry_cras_rma_states_grouped[['b1 PAIF Famílias em situação de extrema pobreza']]\n)\n\ntrabalhos_cras_estados_acompanha = (\n registry_cras_rma_states_grouped[['b5 PAIF Famílias com crianças/adolescentes em situação de trabalho infantil',\n 'b6 PAIF Famílias com crianças e adolescentes em Serviço de Acolhimento']]\n)\n\ntrabalhos_cras_estados_atendimento = (\n registry_cras_rma_states_grouped[['d1 Famílias participando regularmente de grupos no âmbito do PAIF',\n 'd4 Adolescentes de 15 a 17 anos em Serviços de Convivência e Fortalecimentos de Vínculos']]\n)",
"_____no_output_____"
],
[
"def plot_cras_registries(df):\n df.plot(kind='bar', \n title='Registro de Atividades - CRAS',\n figsize=(10,5), \n ylabel='Registros',\n xlabel='UF',\n fontsize=12,\n colormap='Pastel2',\n rot=0, \n grid=True)",
"_____no_output_____"
],
[
"plot_cras_registries(trabalhos_cras_estados_totfam)\nplot_cras_registries(trabalhos_cras_estados_extpobres)\nplot_cras_registries(trabalhos_cras_estados_acompanha)\nplot_cras_registries(trabalhos_cras_estados_atendimento)\n",
"_____no_output_____"
]
],
[
[
"## Recomendação\n\nO CRAS demonstra que, se rankear-mos os estados entra os mais e menos violentos, onde ocorre maior média do índice de registros apresentado por unidades públicas CRAS, o estado tende a controlar o números de homicidios\n\n- índices na identificação de famílias em situação de extrema pobreza\n- índices na identificação de trabalho infantil e acolhimento\n- índices na participação das famílias em grupos no âmbito do PAIF\n",
"_____no_output_____"
],
[
"---------------",
"_____no_output_____"
],
[
"#### (2.2) Estados com CRAS suportam moradores com dificuldade",
"_____no_output_____"
]
],
[
[
"#cras_municipios['populacao'] = list_pop\ncras_rma_municipios['Mortes/Populacao'] = list_mortes_norm",
"_____no_output_____"
],
[
"inspect(cras_rma_municipios);",
"shape: (5525, 25)\ncolumns: ['uf', 'cod_ibge', 'nome_municipio_norm', 'a1', 'a2', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'Mortes/Populacao']\n"
],
[
"cras_rma_municipios = cras_rma_municipios.dropna()",
"_____no_output_____"
],
[
"cras_rma_municipios_mortes = (\n cras_rma_municipios[['uf', \n 'nome_municipio_norm', \n 'a1', 'a2', \n 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', \n 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'd1', \n 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', \n 'Mortes/Populacao']]\n .reset_index(drop=True)\n)",
"_____no_output_____"
],
[
"inspect(cras_rma_municipios_mortes);",
"shape: (612, 24)\ncolumns: ['uf', 'nome_municipio_norm', 'a1', 'a2', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'Mortes/Populacao']\n"
],
[
"corr = cras_rma_municipios_mortes.corr()\ncorr.style.background_gradient(cmap='hot')",
"_____no_output_____"
]
],
[
[
"### Não é possível identificar, através de correlação, que alguma ação registrada pelo CRAS tem influência nos níveis de violência das cidades",
"_____no_output_____"
]
],
[
[
"cor_target = abs(corr[\"Mortes/Populacao\"])\nrelevant_features = cor_target[cor_target>=0.07]",
"_____no_output_____"
],
[
"relevant_features",
"_____no_output_____"
],
[
"X = cras_rma_municipios_mortes.drop(['uf','nome_municipio_norm','Mortes/Populacao'],1)\ny = cras_rma_municipios_mortes['Mortes/Populacao']",
"_____no_output_____"
],
[
"reg = LassoCV()\nreg.fit(X, y)\nprint(\"Melhor valor de alpha usando LassoCV: %f\" % reg.alpha_)\nprint(\"Melhor score usando LassoCV: %f\" % reg.score(X,y))\ncoef = pd.Series(reg.coef_, index = X.columns)",
"Melhor valor de alpha usando LassoCV: 10.928281\nMelhor score usando LassoCV: 0.057438\n"
],
[
"print(\"LASSO manteve \" + str(sum(coef != 0)) + \" variaveis, e elimina \" + str(sum(coef == 0)) + \" variaveis\")",
"LASSO manteve 7 variaveis, e elimina 14 variaveis\n"
],
[
"imp_coef = coef.sort_values()\nimport matplotlib\nmatplotlib.rcParams['figure.figsize'] = (5, 5)\nimp_coef.plot(kind = \"barh\")\nplt.title(\"Feature importance usando LASSO\")",
"_____no_output_____"
]
],
[
[
"C.1. Total de atendimentos individualizados realizados, no mês\nC.3. Famílias encaminhadas para atualização cadastral no Cadastro Único\nD.6. Pessoas que participaram de palestras, oficinas e outras atividades coletivas de caráter não continuado",
"_____no_output_____"
],
[
"A partir do feature importance, tentar identificar alguma caraceristica relevante para recomendar",
"_____no_output_____"
]
],
[
[
"cras_municipios_feat_select = cras_rma_municipios_mortes[['uf', 'nome_municipio_norm', 'Mortes/Populacao', 'c1', 'c3', 'd6']].reset_index(drop=True)",
"_____no_output_____"
],
[
"corr = cras_municipios_feat_select.sort_values(by='Mortes/Populacao', ascending=False).corr()\ncorr.style.background_gradient(cmap='hot')",
"_____no_output_____"
]
],
[
[
"## Recomendação\n\nNão é possível recomendar uma ação do CRAS a nível municipal até este instante.",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"raw",
"code",
"markdown",
"raw",
"code",
"markdown",
"raw",
"code",
"markdown",
"code",
"raw",
"code",
"markdown",
"code",
"markdown",
"code",
"raw",
"code",
"markdown"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"raw"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"raw"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"raw"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"raw"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"raw",
"raw"
],
[
"code",
"code"
],
[
"markdown"
]
] |
4aa6bd87c16dbc68f9400f944d3022aa75b80962
| 552,487 |
ipynb
|
Jupyter Notebook
|
BTCForecast.ipynb
|
MWLKR/BTCForecast
|
9cafc9f682b230458c0824e1d126fd00a14538b2
|
[
"MIT"
] | 3 |
2019-11-22T12:59:29.000Z
|
2021-06-26T14:41:51.000Z
|
BTCForecast.ipynb
|
MWLKR/BTCForecast
|
9cafc9f682b230458c0824e1d126fd00a14538b2
|
[
"MIT"
] | null | null | null |
BTCForecast.ipynb
|
MWLKR/BTCForecast
|
9cafc9f682b230458c0824e1d126fd00a14538b2
|
[
"MIT"
] | 1 |
2019-11-22T13:54:40.000Z
|
2019-11-22T13:54:40.000Z
| 767.343056 | 122,698 | 0.932064 |
[
[
[
"import pandas as pd\nfrom pandas import DataFrame\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom datetime import datetime, timedelta\nfrom statsmodels.tsa.arima_model import ARIMA\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom scipy import stats\nimport statsmodels.api as sm\nfrom itertools import product\nfrom math import sqrt\nfrom sklearn.metrics import mean_squared_error \n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n%matplotlib inline\n\ncolors = [\"windows blue\", \"amber\", \"faded green\", \"dusty purple\"]\nsns.set(rc={\"figure.figsize\": (20,10), \"axes.titlesize\" : 18, \"axes.labelsize\" : 12, \n \"xtick.labelsize\" : 14, \"ytick.labelsize\" : 14 })",
"_____no_output_____"
],
[
"dateparse = lambda dates: pd.datetime.strptime(dates, '%m/%d/%Y')\ndf = pd.read_csv('BTCUSDTEST.csv', parse_dates=['Date'], index_col='Date', date_parser=dateparse)\ndf = df.loc[:, ~df.columns.str.contains('^Unnamed')]",
"_____no_output_____"
],
[
"df.sample(5)",
"_____no_output_____"
],
[
"# Extract the bitcoin data only\nbtc=df[df['Symbol']=='BTCUSD']\n# Drop some columns\nbtc.drop(['Volume', 'Market Cap'],axis=1,inplace=True) ",
"_____no_output_____"
],
[
"# Resampling to monthly frequency\nbtc_month = btc.resample('M').mean()",
"_____no_output_____"
],
[
"#seasonal_decompose(btc_month.close, freq=12).plot()\nseasonal_decompose(btc_month.Close, model='additive').plot()\nprint(\"Dickey–Fuller test: p=%f\" % adfuller(btc_month.Close)[1])",
"Dickey–Fuller test: p=0.446965\n"
],
[
"# Box-Cox Transformations\nbtc_month['close_box'], lmbda = stats.boxcox(btc_month.Close)\nprint(\"Dickey–Fuller test: p=%f\" % adfuller(btc_month.close_box)[1])",
"Dickey–Fuller test: p=0.655145\n"
],
[
"# Seasonal differentiation (12 months)\nbtc_month['box_diff_seasonal_12'] = btc_month.close_box - btc_month.close_box.shift(12)\nprint(\"Dickey–Fuller test: p=%f\" % adfuller(btc_month.box_diff_seasonal_12[12:])[1])",
"Dickey–Fuller test: p=0.486299\n"
],
[
"# Seasonal differentiation (3 months)\nbtc_month['box_diff_seasonal_3'] = btc_month.close_box - btc_month.close_box.shift(3)\nprint(\"Dickey–Fuller test: p=%f\" % adfuller(btc_month.box_diff_seasonal_3[3:])[1])",
"Dickey–Fuller test: p=0.113594\n"
],
[
"# Regular differentiation\nbtc_month['box_diff2'] = btc_month.box_diff_seasonal_12 - btc_month.box_diff_seasonal_12.shift(1)\n\n# STL-decomposition\nseasonal_decompose(btc_month.box_diff2[13:]).plot() \nprint(\"Dickey–Fuller test: p=%f\" % adfuller(btc_month.box_diff2[13:])[1])",
"Dickey–Fuller test: p=0.001415\n"
],
[
"#autocorrelation_plot(btc_month.close)\nplot_acf(btc_month.Close[13:].values.squeeze(), lags=12)\nplt.tight_layout()",
"_____no_output_____"
],
[
"# Initial approximation of parameters using Autocorrelation and Partial Autocorrelation Plots\nax = plt.subplot(211)\n# Plot the autocorrelation function\n#sm.graphics.tsa.plot_acf(btc_month.box_diff2[13:].values.squeeze(), lags=48, ax=ax)\nplot_acf(btc_month.box_diff2[13:].values.squeeze(), lags=12, ax=ax)\nax = plt.subplot(212)\n#sm.graphics.tsa.plot_pacf(btc_month.box_diff2[13:].values.squeeze(), lags=48, ax=ax)\nplot_pacf(btc_month.box_diff2[13:].values.squeeze(), lags=12, ax=ax)\nplt.tight_layout()",
"_____no_output_____"
],
[
"# Initial approximation of parameters\nqs = range(0, 3)\nps = range(0, 3)\nd=1\nparameters = product(ps, qs)\nparameters_list = list(parameters)\nlen(parameters_list)\n\n# Model Selection\nresults = []\nbest_aic = float(\"inf\")\nwarnings.filterwarnings('ignore')\nfor param in parameters_list:\n try:\n model = SARIMAX(btc_month.close_box, order=(param[0], d, param[1])).fit(disp=-1)\n except ValueError:\n print('bad parameter combination:', param)\n continue\n aic = model.aic\n if aic < best_aic:\n best_model = model\n best_aic = aic\n best_param = param\n results.append([param, model.aic])",
"_____no_output_____"
],
[
"# Best Models\nresult_table = pd.DataFrame(results)\nresult_table.columns = ['parameters', 'aic']\nprint(result_table.sort_values(by = 'aic', ascending=True).head())",
" parameters aic\n3 (1, 0) 174.098321\n1 (0, 1) 175.167060\n4 (1, 1) 176.097944\n6 (2, 0) 176.097967\n2 (0, 2) 176.153721\n"
],
[
"print(best_model.summary())",
" Statespace Model Results \n==============================================================================\nDep. Variable: close_box No. Observations: 50\nModel: SARIMAX(1, 1, 0) Log Likelihood -85.049\nDate: Wed, 20 Nov 2019 AIC 174.098\nTime: 08:52:08 BIC 177.882\nSample: 10-31-2015 HQIC 175.534\n - 11-30-2019 \nCovariance Type: opg \n==============================================================================\n coef std err z P>|z| [0.025 0.975]\n------------------------------------------------------------------------------\nar.L1 0.3886 0.071 5.490 0.000 0.250 0.527\nsigma2 1.8779 0.271 6.938 0.000 1.347 2.408\n===================================================================================\nLjung-Box (Q): 21.45 Jarque-Bera (JB): 8.08\nProb(Q): 0.99 Prob(JB): 0.02\nHeteroskedasticity (H): 4.13 Skew: 0.17\nProb(H) (two-sided): 0.01 Kurtosis: 4.96\n===================================================================================\n\nWarnings:\n[1] Covariance matrix calculated using the outer product of gradients (complex-step).\n"
],
[
"print(\"Dickey–Fuller test:: p=%f\" % adfuller(best_model.resid[13:])[1])",
"Dickey–Fuller test:: p=0.000000\n"
],
[
"best_model.plot_diagnostics(figsize=(15, 12))\nplt.show()",
"_____no_output_____"
],
[
"# Inverse Box-Cox Transformation Function\ndef invboxcox(y,lmbda):\n if lmbda == 0:\n return(np.exp(y))\n else:\n return(np.exp(np.log(lmbda*y+1)/lmbda))",
"_____no_output_____"
],
[
"# Prediction\nbtc_month_pred = btc_month[['Close']]\ndate_list = [datetime(2019, 10, 31), datetime(2019, 11, 30), datetime(2020, 7, 31)]\nfuture = pd.DataFrame(index=date_list, columns= btc_month.columns)\nbtc_month_pred = pd.concat([btc_month_pred, future])\n\n#btc_month_pred['forecast'] = invboxcox(best_model.predict(start=0, end=75), lmbda)\nbtc_month_pred['forecast'] = invboxcox(best_model.predict(start=datetime(2015, 10, 31), end=datetime(2020, 7, 31)), lmbda)\n\nbtc_month_pred.Close.plot(linewidth=3)\nbtc_month_pred.forecast.plot(color='r', ls='--', label='Predicted Close', linewidth=3)\nplt.legend()\nplt.grid()\nplt.title('Bitcoin monthly forecast')\nplt.ylabel('USD')",
"_____no_output_____"
],
[
"#from google.colab import files\n#uploaded = files.upload()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aa6bf69448dea64634806835f095ebcb54170ae
| 2,746 |
ipynb
|
Jupyter Notebook
|
notebooks/bayes_sv_analysis.ipynb
|
yipukangda/work_notebooks
|
67f7d98196df60dd6b98c8c0612aab2508c44448
|
[
"MIT"
] | null | null | null |
notebooks/bayes_sv_analysis.ipynb
|
yipukangda/work_notebooks
|
67f7d98196df60dd6b98c8c0612aab2508c44448
|
[
"MIT"
] | null | null | null |
notebooks/bayes_sv_analysis.ipynb
|
yipukangda/work_notebooks
|
67f7d98196df60dd6b98c8c0612aab2508c44448
|
[
"MIT"
] | null | null | null | 26.660194 | 230 | 0.574654 |
[
[
[
"### generate sv file by graph genome tool\n\n#### extract r\n\n1. An unmapped read whose mate is mapped.\n2. A mapped read who’s mate is unmapped\n3. Both reads of the pair are unmapped\n\nThese categories translate to the following filtering commands:",
"_____no_output_____"
]
],
[
[
"%bash \n\n#one version\nsamtools view -u -f 4 -F264 alignments.bam > tmps1.bam\nsamtools view -u -f 8 -F 260 alignments.bam > tmps2.bam\nsamtools view -u -f 12 -F 256 alignments.bam > tmps3.bam\n\n#an alternativ one\nsamtools view -b -F 4 -f 8 file.bam > onlyThisEndMapped.bam\nsamtools view -b -F 8 -f 4 file.bam > onlyThatEndMapped.bam\nsamtools view -b -F12 file.bam > bothEndsMapped.bam\n\nsamtools merge merged.bam onlyThisEndMapped.bam onlyThatEndMapped.bam bothEndsMapped.bam\n\nbedtools bamtofastq -i merged.bam -fq fragment_1.fastq.gz -fq2 fragment_2.fastq.gz",
"_____no_output_____"
]
],
[
[
"### graph genome build index with hgmd sv data ",
"_____no_output_____"
]
],
[
[
"%bash \n\n/usr/local/bin/aligner --vcf [HGMD.sv.vcf.gz] -reference human_g1k_v37_decoy.fasta -q fragment_1.fastq.gz -Q fragment_2.fastq.gz -o sample.bam --read_group_sample 'SAMPLE_READ_GROUP' --read_group_library 'lib' --threads 4\n\nsamtools sort sample.bam > sample.sort.bam samtools index sample.sort.bam\n\n/usr/local/bin/reassembly_variant_caller -b sample.sort.bam -f human_g1k_v37_decoy.fasta -g SBG.Graph.B37.V6.rc6.vcf.gz -v results.vcf\n",
"_____no_output_____"
]
],
[
[
"Support \n>:math:`x \\in \\mathbb{R}`\n> Mean :math:`\\mu`\n> Variance :math:`\\dfrac{1}{\\tau}` or :math:`\\sigma^2`",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aa6c79aaa1251fe769fa9b78024ecfd10b69bd7
| 32,253 |
ipynb
|
Jupyter Notebook
|
Prof. Nik Brown's Notes/B02. DataScienceBasics/2. NBB_Intro_Python.ipynb
|
PratikMahajan/Data-Science-Reference
|
6ce82ef7c61bfb4e9ff148778affe4c521fad836
|
[
"MIT"
] | null | null | null |
Prof. Nik Brown's Notes/B02. DataScienceBasics/2. NBB_Intro_Python.ipynb
|
PratikMahajan/Data-Science-Reference
|
6ce82ef7c61bfb4e9ff148778affe4c521fad836
|
[
"MIT"
] | null | null | null |
Prof. Nik Brown's Notes/B02. DataScienceBasics/2. NBB_Intro_Python.ipynb
|
PratikMahajan/Data-Science-Reference
|
6ce82ef7c61bfb4e9ff148778affe4c521fad836
|
[
"MIT"
] | 1 |
2019-12-02T06:48:30.000Z
|
2019-12-02T06:48:30.000Z
| 22.413482 | 586 | 0.489381 |
[
[
[
"## Intro to Python",
"_____no_output_____"
],
[
"### Learning tips.\n\n* Practice, practice, practice. \n\n* Get used to making mistakes! It’s OK. \n\n* Don’t memorize. There are thousands packages in python. Learn to read documentation. \n",
"_____no_output_____"
],
[
"## Switching between python versions",
"_____no_output_____"
],
[
"### Anaconda Install\n\n[https://docs.continuum.io/anaconda/install](https://docs.continuum.io/anaconda/install)\n\n### Anaconda Docs \n\n[https://conda.io/docs/](https://conda.io/docs/)\n\n[https://conda.io/docs/py2or3.html](https://conda.io/docs/py2or3.html)\n\n### Create a Python 3.5 environment\n\nconda create -n py35 python=3.5 anaconda\n\n\n To activate this environment, use:\n > source activate py35\n\n To deactivate this environment, use:\n > source deactivate py35\n\n### Create a Python 2.7 environment\n\nconda create -n py27 python=2.7 anaconda\n\n To activate this environment, use:\n > source activate py27\n\n To deactivate this environment, use:\n > source deactivate py27\n\n### Update or Upgrade Python \n\nconda update python\n",
"_____no_output_____"
],
[
"### Simple calculator",
"_____no_output_____"
]
],
[
[
"from __future__ import print_function\nprint(33+5)",
"38\n"
],
[
"print(55*11)",
"605\n"
],
[
"print(2**5)",
"32\n"
],
[
"print(3/5)",
"0.6\n"
],
[
"print(3.0/5)",
"0.6\n"
],
[
"# To discard the fractional part and do integer division, you can use a double slash.\nprint(5.5//3.3)",
"1.0\n"
],
[
"print(5.5/3.3)",
"1.6666666666666667\n"
],
[
"print(2^5) # XOR (exclusive OR).\n# 0010 # 2 (binary)\n# 0101 # 5 (binary)\n# ---- # APPLY XOR ('vertically')\n# 0111 # result = 7 (binary)",
"7\n"
],
[
"print(3%2) # Modulo",
"1\n"
],
[
"print(0xAD) # Hexadecimal",
"173\n"
],
[
"print(0o111) # Octal",
"73\n"
],
[
"print(0b0111) # Binary",
"7\n"
],
[
"value = (3.55 / 0.11)**3\nprint(value)",
"33612.978963185575\n"
]
],
[
[
"## Data types",
"_____no_output_____"
]
],
[
[
"months = [\n1.0, \n'January',\n'February',\n'March',\n'April',\n'May',\n'June',\n'July',\n'August',\n'September',\n'October',\n'November',\n'December'\n]\nprint (type(months))\nprint (type(months[0]))\nprint (len(months))\n# print (class(months))\nprint(months[0])\nprint(months[-1])",
"<class 'list'>\n<class 'float'>\n13\n1.0\nDecember\n"
],
[
"print(months[len(months)-1])",
"December\n"
],
[
"print(months)\ndel months[0]\nprint(months)",
"[1.0, 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\n['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\n"
],
[
"print(months[9:11])",
"['October', 'November']\n"
],
[
"print(months[9:])",
"['October', 'November', 'December']\n"
],
[
"print(months[:]) # Print everything\nprint(months[::2]) # Print every other - i.e. skip by 2",
"['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\n['January', 'March', 'May', 'July', 'September', 'November']\n"
],
[
"print(months[-1])\nprint(months[-3])\nprint(months[-3:-1]) # Print second to last to third to last",
"December\nOctober\n['October', 'November']\n"
],
[
"print(months[10:1:-3]) # Print 10 to 1 - i.e. skip by 3",
"['November', 'August', 'May']\n"
],
[
"print(months[10:1:-1]) # Print 10 to 1 - i.e. no skip but descending",
"['November', 'October', 'September', 'August', 'July', 'June', 'May', 'April', 'March']\n"
],
[
"print([1, 2, 3] + [4, 5, 6]) # join two lists",
"[1, 2, 3, 4, 5, 6]\n"
],
[
"# print([1, 2, 3] - [4, 5, 6])",
"_____no_output_____"
],
[
"print('Hello, ' + 'world!') # concatenate two strings",
"Hello, world!\n"
],
[
"name='Bear' # Create string 'Bear'\nprint(name*5) # concatenate 5 times",
"BearBearBearBearBear\n"
],
[
"print('B' in name) # Test if B in Bear\nprint('b' in name) # Test if b in Bear",
"True\nFalse\n"
],
[
"s=range(1,6) # Range doesn't create lists in python 3\nprint(s)",
"range(1, 6)\n"
],
[
"s=list(range(1,9)) # Using range to create lists in python 3\nprint(s)\ns[2]=5\nprint(s)",
"[1, 2, 3, 4, 5, 6, 7, 8]\n[1, 2, 5, 4, 5, 6, 7, 8]\n"
],
[
"del s[2] # Delete an item\nprint(s)\ndel s[2:4] # Delete more than one item\nprint(s)",
"[1, 2, 4, 5, 6, 7, 8]\n[1, 2, 6, 7, 8]\n"
],
[
"t=[1, 2, 3, 4, 5] # Create a list\nprint(t)",
"[1, 2, 3, 4, 5]\n"
],
[
"t=(1, 2, 3, 4, 5) # Create a tuple\nprint(t)",
"(1, 2, 3, 4, 5)\n"
],
[
"# del t[2]\nprint(t)",
"(1, 2, 3, 4, 5)\n"
],
[
"print(2 ** 5) # Power",
"32\n"
],
[
"print(pow(2, 5)) # Power using function",
"32\n"
],
[
"import math # Some common math functions\nprint(math.ceil(33.3))",
"34\n"
],
[
"print(math.sqrt(9))",
"3.0\n"
],
[
"from math import sqrt\nprint(sqrt(9))",
"3.0\n"
]
],
[
[
"## List Methods\n\n* list.append(elem) -- adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.\n* list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right.\n* list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().\n* list.index(elem) -- searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use \"in\" to check without a ValueError).\n* list.remove(elem) -- searches for the first instance of the given element and removes it (throws ValueError if not present)\n* list.sort() -- sorts the list in place (does not return it). (The sorted() function shown below is preferred.)\n* list.reverse() -- reverses the list in place (does not return it)\n* list.pop(index) -- removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).\n",
"_____no_output_____"
]
],
[
[
"l = ['Rick Sanchez', 'Morty Smith', 'Mr. Meeseeks']\nprint (l) \nl.append('Doofus Rick') ## append item at end\nprint (l)\nl.insert(0, 'Scary Terry') ## insert item at index 0\nprint (l)\nl.extend(['Squanchy', 'Mr. Poopybutthole']) ## add list of items at end\nprint (l)\nprint (l.index('Morty Smith')) \nprint (l)\nl.remove('Morty Smith') ## search and remove an item\nprint (l)\nprint(l.pop(1)) ## removes and returns 'Rick Sanchez' second item\nprint (l) ## ['Scary Terry', 'Mr. Meeseeks', 'Doofus Rick', 'Squanchy', 'Mr. Poopybutthole']",
"['Rick Sanchez', 'Morty Smith', 'Mr. Meeseeks']\n['Rick Sanchez', 'Morty Smith', 'Mr. Meeseeks', 'Doofus Rick']\n['Scary Terry', 'Rick Sanchez', 'Morty Smith', 'Mr. Meeseeks', 'Doofus Rick']\n['Scary Terry', 'Rick Sanchez', 'Morty Smith', 'Mr. Meeseeks', 'Doofus Rick', 'Squanchy', 'Mr. Poopybutthole']\n2\n['Scary Terry', 'Rick Sanchez', 'Morty Smith', 'Mr. Meeseeks', 'Doofus Rick', 'Squanchy', 'Mr. Poopybutthole']\n['Scary Terry', 'Rick Sanchez', 'Mr. Meeseeks', 'Doofus Rick', 'Squanchy', 'Mr. Poopybutthole']\nRick Sanchez\n['Scary Terry', 'Mr. Meeseeks', 'Doofus Rick', 'Squanchy', 'Mr. Poopybutthole']\n"
]
],
[
[
"## Dictionaries",
"_____no_output_____"
]
],
[
[
"d={\"python\": 333, \"R\": 222, \"C++\": 111} # Create a dictionary\nprint(d.keys())",
"dict_keys(['python', 'R', 'C++'])\n"
],
[
"print(d[\"python\"]) # List value with key \"python\"",
"333\n"
],
[
"print(\"java\" in d) # Check if \"java\" in dictionary",
"False\n"
],
[
"print(\"python\" in d) # Check if \"python\" in dictionary",
"True\n"
],
[
"d2={\"java\": 33, \"C#\": 22, \"Scala\": 11} # Create a dictionary\nprint(d2)",
"{'java': 33, 'C#': 22, 'Scala': 11}\n"
],
[
"d.update(d2) # add dictionary to another dictionary\nprint(d)",
"{'python': 333, 'R': 222, 'C++': 111, 'java': 33, 'C#': 22, 'Scala': 11}\n"
],
[
"for key in d: # List keys in dictionary\n print(key)\nprint(d.keys())",
"python\nR\nC++\njava\nC#\nScala\ndict_keys(['python', 'R', 'C++', 'java', 'C#', 'Scala'])\n"
],
[
"for key in d: # List values in dictionary\n print(d[key])\nprint(d.values())",
"333\n222\n111\n33\n22\n11\ndict_values([333, 222, 111, 33, 22, 11])\n"
],
[
"d_backup = d.copy() # Create dictionary copy\nprint(d_backup)",
"{'python': 333, 'R': 222, 'C++': 111, 'java': 33, 'C#': 22, 'Scala': 11}\n"
],
[
"d['C++']=55\nprint(d)\nprint(d_backup)",
"{'python': 333, 'R': 222, 'C++': 55, 'java': 33, 'C#': 22, 'Scala': 11}\n{'python': 333, 'R': 222, 'C++': 111, 'java': 33, 'C#': 22, 'Scala': 11}\n"
]
],
[
[
"### Note:\n\n* A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.\n* A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.",
"_____no_output_____"
]
],
[
[
"print(len(d)-len(d_backup))\ndel d_backup[\"java\"]\nprint(d_backup)",
"0\n{'python': 333, 'R': 222, 'C++': 111, 'C#': 22, 'Scala': 11}\n"
],
[
"print(len(d)-len(d_backup)) # Note original isn't changed",
"1\n"
]
],
[
[
"## Dictionary Methods\n\n* d.fromkeys() - Create a new dictonary with keys from seq and values set to value.\n* d.get(key, default=None) - For any key, returns value or default if key not in dictonary\n* d.has_key(key) - Removed, use the in operation instead.\n* d.items() - Returns a list of d.s (key, value) tuple pairs\n* d.keys() - Returns list of dictonary d's keys\n* d.setdefault(key, default = None) - Similar to get(), but will set d.key] = default if key is not already in dict\n* d.update(d2) - Adds dictonary d2's key-values pairs to dict\n* d.values() - Returns list of dictonary d's values\n* d.clear() - Removes all elements of dictonary d\n\nNote:\n\n* A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.\n* A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.",
"_____no_output_____"
],
[
"## Excercise \n\nTry the above methods on a dictonary that you create.",
"_____no_output_____"
],
[
"## Indentation\n\nOne unusual Python feature is that the whitespace indentation of a piece of code affects its meaning. A logical block of statements such as the ones that make up a function should all have the same indentation, set in from the indentation of their parent function or \"if\" or whatever. If one of the lines in a group has a different indentation, it is flagged as a syntax error.",
"_____no_output_____"
],
[
"## Conditionals",
"_____no_output_____"
]
],
[
[
"l=['Scary Terry', 'Rick Sanchez', 'Morty Smith', 'Mr. Meeseeks', 'Doofus Rick', 'Squanchy', 'Mr. Poopybutthole']\nif 'Scary Terry' in l:\n print (\"Oh no!!!\")\n \nif 'Scary Tarry' in l:\n print (\"Oh no!!!\") \nelse:\n print (\"Whew!!!\")\n \nif 'Scary Tarry' in l:\n print (\"Oh no!!!\") \nelif 'Mr. Meeseeks' in l:\n print (\"Oooo yeah, caaan doo!!!!\") \nelse:\n print (\"Whew!!!\") ",
"Oh no!!!\nWhew!!!\nOooo yeah, caaan doo!!!!\n"
]
],
[
[
"## Comparison Operators\n\n* x == y x equals y.\n* x < y x is less than y.\n* x > y x is greater than y.\n* x >= y x is greater than or equal to y.\n* x <= y x is less than or equal to y.\n* x != y x is not equal to y.\n* x is y x and y are the same object.\n* x is not y x and y are different objects.\n* x in y x is a member of the container (e.g., sequence) y.\n* x not in y x is not a member of the container (e.g., sequence) y.",
"_____no_output_____"
],
[
"## Loops\n\n### For loops ",
"_____no_output_____"
]
],
[
[
"for name in l:\n print(name)",
"Scary Terry\nRick Sanchez\nMorty Smith\nMr. Meeseeks\nDoofus Rick\nSquanchy\nMr. Poopybutthole\n"
]
],
[
[
"### While loops ",
"_____no_output_____"
]
],
[
[
"x = 1\nwhile x <= 5:\n print(x)\n x += 1",
"1\n2\n3\n4\n5\n"
],
[
"x = 1\nwhile x <= 5:\n x += 1 \n if (x%2==0):\n print(x)\n",
"2\n4\n6\n"
],
[
"x = 1\nwhile x <= 5:\n x += 1 \n print(x)\n if (x==3): break",
"2\n3\n"
]
],
[
[
"## help(), and dir()\n\nhere are a variety of ways to get help for Python.\n\nDo a Google search, starting with the word \"python\", like \"python list\" or \"python string lowercase\". The first hit is often the answer. This technique seems to work better for Python than it does for other languages for some reason.\nThe official Python docs site — docs.python.org — has high quality docs. Nonetheless, I often find a Google search of a couple words to be quicker.\nThere is also an official Tutor mailing list specifically designed for those who are new to Python and/or programming!\nMany questions (and answers) can be found on StackOverflow and Quora.\nUse the help() and dir() functions (see below).\nInside the Python interpreter, the help() function pulls up documentation strings for various modules, functions, and methods. These doc strings are similar to Java's javadoc. The dir() function tells you what the attributes of an object are. Below are some ways to call help() and dir() from the interpreter:\n\nhelp(len) — help string for the built-in len() function; note that it's \"len\" not \"len()\", which is a call to the function, which we don't want\nhelp(sys) — help string for the sys module (must do an import sys first)\ndir(sys) — dir() is like help() but just gives a quick list of its defined symbols, or \"attributes\"\nhelp(sys.exit) — help string for the exit() function in the sys module\nhelp('xyz'.split) — help string for the split() method for string objects. You can call help() with that object itself or an example of that object, plus its attribute. For example, calling help('xyz'.split) is the same as calling help(str.split).\nhelp(list) — help string for list objects\ndir(list) — displays list object attributes, including its methods\nhelp(list.append) — help string for the append() method for list objects",
"_____no_output_____"
],
[
"## Functions",
"_____no_output_____"
]
],
[
[
"def fibonacci_seq(n): # Function syntax\n result = [0, 1]\n for i in range(n-2):\n result.append(result[-2] + result[-1])\n return result\nprint(fibonacci_seq(9))",
"[0, 1, 1, 2, 3, 5, 8, 13, 21]\n"
],
[
"def fibA(n):\n a,b = 1,1\n for i in range(n-1):\n a,b = b,a+b\n return a\nprint([fibA(i) for i in range(9)]) # Repeatedly calling a function",
"[1, 1, 1, 2, 3, 5, 8, 13, 21]\n"
]
],
[
[
"## Python Tutorials \n\n* [“Dive into Python” (Chapters 2 to 4)] (http://diveintopython.org/)\n\n* [Python 101 – Beginning Python] (http://www.rexx.com/~dkuhlman/python_101/python_101.html) \n\n* [Nice free CS/python book] (https://www.cs.hmc.edu/csforall/index.html)\n\n\n### Things to refer to \n\n* [The Official Python Tutorial] (http://www.python.org/doc/current/tut/tut.html) \n* [The Python Quick Reference] (http://rgruet.free.fr/PQR2.3.html) \n\n### YouTube Python Tutorials \n\n* [Python Fundamentals Training – Classes] (http://www.youtube.com/watch?v=rKzZEtxIX14)\n* [Python 2.7 Tutorial Derek Banas] (http://www.youtube.com/watch?v=UQi-L-_chcc)\n* [Python Programming Tutorial - thenewboston] \n(http://www.youtube.com/watch?v=4Mf0h3HphEA)\n* [Google Python Class](http://www.youtube.com/watch?v=tKTZoB2Vjuk) \n\n\n### datacamp.com\n\n* [datacamp.com] (https://www.datacamp.com/tracks/python-developer)",
"_____no_output_____"
],
[
"Last update September 5, 2017",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
4aa6cfcef726d518e73c055aee1927e3726c3f71
| 70,586 |
ipynb
|
Jupyter Notebook
|
Capstone/M3ExploratoryDataAnalysis-lab.ipynb
|
samiajannat/IBM-Data-Analyst
|
ac617e74a778ab862b1f08c4366b31d02878a6e2
|
[
"MIT"
] | null | null | null |
Capstone/M3ExploratoryDataAnalysis-lab.ipynb
|
samiajannat/IBM-Data-Analyst
|
ac617e74a778ab862b1f08c4366b31d02878a6e2
|
[
"MIT"
] | null | null | null |
Capstone/M3ExploratoryDataAnalysis-lab.ipynb
|
samiajannat/IBM-Data-Analyst
|
ac617e74a778ab862b1f08c4366b31d02878a6e2
|
[
"MIT"
] | null | null | null | 54.338722 | 9,696 | 0.664339 |
[
[
[
"<center>\n <img src=\"https://gitlab.com/ibm/skills-network/courses/placeholder101/-/raw/master/labs/module%201/images/IDSNlogo.png\" width=\"300\" alt=\"cognitiveclass.ai logo\" />\n</center>\n",
"_____no_output_____"
],
[
"# **Exploratory Data Analysis Lab**\n",
"_____no_output_____"
],
[
"Estimated time needed: **30** minutes\n",
"_____no_output_____"
],
[
"In this module you get to work with the cleaned dataset from the previous module.\n\nIn this assignment you will perform the task of exploratory data analysis.\nYou will find out the distribution of data, presence of outliers and also determine the correlation between different columns in the dataset.\n",
"_____no_output_____"
],
[
"## Objectives\n",
"_____no_output_____"
],
[
"In this lab you will perform the following:\n",
"_____no_output_____"
],
[
"* Identify the distribution of data in the dataset.\n\n* Identify outliers in the dataset.\n\n* Remove outliers from the dataset.\n\n* Identify correlation between features in the dataset.\n",
"_____no_output_____"
],
[
"***\n",
"_____no_output_____"
],
[
"## Hands on Lab\n",
"_____no_output_____"
],
[
"Import the pandas module.\n",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"Load the dataset into a dataframe.\n",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv(\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DA0321EN-SkillsNetwork/LargeData/m2_survey_data.csv\")",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"df['Age'].median()",
"_____no_output_____"
],
[
"df[df['Gender'] == 'Woman']['ConvertedComp'].median()",
"_____no_output_____"
],
[
"df['Age'].hist()",
"_____no_output_____"
],
[
"df['ConvertedComp'].median()",
"_____no_output_____"
],
[
"df.boxplot(column=['ConvertedComp'])",
"_____no_output_____"
],
[
"Q1 = df['ConvertedComp'].quantile(0.25)\nQ3 = df['ConvertedComp'].quantile(0.75)\nIQR = Q3 - Q1 #IQR is interquartile range. \n\nfiltered = (df['ConvertedComp'] >= Q1 - 1.5 * IQR) & (df['ConvertedComp'] <= Q3 + 1.5 *IQR)\ndf_remove_outliers = df.loc[filtered]",
"_____no_output_____"
],
[
"df_remove_outliers['ConvertedComp'].median()",
"_____no_output_____"
],
[
"df_remove_outliers['ConvertedComp'].mean()",
"_____no_output_____"
],
[
"df.boxplot(column=['Age'])",
"_____no_output_____"
],
[
"df.corr(method ='pearson')",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nplt.plot(df['Age'],df['WorkWeekHrs'],'o')",
"_____no_output_____"
]
],
[
[
"## Distribution\n",
"_____no_output_____"
],
[
"### Determine how the data is distributed\n",
"_____no_output_____"
],
[
"The column `ConvertedComp` contains Salary converted to annual USD salaries using the exchange rate on 2019-02-01.\n\nThis assumes 12 working months and 50 working weeks.\n",
"_____no_output_____"
],
[
"Plot the distribution curve for the column `ConvertedComp`.\n",
"_____no_output_____"
]
],
[
[
"# your code goes here\n",
"_____no_output_____"
]
],
[
[
"Plot the histogram for the column `ConvertedComp`.\n",
"_____no_output_____"
]
],
[
[
"# your code goes here\n",
"_____no_output_____"
]
],
[
[
"What is the median of the column `ConvertedComp`?\n",
"_____no_output_____"
]
],
[
[
"# your code goes here\n",
"_____no_output_____"
]
],
[
[
"How many responders identified themselves only as a **Man**?\n",
"_____no_output_____"
]
],
[
[
"# your code goes here\n",
"_____no_output_____"
]
],
[
[
"Find out the median ConvertedComp of responders identified themselves only as a **Woman**?\n",
"_____no_output_____"
]
],
[
[
"# your code goes here\n",
"_____no_output_____"
]
],
[
[
"Give the five number summary for the column `Age`?\n",
"_____no_output_____"
],
[
"**Double click here for hint**.\n\n<!--\nmin,q1,median,q3,max of a column are its five number summary.\n-->\n",
"_____no_output_____"
]
],
[
[
"# your code goes here\n",
"_____no_output_____"
]
],
[
[
"Plot a histogram of the column `Age`.\n",
"_____no_output_____"
]
],
[
[
"# your code goes here\n",
"_____no_output_____"
]
],
[
[
"## Outliers\n",
"_____no_output_____"
],
[
"### Finding outliers\n",
"_____no_output_____"
],
[
"Find out if outliers exist in the column `ConvertedComp` using a box plot?\n",
"_____no_output_____"
]
],
[
[
"# your code goes here\n",
"_____no_output_____"
]
],
[
[
"Find out the Inter Quartile Range for the column `ConvertedComp`.\n",
"_____no_output_____"
]
],
[
[
"# your code goes here\n",
"_____no_output_____"
]
],
[
[
"Find out the upper and lower bounds.\n",
"_____no_output_____"
]
],
[
[
"# your code goes here\n",
"_____no_output_____"
]
],
[
[
"Identify how many outliers are there in the `ConvertedComp` column.\n",
"_____no_output_____"
]
],
[
[
"# your code goes here\n",
"_____no_output_____"
]
],
[
[
"Create a new dataframe by removing the outliers from the `ConvertedComp` column.\n",
"_____no_output_____"
]
],
[
[
"# your code goes here\n",
"_____no_output_____"
]
],
[
[
"## Correlation\n",
"_____no_output_____"
],
[
"### Finding correlation\n",
"_____no_output_____"
],
[
"Find the correlation between `Age` and all other numerical columns.\n",
"_____no_output_____"
]
],
[
[
"# your code goes here\n",
"_____no_output_____"
]
],
[
[
"## Authors\n",
"_____no_output_____"
],
[
"Ramesh Sannareddy\n",
"_____no_output_____"
],
[
"### Other Contributors\n",
"_____no_output_____"
],
[
"Rav Ahuja\n",
"_____no_output_____"
],
[
"## Change Log\n",
"_____no_output_____"
],
[
"| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n| ----------------- | ------- | ----------------- | ---------------------------------- |\n| 2020-10-17 | 0.1 | Ramesh Sannareddy | Created initial version of the lab |\n",
"_____no_output_____"
],
[
"Copyright © 2020 IBM Corporation. This notebook and its source code are released under the terms of the [MIT License](https://cognitiveclass.ai/mit-license?utm_medium=Exinfluencer\\&utm_source=Exinfluencer\\&utm_content=000026UJ\\&utm_term=10006555\\&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDA0321ENSkillsNetwork21426264-2021-01-01\\&cm_mmc=Email_Newsletter-\\_-Developer_Ed%2BTech-\\_-WW_WW-\\_-SkillsNetwork-Courses-IBM-DA0321EN-SkillsNetwork-21426264\\&cm_mmca1=000026UJ\\&cm_mmca2=10006555\\&cm_mmca3=M12345678\\&cvosrc=email.Newsletter.M12345678\\&cvo_campaign=000026UJ).\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4aa6d82062219c845333a89c63304a81778de8b1
| 191,740 |
ipynb
|
Jupyter Notebook
|
.ipynb_checkpoints/lab exercise-checkpoint.ipynb
|
brunoasika/brunoCSC102
|
5e1ae1bf91993d33174e306fbba8e0832b8912e6
|
[
"MIT"
] | null | null | null |
.ipynb_checkpoints/lab exercise-checkpoint.ipynb
|
brunoasika/brunoCSC102
|
5e1ae1bf91993d33174e306fbba8e0832b8912e6
|
[
"MIT"
] | null | null | null |
.ipynb_checkpoints/lab exercise-checkpoint.ipynb
|
brunoasika/brunoCSC102
|
5e1ae1bf91993d33174e306fbba8e0832b8912e6
|
[
"MIT"
] | null | null | null | 697.236364 | 60,488 | 0.948952 |
[
[
[
"# Bruno asika\n# 20120612166\n# [email protected]\n",
"_____no_output_____"
],
[
"# exercise 1 \n",
"_____no_output_____"
],
[
" ",
"_____no_output_____"
]
],
[
[
"a = 44\nb = 17\nc = a - b\nprint(c)\nif a > 17:\n Y = c*2\n print(Y)\nelse:\n print(c)",
"27\n54\n"
]
],
[
[
"# exercise 2",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"a = 3\nb = 7\nc = 8\nif a == b == c:\n y = ((a**3)*3)\n print(y)\nelse: \n z = (a + b + c)\n print(z)",
"18\n"
]
],
[
[
"# exercise 3 ",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"a = 4\nb = 4\nif a == b:\n print(True)\nelif a + b == 5:\n print(True)\nelif a - b == 5:\n print(True) \nelse:\n print(False) \n",
"True\n"
]
],
[
[
"# exercise 4",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"a = 8\nb = 5\nc = 9\ng = max(a, b, c)\nh = min(a, b, c)\ni = (a + b + c) - g - h\nprint(\"the maximum value is, \", g)\nprint(\"the minimum value is, \", h)\nprint(\"the middle number is, \", i)",
"the maximum value is, 9\nthe minimum value is, 5\nthe middle number is, 8\n"
]
],
[
[
"# exercise 5",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"a = 6\nb = [5,4,3,2,1]\nb[0] = b[0]**3\nb[1] = b[1]**3\nb[2] = b[2]**3\nb[3] = b[3]**3\nb[4] = b[4]**3\nc = sum(b)\nprint(c)",
"225\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
4aa6dd7ea34a9a0988f94d9ddad14ff83e23d9d0
| 4,561 |
ipynb
|
Jupyter Notebook
|
Python Practical Exam.ipynb
|
AaradhyaArneja/Python-Practical-Exam
|
5344b4cd6c02a3ef88299e20c2f2d2e6d1b992cb
|
[
"Apache-2.0"
] | null | null | null |
Python Practical Exam.ipynb
|
AaradhyaArneja/Python-Practical-Exam
|
5344b4cd6c02a3ef88299e20c2f2d2e6d1b992cb
|
[
"Apache-2.0"
] | null | null | null |
Python Practical Exam.ipynb
|
AaradhyaArneja/Python-Practical-Exam
|
5344b4cd6c02a3ef88299e20c2f2d2e6d1b992cb
|
[
"Apache-2.0"
] | null | null | null | 26.672515 | 89 | 0.369656 |
[
[
[
"#Q1\n#(a)\ndef odd(): \n sum = 0 \n n = int(input(\"Print sum of odd numbers till: \"))\n for i in range (0 , n+1): \n if i % 2 == 1: \n sum += i \n print(\"term = \",i,\", sum till this step = \", sum ) \n else: \n continue \n odd()\n\nodd()\n\n#(b) \ndef even(): \n sum = 0 \n n = int(input(\"Print sum of even numbers till: \")) \n for i in range (0 , n+1): \n if i % 2 == 0 : \n sum += i\n print(\"term = \",i,\", sum till this step = \", sum ) \n else: \n continue \n even()\n\neven()\n\n#(c) \nn = input(\"Enter Number to calculate sum: \")\nn = int (n)\nsum = 0\nfor num in range(0, n+1, 1):\n sum = sum+num\nprint(\"SUM of first \", n, \"numbers is: \", sum )",
"_____no_output_____"
],
[
"#Q2\n#(A)\n \nt1=(1,2,3,4,5,6,7,8,9,10)\nt1a=t1[:5]\nt1b=t1[5:]\nprint(t1a)\nprint(t1b)\nprint()\n\n#(B)\n \nt1=(1,2,3,4,5,6,7,8,9,10)\nn=list(t1)\nlist1=list()\nfor i in n:\n if i in n:\n if i%2==0:\n list1.append(i)\n p=tuple(list1)\nprint('tuple:',p)\nprint()\n\n#(C)\n \nt1=(1,2,3,4,5,6,7,8,9,10)\nt2=(11,13,15)\na=list(t1)\nb=list(t2)\nc=(a+b)\nprint(c)\n\n#(D)\n \nt1=(1,2,3,4,5,6,7,8,9,10)\nmax(t1)\nmin(t2)\nprint('max no. is',max(t1))\nprint('min no. is',min(t1))\n",
"_____no_output_____"
],
[
"#Q3\ndef string():\n choice =int(input('''Enter your choice \n1 = length of the string\n2 = maximum of three strrings\n3 = Replace every successive character with #\n4 = number of words in the string\n'''))\n\n if choice == 1:\n n = input(\"Enter a string : \")\n l=len(n)\n print(\"The length of the string is =\",l) \n elif choice == 2:\n n1 = input(\"Enter 1st string : \")\n n2 = input(\"Enter 2nd string : \")\n n3 = input(\"Enter 3rd string : \")\n print(\"The maximum of the three strings is =\",max(n1,n2,n3)) \n elif choice == 3:\n n = input(\"Enter a string : \")\n s = \"\"\n m = list(n)\n for i in range(len(n)):\n if (i%2 != 0):\n if m[i] == \" \":\n m[i] = \" \"\n else:\n m[i] = \"#\"\n for x in m:\n s=s+x\n print(\"The sucessive character in the string is replaced with # :\",s) \n elif choice == 4:\n n = input(\"Enter a string : \")\n c = 0\n for y in n :\n if y == \" \" :\n c += 1\n w = c+1\n print(\"The number of words = \",w) \n else :\n print(\"Please Choose from the given option only\")\n\nstring()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
4aa70777fe9a3e07ef364e424c774f275ee72d80
| 10,466 |
ipynb
|
Jupyter Notebook
|
Scraping_Investopedia_Dictionary_Items.ipynb
|
ali1k/InvestopediaGlossaryScraping
|
f45cf3f1270a31336ddb5df462995c8dfdb28b8d
|
[
"MIT"
] | 2 |
2021-06-14T05:45:59.000Z
|
2021-06-14T10:53:33.000Z
|
Scraping_Investopedia_Dictionary_Items.ipynb
|
ali1k/InvestopediaKnowledgeGraph
|
f45cf3f1270a31336ddb5df462995c8dfdb28b8d
|
[
"MIT"
] | null | null | null |
Scraping_Investopedia_Dictionary_Items.ipynb
|
ali1k/InvestopediaKnowledgeGraph
|
f45cf3f1270a31336ddb5df462995c8dfdb28b8d
|
[
"MIT"
] | null | null | null | 34.314754 | 172 | 0.544716 |
[
[
[
"# Install a pip package in the current Jupyter kernel\nimport sys\n!{sys.executable} -m pip install pip install python-slugify\n!{sys.executable} -m pip install pip install bs4\n!{sys.executable} -m pip install pip install lxml",
"Requirement already satisfied: pip in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (20.2.4)\nRequirement already satisfied: install in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (1.3.4)\nRequirement already satisfied: python-slugify in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (4.0.1)\nRequirement already satisfied: text-unidecode>=1.3 in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (from python-slugify) (1.3)\nRequirement already satisfied: pip in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (20.2.4)\nRequirement already satisfied: install in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (1.3.4)\nCollecting bs4\n Downloading bs4-0.0.1.tar.gz (1.1 kB)\nRequirement already satisfied: beautifulsoup4 in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (from bs4) (4.9.3)\nRequirement already satisfied: soupsieve>1.2; python_version >= \"3.0\" in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (from beautifulsoup4->bs4) (2.0.1)\nBuilding wheels for collected packages: bs4\n Building wheel for bs4 (setup.py): started\n Building wheel for bs4 (setup.py): finished with status 'done'\n Created wheel for bs4: filename=bs4-0.0.1-py3-none-any.whl size=1277 sha256=25e07933f00cccd226db5310650c03a87f232b490433719187c55ce5f86f8359\n Stored in directory: c:\\users\\alkhalili\\appdata\\local\\pip\\cache\\wheels\\75\\78\\21\\68b124549c9bdc94f822c02fb9aa3578a669843f9767776bca\nSuccessfully built bs4\nInstalling collected packages: bs4\nSuccessfully installed bs4-0.0.1\nRequirement already satisfied: pip in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (20.2.4)\nRequirement already satisfied: install in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (1.3.4)\nRequirement already satisfied: lxml in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (4.6.1)\n"
],
[
"import requests, random, logging, urllib.request, json\nfrom bs4 import BeautifulSoup\nfrom tqdm import tqdm\nfrom slugify import slugify",
"_____no_output_____"
],
[
"logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')",
"_____no_output_____"
],
[
"url = 'https://www.investopedia.com/financial-term-dictionary-4769738'",
"_____no_output_____"
],
[
"master_links = []\n\npage = urllib.request.urlopen(url).read().decode('utf8','ignore') \nsoup = BeautifulSoup(page,\"lxml\")\n\nfor link in soup.find_all('a',{'class': 'terms-bar__link mntl-text-link'}, href = True):\n\n master_links.append(link.get('href'))",
"_____no_output_____"
],
[
"master_links = master_links[0:27]",
"_____no_output_____"
],
[
"with open('URL_INDEX_BY_ALPHA.txt', 'w') as f:\n for item in master_links:\n f.write(\"%s\\n\" % item)",
"_____no_output_____"
],
[
"list_alpha = []\n\nfor articleIdx in master_links:\n \n page = urllib.request.urlopen(articleIdx).read().decode('utf8','ignore') \n soup = BeautifulSoup(page,\"lxml\")\n \n for link in soup.find_all('a',{'class': 'dictionary-top300-list__list mntl-text-link'}, href = True):\n \n list_alpha.append(link.get('href'))",
"_____no_output_____"
],
[
"with open('FULL_URL_INDEX.txt', 'w') as f:\n for item in list_alpha:\n f.write(\"%s\\n\" % item)",
"_____no_output_____"
],
[
"logf = open(\"error.log\", \"w\")",
"_____no_output_____"
],
[
"# for article in tqdm(random.sample(list_alpha, 10)):\ndata = {} #json file\nfor article in tqdm(list_alpha):\n list_related = []\n body = []\n try:\n \n page = urllib.request.urlopen(article, timeout = 3).read().decode('utf8','ignore')\n soup = BeautifulSoup(page,\"lxml\")\n \n myTags = soup.find_all('p', {'class': 'comp mntl-sc-block finance-sc-block-html mntl-sc-block-html'})\n \n for link in soup.find_all('a',{'class': 'related-terms__title mntl-text-link'}, href = True):\n list_related.append(link.get('href'))\n \n title = slugify(soup.find('title').get_text(strip=True)) + '.json'\n data['name'] = soup.find('title').get_text(strip=True)\n data['@id'] = article\n data['related'] = list_related\n post = ''\n \n for tag in myTags:\n # body.append(str(tag.get_text(strip=True).encode('utf8', errors='replace'))) #get text content\n body.append(tag.decode_contents()) # get html content\n\n f = 'data/' + title\n data['body'] = body\n\n w = open(f, 'w')\n w.write(json.dumps(data))\n w.close()\n \n except:\n \n logf.write(\"Failed to extract: {0}\\n\".format(str(article)))\n logging.error(\"Exception occurred\", exc_info=True)\n \n finally:\n \n pass",
"100%|██████████████████████████████████████████████████████████████████████████████| 6321/6321 [47:22<00:00, 2.22it/s]\n"
]
],
[
[
" # create RDF from JSON ",
"_____no_output_____"
]
],
[
[
"# Install a pip package in the current Jupyter kernel\nimport sys\n!{sys.executable} -m pip install pip install rdflib",
"Requirement already satisfied: pip in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (20.2.4)\nRequirement already satisfied: install in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (1.3.4)\nRequirement already satisfied: rdflib in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (5.0.0)\nRequirement already satisfied: pyparsing in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (from rdflib) (2.4.7)\nRequirement already satisfied: six in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (from rdflib) (1.15.0)\nRequirement already satisfied: isodate in c:\\users\\alkhalili\\anaconda3\\lib\\site-packages (from rdflib) (0.6.0)\n"
],
[
"import os, json, rdflib\nfrom rdflib import URIRef, BNode, Literal, Namespace, Graph\nfrom rdflib.namespace import CSVW, DC, DCAT, DCTERMS, DOAP, FOAF, ODRL2, ORG, OWL, \\\n PROF, PROV, RDF, RDFS, SDO, SH, SKOS, SOSA, SSN, TIME, \\\n VOID, XMLNS, XSD\n\npath_to_json = 'data/'\njson_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]\nfor link in json_files: \n with open('data/'+link) as f:\n data = json.load(f)\n #create RDF graph\n g = Graph()\n INVP = Namespace(\"https://www.investopedia.com/vocab/\")\n g.bind(\"rdfs\", RDFS)\n g.bind(\"schema\", SDO)\n g.bind(\"invp\", INVP)\n rdf_content = ''\n termS = URIRef(data['@id'])\n g.add((termS, RDF.type, INVP.Term))\n g.add((termS, SDO.url, termS))\n g.add((termS, RDFS.label, Literal(data['name'])))\n for rel in data['related']:\n g.add((termS, INVP.relates_to, URIRef(rel)))\n\n separator = ''\n content= separator.join(data['body'])\n g.add((termS, INVP.description, Literal(content)))\n output = '# '+data['name']+ '\\n' + g.serialize(format=\"turtle\").decode(\"utf-8\")\n w = open('rdf/'+link.replace('.json','')+'.ttl', 'wb')\n w.write(output.encode(\"utf8\"))\n w.close()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4aa7080e91db5dde2da45c504f23e37155a0e54d
| 14,453 |
ipynb
|
Jupyter Notebook
|
collection-manager/manage_other_nodes_config.ipynb
|
whatevery1says/jupyter-notebooks
|
92bfc07fd0bc7f76965ab4159abd028a89ea1ab2
|
[
"MIT"
] | 2 |
2017-11-28T17:50:31.000Z
|
2019-09-27T17:39:41.000Z
|
collection-manager/manage_other_nodes_config.ipynb
|
whatevery1says/jupyter-notebooks
|
92bfc07fd0bc7f76965ab4159abd028a89ea1ab2
|
[
"MIT"
] | null | null | null |
collection-manager/manage_other_nodes_config.ipynb
|
whatevery1says/jupyter-notebooks
|
92bfc07fd0bc7f76965ab4159abd028a89ea1ab2
|
[
"MIT"
] | null | null | null | 50.010381 | 213 | 0.485366 |
[
[
[
"from datetime import datetime\nfrom IPython.display import display, HTML, clear_output\nimport ipywidgets as widgets\nfrom ipywidgets import Checkbox, Box, Dropdown, fixed, interact, interactive, interact_manual, Label, Layout, Textarea\n\n# Override ipywidgets styles\ndisplay(HTML('''\n<style>\ntextarea {min-height: 110px !important;}\n/* Allow extra-long labels */\n.widget-label {min-width: 25ex !important; font-weight: bold;}\n.widget-checkbox {padding-right: 300px !important;}\n/* Classes for toggling widget visibility */\n.hidden {display: none;}\n.visible {display: flex;}\n</style>\n'''))\n\n\nclass ConfigForm(object):\n # Define widgets\n path_caption_msg = '''\n <h4>The path should be entire path after the <code>collection</code> name, including node type, \n sub-branches, and <code>_id</code>.<br>For example, <code>,Metadata,sub-branch,node_id,</code>.</h4>\n '''\n path_caption = widgets.HTML(value=path_caption_msg)\n caption = widgets.HTML(value='<h3>Configure Your Action</h3>')\n button = widgets.Button(description='Submit')\n action = widgets.Dropdown(options=['Insert', 'Delete', 'Display', 'Update'], value='Insert')\n collection = widgets.Text(value='')\n datatype = widgets.RadioButtons(options=['Metadata', 'Outputs', 'Related', 'Generic'], value='Metadata')\n path = widgets.Text(value='')\n title = widgets.Text(value='')\n altTitle = widgets.Text(value='')\n description = widgets.Textarea(value='')\n date = widgets.Textarea(placeholder='List each date on a separate line.\\nDate ranges should use the separate start and end dates with commas.\\nValid formats are YYYY-MM-DD and YYYY-MM-DDTHH:MM:SS.')\n label = widgets.Text(value='')\n precise = widgets.Checkbox(value=False)\n notes = widgets.Textarea(placeholder='List each note on a separate line.')\n \n # Configure widget layout\n flex = Layout(display='flex', flex_flow='row', justify_content='space-between')\n\n # Assemble widgets in Boxes\n form_items = [\n Box([Label(value='Action:'), action], layout=flex),\n Box([Label(value='Collection: (required)'), collection], layout=flex),\n Box([Label(value='Node Type:'), datatype], layout=flex),\n Box([Label(value='Path: (required)'), path], layout=flex),\n Box([Label(value='title (optional):'), title], layout=flex),\n Box([Label(value='altTitle (optional):'), altTitle], layout=flex),\n Box([Label(value='description (optional):'), description], layout=flex),\n Box([Label(value='date (optional):'), date], layout=flex),\n Box([Label(value='label (optional):'), label], layout=flex),\n Box([Label(value='notes (optional):'), notes], layout=flex)\n ]\n \n # Initialise the class object\n def __init__(self, object):\n self.path_caption = ConfigForm.path_caption\n self.caption = ConfigForm.caption\n self.button = ConfigForm.button\n self.action = ConfigForm.form_items[0]\n self.collection = ConfigForm.form_items[1]\n self.datatype = ConfigForm.form_items[2]\n self.path = ConfigForm.form_items[3]\n self.title = ConfigForm.form_items[4]\n self.altTitle = ConfigForm.form_items[5]\n self.description = ConfigForm.form_items[6]\n self.date = ConfigForm.form_items[7]\n self.label = ConfigForm.form_items[8]\n self.notes = ConfigForm.form_items[9]\n\n # Helper method\n def show(widgets, all_widgets):\n for widget in all_widgets:\n if widget in widgets:\n widget.add_class('visible').remove_class('hidden')\n else:\n widget.remove_class('visible').add_class('hidden') \n\n # Modify widget visibility when the form is changed\n def change_visibility(change):\n box = self.form\n collection_widget = box.children[1]\n datatype_widget = box.children[2]\n path_widget = box.children[3]\n global_widgets = [box.children[4], box.children[5], box.children[6], box.children[7], box.children[8], box.children[9]]\n all_widgets = [collection_widget, datatype_widget, path_widget] + global_widgets\n generic_widgets = {\n 'Insert': [collection_widget, datatype_widget, path_widget] + global_widgets,\n 'Update': [collection_widget, datatype_widget, path_widget] + global_widgets,\n 'Display': [collection_widget, datatype_widget, path_widget],\n 'Delete': [collection_widget, datatype_widget, path_widget]\n }\n\n nongeneric_widgets = {\n 'Insert': [collection_widget, datatype_widget] + global_widgets,\n 'Update': [collection_widget, datatype_widget] + global_widgets,\n 'Display': [collection_widget, datatype_widget],\n 'Delete': [collection_widget, datatype_widget]\n }\n if str(ConfigForm.datatype.value) == 'Generic':\n widget_list = generic_widgets\n self.path_caption.remove_class('hidden')\n else:\n widget_list = nongeneric_widgets\n self.path_caption.add_class('hidden')\n\n active = str(ConfigForm.action.value)\n if active == 'Insert':\n show(widget_list['Insert'], all_widgets)\n elif active == 'Delete':\n show(widget_list['Delete'], all_widgets)\n elif active == 'Update':\n show(widget_list['Update'], all_widgets)\n else:\n show(widget_list['Display'], all_widgets)\n \n\n def split_list(str):\n seq = str.split('\\n')\n for key, value in enumerate(seq):\n seq[key] = value.strip()\n return seq\n\n # Ensure that a date is correctly formatted and start dates precede end dates\n def check_date_format(date):\n items = date.replace(' ', '').split(',')\n for item in items:\n if len(item) > 10:\n format = '%Y-%m-%dT%H:%M:%S'\n else:\n format = '%Y-%m-%d'\n try:\n if item != datetime.strptime(item, format).strftime(format):\n raise ValueError\n return True\n except ValueError:\n print('The date value ' + item + ' is in an incorrect format. Use YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.')\n if len(items) == 2:\n try:\n assert items[1] > items[0]\n except:\n print('Your end date ' + items[1] + ' must be after your start date ' + items[0] + '.')\n\n\n # Transform textarea with dates to a valid schema array\n def process_dates(datefield):\n date = datefield.strip().split('\\n')\n new_date = []\n d = {}\n\n # Validate all the date formats individually\n for item in date:\n check_date_format(item)\n\n # Determine if the datelist is a mix of normal and precise dates\n contains_precise = []\n for item in date:\n if ',' in item:\n start, end = item.replace(' ', '').split(',')\n if len(start) > 10 or len(end) > 10:\n contains_precise.append('precise')\n else:\n contains_precise.append('normal')\n elif len(item) > 10:\n contains_precise.append('precise')\n else:\n contains_precise.append('normal')\n # Handle a mix of normal and precise dates\n if 'normal' in contains_precise and 'precise' in contains_precise:\n d['normal'] = []\n d['precise'] = []\n for item in date:\n if ',' in item:\n start, end = item.replace(' ', '').split(',')\n if len(start) > 10 or len(end) > 10:\n d['precise'].append({'start': start, 'end': end})\n else:\n d['normal'].append({'start': start, 'end': end})\n else:\n if len(item) > 10:\n d['precise'].append(item)\n else:\n d['normal'].append(item)\n new_date.append(d)\n # Handle only precise dates\n elif 'precise' in contains_precise:\n d['precise'] = []\n for item in date:\n if ',' in item:\n start, end = item.replace(' ', '').split(',')\n d['precise'].append({'start': start, 'end': end})\n else:\n d['precise'].append(item)\n new_date.append(d)\n # Handle only normal dates\n else:\n for item in date:\n if ',' in item:\n start, end = item.replace(' ', '').split(',')\n new_date.append({'start': start, 'end': end})\n else:\n new_date.append(item)\n\n return new_date\n\n def handle_submit(values):\n # Save the form values in a dict\n self.values = {'action': ConfigForm.action.value}\n self.values['datatype'] = ConfigForm.datatype.value \n self.values['collection'] = ConfigForm.collection.value.strip()\n self.values['title'] = ConfigForm.title.value \n self.values['altTitle'] = ConfigForm.altTitle.value\n self.values['date'] = process_dates(ConfigForm.date.value) \n self.values['description'] = ConfigForm.description.value \n self.values['label'] = ConfigForm.label.value \n self.values['notes'] = split_list(ConfigForm.notes.value) \n if ConfigForm.action.value == 'Insert' or ConfigForm.action.value == 'Update':\n if ConfigForm.datatype.value == 'Generic':\n self.values['path'] = ConfigForm.rights.value.strip()\n self.values['path'] = ',' + self.values['path'].strip(',') + ','\n clear_output()\n print('Configuration saved. Values will be available is the cells below.')\n print(self.values)\n \n # Initialise widgets in the container Box\n self.form = Box([self.action, self.datatype, self.collection, self.path, self.title, \n self.altTitle, self.date, self.description, self.label, self.notes],\n layout=Layout(\n display='flex',\n flex_flow='column',\n border='solid 2px',\n align_items='stretch',\n width='50%'))\n\n # Modify the CSS and set up some helper variables\n box = self.form\n box.children[2].add_class('hidden')\n action_field = box.children[0].children[1]\n nodetype_field = box.children[1].children[1]\n \n # Display the form and watch for changes\n display(self.caption)\n display(self.path_caption)\n display(box)\n display(self.button)\n self.path_caption.add_class('hidden')\n nodetype_field.observe(change_visibility)\n action_field.observe(change_visibility)\n self.button.on_click(handle_submit)\n\n# Instantiate the form - values accessible with e.g. config.values['delete_id]\nconfig = ConfigForm(object)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
4aa70b7d66a8cdf1dff83f5721aa15d1c63a27ff
| 23,523 |
ipynb
|
Jupyter Notebook
|
1_MLP.ipynb
|
ChistyakovArtem/MyVeryOwnNeuralNetwork
|
cd946b13c92a06075a5ab720f2ddb755edbc831d
|
[
"MIT"
] | null | null | null |
1_MLP.ipynb
|
ChistyakovArtem/MyVeryOwnNeuralNetwork
|
cd946b13c92a06075a5ab720f2ddb755edbc831d
|
[
"MIT"
] | null | null | null |
1_MLP.ipynb
|
ChistyakovArtem/MyVeryOwnNeuralNetwork
|
cd946b13c92a06075a5ab720f2ddb755edbc831d
|
[
"MIT"
] | null | null | null | 38.124797 | 1,814 | 0.474259 |
[
[
[
"import numpy as np",
"_____no_output_____"
],
[
"class Regularizations:\n\n class L2:\n @staticmethod\n def reg(a):\n return np.mean(a**2)\n\n @staticmethod\n def reg_prime(a):\n return 2 * a / a.size",
"_____no_output_____"
],
[
"class Losses:\n\n class MSE:\n @staticmethod\n def loss(y_true, y_pred):\n return np.mean(np.power(y_true-y_pred, 2))\n\n @staticmethod\n def loss_prime(y_true, y_pred):\n # print(y_true.shape, y_pred.shape)\n return 2*(y_pred-y_true) / y_true.size",
"_____no_output_____"
],
[
"class Activations: # alphabet order\n\n class activation:\n @staticmethod\n def activation(a):\n return a\n\n @staticmethod\n def activation_prime(a):\n return 1\n\n\n class ReLU(activation):\n @staticmethod\n def activation(a):\n return np.maximum(a, 0)\n\n @staticmethod\n def activation_prime(a):\n ret = np.array(1 * (a > 0))\n return ret\n\n\n class sigmoid(activation):\n @staticmethod\n def activation(a):\n return 1 / (1 + np.exp(-a))\n\n @staticmethod\n def activation_prime(a):\n return a * (1 - a)\n\n\n class softmax(activation):\n @staticmethod\n def activation(a):\n exp = np.exp(a)\n return exp / (0.0001 + np.sum(exp, axis=0)) # mb 0\n\n @staticmethod\n def activation_prime(a):\n t = np.eye(N=a.shape[0], M=a.shape[1])\n return t * a * (1 - a) - (1 - t) * a * a\n\n\n class stable_softmax(activation):\n @staticmethod\n def activation(a):\n a = a - max(a)\n exp = np.exp(a)\n return exp / np.sum(exp, axis=1)\n\n # dont know prime\n\n\n class tanh(activation):\n @staticmethod\n def activation(a):\n return np.tanh(a)\n\n @staticmethod\n def activation_prime(a):\n return 1 - np.tanh(a)**2",
"_____no_output_____"
],
[
"class Layers:\n\n class DummyLayer:\n\n def __init__(self):\n self.input_shape = None\n self.output_shape = None\n\n def forward_pass(self, input):\n raise NotImplementedError\n\n def backward_pass(self, output):\n raise NotImplementedError\n\n\n\n class Dense(DummyLayer):\n\n def __init__(self, input_shape=None, output_shape=None, learning_rate=None, reg_const=None, reg_type=None):\n super().__init__()\n self.input_shape = input_shape\n self.output_shape = output_shape\n\n self.input = None\n self.output = None\n\n self.learning_rate = learning_rate\n self.reg_const = reg_const\n\n self.reg_type = reg_type\n\n if self.reg_type is None:\n self.reg_function = None\n self.reg_prime = None\n else:\n self.reg_function = reg_type.reg\n self.reg_prime = reg_type.reg_prime\n\n self.features_weights = np.random.rand(input_shape, output_shape) - 0.5\n self.bias_weights = np.random.rand(1, output_shape) - 0.5\n\n self.learnable = True\n\n def forward_pass(self, input):\n self.input = input\n self.output = input @ self.features_weights + self.bias_weights\n return self.output\n\n def backward_pass(self, output_error):\n input_error = output_error @ self.features_weights.T\n weights_error = self.input.T @ output_error + self.reg_const * self.reg_prime(self.features_weights)\n bias_error = np.sum(output_error, axis=0)\n\n self.features_weights -= self.learning_rate * weights_error\n self.bias_weights -= self.learning_rate * bias_error\n\n return input_error\n\n\n\n class Activation(DummyLayer):\n\n def __init__(self, activation_type=Activations.tanh):\n super().__init__()\n self.activation = activation_type.activation\n self.activation_prime = activation_type.activation_prime\n\n self.input = None\n self.output = None\n\n self.learnable = False\n\n def forward_pass(self, input):\n self.input = input\n self.output = self.activation(self.input)\n return self.output\n\n def backward_pass(self, output):\n return self.activation_prime(self.input) * output",
"_____no_output_____"
],
[
"class NeuralNetwork:\n\n def __init__(self, layers, default_learning_rate=0.01, default_reg_const=0.01, reg_type=Regularizations.L2, loss_class=Losses.MSE):\n self.layers = []\n for layer in layers:\n if layer.learnable:\n if layer.learning_rate is None:\n layer.learning_rate = default_learning_rate\n\n if layer.reg_const is None:\n layer.reg_const = default_reg_const\n\n if layer.reg_type is None:\n layer.reg_function = reg_type.reg\n layer.reg_prime = reg_type.reg_prime\n self.layers.append(layer)\n\n self.loss = loss_class.loss\n self.loss_prime = loss_class.loss_prime\n\n def fit(self, X, y, cnt_epochs=10, cnt_it=10000): # add optimizer\n it_for_epoch = cnt_it // cnt_epochs\n for i in range(cnt_epochs):\n for j in range(it_for_epoch):\n\n output = X\n for layer in self.layers:\n output = layer.forward_pass(output)\n\n error = self.loss_prime(y, output)\n\n for layer in reversed(self.layers):\n error = layer.backward_pass(error)\n\n print('epoch %d/%d error=%f' % (i+1, cnt_epochs, self.loss(y, self.predict(X))))\n\n def predict(self, X):\n output = X\n for layer in self.layers:\n output = layer.forward_pass(output)\n\n return output",
"_____no_output_____"
],
[
"X = np.array([[0, 0],\n [0, 1],\n [1, 0],\n [1, 1]])\n\ny = np.array([[0],\n [1],\n [1],\n [0]])\n\nprint(X.shape, y.shape)\n\nnn = NeuralNetwork([\n Layers.Dense(2, 2),\n Layers.Activation(activation_type=Activations.tanh),\n Layers.Dense(2, 1),\n Layers.Activation(activation_type=Activations.tanh)\n], default_learning_rate=0.01, default_reg_const=0)\n\nnn.fit(X, y, cnt_epochs=10, cnt_it=30000)\n\nnn.predict(X)",
"(4, 2) (4, 1)\nepoch 1/10 error=0.193711\nepoch 2/10 error=0.139242\nepoch 3/10 error=0.013316\nepoch 4/10 error=0.003122\nepoch 5/10 error=0.001546\nepoch 6/10 error=0.000989\nepoch 7/10 error=0.000715\nepoch 8/10 error=0.000555\nepoch 9/10 error=0.000451\nepoch 10/10 error=0.000378\n"
],
[
"# for mnist in colab\n!wget https://raw.githubusercontent.com/yandexdataschool/Practical_DL/35c067adcc1ab364c8803830cdb34d0d50eea37e/week01_backprop/util.py -O util.py\n!wget https://raw.githubusercontent.com/yandexdataschool/Practical_DL/35c067adcc1ab364c8803830cdb34d0d50eea37e/week01_backprop/mnist.py -O mnist.py",
"--2021-10-19 20:26:26-- https://raw.githubusercontent.com/yandexdataschool/Practical_DL/35c067adcc1ab364c8803830cdb34d0d50eea37e/week01_backprop/util.py\nResolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.109.133, 185.199.110.133, ...\nConnecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 3782 (3.7K) [text/plain]\nSaving to: ‘util.py’\n\nutil.py 100%[===================>] 3.69K --.-KB/s in 0s \n\n2021-10-19 20:26:26 (40.8 MB/s) - ‘util.py’ saved [3782/3782]\n\n--2021-10-19 20:26:26-- https://raw.githubusercontent.com/yandexdataschool/Practical_DL/35c067adcc1ab364c8803830cdb34d0d50eea37e/week01_backprop/mnist.py\nResolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...\nConnecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 2697 (2.6K) [text/plain]\nSaving to: ‘mnist.py’\n\nmnist.py 100%[===================>] 2.63K --.-KB/s in 0s \n\n2021-10-19 20:26:26 (16.0 MB/s) - ‘mnist.py’ saved [2697/2697]\n\n"
],
[
"import mnist",
"_____no_output_____"
],
[
"from mnist import load_dataset\nX_train, y_train, X_val, y_val, X_test, y_test = load_dataset(flatten=True)",
"_____no_output_____"
],
[
"a = y_train\nb = np.zeros((a.size, a.max()+1))\nb[np.arange(a.size),a] = 1\nb.shape",
"_____no_output_____"
],
[
"y_train_prepr = b",
"_____no_output_____"
],
[
"nn = NeuralNetwork([\n Layers.Dense(28*28, 100),\n Layers.Activation(activation_type=Activations.ReLU),\n Layers.Dense(100, 200),\n Layers.Activation(activation_type=Activations.ReLU),\n Layers.Dense(200, 10),\n], default_learning_rate=0.01)\n\nnn.fit(X_train, y_train_prepr, cnt_epochs=100, cnt_it=1000)",
"epoch 1/100 error=4.739836\n"
],
[
"val = np.argmax(nn.predict(X_train), axis=1)",
"_____no_output_____"
],
[
"print(y_train[0], val[0])",
"5 8\n"
],
[
"cnt = 0\nfor i in range(val.shape[0]):\n if val[i] == y_train[i]:\n cnt += 1\n\nprint(cnt / val.shape[0])",
"0.22102\n"
],
[
"",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aa715786b8a1d82173e03c67922b3cf07bec83c
| 23,769 |
ipynb
|
Jupyter Notebook
|
notebooks/03-defining-functions-with-python.ipynb
|
yaojenkuo/ntnu-fall-2020
|
5c2b3df1eae8e81cd05b883d20691ee40e349530
|
[
"MIT"
] | 3 |
2020-09-14T02:29:39.000Z
|
2020-09-28T08:13:53.000Z
|
notebooks/03-defining-functions-with-python.ipynb
|
yaojenkuo/ntnu-fall-2020
|
5c2b3df1eae8e81cd05b883d20691ee40e349530
|
[
"MIT"
] | null | null | null |
notebooks/03-defining-functions-with-python.ipynb
|
yaojenkuo/ntnu-fall-2020
|
5c2b3df1eae8e81cd05b883d20691ee40e349530
|
[
"MIT"
] | 5 |
2020-09-21T02:26:32.000Z
|
2021-01-11T04:10:32.000Z
| 23.121595 | 596 | 0.504565 |
[
[
[
"# Introduction to Python\n\n> Defining Functions with Python\n\nKuo, Yao-Jen",
"_____no_output_____"
],
[
"## TL; DR\n\n> In this lecture, we will talk about defining functions with Python.",
"_____no_output_____"
],
[
"## Encapsulations",
"_____no_output_____"
],
[
"## What is encapsulation?\n\n> Encapsulation refers to one of two related but distinct notions, and sometimes to the combination thereof:\n> 1. A language mechanism for restricting direct access to some of the object's components.\n> 2. A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.\n\nSource: <https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)>",
"_____no_output_____"
],
[
"## Why encapsulation?\n\nAs our codes piled up, we need a mechanism making them:\n- more structured\n- more reusable\n- more scalable",
"_____no_output_____"
],
[
"## Python provides several tools for programmers organizing their codes\n\n- Functions\n- Classes\n- Modules\n- Libraries",
"_____no_output_____"
],
[
"## How do we decide which tool to adopt?\n\nSimply put, that depends on **scale** and project spec.",
"_____no_output_____"
],
[
"## These components are mixed and matched with great flexibility\n\n- A couple lines of code assembles a function\n - A couple of functions assembles a class\n - A couple of classes assembles a module\n - A couple of modules assembles a library\n - A couple of libraries assembles a larger library",
"_____no_output_____"
],
[
"## Codes, assemble!\n\n\n\nSource: <https://giphy.com/>",
"_____no_output_____"
],
[
"## Functions",
"_____no_output_____"
],
[
"## What is a function\n\n> A function is a named sequence of statements that performs a computation, either mathematical, symbolic, or graphical. When we define a function, we specify the name and the sequence of statements. Later, we can call the function by name.",
"_____no_output_____"
],
[
"## Besides built-in functions or library-powered functions, we sometimes need to self-define our own functions\n\n- `def` the name of our function\n- `return` the output of our function\n\n```python\ndef function_name(INPUTS, ARGUMENTS, ...):\n \"\"\"\n docstring: print documentation when help() is called\n \"\"\"\n # sequence of statements\n return OUTPUTS\n```",
"_____no_output_____"
],
[
"## The principle of designing of a function is about mapping the relationship of inputs and outputs\n\n- The one-on-one relationship\n- The many-on-one relationship\n- The one-on-many relationship\n- The many-on-many releationship",
"_____no_output_____"
],
[
"## The one-on-one relationship\n\nUsing scalar as input and output.",
"_____no_output_____"
]
],
[
[
"def absolute(x):\n \"\"\"\n Return the absolute value of the x.\n \"\"\"\n if x >= 0:\n return x\n else:\n return -x",
"_____no_output_____"
]
],
[
[
"## Once the function is defined, call as if it is a built-in function",
"_____no_output_____"
]
],
[
[
"help(absolute)\nprint(absolute(-5566))\nprint(absolute(5566))\nprint(absolute(0))",
"Help on function absolute in module __main__:\n\nabsolute(x)\n Return the absolute value of the x.\n\n5566\n5566\n0\n"
]
],
[
[
"## The many-on-one relationship relationship\n\n- Using scalars or structures for fixed inputs\n- Using `*args` or `**kwargs` for flexible inputs",
"_____no_output_____"
],
[
"## Using scalars for fixed inputs",
"_____no_output_____"
]
],
[
[
"def product(x, y):\n \"\"\"\n Return the product values of x and y.\n \"\"\"\n return x*y\n\nprint(product(5, 6))",
"30\n"
]
],
[
[
"## Using structures for fixed inputs",
"_____no_output_____"
]
],
[
[
"def product(x):\n \"\"\"\n x: an iterable.\n Return the product values of x.\n \"\"\"\n prod = 1\n for i in x:\n prod *= i\n return prod\n\nprint(product([5, 5, 6, 6]))",
"900\n"
]
],
[
[
"## Using `*args` for flexible inputs\n\n- As in flexible arguments\n- Getting flexible `*args` as a `tuple`",
"_____no_output_____"
]
],
[
[
"def plain_return(*args):\n \"\"\"\n Return args.\n \"\"\"\n return args\n\nprint(plain_return(5, 5, 6, 6))",
"(5, 5, 6, 6)\n"
]
],
[
[
"## Using `**kwargs` for flexible inputs\n\n- AS in keyword arguments\n- Getting flexible `**kwargs` as a `dict`",
"_____no_output_____"
]
],
[
[
"def plain_return(**kwargs):\n \"\"\"\n Retrun kwargs.\n \"\"\"\n return kwargs\n\nprint(plain_return(TW='Taiwan', JP='Japan', CN='China', KR='South Korea'))",
"{'TW': 'Taiwan', 'JP': 'Japan', 'CN': 'China', 'KR': 'South Korea'}\n"
]
],
[
[
"## The one-on-many relationship\n\n- Using default `tuple` with comma\n- Using preferred data structure",
"_____no_output_____"
],
[
"## Using default `tuple` with comma",
"_____no_output_____"
]
],
[
[
"def as_integer_ratio(x):\n \"\"\"\n Return x as integer ratio.\n \"\"\"\n x_str = str(x)\n int_part = int(x_str.split(\".\")[0])\n decimal_part = x_str.split(\".\")[1]\n n_decimal = len(decimal_part)\n denominator = 10**(n_decimal)\n numerator = int(decimal_part)\n while numerator % 2 == 0 and denominator % 2 == 0:\n denominator /= 2\n numerator /= 2\n while numerator % 5 == 0 and denominator % 5 == 0:\n denominator /= 5\n numerator /= 5\n final_numerator = int(int_part*denominator + numerator)\n final_denominator = int(denominator)\n return final_numerator, final_denominator\n\nprint(as_integer_ratio(3.14))\nprint(as_integer_ratio(0.56))",
"(157, 50)\n(14, 25)\n"
]
],
[
[
"## Using preferred data structure",
"_____no_output_____"
]
],
[
[
"def as_integer_ratio(x):\n \"\"\"\n Return x as integer ratio.\n \"\"\"\n x_str = str(x)\n int_part = int(x_str.split(\".\")[0])\n decimal_part = x_str.split(\".\")[1]\n n_decimal = len(decimal_part)\n denominator = 10**(n_decimal)\n numerator = int(decimal_part)\n while numerator % 2 == 0 and denominator % 2 == 0:\n denominator /= 2\n numerator /= 2\n while numerator % 5 == 0 and denominator % 5 == 0:\n denominator /= 5\n numerator /= 5\n final_numerator = int(int_part*denominator + numerator)\n final_denominator = int(denominator)\n integer_ratio = {\n 'numerator': final_numerator,\n 'denominator': final_denominator\n }\n return integer_ratio\n\nprint(as_integer_ratio(3.14))\nprint(as_integer_ratio(0.56))",
"{'numerator': 157, 'denominator': 50}\n{'numerator': 14, 'denominator': 25}\n"
]
],
[
[
"## The many-on-many relationship\n\nA mix-and-match of one-on-many and many-on-one relationship.",
"_____no_output_____"
],
[
"## Handling errors",
"_____no_output_____"
],
[
"## Coding mistakes are common, they happen all the time\n\n\n\nSource: Google Search",
"_____no_output_____"
],
[
"## How does a function designer handle errors?\n\nPython mistakes come in three basic flavors:\n- Syntax errors\n- Runtime errors\n- Semantic errors",
"_____no_output_____"
],
[
"## Syntax errors\n\nErrors where the code is not valid Python (generally easy to fix).",
"_____no_output_____"
]
],
[
[
"# Python does not need curly braces to create a code block\nfor (i in range(10)) {print(i)}",
"_____no_output_____"
]
],
[
[
"## Runtime errors\n\nErrors where syntactically valid code fails to execute, perhaps due to invalid user input (sometimes easy to fix)\n\n- `NameError`\n- `TypeError`\n- `ZeroDivisionError`\n- `IndexError`\n- ...etc.",
"_____no_output_____"
]
],
[
[
"print('5566'[4])",
"_____no_output_____"
]
],
[
[
"## Semantic errors\n\nErrors in logic: code executes without a problem, but the result is not what you expect (often very difficult to identify and fix)",
"_____no_output_____"
]
],
[
[
"def product(x):\n \"\"\"\n x: an iterable.\n Return the product values of x.\n \"\"\"\n prod = 0 # set \n for i in x:\n prod *= i\n return prod\n\nprint(product([5, 5, 6, 6])) # expecting 900",
"0\n"
]
],
[
[
"## Using `try` and `except` to catch exceptions\n\n```python\ntry:\n # sequence of statements if everything is fine\nexcept TYPE_OF_ERROR:\n # sequence of statements if something goes wrong\n```",
"_____no_output_____"
]
],
[
[
"try:\n exec(\"\"\"for (i in range(10)) {print(i)}\"\"\")\nexcept SyntaxError:\n print(\"Encountering a SyntaxError.\")",
"Encountering a SyntaxError.\n"
],
[
"try:\n print('5566'[4])\nexcept IndexError:\n print(\"Encountering a IndexError.\")",
"Encountering a IndexError.\n"
],
[
"try:\n print(5566 / 0)\nexcept ZeroDivisionError:\n print(\"Encountering a ZeroDivisionError.\")",
"Encountering a ZeroDivisionError.\n"
],
[
"# it is optional to specify the type of error\ntry:\n print(5566 / 0)\nexcept:\n print(\"Encountering a whatever error.\")",
"Encountering a whatever error.\n"
]
],
[
[
"## Scope",
"_____no_output_____"
],
[
"## When it comes to defining functions, it is vital to understand the scope of a variable",
"_____no_output_____"
],
[
"## What is scope?\n\n> In computer programming, the scope of a name binding, an association of a name to an entity, such as a variable, is the region of a computer program where the binding is valid.\n\nSource: <https://en.wikipedia.org/wiki/Scope_(computer_science)>",
"_____no_output_____"
],
[
"## Simply put, now we have a self-defined function, so the programming environment is now split into 2:\n\n- Global\n- Local",
"_____no_output_____"
],
[
"## A variable declared within the indented block of a function is a local variable, it is only valid inside the `def` block",
"_____no_output_____"
]
],
[
[
"def check_odd_even(x):\n mod = x % 2 # local variable, declared inside def block\n if mod == 0:\n return '{} is a even number.'.format(x)\n else:\n return '{} is a odd number.'.format(x)\n\nprint(check_odd_even(0))\nprint(x)",
"0 is a even number.\n"
],
[
"print(mod)",
"_____no_output_____"
]
],
[
[
"## A variable declared outside of the indented block of a function is a glocal variable, it is valid everywhere",
"_____no_output_____"
]
],
[
[
"x = 0\nmod = x % 2\ndef check_odd_even():\n if mod == 0:\n return '{} is a even number.'.format(x)\n else:\n return '{} is a odd number.'.format(x)\n\nprint(check_odd_even())\nprint(x)\nprint(mod)",
"0 is a even number.\n0\n0\n"
]
],
[
[
"## Although global variable looks quite convenient, it is HIGHLY recommended NOT using global variable directly in a indented function block.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aa74dd6f648f32c26197e9d92d7078d7ee01e1a
| 122,070 |
ipynb
|
Jupyter Notebook
|
hcds-a1-data-curation.ipynb
|
EdmundTse/data-512-a1
|
4a5e00fea5462300ed74b79fb89e0ab40063e0ef
|
[
"MIT"
] | null | null | null |
hcds-a1-data-curation.ipynb
|
EdmundTse/data-512-a1
|
4a5e00fea5462300ed74b79fb89e0ab40063e0ef
|
[
"MIT"
] | null | null | null |
hcds-a1-data-curation.ipynb
|
EdmundTse/data-512-a1
|
4a5e00fea5462300ed74b79fb89e0ab40063e0ef
|
[
"MIT"
] | null | null | null | 132.11039 | 89,088 | 0.835029 |
[
[
[
"# DATA512 A1: Data Curation\n\nHow does English Wikipedia page traffic trend over time? To answer this question, we plot Wikimedia traffic data spanning from 1 January, 2008 to 30 September 2018. We combine data from two Wikimedia APIs, each covering a different period of time, so that we can show the trend over 10 years.\n\nThe first API is [Legacy Pagecounts](https://wikitech.wikimedia.org/wiki/Analytics/AQS/Legacy_Pagecounts), with aggregated data from January 2008 to July 2016. The second API is [Pageviews](https://wikitech.wikimedia.org/wiki/Analytics/AQS/Pageviews), with aggregated data starting from May 2015. Besides the difference in periods for which data is available, there is a quality difference between the two APIs: Pagecounts did not differentiate between traffic generated by a person or by automated robots and web crawlers. The new Pageviews API does make this differentiation and lets us count traffic from agents not identified as web spiders.\n\nThe data acquired from both these two API endpoints were available in the public domain under the CC0 1.0 license, according to Wikimedia's [RESTBase](https://wikimedia.org/api/rest_v1/) documentation. Use of these APIs are subject to [terms and conditions from Wikimedia](https://www.mediawiki.org/wiki/REST_API#Terms_and_conditions).\n\n## Data dictionary\nCleaned data from the Wikimedia API are saved to `en-wikipedia_traffic_200712-201809.csv` with the following fields:\n\n| Column Name | Description | Format |\n|-------------------------|-----------------------------|---------|\n| year | 4-digit year of the period | YYYY |\n| month | 2-digit month of the period | MM |\n| pagecount_all_views | Number of desktop views | integer |\n| pagecount_desktop_views | Number of desktop views | integer |\n| pagecount_mobile_views | Number of desktop views | integer |\n| pageview_all_views | Number of desktop views | integer |\n| pageview_desktop_views | Number of desktop views | integer |\n| pageview_mobile_views | Number of desktop views | integer |\n",
"_____no_output_____"
],
[
"## Data acquisition\nIn this section, we download data from the Wikimedia APIs and save the raw response JSON object to the raw data folder.",
"_____no_output_____"
]
],
[
[
"import os, errno\nimport json\nimport requests\n\n# API rules require setting a unique User-Agent or Api-User-Agent\n# that makes it easy for the API caller to be contacted.\nHEADERS = {\n 'Api-User-Agent': 'https://github.com/EdmundTse/data-512-a1'\n}\n\ndef api_call(endpoint, parameters):\n \"\"\"Makes an web request to the supplied Wikimedia API endpoint.\"\"\"\n call = requests.get(endpoint.format(**parameters), headers=HEADERS)\n response = call.json()\n return response",
"_____no_output_____"
],
[
"# Create the raw data folder, if it doesn't already exist.\n# https://stackoverflow.com/questions/273192/\n\nRAW_DATA_DIR = \"data_raw\"\n\ntry:\n os.makedirs(RAW_DATA_DIR)\n print(\"Created a folder named '%s'.\" % RAW_DATA_DIR)\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n raise",
"Created a folder named 'data_raw'.\n"
]
],
[
[
"First, collect data from the legacy API for all of the months where data is available. The API call requests data for the entire period of interest, and the API should return the months where data is available.",
"_____no_output_____"
]
],
[
[
"ENDPOINT_LEGACY = 'https://wikimedia.org/api/rest_v1/metrics/legacy/' + \\\n 'pagecounts/aggregate/{project}/{access-site}/{granularity}/{start}/{end}'\n\naccess_types = [\"all-sites\", \"desktop-site\", \"mobile-site\"]\npagecounts_data_files = []\n\nfor access in access_types:\n filename = 'pagecounts_%s_200801-201809.json' % access\n path = os.path.join(RAW_DATA_DIR, filename)\n pagecounts_data_files.append(path)\n \n # Don't re-download if we already have the data.\n if os.path.exists(path):\n print(\"Skipped download of pagecounts '%s' data since %s already exists.\" % (access, filename))\n continue\n \n params = {\n \"project\": \"en.wikipedia\",\n \"access-site\": access,\n \"granularity\": \"monthly\",\n \"start\": \"2008010100\",\n # In monthly granularity, the value is exclusive. So we use\n # the first day of the month after the final month of data\n \"end\": \"2018100100\"\n }\n\n pageviews = api_call(ENDPOINT_LEGACY, params)\n \n with open(path, 'w') as f:\n json.dump(pageviews, f)\n print(\"Pagecounts '%s' data saved to %s.\" % (access, filename))",
"Pagecounts 'all-sites' data saved to pagecounts_all-sites_200801-201809.json.\nPagecounts 'desktop-site' data saved to pagecounts_desktop-site_200801-201809.json.\nPagecounts 'mobile-site' data saved to pagecounts_mobile-site_200801-201809.json.\n"
]
],
[
[
"Similarly, collect data from the new pagecounts API for all of the months where data is available.",
"_____no_output_____"
]
],
[
[
"ENDPOINT_PAGEVIEWS = 'https://wikimedia.org/api/rest_v1/metrics/' + \\\n 'pageviews/aggregate/{project}/{access}/{agent}/{granularity}/{start}/{end}'\n\naccess_types = [\"all-access\", \"desktop\", \"mobile-app\", \"mobile-web\"]\npageviews_data_files = []\n\nfor access in access_types:\n filename = 'pageviews_%s_200801-201809.json' % access\n path = os.path.join(RAW_DATA_DIR, filename)\n pageviews_data_files.append(path)\n \n # Don't re-download if we already have the data.\n if os.path.exists(path):\n print(\"Skipping download of pageviews '%s' data since %s already exists.\" % (access, filename))\n continue\n \n params = {\n \"project\": \"en.wikipedia\",\n \"access\": access,\n \"agent\": \"user\", # Ignore traffic generated by spiders\n \"granularity\": \"monthly\",\n \"start\": \"2008010100\",\n # Unlike the legacy API, the end value here value is exclusive.\n # So we use the last day of the month of data we need\n \"end\": \"2018093000\"\n }\n\n pageviews = api_call(ENDPOINT_PAGEVIEWS, params)\n \n with open(path, 'w') as f:\n json.dump(pageviews, f)\n print(\"Pageviews '%s' data downloaded to %s.\" % (access, filename))",
"Pageviews 'all-access' data downloaded to pageviews_all-access_200801-201809.json.\nPageviews 'desktop' data downloaded to pageviews_desktop_200801-201809.json.\nPageviews 'mobile-app' data downloaded to pageviews_mobile-app_200801-201809.json.\nPageviews 'mobile-web' data downloaded to pageviews_mobile-web_200801-201809.json.\n"
]
],
[
[
"## Data processing\nIn this step, we combine the data from both APIs",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nfrom pandas.io.json import json_normalize\n\n# Create the cleaned data folder, if it doesn't already exist.\n\nCLEAN_DATA_DIR = \"data_clean\"\n\ntry:\n os.makedirs(CLEAN_DATA_DIR)\n print(\"Created a folder named '%s'.\" % CLEAN_DATA_DIR)\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n raise",
"Created a folder named 'data_clean'.\n"
]
],
[
[
"First, process the data from the legacy pagecounts API.",
"_____no_output_____"
]
],
[
[
"# Read and combine all of the downloaded pagecounts data into one dataframe\ndataframes = []\n\nfor file in pagecounts_data_files:\n with open(file) as f:\n data = json.load(f)\n \n df = json_normalize(data, record_path=\"items\")\n dataframes.append(df)\n\n# Concatenate the dataframes and adapt to the desired format\ndf_pagecounts = pd.concat(dataframes)\ndf_pagecounts.loc[:, \"source\"] = df_pagecounts['access-site'] \\\n .replace({\n \"all-sites\": \"pagecount_all_views\",\n \"desktop-site\": \"pagecount_desktop_views\",\n \"mobile-site\": \"pagecount_mobile_views\"\n })\ndf_pagecounts.loc[:, 'date'] = pd.to_datetime(df_pagecounts.timestamp, format='%Y%m%d00')\ndf_pagecounts = df_pagecounts.drop(['access-site', 'granularity', 'project', 'timestamp'], axis=1)\ndf_pagecounts = df_pagecounts.rename(index=str, columns={'count': 'views'})\ndf_pagecounts.tail()",
"_____no_output_____"
]
],
[
[
"We see that there is an entry for the month of August 2016, and it is about an order of magnitude smaller than previous months. The API documentation states that data will never be updated after July 2016, so the value we see for August 2016 might be from the first few days of the month while the data processing is being shut down. For our purposes, we will remove all entries after July 2016.",
"_____no_output_____"
]
],
[
[
"df_pagecounts = df_pagecounts[df_pagecounts.date < pd.datetime(2016, 8, 1)]",
"_____no_output_____"
]
],
[
[
"Now, process the data from the pageviews API. This API not only allows us to request only organic user traffic, it also splits mobile views into mobile app and mobile web. We shall add these two values together to produce one mobile views number.",
"_____no_output_____"
]
],
[
[
"# Read and combine all of the downloaded pageviews data into one dataframe\ndataframes = []\n\nfor file in pageviews_data_files:\n with open(file) as f:\n data = json.load(f)\n \n df = json_normalize(data, record_path=\"items\")\n dataframes.append(df)\n\n# Concatenate the dataframes and adapt to the desired format\ndf_pageviews = pd.concat(dataframes)\ndf_pageviews.loc[:, \"source\"] = df_pageviews['access'] \\\n .replace({\n \"all-access\": \"pageview_all_views\",\n \"desktop\": \"pageview_desktop_views\",\n \"mobile-app\": \"pageview_mobile_views\", # Combine mobile-app and mobile-web\n \"mobile-web\": \"pageview_mobile_views\" # views into mobile views\n })\ndf_pageviews.loc[:, 'date'] = pd.to_datetime(df_pageviews.timestamp, format='%Y%m%d00')\ndf_pageviews = df_pageviews.drop(['access', 'agent', 'granularity', 'project', 'timestamp'], axis=1)\n\ndf_pageviews.head()",
"_____no_output_____"
]
],
[
[
"With the data from both APIs in tables with common columns, we can now concatenate them before using a pivot table reshape it into the required format for outputting to CSV. With a pivot table, we specify that values for the same month and source are combined by taking the sum over the values. This is needed for pageview_mobile_views since we converted both mobile-app and mobile-web access types into the same 'mobile' type.",
"_____no_output_____"
]
],
[
[
"df = pd.concat([df_pagecounts, df_pageviews], sort=False)\nnew_index = pd.DatetimeIndex(df.date).to_period(freq='M')\ndf = df.pivot_table(values='views', index=new_index, columns='source', aggfunc='sum', fill_value=0)\ndf.loc[:, 'year'] = df.index.year\ndf.loc[:, 'month'] = df.index.month\ndf.head()",
"_____no_output_____"
],
[
"# Output the cleaned data in the required format\nCLEANED_FILENAME = 'en-wikipedia_traffic_200712-201809.csv'\ncleaned_filepath = os.path.join(CLEAN_DATA_DIR, CLEANED_FILENAME)\n\nOUTPUT_COLUMNS = [\n 'year',\n 'month',\n 'pagecount_all_views',\n 'pagecount_desktop_views',\n 'pagecount_mobile_views',\n 'pageview_all_views',\n 'pageview_desktop_views',\n 'pageview_mobile_views'\n]\n\ndf.to_csv(cleaned_filepath, columns=OUTPUT_COLUMNS, index=False)",
"_____no_output_____"
]
],
[
[
"## Analysis\n\nTo understand how the English Wikipedia page traffic trends over time, we will plot each of the series of data from old and new API as well as for mobile, desktop and the total traffic (mobile plus desktop). Because the pageviews count ranges into the billions, we divide the counts by 1 million to make the numbers shown on the y-axis more readable.",
"_____no_output_____"
]
],
[
[
"# Create the results data folder, if it doesn't already exist.\n\nRESULTS_DIR = \"results\"\n\ntry:\n os.makedirs(RESULTS_DIR)\n print(\"Created a folder named '%s'.\" % RESULTS_DIR)\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n raise",
"Created a folder named 'results'.\n"
],
[
"# Re-create the pivot table, without filling NA values with zeros, for a cleaner plot\ndf = pd.concat([df_pagecounts, df_pageviews], sort=False)\ndf = df.pivot_table(values='views', index=new_index, columns='source', aggfunc='sum')\n\n# Rescale the values into \"millions of views\" for easier to read numbers\ndf = df / 1e6\n\ndf.head()",
"_____no_output_____"
],
[
"%matplotlib inline\n\nimport matplotlib.lines as mlines\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\n\nplt.style.use('seaborn-bright')\n\npagecount_series = ['pagecount_all_views', 'pagecount_desktop_views', 'pagecount_mobile_views']\npageview_series = ['pageview_all_views', 'pageview_desktop_views', 'pageview_mobile_views']\n\nfig, ax = plt.subplots(figsize=(16,8))\ndf.loc[:, pageview_series].plot(ax=ax, style='-')\nax.set_prop_cycle(None) # Reset colour cycling\ndf.loc[:, pagecount_series].plot(ax=ax, style='--')\n\nlinestyle_legend = [mlines.Line2D([], [], color='k', linestyle='--', label=\"'Pagecounts' data from legacy API\"),\n mlines.Line2D([], [], color='k', linestyle='-', label=\"New 'Pageviews' data ignore web crawlers\")]\nax.add_artist(ax.legend(handles=linestyle_legend))\n\nax.legend([\"Total\", \"Desktop site\", \"Mobile site\"], loc=2)\n\nax.set_title(\"English Wikipedia's monthly page views stabilised since 2014\")\nax.set_xlabel(\"Year\")\nax.set_ylabel(\"Monthly page views (millions)\")\nax.set_ylim((0, None)) # Make the value axis for page views start from 0",
"_____no_output_____"
],
[
"# Save the plot to file\nPLOT_FILENAME = 'en-wikipedia_traffic_200712-201809.png'\nplot_filepath = os.path.join(RESULTS_DIR, PLOT_FILENAME)\nfig.savefig(plot_filepath)",
"_____no_output_____"
]
],
[
[
"## Findings\nFrom the plot, we can see that page traffic for English Wikipedia steadily rose from 2008 until about 2014, when the page traffic became stable at around 8 billion views per month.\n\nBefore mid-2014, Wikimedia only reported one desktop pagecounts number. Since then it separated page views into desktop and mobile, when it also started to report a total value for the combination of the two.\n\nThe total pageviews using the new Pageviews API reported substantially fewer views than the legacy API. Comparing the two lines during the overlapping period, it appears roughly one tenth of all traffic was due to web crawlers.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
4aa75bb3787251d9ce61392cb9e85692c3ac41f1
| 88,092 |
ipynb
|
Jupyter Notebook
|
sample_project/Introduction to pandas.ipynb
|
Istiakmorsalin/ML-Data-Science
|
681e68059b146343ef55b0671432dc946970730d
|
[
"MIT"
] | null | null | null |
sample_project/Introduction to pandas.ipynb
|
Istiakmorsalin/ML-Data-Science
|
681e68059b146343ef55b0671432dc946970730d
|
[
"MIT"
] | null | null | null |
sample_project/Introduction to pandas.ipynb
|
Istiakmorsalin/ML-Data-Science
|
681e68059b146343ef55b0671432dc946970730d
|
[
"MIT"
] | null | null | null | 37.95433 | 18,692 | 0.546009 |
[
[
[
"import pandas as pd",
"_____no_output_____"
],
[
"# 2 main datatypes \nseries = pd.series([\"BMW\",\"Toyota\", \"Honda\", \"RangeRover\"])",
"_____no_output_____"
],
[
"# 2 main datatypes \nseries = pd.Series([\"BMW\",\"Toyota\", \"Honda\", \"RangeRover\"])",
"_____no_output_____"
],
[
"series",
"_____no_output_____"
],
[
"colors = pd.Series([\"red\", \"blue\", \"green\", \"white\"])",
"_____no_output_____"
],
[
"colors",
"_____no_output_____"
],
[
"car_data = pd.DataFrame({\"Car make\": series, \"Color\": colors})\n",
"_____no_output_____"
],
[
"car_data",
"_____no_output_____"
],
[
"car_sales = pd.read_csv('car-sales.csv')",
"_____no_output_____"
],
[
"car_sales",
"_____no_output_____"
],
[
"## Describe data",
"_____no_output_____"
],
[
"## Describe Data",
"_____no_output_____"
],
[
"import pandas as pd",
"_____no_output_____"
],
[
"car_sales = pd.read_csv('car-sales.csv')",
"_____no_output_____"
],
[
"car_sales.dtypes",
"_____no_output_____"
],
[
"car_sales.columns",
"_____no_output_____"
],
[
"car_colums = car_sales.columns\ncar_colums",
"_____no_output_____"
],
[
"car_sales.index",
"_____no_output_____"
],
[
"car_sales",
"_____no_output_____"
],
[
"car_sales.describe()",
"_____no_output_____"
],
[
"car_sales.mean",
"_____no_output_____"
],
[
"car_sales.sum()",
"_____no_output_____"
],
[
"car_sales.describe()",
"_____no_output_____"
],
[
"car_sales",
"_____no_output_____"
],
[
"car_sales[\"Doors\"].sum()",
"_____no_output_____"
],
[
"car_sales[\"Make\"].sum()",
"_____no_output_____"
],
[
"len(car_sales)",
"_____no_output_____"
],
[
"car-sales",
"_____no_output_____"
],
[
"car_sales",
"_____no_output_____"
],
[
"car_sales = pd.read_csv('car-sales.csv')",
"_____no_output_____"
],
[
"car_sales = pd.read_csv('car-sales.csv')",
"_____no_output_____"
],
[
"import pandas as pd",
"_____no_output_____"
],
[
"car_sales = pd.read_csv('car-sales.csv')",
"_____no_output_____"
],
[
"car_sales.head()",
"_____no_output_____"
],
[
"car_sales.head(7)",
"_____no_output_____"
],
[
"car_sales.tail()",
"_____no_output_____"
],
[
"car_sales.tail(3)",
"_____no_output_____"
],
[
"# .loc & .iloc",
"_____no_output_____"
],
[
"animals = pd.Series([\"cat\", \"dog\", \"bird\", \"panda\", \"snake\"], index=[0,3,9,8,3])",
"_____no_output_____"
],
[
"animals",
"_____no_output_____"
],
[
"animals",
"_____no_output_____"
],
[
"animals.loc[3]",
"_____no_output_____"
],
[
"animals.loc[9]",
"_____no_output_____"
],
[
"car_sales",
"_____no_output_____"
],
[
"car_sales.loc[3]",
"_____no_output_____"
],
[
"animal.iloc[3]",
"_____no_output_____"
],
[
"animals.iloc[3]",
"_____no_output_____"
],
[
"car_sales.loc[:3]",
"_____no_output_____"
],
[
"pd.crosstab(car_sales[\"Make\"], car_sales[\"Doors\"])",
"_____no_output_____"
],
[
"car_sales.",
"_____no_output_____"
],
[
"#Groupby",
"_____no_output_____"
],
[
"car_sales.groupby([\"Make\"]).mean()",
"_____no_output_____"
],
[
"car_sales[\"Odometer (KM)\"].plot()",
"_____no_output_____"
],
[
"car_sales[\"Odometer (KM)\"].hist()",
"_____no_output_____"
],
[
"## Manipulating Data",
"_____no_output_____"
],
[
"car_sales[\"Make\"].str.lower()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aa764bc173c05ab4f95104d0998d747f48e8176
| 21,625 |
ipynb
|
Jupyter Notebook
|
questions_and_problem_sets/module_10/m10_notebook.ipynb
|
UWNETLAB/doing_computational_social_science
|
b9266460d04845dd6131630454b98f18d2587946
|
[
"MIT"
] | 2 |
2022-01-02T19:45:48.000Z
|
2022-01-07T15:01:26.000Z
|
questions_and_problem_sets/module_10/m10_notebook.ipynb
|
UWNETLAB/dcss_supplementary
|
67513a9f8c96df5fd9f1b70089122a74574e8e51
|
[
"MIT"
] | null | null | null |
questions_and_problem_sets/module_10/m10_notebook.ipynb
|
UWNETLAB/dcss_supplementary
|
67513a9f8c96df5fd9f1b70089122a74574e8e51
|
[
"MIT"
] | 3 |
2021-09-13T17:44:44.000Z
|
2021-11-17T00:45:50.000Z
| 21,625 | 21,625 | 0.697064 |
[
[
[
"<br><br><font color=\"gray\">DOING COMPUTATIONAL SOCIAL SCIENCE<br>MODULE 10 <strong>PROBLEM SETS</strong></font>\n\n# <font color=\"#49699E\" size=40>MODULE 10 </font>\n\n\n# What You Need to Know Before Getting Started\n\n- **Every notebook assignment has an accompanying quiz**. Your work in each notebook assignment will serve as the basis for your quiz answers.\n- **You can consult any resources you want when completing these exercises and problems**. Just as it is in the \"real world:\" if you can't figure out how to do something, look it up. My recommendation is that you check the relevant parts of the assigned reading or search for inspiration on [https://stackoverflow.com](https://stackoverflow.com).\n- **Each problem is worth 1 point**. All problems are equally weighted.\n- **The information you need for each problem set is provided in the blue and green cells.** General instructions / the problem set preamble are in the blue cells, and instructions for specific problems are in the green cells. **You have to execute all of the code in the problem set, but you are only responsible for entering code into the code cells that immediately follow a green cell**. You will also recognize those cells because they will be incomplete. You need to replace each blank `▰▰#▰▰` with the code that will make the cell execute properly (where # is a sequentially-increasing integer, one for each blank).\n- Most modules will contain at least one question that requires you to load data from disk; **it is up to you to locate the data, place it in an appropriate directory on your local machine, and replace any instances of the `PATH_TO_DATA` variable with a path to the directory containing the relevant data**.\n- **The comments in the problem cells contain clues indicating what the following line of code is supposed to do.** Use these comments as a guide when filling in the blanks. \n- **You can ask for help**. If you run into problems, you can reach out to John ([email protected]) or Pierson ([email protected]) for help. You can ask a friend for help if you like, regardless of whether they are enrolled in the course.\n\nFinally, remember that you do not need to \"master\" this content before moving on to other course materials, as what is introduced here is reinforced throughout the rest of the course. You will have plenty of time to practice and cement your new knowledge and skills.\n<div class='alert alert-block alert-danger'>As you complete this assignment, you may encounter variables that can be assigned a wide variety of different names. Rather than forcing you to employ a particular convention, we leave the naming of these variables up to you. During the quiz, submit an answer of 'USER_DEFINED' (without the quotation marks) to fill in any blank that you assigned an arbitrary name to. In most circumstances, this will occur due to the presence of a local iterator in a for-loop.</b></div>",
"_____no_output_____"
],
[
"## Package Imports",
"_____no_output_____"
]
],
[
[
"import pandas as pd \n\nimport numpy as np\nfrom numpy.random import seed as np_seed\n\n\nimport graphviz\nfrom graphviz import Source\n\nfrom pyprojroot import here\n\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport seaborn as sns\n\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split, cross_val_score, ShuffleSplit\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso, LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier, export_graphviz\nfrom sklearn.ensemble import BaggingClassifier, RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.preprocessing import LabelEncoder, LabelBinarizer\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.random import set_seed\n\nimport spacy \n\nfrom time import time\n\nset_seed(42)\nnp_seed(42)\n\n",
"_____no_output_____"
]
],
[
[
"## Defaults",
"_____no_output_____"
]
],
[
[
"x_columns = [\n\n # Religion and Morale\n 'v54', # Religious services? - 1=More than Once Per Week, 7=Never\n 'v149', # Do you justify: claiming state benefits? - 1=Never, 10=Always\n 'v150', # Do you justify: cheating on tax? - 1=Never, 10=Always \n 'v151', # Do you justify: taking soft drugs? - 1=Never, 10=Always \n 'v152', # Do you justify: taking a bribe? - 1=Never, 10=Always \n 'v153', # Do you justify: homosexuality? - 1=Never, 10=Always \n 'v154', # Do you justify: abortion? - 1=Never, 10=Always \n 'v155', # Do you justify: divorce? - 1=Never, 10=Always \n 'v156', # Do you justify: euthanasia? - 1=Never, 10=Always \n 'v157', # Do you justify: suicide? - 1=Never, 10=Always \n 'v158', # Do you justify: having casual sex? - 1=Never, 10=Always \n 'v159', # Do you justify: public transit fare evasion? - 1=Never, 10=Always \n 'v160', # Do you justify: prostitution? - 1=Never, 10=Always \n 'v161', # Do you justify: artificial insemination? - 1=Never, 10=Always \n 'v162', # Do you justify: political violence? - 1=Never, 10=Always \n 'v163', # Do you justify: death penalty? - 1=Never, 10=Always \n\n # Politics and Society\n 'v97', # Interested in Politics? - 1=Interested, 4=Not Interested\n 'v121', # How much confidence in Parliament? - 1=High, 4=Low\n 'v126', # How much confidence in Health Care System? - 1=High, 4=Low\n 'v142', # Importance of Democracy - 1=Unimportant, 10=Important\n 'v143', # Democracy in own country - 1=Undemocratic, 10=Democratic\n 'v145', # Political System: Strong Leader - 1=Good, 4=Bad\n# 'v208', # How often follow politics on TV? - 1=Daily, 5=Never\n# 'v211', # How often follow politics on Social Media? - 1=Daily, 5=Never\n\n # National Identity\n 'v170', # How proud are you of being a citizen? - 1=Proud, 4=Not Proud\n 'v184', # Immigrants: impact on development of country - 1=Bad, 5=Good\n 'v185', # Immigrants: take away jobs from Nation - 1=Take, 10=Do Not Take\n 'v198', # European Union Enlargement - 1=Should Go Further, 10=Too Far Already\n]\n\ny_columns = [\n # Overview\n 'country',\n \n # Socio-demographics\n 'v226', # Year of Birth by respondent \n 'v261_ppp', # Household Monthly Net Income, PPP-Corrected\n\n]\n",
"_____no_output_____"
]
],
[
[
"## Problem 1:\n<div class=\"alert alert-block alert-info\"> \nIn this assignment, we're going to continue our exploration of the European Values Survey dataset. By wielding the considerable power of Artificial Neural Networks, we'll aim to create a model capable of predicting an individual survey respondent's country of residence. As with all machine/deep learning projects, our first task will involve loading and preparing the data.\n</div>\n<div class=\"alert alert-block alert-success\">\nLoad the EVS dataset and use it to create a feature matrix (using all columns from x_columns) and (with the assistance of Scikit Learn's LabelBinarizer) a target array (representing each respondent's country of residence). \n</div>",
"_____no_output_____"
]
],
[
[
"# Load EVS Dataset \ndf = pd.read_csv(PATH_TO_DATA/\"evs_module_08.csv\")\n\n# Create Feature Matrix (using all columns from x_columns)\nX = df[x_columns] \n\n# Initialize LabelBinarizer\ncountry_encoder = ▰▰1▰▰()\n\n# Fit the LabelBinarizer instance to the data's 'country' column and store transformed array as target \ny = country_encoder.▰▰2▰▰(np.array(▰▰3▰▰))",
"_____no_output_____"
]
],
[
[
"## Problem 2:\n\n<div class=\"alert alert-block alert-info\"> \nAs part of your work in the previous module, you were introduced to the concept of the train-validate-test split. Up until now, we had made extensive use of Scikit Learn's preprocessing and cross-validation suites in order to easily get the most out of our data. Since we're using TensorFlow for our Artificial Neural Networks, we're going to have to change course a little: we can still use the <code>train_test_split</code> function, but we must now use it twice: the first iteration will produce our test set and a 'temporary' dataset; the second iteration will split the 'temporary' data into training and validation sets. Throughout this process, we must take pains to ensure that each of the data splits are shuffled and stratified. \n</div>\n<div class=\"alert alert-block alert-success\">\nCreate shuffled, stratified splits for testing (10% of original dataset), validation (10% of data remaining from test split), and training (90% of data remaining from test split) sets. Submit the number of observations in the <code>X_valid</code> set, as an integer.\n</div>",
"_____no_output_____"
]
],
[
[
"\n# Split into temporary and test sets\nX_t, X_test, y_t, y_test = ▰▰1▰▰(\n ▰▰2▰▰,\n ▰▰3▰▰,\n test_size = ▰▰4▰▰,\n shuffle = ▰▰5▰▰,\n stratify = y,\n random_state = 42\n)\n\n# Split into training and validation sets\nX_train, X_valid, y_train, y_valid = train_test_split(\n ▰▰6▰▰,\n ▰▰7▰▰,\n test_size = ▰▰8▰▰,\n shuffle = ▰▰9▰▰,\n stratify = ▰▰10▰▰,\n random_state = 42,\n)\n\nlen(X_valid)",
"_____no_output_____"
]
],
[
[
"## Problem 3:\n\n<div class=\"alert alert-block alert-info\"> \nAs you work with Keras and Tensorflow, you'll rapidly discover that both packages are very picky about the 'shape' of the data you're using. What's more, you can't always rely on them to correctly infer your data's shape. As such, it's usually a good idea to store the two most important shapes -- number of variables in the feature matrix and number of unique categories in the target -- as explicit, named variables; doing so will save you the trouble of trying to retrieve them later (or as part of your model specification, which can get messy). We'll start with the number of variables in the feature matrix.\n</div>\n<div class=\"alert alert-block alert-success\">\nStore the number of variables in the feature matrix, as an integer, in the <code>num_vars</code> variable. Submit the resulting number as an integer.\n</div>",
"_____no_output_____"
]
],
[
[
"# The code we've provided here is just a suggestion; feel free to use any approach you like\nnum_vars = np.▰▰1▰▰(▰▰2▰▰).▰▰3▰▰[1]\n\nprint(num_vars)",
"_____no_output_____"
]
],
[
[
"## Problem 4:\n\n<div class=\"alert alert-block alert-info\"> \nNow, for the number of categories (a.k.a. labels) in the target.\n</div>\n<div class=\"alert alert-block alert-success\">\nStore the number of categories in the target, as an integer, in the <code>num_vars</code> variable. Submit the resulting number as an integer.\n</div>",
"_____no_output_____"
]
],
[
[
"# The code we've provided here is just a suggestion; feel free to use any approach you like\nnum_labels = ▰▰1▰▰.▰▰2▰▰[1]\n\nprint(num_labels)",
"_____no_output_____"
]
],
[
[
"## Problem 5:\n\n<div class=\"alert alert-block alert-info\"> \nEverything is now ready for us to begin building an Artifical Neural Network! Aside from specifying that the ANN must be built using Keras's <code>Sequential</code> API, we're going to give you the freedom to tackle the creation of your ANN in whichever manner you like. Feel free to use the 'add' method to build each layer one at a time, or pass all of the layers to your model at instantiation as a list, or any other approach you may be familiar with. Kindly ensure that your model matches the specifications below <b>exactly</b>!\n</div>\n<div class=\"alert alert-block alert-success\">\nUsing Keras's <code>Sequential</code> API, create a new ANN. Your ANN should have the following layers, in this order:\n<ol>\n<li> Input layer with one argument: number of variables in the feature matrix\n<li> Dense layer with 400 neurons and the \"relu\" activation function\n<li> Dense layer with 10 neurons and the \"relu\" activation function\n<li> Dense layer with neurons equal to the number of labels in the target and the \"softmax\" activation function\n</ol>\nSubmit the number of hidden layers in your model.\n</div>",
"_____no_output_____"
]
],
[
[
"# Create your ANN!\nnn_model = keras.models.Sequential()",
"_____no_output_____"
]
],
[
[
"## Problem 6:\n<div class=\"alert alert-block alert-info\"> \nEven though we've specified all of the layers in our model, it isn't yet ready to go. We must first 'compile' the model, during which time we'll specify a number of high-level arguments. Just as in the textbook, we'll go with a fairly standard set of arguments: we'll use Stochastic Gradient Descent as our optimizer, and our only metric will be Accuracy (an imperfect but indispensably simple measure). It'll be up to you to figure out what loss function we should use: you might have to go digging in the textbook to find it!\n</div>\n<div class=\"alert alert-block alert-success\">\nCompile the model according to the specifications outlined in the blue text above. Submit the name of the loss function <b>exactly</b> as it appears in your code (you should only need to include a single underscore -- no other punctuation, numbers, or special characters). \n</div>",
"_____no_output_____"
]
],
[
[
"nn_model.▰▰1▰▰(\n loss=keras.losses.▰▰2▰▰,\n optimizer=▰▰3▰▰,\n metrics=[▰▰4▰▰]\n)",
"_____no_output_____"
]
],
[
[
"## Problem 7:\n<div class=\"alert alert-block alert-info\"> \nEverything is prepared. All that remains is to train the model! \n</div>\n<div class=\"alert alert-block alert-success\">\nTrain your neural network for 100 epochs. Be sure to include the validation data variables. \n</div>",
"_____no_output_____"
]
],
[
[
"np_seed(42)\ntf.random.set_seed(42)\n\nhistory = nn_model.▰▰1▰▰(▰▰2▰▰, ▰▰3▰▰, epochs=▰▰4▰▰, validation_data = (▰▰5▰▰, ▰▰6▰▰))",
"_____no_output_____"
]
],
[
[
"## Problem 8:\n<div class=\"alert alert-block alert-info\"> \nFor some Neural Networks, 100 epochs is more than ample time to reach a best solution. For others, 100 epochs isn't enough time for the learning process to even get underway. One good method for assessing the progress of your model at a glance involves visualizing how your loss scores and metric(s) -- for both your training and validation sets) -- changed during training. \n</div>\n<div class=\"alert alert-block alert-success\">\nAfter 100 epochs of training, is the model still appreciably improving? (If it is still improving, you shouldn't see much evidence of overfitting). Submit your answer as a boolean value (True = still improving, False = not still improving). \n</div>",
"_____no_output_____"
]
],
[
[
"pd.DataFrame(history.history).plot(figsize = (8, 8))\nplt.grid(True)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Problem 9:\n<div class=\"alert alert-block alert-info\"> \nRegardless of whether this model is done or not, it's time to dig into what our model has done. Here, we'll continue re-tracing the steps taken in the textbook, producing a (considerably more involved) confusion matrix, visualizing it as a heatmap, and peering into our model's soul. The first step in this process involves creating the confusion matrix.\n</div>\n<div class=\"alert alert-block alert-success\">\nUsing the held-back test data, create a confusion matrix. \n</div>",
"_____no_output_____"
]
],
[
[
"y_pred = np.argmax(nn_model.predict(▰▰1▰▰), axis=1)\n\ny_true = np.argmax(▰▰2▰▰, axis=1)\n\nconf_mat = tf.math.confusion_matrix(▰▰3▰▰, ▰▰4▰▰)",
"_____no_output_____"
]
],
[
[
"## Problem 10:\n<div class=\"alert alert-block alert-info\"> \nFinally, we're ready to visualize the matrix we created above. Rather than asking you to recreate the baroque visualization code, we're going to skip straight to interpretation. \n</div>\n<div class=\"alert alert-block alert-success\">\nPlot the confusion matrix heatmap and examine it. Based on what you know about the dataset, should the sum of the values in a column (representing the number of observations from a country) be the same for each country? If so, submit the integer that each column adds up to. If not, submit 0.\n</div>",
"_____no_output_____"
]
],
[
[
"sns.set(rc={'figure.figsize':(12,12)})\nplt.figure()\nsns.heatmap(\n np.array(conf_mat).T,\n xticklabels=country_encoder.classes_,\n yticklabels=country_encoder.classes_,\n square=True,\n annot=True,\n fmt='g',\n)\nplt.xlabel(\"Observed\")\nplt.ylabel(\"Predicted\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Problem 11:\n<div class=\"alert alert-block alert-success\">\nBased on what you know about the dataset, should the sum of the values in a row (representing the number of observations your model <b>predicted</b> as being from a country) be the same for each country? If so, submit the integer that each row adds up to. If not, submit 0.\n</div>",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"## Problem 12:\n<div class=\"alert alert-block alert-success\">\nIf your model was built and run to the specifications outlined in the assignment, your results should include at least three countries whose observations the model struggled to identify (fewer than 7 accurate predictions each). Submit the name of one such country.<br><br>As a result of the randomness inherent to these models, it is possible that your interpretation will be correct, but will be graded as incorrect. If you feel that your interpretation was erroneously graded, please email a screenshot of your confusion matrix heatmap to Pierson along with an explanation of how you arrived at the answer you did. \n</div>",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aa76cd6089a20ab3c63b27aab48d12417fca710
| 15,672 |
ipynb
|
Jupyter Notebook
|
analysis/2020-03-28-anapaulagomes-camara-e-covid-19.ipynb
|
AndreAngelucci/analises
|
86c86f536aab30ea8d4517530b1ac229252bc9b0
|
[
"MIT"
] | 31 |
2020-01-06T17:41:03.000Z
|
2021-12-03T13:10:28.000Z
|
analysis/2020-03-28-anapaulagomes-camara-e-covid-19.ipynb
|
AndreAngelucci/analises
|
86c86f536aab30ea8d4517530b1ac229252bc9b0
|
[
"MIT"
] | 71 |
2020-05-30T18:20:24.000Z
|
2022-03-01T21:04:00.000Z
|
analysis/2020-03-28-anapaulagomes-camara-e-covid-19.ipynb
|
AndreAngelucci/analises
|
86c86f536aab30ea8d4517530b1ac229252bc9b0
|
[
"MIT"
] | 16 |
2019-11-27T01:18:44.000Z
|
2021-10-11T11:07:51.000Z
| 40.391753 | 432 | 0.644589 |
[
[
[
"# A Câmara de Vereadores e o COVID-19\n\nVocê também fica curioso(a) para saber o que a Câmara de Vereadores\nde Feira de Santana fez em relação ao COVID-19? O que discutiram?\nO quão levaram a sério o vírus? Vamos responder essas perguntas e\ntambém te mostrar como fazer essa análise. Vem com a gente!\n\nDesde o início do ano o mundo tem falado a respeito do COVID-19.\nPor isso, vamos basear nossa análise no período de 1 de Janeiro\na 27 de Março de 2020. Para entender o que se passou na Câmara\nvamos utilizar duas fontes de dados:\n\n* [Diário Oficial](diariooficial.feiradesantana.ba.gov.br/)\n* [Atas das sessões](https://www.feiradesantana.ba.leg.br/atas)\n\nNas atas temos acesso ao que foi falado nos discursos e no Diário\nOficial temos acesso ao que realmente virou (ou não) lei. Você\npode fazer _download_ dos dados [aqui]()\ne [aqui](https://www.kaggle.com/anapaulagomes/dirios-oficiais-de-feira-de-santana).\nProcuramos mas não foi encontrada nenhuma menção ao vírus na\n[Agenda da Câmara Municipal](https://www.feiradesantana.ba.leg.br/agenda).\n\nLembrando que as atas foram disponibilizadas no site da casa apenas\ndepois de uma reunião nossa com o presidente em exercício José Carneiro.\nUma grande vitória dos dados abertos e da transparência na cidade.\n\nOs dados são coletados por nós e todo código está [aberto e disponível\nno Github](https://github.com/DadosAbertosDeFeira/maria-quiteria/).\n\n## Vamos começar por as atas\n\nAs atas trazem uma descrição do que foi falado durante as sessões.\nSe você quer acompanhar o posicionamento do seu vereador(a), é uma\nboa maneira. Vamos ver se encontramos alguém falando sobre *coronavírus*\nou *vírus*.\n\nSe você não é uma pessoa técnica, não se preocupe. Vamos continuar o texto\njunto com o código.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\n\n\n# esse arquivo pode ser baixado aqui: https://www.kaggle.com/anapaulagomes/atas-da-cmara-de-vereadores\natas = pd.read_csv('atas-28.03.2020.csv')\natas.describe()",
"_____no_output_____"
]
],
[
[
"Explicando um pouco sobre os dados (colunas):\n\n* `crawled_at`: data da coleta\n* `crawled_from`: fonte da coleta (site de onde a informação foi retirada)\n* `date`: data da sessão\n* `event_type`: tipo do evento: sessão ordinária, ordem do dia, solene, etc\n* `file_content`: conteúdo do arquivo da ata\n* `file_urls`: url(s) do arquivo da ata\n* `title`: título da ata\n\n### Filtrando por data\n\nBom, vamos então filtrar os dados e pegar apenas as atas entre 1 de Janeiro\ne 28 de Março:",
"_____no_output_____"
]
],
[
[
"atas[\"date\"] = pd.to_datetime(atas[\"date\"])\natas[\"date\"]\natas = atas[atas[\"date\"].isin(pd.date_range(\"2020-01-01\", \"2020-03-28\"))]\natas = atas.sort_values('date', ascending=True) # aqui ordenados por data em ordem crescente\natas.head()",
"_____no_output_____"
]
],
[
[
"Bom, quantas atas temos entre Janeiro e Março?",
"_____no_output_____"
]
],
[
[
"len(atas)",
"_____no_output_____"
]
],
[
[
"Apenas 21 atas, afinal os trabalhos na casa começaram no início de Fevereiro\ne pausaram por uma semana por conta do coronavírus.\n\nFonte:\nhttps://www.feiradesantana.ba.leg.br/agenda\nhttps://www.feiradesantana.ba.leg.br/noticia/2029/c-mara-municipal-suspende-sess-es-ordin-rias-da-pr-xima-semana\n\n### Filtrando conteúdo relacionado ao COVID-19\n\nAgora que temos nossos dados filtrados por data, vamos ao conteúdo.\nNa coluna `file_content` podemos ver o conteúdo das atas. Nelas vamos\nbuscar por as palavras:\n\n- COVID, COVID-19\n- coronavírus, corona vírus",
"_____no_output_____"
]
],
[
[
"termos_covid = \"COVID-19|coronavírus\"\natas = atas[atas['file_content'].str.contains(termos_covid, case=False)]\natas",
"_____no_output_____"
],
[
"len(atas)",
"_____no_output_____"
]
],
[
[
"Doze atas mencionando termos que representam o COVID-19 foram encontradas.\nVamos ver o que elas dizem?\n\nAtenção: o conteúdo das atas é grande para ser mostrado aqui. Por isso vamos\ndestacar as partes que contém os termos encontrados.",
"_____no_output_____"
]
],
[
[
"import re\n\npadrao = r'[A-Z][^\\\\.;]*(coronavírus|covid)[^\\\\.;]*'\n\n\ndef trecho_encontrado(conteudo_do_arquivo):\n frases_encontradas = []\n for encontrado in re.finditer(padrao, conteudo_do_arquivo, re.IGNORECASE):\n frases_encontradas.append(encontrado.group().strip().replace('\\n', ''))\n return '\\n'.join(frases_encontradas)\n\natas['trecho'] = atas['file_content'].apply(trecho_encontrado)\npd.set_option('display.max_colwidth', 100)\n\natas[['date', 'event_type', 'title', 'file_urls', 'trecho']]",
"_____no_output_____"
]
],
[
[
"Já que não temos tantos dados assim (apenas 12 atas) podemos fazer parte dessa análise manual,\npara ter certeza que nenhum vereador foi deixado de fora. Vamos usar o próximo comando\npara exportar os dados para um novo CSV. Nesse CSV vai ter os dados filtrados por data\ne também o trecho, além do conteúdo da ata completo.",
"_____no_output_____"
]
],
[
[
"def converte_para_arquivo(df, nome_do_arquivo):\n conteudo_do_csv = df.to_csv(index=False) # convertemos o conteudo para CSV\n arquivo = open(nome_do_arquivo, 'w') # criamos um arquivo\n arquivo.write(conteudo_do_csv)\n arquivo.close()\n\nconverte_para_arquivo(atas, 'analise-covid19-atas-camara.csv')",
"_____no_output_____"
]
],
[
[
"### Quem levantou a bola do COVID-19 na Câmara?\n\nUma planilha com a análise do quem-disse-o-que pode ser encontrada [aqui](https://docs.google.com/spreadsheets/d/1h7ioFnHH8sGSxglThTpQX8W_rK9cgI_QRB3u5aAcNMI/edit?usp=sharing).",
"_____no_output_____"
],
[
"## E o que dizem os diários oficiais?\n\nNo diário oficial do município você encontra informações sobre o que virou\nrealidade: as decretas, medidas, nomeações, vetos.\n\nEm Feira de Santana os diários dos poderes executivo e legislativo estão juntos.\nVamos filtrar os diários do legislativo, separar por data, como fizemos com as\natas, e ver o que foi feito.",
"_____no_output_____"
]
],
[
[
"# esse arquivo pode ser baixado aqui: https://www.kaggle.com/anapaulagomes/dirios-oficiais-de-feira-de-santana\ndiarios = pd.read_csv('gazettes-28.03.2020.csv')\ndiarios = diarios[diarios['power'] == 'legislativo']\n\ndiarios[\"date\"] = pd.to_datetime(diarios[\"date\"])\ndiarios = diarios[diarios[\"date\"].isin(pd.date_range(\"2020-01-01\", \"2020-03-28\"))]\ndiarios = diarios.sort_values('date', ascending=True) # aqui ordenados por data em ordem crescente\n\ndiarios.head()",
"_____no_output_____"
]
],
[
[
"O que é importante saber sobre as colunas dessa base de dados:\n\n* `date`: quando o diário foi publicado\n* `power`: poder executivo ou legislativo (sim, os diários são unificados)\n* `year_and_edition`: ano e edição do diário\n* `events`:\n* `crawled_at`: quando foi feita essa coleta\n* `crawled_from`: qual a fonte dos dados\n* `file_urls`: url dos arquivos\n* `file_content`: o conteúdo do arquivo do diário\n\nVamos filtrar o conteúdo dos arquivos que contém os termos relacionados ao COVID-19\n(os mesmos que utilizamos com as atas).",
"_____no_output_____"
]
],
[
[
"diarios = diarios[diarios['file_content'].str.contains(termos_covid, case=False)]\ndiarios['trecho'] = diarios['file_content'].apply(trecho_encontrado)\n\ndiarios[['date', 'power', 'year_and_edition', 'file_urls', 'trecho']]",
"_____no_output_____"
]
],
[
[
"Apenas 4 diários com menção ao termo, entre 1 de Janeiro e 28 de Março de 2020\nforam encontrados. O que será que eles dizem? Vamos exportar os resultados para\num novo CSV e continuar no Google Sheets.",
"_____no_output_____"
]
],
[
[
"converte_para_arquivo(diarios, 'analise-covid19-diarios-camara.csv')",
"_____no_output_____"
]
],
[
[
"### O que encontramos nos diários\n\nOs 4 diários tratam de suspender licitações por conta da situação na cidade.\nApenas um dos diários, o diário do dia 17 de Março de 2020, [Ano VI - Edição Nº 733](http://www.diariooficial.feiradesantana.ba.gov.br/atos/legislativo/2CI2L71632020.pdf),\ntraz instruções a respeito do que será feito na casa. Aqui citamos o trecho que fala\na respeito das medidas:\n\n> Art. 1º **Qualquer servidor, estagiário, terceirizado, vereador que apresentar febre ou sintomas respiratórios (tosse seca, dor de garganta, mialgia, cefaleia e prostração, dificuldade para respirar e batimento das asas nasais) passa a ser considerado um caso suspeito e deverá notificar imediatamente em até 24 horas à Vigilância Sanitária Epidemiológica/Secretaria Municipal de Saúde**.\n§ 1ºQualquer servidor, estagiário, terceirizado, a partir dos 60 (sessenta)anos; portador de doença crônica e gestante estarão liberados das atividades laborais na Câmara Municipal de Feira de Santana sem prejuízo a sua remuneração.\n§ 2º A(o) vereador(a) a partir dos 60 (sessenta)anos; portador de doença crônica e gestante será facultado as atividades laborais na Câmara Municipal de Feira de Santana sem prejuízo a sua remuneração\n§ 3º Será considerado falta justificada ao serviço público ou à atividade laboral privada o período de ausência decorrente de afastamento por orientação médica.\n\n> Art. 2º **Fica interditado o elevador no prédio anexo por tempo indeterminado**, até que sejam efetivamente contida a propagação do Coronavírus no Município e estabilizada a situação. _Parágrafo único_ O uso do elevador nesse período só será autorizado para transporte de portadores de necessidades especiais, como cadeirantes e pessoas com mobilidade reduzida.\n\n> Art. 3º Será liberada a catraca para acesso ao prédio anexo. \n\n> Art. 4º O portãolateral (acesso a rua do prédio anexo) será fechado com entrada apenas pela portaria principal.\n\n> Art. 5º Será disponibilizado nas áreas comuns dispensadores para álcool em gel.\n\n> Art.6º Será intensificada a limpeza nos banheiros, elevadores, corrimãos, maçanetase áreas comuns com grande circulação de pessoas.\n\n> Art.7º Na cozinha e copa só será permitido simultaneamente à permanência de uma pessoa. \n\n> Art. 8º **Ficam suspensas as Sessões Solenes, Especiais e Audiências Públicas por tempo indeterminado**, até que sejam efetivamente contida a propagação do Coronavírus no Município e estabilizada a situação. \n\n> Art. 9º Nesse período de contenção é recomendado que o público/visitante assista a Sessão Ordinária on-line via TV Câmara. Parágrafo - Na Portaria do Prédio Sede **haverá um servidor orientando as pessoas a assistirem os trabalhos legislativos pela TV Câmara** disponível em https://www.feiradesantana.ba.leg.br/ distribuindo panfletos informativos sobre sintomas e métodos de prevenção.\n\n> Art. 10º No âmbito dos gabinetes dos respectivos Vereadores, **fica a critério de cada qual adotar restrições ao atendimento presencial do público externo ou visitação à sua respectiva área**.\n\n> Art.11º A Gerência Administrativa fica autorizada a adotar outras providências administrativas necessárias para evitar a propagação interna do vírus COVID-19, devendo as medidas serem submetidas ao conhecimento da Presidência.\n\n> Art.12º A validade desta Portaria será enquanto valer oestado de emergência de saúde pública realizado pela Secretaria Municipal de Saúde e pelo Comitê de Ações de Enfrentamento ao Coronavírus no Município de Feira de Santana.\n\n> Art.13º Esta Portaria entra em vigor na data de sua publicação, revogadas disposições em contrário.\n",
"_____no_output_____"
],
[
"## Conclusão\n\nCaso os edis da casa tenham feito mais nós não teríamos como saber sem ser por as atas,\npelo diário oficial ou por notícias do site. O ideal seria ter uma página com projetos\ne iniciativas de cada vereador. Dessa forma, seria mais fácil se manter atualizado a\nrespeito do trabalho de cada um na cidade.\n\nAs análises manuais e o que encontramos pode ser visto [aqui](https://docs.google.com/spreadsheets/d/1h7ioFnHH8sGSxglThTpQX8W_rK9cgI_QRB3u5aAcNMI/edit?usp=sharing).\nUm texto sobre a análise e as descobertas podem ser encontradas no blog do [Dados Abertos de Feira](https://medium.com/@dadosabertosdefeira).\n\nGostou do que viu? Achou interessante? Compartilhe com outras pessoas e não esqueça de mencionar\no projeto.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
4aa785c40538577a8636c0eb4c4943d9ce3eb819
| 273,978 |
ipynb
|
Jupyter Notebook
|
_notebooks/2020-09-29-Titanic.ipynb
|
nrosanas/blog
|
f8b5a99301c5cd7034718629c6600d54775a65d0
|
[
"Apache-2.0"
] | null | null | null |
_notebooks/2020-09-29-Titanic.ipynb
|
nrosanas/blog
|
f8b5a99301c5cd7034718629c6600d54775a65d0
|
[
"Apache-2.0"
] | 1 |
2022-02-26T09:53:13.000Z
|
2022-02-26T09:53:13.000Z
|
_notebooks/2020-09-29-Titanic.ipynb
|
nrosanas/blog
|
f8b5a99301c5cd7034718629c6600d54775a65d0
|
[
"Apache-2.0"
] | null | null | null | 130.590086 | 63,004 | 0.859131 |
[
[
[
"# Titanic \n\n",
"_____no_output_____"
],
[
"In this notebook we will experiment with tabular data and fastai v2 and other machine learning techniques\n",
"_____no_output_____"
]
],
[
[
"#collapse-hide\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom fastai.tabular.all import *\nfrom pathlib import Path\nimport seaborn as sns\nsns.set_palette('Set1')\nsns.set_style(\"white\")\n\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"#collapse-hide\npath = Path('/home/jupyter/kaggle/titanic/')\ntrain = pd.read_csv(path/'train.csv')\ntest = pd.read_csv(path/'test.csv')",
"_____no_output_____"
]
],
[
[
"Let's take a look of the data composing the dataset",
"_____no_output_____"
]
],
[
[
"train.head()",
"_____no_output_____"
]
],
[
[
"Notes about the columns:\n\n| Column name | Description |\n|---|---|\n| PassangerID | Unique identifier for each passanger | \n| Survived | 1 survived, 0 did not survive | \n| Pclass | From the problem description: A proxy for socio-economic status (SES) 1 = Upper ,2= Middle, 3 = Lower |\n| Name | Name of the passanger | \n| Sex | Sex of passanger | \n| Age | Age of the passanger, if younger than 1 it will be fractionary | \n| SibSp | Number of brothers, sisters, stepbrother, stepsister and wife or husband of the given passanger embarked | \n| Parch | Number of parents or children embarked of the passanger | \n| Ticket | Ticket number | \n| Cabin | Cabin number | \n| Embarked | Port of embarkation -> C = Cherbourg, Q = Queenstown, S = Southampton | ",
"_____no_output_____"
],
[
"Before preparing the data for our model, let's take a look how each column influences survivality",
"_____no_output_____"
]
],
[
[
"#collapse-hide\nsns.displot(data=train, x='Sex', hue='Survived', multiple = 'stack',alpha=0.6)",
"_____no_output_____"
]
],
[
[
"There is almost double male than female passengers but there is much more female survivors. Next let's take a look how the passengers where distributed among the classes and age.",
"_____no_output_____"
]
],
[
[
"#collapse-hide\ng = sns.FacetGrid(train, col='Pclass',row='Sex',hue='Survived', )\ng.map(sns.histplot,'Age', alpha=0.6)\ng.add_legend()",
"_____no_output_____"
]
],
[
[
"1st and 2nd class female passengers where much more likely to survive than male passengers from 2nd and 3rd class.",
"_____no_output_____"
]
],
[
[
"#collapse-hide\ntrain['Family']=(train['SibSp']+train['Parch']).astype(int)\norder=[]\nfor i in range(10):\n order.append(str(i))\na=sns.countplot(data=train, x='Family', hue='Survived',dodge=True, alpha=0.6)",
"_____no_output_____"
]
],
[
[
"There are many passengers travelling alone and they are much less likely to survive. Then people who had between 2 and 3 relatives was more likely to survive than the rest of passengers.",
"_____no_output_____"
]
],
[
[
"#hide\ng = sns.FacetGrid(train, col='Family',row='Sex',hue='Survived', )\ng.map(sns.histplot,'Age', alpha=0.6)\ng.add_legend()",
"_____no_output_____"
],
[
"#hide\nplt.figure(figsize=(10,10))\na=sns.stripplot(data=train, x='Family', y='Age', hue='Survived', alpha=0.5)",
"_____no_output_____"
]
],
[
[
"There are some columns not very useful predicting the survival rate of a given passanger, these are: 'PassengerId', 'Name', 'Ticket' and 'Fare'. Let's remove this columns. ",
"_____no_output_____"
]
],
[
[
"#hide\ndef remove_cols(df, cols, debug=False):\n df.drop(columns = cols, inplace=True);\n if debug: print('columns_droped')\n return(df)",
"_____no_output_____"
],
[
"#hide\ncols = ['PassengerId', 'Ticket', 'Fare','Name']\nprint(f'This features:{cols} will be removed from the data set')",
"This features:['PassengerId', 'Ticket', 'Fare', 'Name'] will be removed from the data set\n"
]
],
[
[
"We can check the unique values the dataset takes for each column",
"_____no_output_____"
]
],
[
[
"#hide_input\n\nprint('Number of unique classes in each feature: ')\nprint(train.nunique())\n",
"Number of unique classes in each feature: \nPassengerId 891\nSurvived 2\nPclass 3\nName 891\nSex 2\nAge 88\nSibSp 7\nParch 7\nTicket 681\nFare 248\nCabin 147\nEmbarked 3\nFamily 9\ndtype: int64\n"
]
],
[
[
"We can take a look of the missing values in the columns, we can se there is missing data in 'Age' and 'Cabin'. ",
"_____no_output_____"
]
],
[
[
"#hide_input\nprint('Number of passengers missing each feature:')\ntrain.isna().sum()",
"Number of passengers missing each feature:\n"
]
],
[
[
"We will create a new column indicating is that the data is missing and impute the **mean age of the training set** and fill cabin with the text 'Missing'. \nCabin might look as it is not relevant but the letter of leading the number can indicate the deck it was and might be relevant to the survivality. There are also 2 passengers missing where they embarked, this can be very relevant so we will create a new column for missing embarkation port. This might be relevant because it could be very easy to retrieve this information from the survivors. So instead of keeping the whole cabin number, we will just save the cabin letter.",
"_____no_output_____"
]
],
[
[
"MEAN_AGE = train['Age'].mean()\ndef fill_na(df,debug=False):\n df.loc[:,'AgeMissing'] = df['Age'].isna() # New column for missing data\n if debug: print('fillna complete: 1/4')\n df['Age'].fillna(MEAN_AGE, inplace=True) #filling 'Age' with the mean \n if debug: print('fillna complete: 2/4')\n df['Cabin'].fillna('Missing', inplace=True)\n if debug: print('fillna complete: 3/4')\n df['Cabin'] = df['Cabin'].apply(lambda x: x[0])\n if debug: print('fillna complete')\n return df",
"_____no_output_____"
]
],
[
[
"Next is to convert all categorical feature columns to multiple binnary columns using [one hot encoding](https://en.wikipedia.org/wiki/One-hot 'One-hot\nFrom Wikipedia, the free encyclopedia') technique. Each category in a given feature will be a new column.",
"_____no_output_____"
]
],
[
[
"#hide_input\nOHE_COLS = ['Pclass', 'Sex','Cabin']\ndef ohe_data(df, columns):\n new_pd = pd.get_dummies(df)\n return new_pd ",
"_____no_output_____"
],
[
"#hide_input\ndef prepare_data(df, cols, ohe_cols, debug=False):\n df = df.copy()\n df = remove_cols(df, cols,debug)\n df = fill_na(df, debug)\n df['Pclass'] = df['Pclass'].astype(str)\n df = ohe_data(df, ohe_cols)\n return df",
"_____no_output_____"
],
[
"#hide_input\ndf_test = pd.read_csv(path/'test.csv')\nfull = pd.concat([train,df_test])",
"_____no_output_____"
],
[
"#hide\nfull_clean = prepare_data(full, cols, OHE_COLS,True)",
"columns_droped\nfillna complete: 1/4\nfillna complete: 2/4\nfillna complete: 3/4\nfillna complete\n"
],
[
"train_clean = full_clean.iloc[:len(train)].copy()\ntrain_clean1 = train_clean.copy()\ntest_clean = full_clean.iloc[-len(test):].copy()",
"_____no_output_____"
],
[
"y = train_clean['Survived']",
"_____no_output_____"
],
[
"train_clean.drop(columns='Survived', inplace=True)",
"_____no_output_____"
]
],
[
[
"With the data cleaned we can train the classifier. First we need a validation set to check the performance of the classifier with data not used in training",
"_____no_output_____"
]
],
[
[
"x_train, x_val, y_train, y_val = train_test_split(train_clean,y, test_size=0.2, random_state=42)",
"_____no_output_____"
],
[
"clf = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=4, random_state=42)",
"_____no_output_____"
],
[
"clf.fit(x_train,y_train)",
"_____no_output_____"
],
[
"#hide_input\nscore = clf.score(x_val,y_val)\nprint(f'With a Gradient Boosting Classifier we get a validation accuracy of {score*100:.2f}%')\n",
"With a Gradient Boosting Classifier we get a validation accuracy of 82.68%\n"
]
],
[
[
"With this classifier it is easy to analyse which features are the most important to predict the survivality",
"_____no_output_____"
]
],
[
[
"clf.feature_importances_",
"_____no_output_____"
],
[
"chart=sns.barplot(x=train_clean.columns, y=clf.feature_importances_,);\nchart.set_xticklabels(train_clean.columns,rotation=90);",
"_____no_output_____"
],
[
"submission = pd.read_csv('gender_submission.csv')",
"_____no_output_____"
],
[
"test_clean.drop(columns='Survived', inplace=True)",
"_____no_output_____"
],
[
"test_clean['Family']=(test_clean['SibSp']+test_clean['Parch']).astype(int)",
"_____no_output_____"
],
[
"y_sub = clf.predict(test_clean)",
"_____no_output_____"
],
[
"submission['Survived']=y_sub.astype(int)",
"_____no_output_____"
],
[
"submission",
"_____no_output_____"
],
[
"submission.to_csv('sub.csv',index=False)",
"_____no_output_____"
],
[
"#!kaggle competitions submit titanic -f sub.csv -m \"first submision\"",
"_____no_output_____"
]
],
[
[
"Let's try a more sophisticated method using Fast.ai library",
"_____no_output_____"
]
],
[
[
"path = Path('/home/jupyter/kaggle/titanic/')\ntrain = pd.read_csv(path/'train.csv')\ntest = pd.read_csv(path/'test.csv')",
"_____no_output_____"
],
[
"train.drop(columns=['PassengerId','Ticket','Name'],inplace = True)\ntest.drop(columns=['PassengerId','Ticket','Name'],inplace = True)\n",
"_____no_output_____"
],
[
"train['Cabin'] = train['Cabin'].fillna(value='Missing')\ntest['Cabin'] = train['Cabin'].fillna(value='Missing')",
"_____no_output_____"
],
[
"train['Cabin'] = train['Cabin'].apply(lambda x:x[0])\ntest['Cabin'] = train['Cabin'].apply(lambda x:x[0])\n",
"_____no_output_____"
],
[
"train['Cabin']",
"_____no_output_____"
],
[
"y_names = 'Survived'\ncat_names = ['Pclass','Sex','Cabin', 'Embarked']\ncont_names = ['Age', 'SibSp','Parch',]\nprocs = [ Categorify, FillMissing, Normalize]\nsplits = RandomSplitter(valid_pct=0.2)(range_of(train_clean1))",
"_____no_output_____"
],
[
"to = TabularPandas(df=train, \n cat_names=cat_names, \n cont_names=cont_names, \n procs=procs,\n y_names=y_names, \n splits=splits,\n y_block= CategoryBlock,)",
"_____no_output_____"
],
[
"dls = to.dataloaders(bs=128)",
"_____no_output_____"
],
[
"dls.show_batch()",
"_____no_output_____"
],
[
"learn = tabular_learner(dls, metrics=[ accuracy],layers=[50,25])",
"_____no_output_____"
],
[
"learn.model",
"_____no_output_____"
],
[
"learn.lr_find()",
"_____no_output_____"
],
[
"learn.save('empty')",
"_____no_output_____"
],
[
"learn = learn.load('empty')",
"_____no_output_____"
],
[
"learn.fit_one_cycle(16,0.005)",
"_____no_output_____"
],
[
"learn.recorder.plot_loss()",
"_____no_output_____"
],
[
"learn.save('16_epoch')",
"_____no_output_____"
],
[
"learn.show_results()",
"_____no_output_____"
],
[
"dl_test=learn.dls.test_dl(test)",
"_____no_output_____"
],
[
"probs,_ =learn.get_preds(dl=dl_test)",
"_____no_output_____"
],
[
"y = np.argmax(probs,1)\ny = np.array(y)",
"_____no_output_____"
],
[
"submission['Survived']=y.astype(int)",
"_____no_output_____"
],
[
"submission.to_csv('sub.csv',index=False)\n!kaggle competitions submit titanic -f sub.csv -m \"nn mid\"",
"100%|██████████████████████████████████████| 2.77k/2.77k [00:02<00:00, 1.07kB/s]\nSuccessfully submitted to Titanic: Machine Learning from Disaster"
],
[
"learn.model",
"_____no_output_____"
],
[
"learn.recorder.plot_sched()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aa78cc3a4bc5077776a344e9afc4fcb4e9fe055
| 5,777 |
ipynb
|
Jupyter Notebook
|
code/99_test/StewartPlatform.ipynb
|
AlCap23/crrn_2018
|
17f593d35182104e1705255ac81765dc42e674f0
|
[
"Unlicense"
] | null | null | null |
code/99_test/StewartPlatform.ipynb
|
AlCap23/crrn_2018
|
17f593d35182104e1705255ac81765dc42e674f0
|
[
"Unlicense"
] | null | null | null |
code/99_test/StewartPlatform.ipynb
|
AlCap23/crrn_2018
|
17f593d35182104e1705255ac81765dc42e674f0
|
[
"Unlicense"
] | null | null | null | 27.641148 | 140 | 0.526917 |
[
[
[
"# Closed Loop Kinematics\n\nWe want to simulate a closed loop system - just because . As a starting point, we will tackle the **STEWART PLATFORM**.\nWhile this seems like an overkill, applying the closure conditions in pybullet is quite easy.\n\nFirst, we import the needed modules.",
"_____no_output_____"
]
],
[
[
"import pybullet as pb\nimport pybullet_data as pbd",
"_____no_output_____"
]
],
[
[
"And start a server. Additionally, we supply the open loop model of the stewart platform.",
"_____no_output_____"
]
],
[
[
"client = pb.connect(pb.GUI)\n\nrobot_path = '../../models/urdf/Stewart.urdf'",
"_____no_output_____"
]
],
[
[
"We will start by simulating the open loop kinematics under the influence of gravity.",
"_____no_output_____"
]
],
[
[
"pb.resetSimulation()\npb.removeAllUserDebugItems()\n\npb.setGravity(0, 0, -9.81, client)\n\nrobot = pb.loadURDF(robot_path, useFixedBase=True, flags = pb.URDF_USE_INERTIA_FROM_FILE|pb.URDF_USE_SELF_COLLISION_INCLUDE_PARENT)\n\npb.setRealTimeSimulation(1)",
"_____no_output_____"
],
[
"pb.resetSimulation()\npb.removeAllUserDebugItems()\n\nrobot = pb.loadURDF(robot_path, useFixedBase=True)\n\npb.setPhysicsEngineParameter(\n fixedTimeStep = 1e-4,\n numSolverIterations = 200,\n constraintSolverType = pb.CONSTRAINT_SOLVER_LCP_DANTZIG,\n globalCFM = 0.000001 \n)\npb.setRealTimeSimulation(1)",
"_____no_output_____"
],
[
"# Gather all joints and links\njoint_dict = {}\nfor i in range(pb.getNumJoints(robot, client)):\n joint_info = pb.getJointInfo(robot, i)\n name = (joint_info[1]).decode('UTF-8')\n if not name in joint_dict.keys():\n joint_dict.update(\n {name : i}\n )\n\n# Make some new constraints\nparents = ['top_11', 'top_12', 'top_13']\nchildren = {'top_11' : ['ITF_31'], 'top_12' : ['ITF_22', 'ITF_12'], 'top_13' : ['ITF_23', 'ITF_33']}\nconstraint_dict = {}\nfor parent in parents:\n parent_id = joint_dict[parent]\n for child in children[parent]:\n constraint_name = parent + '_2_' + child \n child_id = joint_dict[child]\n # Create a p2p connection\n constraint_id = pb.createConstraint(\n parentBodyUniqueId = robot,\n parentLinkIndex = parent_id,\n childBodyUniqueId = robot,\n childLinkIndex = child_id, \n jointType = pb.JOINT_POINT2POINT,\n jointAxis = (0,0,0),\n parentFramePosition = (0,0,0),\n childFramePosition = (0,0,0), \n )\n # Store the constraint information\n constraint_dict.update(\n {constraint_name : constraint_id}\n )\n # Change the constraint erp\n pb.changeConstraint(\n constraint_id,\n erp = 1e-4,\n )",
"_____no_output_____"
],
[
"# Create Actuation\ncontrol = ['P_11', 'P_33', 'P_55', 'P_22', 'P_44', 'P_55']\ndebug_dict = {}\nfor actor in control:\n actor_id = joint_dict[actor]\n joint_info = pb.getJointInfo(robot, actor_id)\n min_val = joint_info[8]\n max_val = joint_info[9]\n current_val = pb.getJointState(robot, actor_id, client)[0]\n debug_id = pb.addUserDebugParameter(actor, min_val, max_val, current_val, client)\n debug_dict.update(\n {debug_id : actor_id}\n ) ",
"_____no_output_____"
],
[
"# Enable Position control\nwhile True:\n for debug, actor in debug_dict.items():\n current_val = pb.readUserDebugParameter(debug, client)\n pb.setJointMotorControl2(\n robot,\n actor,\n controlMode = pb.POSITION_CONTROL,\n targetPosition = current_val,\n )",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
4aa78ee273690238aab51fead2954df2aed0163a
| 9,640 |
ipynb
|
Jupyter Notebook
|
workspace_files/resources/Readability_Level.ipynb
|
son520804/Video_Composition_Project
|
0b0aad5251b579f0f1133f60dc5fcd77e5ff8521
|
[
"MIT"
] | null | null | null |
workspace_files/resources/Readability_Level.ipynb
|
son520804/Video_Composition_Project
|
0b0aad5251b579f0f1133f60dc5fcd77e5ff8521
|
[
"MIT"
] | null | null | null |
workspace_files/resources/Readability_Level.ipynb
|
son520804/Video_Composition_Project
|
0b0aad5251b579f0f1133f60dc5fcd77e5ff8521
|
[
"MIT"
] | null | null | null | 52.108108 | 637 | 0.669813 |
[
[
[
"from readability import Readability\n\ntext = \"\"\"\n# Introduction to PyMC3 - Concept \n\nIn this lecture we're going to talk about the theories, advantages and application of using Bayesian\nstatistics. \n\nBayesian inference is a method of making statistical decisions as more information or evidence becomes\navailable. It is a powerful tool to help us understand uncertain events in the form of probabilities.\n\nCentral to the application of Bayesian methods is the idea of a distribution. In general, a distribution\ndescribes how likely a certain outcome will occur given a series of inputs. For instance, we might have a\ndistribution which describes how likely a given kicker on a football team will make a field goal (the\noutcome).\n\n# We can use the line magic %run to load all variables from the previous Overview lecture\n# and revisit the histogram\n%run PyMC3_Code_Training_Overview.ipynb\n\nHere is an example of what the distribution of National Football League kicker's field goal probability\nlooks like. It shows that most kickers score roughly 85 percent of the field goals and the number drops\ngradually on both sides as field goal percentage goes up and down. So the graph looks pretty much a bell\ncurve, a shape reminiscent of a bell.\n\nIn Bayesian statistics, we consider our initial understanding of the outcome of an event before data is\ncollected. We do this by creating a **prior distribution**. Similar to most data science methods, we will\nthen collect the observed data to create a model using some probability distribution. We rely on that model\ncalled **likelihood** to update our initial understanding (**prior distribution**) using the **Bayes'\nTheorem**.\n\nWe won't go into the maths of Bayes' theorem, but the theorem suggests that by using the observed data as\nnew evidence, the updated belief incorporates our initial understanding and the evidence related to the\nproblem being examined, just like we cumulate knowledge by learning the problems or doing experiments.\n**Bayes's theorem** also suggests a nice property that the updated belief is proportional to the product of\nthe **prior distribution** and the **likelihood**. We call the updated belief **posterior distribution**. \n\n\n\nBayesian inference is carried out in four steps. \n\nFirst, specify prior distribution. We can start with forming some prior distribution for our initial\nunderstanding of a subject matter, before observing data. This **prior distribution** can come from personal\nexperience, literature, or even thoughts from experts.\n\nDuring the second and third step, we move on to **collect the data** from observations or experiments and\nthen **construct a model** using probability distribution(s) to represent how likely the outcomes occur\ngiven the data input. In our example, we can collect evidence by recording American football players' field\ngoal performance for a few NFL seasons in a database. Then based on the data we collect, we can use\nvisualizations to understand how to construct a suitable probabilistic model (**likelihood**) to represent\nthe distribution of the NFL data.\n\nFinally, apply the Bayes' rules. In this step, we incorporate the **prior distribution** and the\n**likelihood** using Bayes' rules to update our understanding and return the **posterior distribution**. \n\nLet's first focus on the first three steps. \n\nFor the NFL example, as we observe kicks from a player, we can record the success and failures for each kick\nand then assign binomial distribution to represent the how likely a field goal is made for different\nplayers. We usually use **beta distribution** to set up a prior distribution involving success and failure\ntrials, where you can specify the parameters to decide how likely a player will make a field goal based on\nyour knowledge.\n\n# We can randomly generate binomial distributed samples by \n# setting the sample size as 100 and success probability of making a field goal as 0.8\nn = 100\np = 0.8\nsize = 100\n# Next we can set up binom as a random binomial variable that will give us 100 draws of binomial distributions\nbinom = np.random.binomial(n, p, size)\n\n# Now we use plt.figure function to define the figure size and plt.hist to draw a histogram, so you \n# can visualize what's going on here\nplt.figure(figsize=(8,8))\nplt.hist(binom/n)\n# Let's set the x and y axis and the title as well.\nplt.xlabel(\"Success Probability\")\nplt.ylabel(\"Frequency\")\nplt.title(\"Binomial Distribution\")\n# and show the plot\nplt.show()\n\nOnce again, you can see from this graph that most samples made roughly 80% of the field goal, with only few\nof those making less than 72.5% and more than 87.5%. We can again say the histogram shows a binomial\ndistribution with mean closed to 0.8.\n\n## Posterior Distribution\n\nThe question of how to obtain the posterior distribution by Bayes' rules represents the coolest part of\nBayesian analysis.\n\nTraditional methods include integrating the random variables and determining the resulting distribution in\nclosed form. However, it is not always the case that posterior distribution is obtainable through\nintegration. \n\n**Probabilistic programming languages**, a renowned programming tool to perform probabilistic models\nautomatically, can help update the belief iteratively to approximate the posterior distribution even when a\nmodel is complex or hierarchical. For example, the NUTS algorithm under Monte Carlo Markov Chain (MCMC),\nwhich we will discuss in the next video, is found to be effective in computing and representing the\nposterior distribution. \n\n## Bayesian Inference Advantages\n\n\n\nSo why Bayesian Inference useful? A salient advantage of the Bayesian approach in statistics lies on its\ncapability of easily cumulating knowledge. For every time when you have new evidence, using Bayesian\napproach can effectively update our prior knowledge. \n\nAnother potential of Bayesian statistics is that it allows every parameters, such as the probability of\nmaking the field goal, be summarized by probability distributions, regardless of whether it is prior,\nlikelihood, or posterior. With that, we can always look at the distributions to quantify the degree of\nuncertainty. \n\nFurthermore, Bayesian approach generates more robust posterior statistics by utilizing flexible\ndistributions in prior and the observed data.\n\nIn the next video, we will introduce PyMC3, a Python package to perform MCMC conveniently and obtain easily\ninterpretable Bayesian estimations and plots, with a worked example. Bye for now!\n\n\"\"\"\nr = Readability(text)\n\nr.flesch_kincaid()\n# r.flesch()\n# r.gunning_fog()\n# r.coleman_liau()\n# r.dale_chall()\n# r.ari()\n# r.linsear_write()\n# r.smog()\n# r.spache()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
4aa7939bee9706c1d34a3a8b6b04faf70d79c251
| 7,567 |
ipynb
|
Jupyter Notebook
|
Exercise/.ipynb_checkpoints/12_PyEx-checkpoint.ipynb
|
pytopia/PyExercises
|
b24488d24e15d85093a955bd8c9ae98d6505f1da
|
[
"MIT"
] | 6 |
2021-12-17T15:31:58.000Z
|
2022-02-14T18:24:21.000Z
|
Exercise/12_PyEx.ipynb
|
siniorone/PyExercises
|
b24488d24e15d85093a955bd8c9ae98d6505f1da
|
[
"MIT"
] | null | null | null |
Exercise/12_PyEx.ipynb
|
siniorone/PyExercises
|
b24488d24e15d85093a955bd8c9ae98d6505f1da
|
[
"MIT"
] | 6 |
2021-11-05T21:18:42.000Z
|
2021-12-11T11:37:46.000Z
| 26.644366 | 159 | 0.518964 |
[
[
[
"\n# 12 - Beginner Exercises\n\n* Conditional Statements\n\n\n\n",
"_____no_output_____"
],
[
"## 🍼 🍼 🍼 \n1.Create a Python program that receive a number from the user and determines if a given integer is even or odd. ",
"_____no_output_____"
]
],
[
[
"# Write your own code in this cell\nn = ",
"_____no_output_____"
]
],
[
[
"## 🍼🍼\n2.Write a Python code that would read any integer day number and show the day's name in the word ",
"_____no_output_____"
]
],
[
[
"# Write your own code in this cell\n",
"_____no_output_____"
]
],
[
[
"## 🍼🍼\n3.Create a Python program that receive three angles from the user to determine whether the supplied angle values may be used to construct a triangle. \n",
"_____no_output_____"
]
],
[
[
"# Write your own code in this cell\na = \nb =\nc =\n",
"_____no_output_____"
]
],
[
[
"## 🍼\n\n4.Write a Python program that receive three numbers from the user to calculate the root of a Quadratic Equation.\n$$ax^2+bx+c$$\n\nAs you know, the roots of the quadratic equation can be obtained using the following formula: \n$$x= \\frac{-b \\pm \\sqrt{ \\Delta } }{2a} $$\n\n* If the delta is a number greater than zero ($\\Delta > 0$), our quadratic equation has two roots as follows: \n$$x_{1}= \\frac{-b+ \\sqrt{ \\Delta } }{2a} $$\n$$x_{2}= \\frac{-b- \\sqrt{ \\Delta } }{2a} $$\n* If the delta is zero, then there is exactly one real root:\n$$x= \\frac{-b}{2a} $$\n* If the delta is negative, then there are no real roots\n\n\nWe also know that Delta equals: \n$$ \\Delta = b^{2} - 4ac$$\n",
"_____no_output_____"
]
],
[
[
"# Write your own code in this cell\na =\nb =\nc =\n\n",
"_____no_output_____"
]
],
[
[
"## 🍼 \n5.Create an application that takes the user's systolic and diastolic blood pressures and tells them category of their current condition . \n\n\n|BLOOD PRESSURE CATEGORY |\tSYSTOLIC mm Hg \t|and/or| \tDIASTOLIC mm Hg |\n|---|---|---|---|\n|**NORMAL**| \tLESS THAN 120 |\tand | \tLESS THAN 80|\n|**ELEVATED**| \t120 – 129 |\tand |\tLESS THAN 80 |\n|**HIGH BLOOD PRESSURE (HYPERTENSION) STAGE 1**| \t130 – 139 |\tor |\t80 – 89 |\n|**HIGH BLOOD PRESSURE (HYPERTENSION) STAGE 2**|\t140 OR HIGHER | \tor |\t90 OR HIGHER |\n|**HYPERTENSIVE CRISIS *(consult your doctor immediately)***| \tHIGHER THAN 180 |\tand/or |\tHIGHER THAN 120|",
"_____no_output_____"
]
],
[
[
"# Write your own code in this cell\n",
"_____no_output_____"
]
],
[
[
"## 🍼\n6.Create an application that initially displays a list of geometric shapes to the user.\nBy entering a number, the user can pick one of those shapes.\nThen, based on the geometric shape selected, obtain the shape parameters from the user.\nFinally, as the output, display the shape's area. \n",
"_____no_output_____"
]
],
[
[
"# Write your own code in this cell\n",
"_____no_output_____"
]
],
[
[
"## 🌶️🌶️\n7.Create a lambda function that accepts a number and returns a string based on this logic,\n\n* If the given value is between 3 to 8 then return \"Severe\"\n* else if it’s between 9 to 15 then return \"Mild to Moderate\"\n* else returns the \"The number is not valid\"\n\n```The above numbers are derived from the Glasgow Coma Scale.```",
"_____no_output_____"
]
],
[
[
"# Write your own code in this cell\n",
"_____no_output_____"
]
],
[
[
"## 🌶️\n**```You can nest expressions to evaluate inside expressions in an f-string```**\n\n8.You are given a set of prime numbers less than 1000.\nCreate a program that receives a number and then uses a single print() function with F-String to determine whether or not it was a prime number.\n\nfor example:\n\n\"997 is a prime number,\" \n\n\"998 is not a prime number.\" \n\n\n\n",
"_____no_output_____"
]
],
[
[
"# Write your own code in this cell\nP = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n 101, 103, 107, 109, 113, 127, 131, 137, 139, 149,\n 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,\n 199, 211, 223, 227, 229, 233, 239, 241, 251, 257,\n 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,\n 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,\n 383, 389, 397, 401, 409, 419, 421, 431, 433, 439,\n 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,\n 503, 509, 521, 523, 541, 547, 557, 563, 569, 571,\n 577, 587, 593, 599, 601, 607, 613, 617, 619, 631,\n 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,\n 701, 709, 719, 727, 733, 739, 743, 751, 757, 761,\n 769, 773, 787, 797, 809, 811, 821, 823, 827, 829,\n 839, 853, 857, 859, 863, 877, 881, 883, 887, 907,\n 911, 919, 929, 937, 941, 947, 953, 967, 971, 977,\n 983, 991, 997}\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aa79975220dd9ccac0fc6a17b87d674d08c6afc
| 76,439 |
ipynb
|
Jupyter Notebook
|
05_CorrectiveSolutions-6nodes-2loops.ipynb
|
Ccaccia73/semimonocoque
|
b67fc1a7f64f4ded85821b4ece779521724d5d55
|
[
"MIT"
] | null | null | null |
05_CorrectiveSolutions-6nodes-2loops.ipynb
|
Ccaccia73/semimonocoque
|
b67fc1a7f64f4ded85821b4ece779521724d5d55
|
[
"MIT"
] | null | null | null |
05_CorrectiveSolutions-6nodes-2loops.ipynb
|
Ccaccia73/semimonocoque
|
b67fc1a7f64f4ded85821b4ece779521724d5d55
|
[
"MIT"
] | null | null | null | 100.051047 | 17,988 | 0.829747 |
[
[
[
"# Semi-Monocoque Theory: corrective solutions",
"_____no_output_____"
]
],
[
[
"from pint import UnitRegistry\nimport sympy\nimport networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n%matplotlib inline\nfrom IPython.display import display",
"_____no_output_____"
]
],
[
[
"Import **Section** class, which contains all calculations",
"_____no_output_____"
]
],
[
[
"from Section import Section",
"_____no_output_____"
]
],
[
[
"Initialization of **sympy** symbolic tool and **pint** for dimension analysis (not really implemented rn as not directly compatible with sympy)",
"_____no_output_____"
]
],
[
[
"ureg = UnitRegistry()\nsympy.init_printing()",
"_____no_output_____"
]
],
[
[
"Define **sympy** parameters used for geometric description of sections",
"_____no_output_____"
]
],
[
[
"A, A0, t, t0, a, b, h, L, E, G = sympy.symbols('A A_0 t t_0 a b h L E G', positive=True)",
"_____no_output_____"
]
],
[
[
"We also define numerical values for each **symbol** in order to plot scaled section and perform calculations",
"_____no_output_____"
]
],
[
[
"values = [(A, 150 * ureg.millimeter**2),(A0, 250 * ureg.millimeter**2),(a, 80 * ureg.millimeter), \\\n (b, 20 * ureg.millimeter),(h, 35 * ureg.millimeter),(L, 2000 * ureg.millimeter), \\\n (t, 0.8 *ureg.millimeter),(E, 72e3 * ureg.MPa), (G, 27e3 * ureg.MPa)]\ndatav = [(v[0],v[1].magnitude) for v in values]",
"_____no_output_____"
]
],
[
[
"# Second example: Rectangular section with 6 nodes and 2 loops",
"_____no_output_____"
],
[
"Define graph describing the section:\n\n1) **stringers** are **nodes** with parameters:\n- **x** coordinate\n- **y** coordinate\n- **Area**\n\n2) **panels** are **oriented edges** with parameters:\n- **thickness**\n- **lenght** which is automatically calculated",
"_____no_output_____"
]
],
[
[
"stringers = {1:[(2*a,h),A],\n 2:[(a,h),A],\n 3:[(sympy.Integer(0),h),A],\n 4:[(sympy.Integer(0),sympy.Integer(0)),A],\n 5:[(a,sympy.Integer(0)),A],\n 6:[(2*a,sympy.Integer(0)),A]}\n\npanels = {(1,2):t,\n (2,3):t,\n (3,4):t,\n (4,5):t,\n (5,6):t,\n (6,1):t,\n (5,2):t}",
"_____no_output_____"
]
],
[
[
"Define section and perform first calculations",
"_____no_output_____"
]
],
[
[
"S1 = Section(stringers, panels)",
"_____no_output_____"
],
[
"S1.cycles",
"_____no_output_____"
]
],
[
[
"## Plot of **S1** section in original reference frame",
"_____no_output_____"
],
[
"Define a dictionary of coordinates used by **Networkx** to plot section as a Directed graph.\nNote that arrows are actually just thicker stubs",
"_____no_output_____"
]
],
[
[
"start_pos={ii: [float(S1.g.node[ii]['ip'][i].subs(datav)) for i in range(2)] for ii in S1.g.nodes() }",
"_____no_output_____"
],
[
"plt.figure(figsize=(12,8),dpi=300)\nnx.draw(S1.g,with_labels=True, arrows= True, pos=start_pos)\nplt.arrow(0,0,20,0)\nplt.arrow(0,0,0,20)\n#plt.text(0,0, 'CG', fontsize=24)\nplt.axis('equal')\nplt.title(\"Section in starting reference Frame\",fontsize=16);",
"_____no_output_____"
]
],
[
[
"## Plot of **S1** section in inertial reference Frame",
"_____no_output_____"
],
[
"Section is plotted wrt **center of gravity** and rotated (if necessary) so that *x* and *y* are principal axes.\n**Center of Gravity** and **Shear Center** are drawn",
"_____no_output_____"
]
],
[
[
"positions={ii: [float(S1.g.node[ii]['pos'][i].subs(datav)) for i in range(2)] for ii in S1.g.nodes() }",
"_____no_output_____"
],
[
"x_ct, y_ct = S1.ct.subs(datav)\n\nplt.figure(figsize=(12,8),dpi=300)\nnx.draw(S1.g,with_labels=True, pos=positions)\nplt.plot([0],[0],'o',ms=12,label='CG')\nplt.plot([x_ct],[y_ct],'^',ms=12, label='SC')\n#plt.text(0,0, 'CG', fontsize=24)\n#plt.text(x_ct,y_ct, 'SC', fontsize=24)\nplt.legend(loc='lower right', shadow=True)\nplt.axis('equal')\nplt.title(\"Section in pricipal reference Frame\",fontsize=16);",
"_____no_output_____"
]
],
[
[
"Expression of **inertial properties** in *principal reference frame*",
"_____no_output_____"
]
],
[
[
"sympy.simplify(S1.Ixx), sympy.simplify(S1.Iyy), sympy.simplify(S1.Ixy), sympy.simplify(S1.θ)",
"_____no_output_____"
],
[
"S1.symmetry",
"_____no_output_____"
]
],
[
[
"Compute **L** matrix: with 6 nodes we expect 3 **dofs**, two with _symmetric load_ and one with _antisymmetric load_",
"_____no_output_____"
]
],
[
[
"S1.compute_L()",
"_____no_output_____"
],
[
"S1.L",
"_____no_output_____"
]
],
[
[
"Compute **H** matrix",
"_____no_output_____"
]
],
[
[
"S1.compute_H()",
"_____no_output_____"
],
[
"S1.H.subs(datav)",
"_____no_output_____"
]
],
[
[
"Compute $\\tilde{K}$ and $\\tilde{M}$",
"_____no_output_____"
]
],
[
[
"S1.compute_KM(A,h,t)",
"_____no_output_____"
],
[
"S1.Ktilde",
"_____no_output_____"
],
[
"S1.Mtilde.subs(datav)",
"_____no_output_____"
]
],
[
[
"Compute **eigenvalues** and **eigenvectors**: results are in the form:\n- eigenvalue\n- multiplicity\n- eigenvector",
"_____no_output_____"
]
],
[
[
"sol_data = (S1.Ktilde.inv()*(S1.Mtilde.subs(datav))).eigenvects()\nsol_data",
"_____no_output_____"
]
],
[
[
"Extract eigenvalues",
"_____no_output_____"
]
],
[
[
"β2 = [sol[0] for sol in sol_data]\nβ2",
"_____no_output_____"
]
],
[
[
"Extract and normalize eigenvectors",
"_____no_output_____"
]
],
[
[
"X = [sol[2][0]/sol[2][0].norm() for sol in sol_data]\nX",
"_____no_output_____"
]
],
[
[
"Compute numerical value of $\\lambda$",
"_____no_output_____"
]
],
[
[
"λ = [sympy.N(sympy.sqrt(E*A*h/(G*t)*βi).subs(datav)) for βi in β2]\nλ",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aa7a4d4e058fb261a0455e303cdc2d823b848ff
| 195,033 |
ipynb
|
Jupyter Notebook
|
test-image-bank-marketing.ipynb
|
Hartorn/thc-net
|
c39c01cbd9ddc625d779e52398c128f1b0099e14
|
[
"MIT"
] | null | null | null |
test-image-bank-marketing.ipynb
|
Hartorn/thc-net
|
c39c01cbd9ddc625d779e52398c128f1b0099e14
|
[
"MIT"
] | 7 |
2020-04-17T11:18:00.000Z
|
2022-03-26T15:17:22.000Z
|
test-image-bank-marketing.ipynb
|
Hartorn/thc-net
|
c39c01cbd9ddc625d779e52398c128f1b0099e14
|
[
"MIT"
] | null | null | null | 79.18514 | 19,212 | 0.646168 |
[
[
[
"# Pre requisites for this notebook\n!pip install Pillow\n!pip install nb_black\n%load_ext nb_black",
"Requirement already satisfied: Pillow in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (7.1.1)\n\u001b[33mWARNING: You are using pip version 19.2.3, however version 20.0.2 is available.\nYou should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\nRequirement already satisfied: nb_black in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (1.0.7)\nRequirement already satisfied: ipython in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from nb_black) (7.13.0)\nRequirement already satisfied: black>='19.3'; python_version >= \"3.6\" in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from nb_black) (19.10b0)\nRequirement already satisfied: setuptools>=18.5 in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from ipython->nb_black) (41.2.0)\nRequirement already satisfied: backcall in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from ipython->nb_black) (0.1.0)\nRequirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from ipython->nb_black) (3.0.4)\nRequirement already satisfied: decorator in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from ipython->nb_black) (4.4.2)\nRequirement already satisfied: jedi>=0.10 in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from ipython->nb_black) (0.16.0)\nRequirement already satisfied: pickleshare in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from ipython->nb_black) (0.7.5)\nRequirement already satisfied: pexpect; sys_platform != \"win32\" in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from ipython->nb_black) (4.8.0)\nRequirement already satisfied: pygments in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from ipython->nb_black) (2.6.1)\nRequirement already satisfied: traitlets>=4.2 in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from ipython->nb_black) (4.3.3)\nRequirement already satisfied: pathspec<1,>=0.6 in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb_black) (0.8.0)\nRequirement already satisfied: toml>=0.9.4 in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb_black) (0.10.0)\nRequirement already satisfied: click>=6.5 in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb_black) (7.1.1)\nRequirement already satisfied: appdirs in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb_black) (1.4.3)\nRequirement already satisfied: attrs>=18.1.0 in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb_black) (19.3.0)\nRequirement already satisfied: typed-ast>=1.4.0 in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb_black) (1.4.1)\nRequirement already satisfied: regex in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from black>='19.3'; python_version >= \"3.6\"->nb_black) (2020.4.4)\nRequirement already satisfied: wcwidth in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython->nb_black) (0.1.9)\nRequirement already satisfied: parso>=0.5.2 in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from jedi>=0.10->ipython->nb_black) (0.6.2)\nRequirement already satisfied: ptyprocess>=0.5 in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from pexpect; sys_platform != \"win32\"->ipython->nb_black) (0.6.0)\nRequirement already satisfied: six in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from traitlets>=4.2->ipython->nb_black) (1.14.0)\nRequirement already satisfied: ipython-genutils in ./.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages (from traitlets>=4.2->ipython->nb_black) (0.2.0)\n\u001b[33mWARNING: You are using pip version 19.2.3, however version 20.0.2 is available.\nYou should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n"
],
[
"import os\nfrom requests import get\nfrom pathlib import Path\nimport gc\nimport tensorflow as tf\nfrom concurrent.futures import ProcessPoolExecutor as PoolExecutor\n\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow_addons.optimizers import RectifiedAdam, Lookahead\nfrom tensorflow_addons.activations import mish\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import roc_auc_score\n\nnp.random.seed(0)\n\nfrom PIL import Image, ImageDraw, ImageFont\nfrom matplotlib.pyplot import imshow\nimport matplotlib.pyplot as plt\n\n%matplotlib inline",
"_____no_output_____"
],
[
"def download(url, out, force=False, verify=True):\n out.parent.mkdir(parents=True, exist_ok=True)\n if force:\n print(f\"Removing file at {str(out)}\")\n out.unlink()\n\n if out.exists():\n print(\"File already exists.\")\n return\n print(f\"Downloading {url} at {str(out)} ...\")\n # open in binary mode\n with out.open(mode=\"wb\") as file:\n # get request\n response = get(url, verify=verify)\n for chunk in response.iter_content(100000):\n # write to file\n file.write(chunk)",
"_____no_output_____"
]
],
[
[
"## Download census-income dataset",
"_____no_output_____"
]
],
[
[
"# url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data\"\n# url_test = \"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test\"\nfont_url = \"https://ff.static.1001fonts.net/r/o/roboto-condensed.regular.ttf\"\n\ndataset_name = \"bank-marketing\"\nout = Path(os.getcwd()) / f\"data/{dataset_name}/train_bench.csv\"\n# out_test = Path(os.getcwd()) / f\"data/{dataset_name}_test.csv\"\nout_font = Path(os.getcwd()) / f\"RobotoCondensed-Regular.ttf\"\n\n# download(url, out)\n# download(url_test, out_test)\ndownload(font_url, out_font)",
"File already exists.\n"
]
],
[
[
"### Load bank-marketing as a dataframe",
"_____no_output_____"
]
],
[
[
"target = \"y\"\ntrain = pd.read_csv(out, low_memory=False)\nprint(train.shape)",
"(41188, 21)\n"
]
],
[
[
"### Prepare split",
"_____no_output_____"
]
],
[
[
"train_indices = train[train.Set == \"train\"].index.values\nnp.random.shuffle(train_indices)\nvalid_indices = train[train.Set == \"valid\"].index.values\ntest_indices = train[train.Set == \"test\"].index.values",
"_____no_output_____"
]
],
[
[
"### Encode target",
"_____no_output_____"
]
],
[
[
"from sklearn import preprocessing\n\n# label_encoder object knows how to understand word labels.\nlabel_encoder = preprocessing.LabelEncoder()\n\n# Encode labels in column 'species'.\nY = (\n label_encoder.fit_transform(train[[target]].values.reshape(-1))\n .reshape(-1, 1)\n .astype(\"uint8\")\n)\nprint(Y.shape)\n\nX = train.drop(columns=[target, \"Set\"]).values.astype(\"str\")\nprint(X.shape)\n\ndel train\ngc.collect()",
"(41188, 1)\n(41188, 19)\n"
],
[
"# https://he-arc.github.io/livre-python/pillow/index.html#methodes-de-dessin\n# https://stackoverflow.com/questions/26649716/how-to-show-pil-image-in-ipython-notebook\n# https://stackoverflow.com/questions/384759/how-to-convert-a-pil-image-into-a-numpy-array\n# line = np.array(pic, dtypes=\"uint8\")\n# from https://arxiv.org/pdf/1902.02160.pdf page 2",
"_____no_output_____"
],
[
"WHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\n\n\ndef word_to_square_image(text, size, cut_length=None):\n\n truncated = text[:cut_length] if cut_length is not None else text\n max_x = np.ceil(np.sqrt(len(truncated))).astype(\"int\")\n character_size = np.floor(size / max_x).astype(\"int\")\n padding = np.floor((size - (max_x * character_size)) / 2).astype(\"int\")\n # Do we need pt to px conversion ? Seems like not\n # font_size = int(np.floor(character_size*0.75))\n font_size = character_size\n\n fnt = ImageFont.truetype(out_font.as_posix(), font_size)\n image = Image.new(\"RGB\", (size, size), BLACK)\n # Obtention du contexte graphique\n draw = ImageDraw.Draw(image)\n x = 0\n y = 0\n for letter in text:\n draw.text(\n (padding + x * character_size, padding + y * character_size),\n letter,\n font=fnt,\n fill=WHITE,\n )\n if x + 1 < max_x:\n x += 1\n else:\n y += 1\n x = 0\n return np.array(image)",
"_____no_output_____"
],
[
"def text_to_square_image(features, image_size=299, cut_length=None):\n square_nb = np.ceil(np.sqrt(len(features))).astype(\"int\")\n word_size = np.floor(image_size / square_nb).astype(\"int\")\n max_features = len(features)\n padding = np.floor((image_size - square_nb * word_size) / 2).astype(\"int\")\n result_image = np.zeros((image_size, image_size, 3), dtype=\"uint8\")\n results = []\n i_feature = 0\n for x in range(0, square_nb):\n if i_feature is None:\n break\n for y in range(0, square_nb):\n i_feature = x * (square_nb) + y\n if i_feature >= max_features:\n i_feature = None\n break\n x_pos = x * word_size + padding\n y_pos = y * word_size + padding\n result_image[\n x_pos : x_pos + word_size, y_pos : y_pos + word_size\n ] = word_to_square_image(\n features[i_feature], size=word_size, cut_length=cut_length\n )\n return result_image",
"_____no_output_____"
],
[
"def preprocess_data(data, map_func):\n preprocessed_df = None\n with PoolExecutor() as executor:\n preprocessed_df = np.stack(list(executor.map(map_func, data)), axis=0)\n print(preprocessed_df.shape)\n print(preprocessed_df.nbytes / (1024 * 1024)) # Memory size in RAM\n gc.collect()\n return preprocessed_df",
"_____no_output_____"
],
[
"def fixed_text_to_square_image(values):\n return text_to_square_image(values, image_size=96, cut_length=None)",
"_____no_output_____"
],
[
"from tensorflow.keras.utils import to_categorical\nfrom concurrent.futures import ProcessPoolExecutor as PoolExecutor\n\n\nclass TabularToImagesDataset:\n def __init__(self, values, target, func, prefetch=1024):\n self.values = values\n self.target = to_categorical(target.reshape(-1))\n assert target.shape[0] == self.values.shape[0]\n self.current = -1\n self.max_prefetch = -1\n self.prefetch_nb = prefetch\n self.func = func\n self.ready = None\n\n def __iter__(self):\n # print(\"Calling __iter__\")\n self.current = -1\n self.max_prefetch = -1\n return self\n\n def __call__(self):\n # print(\"Calling __call__\")\n self.current = -1\n self.max_prefetch = -1\n return self\n\n def __next__(self):\n return self.next()\n\n def __len__(self):\n return self.values.shape[0]\n\n def prefetch(self):\n if self.ready is not None and self.ready.shape[0] == self.values.shape[0]:\n return\n # print(\"HERE\")\n self.max_prefetch = min(self.current + self.prefetch_nb, self.values.shape[0])\n # if self.current == self.max_prefetch:\n\n with PoolExecutor() as executor:\n self.ready = np.stack(\n list(\n executor.map(\n self.func, self.values[self.current : self.max_prefetch]\n )\n ),\n axis=0,\n )\n return\n\n def next(self):\n self.current += 1\n # print(self.current)\n if self.current >= self.values.shape[0]:\n raise StopIteration()\n # self.current = 0\n # self.max_prefetch = -1\n if self.current >= self.max_prefetch:\n # print(\"Will prefetch\")\n self.prefetch()\n # print(self.ready.shape)\n return (\n self.ready[self.current % self.prefetch_nb],\n # text_to_square_image(self.values[self.current]),\n self.target[self.current],\n )",
"_____no_output_____"
],
[
"def build_tf_dataset(X_values, Y_values, image_size, fix_func, prefetch, batch_size):\n gen = TabularToImagesDataset(\n X_values, Y_values, fix_func, prefetch=prefetch * batch_size,\n )\n if prefetch * batch_size > X_values.shape[0]:\n prefetch = np.ceil(X_values.shape[0] / batch_size).astype(\"int\")\n\n dataset = tf.data.Dataset.from_generator(\n gen,\n (tf.uint8, tf.uint8),\n (tf.TensorShape([image_size, image_size, 3]), tf.TensorShape([2])),\n )\n\n dataset = dataset.repeat().batch(batch_size)\n return dataset.prefetch(prefetch)",
"_____no_output_____"
],
[
"epochs_1 = 2\nepochs_2 = 200\nimage_size = 96\ncut_length = None\nBATCH_SIZE = 64\nPREFETCH = 10000 # 40\n# SHUFFLE_BUFFER_SIZE = 10000\npatience = 5\n\n\ndef fixed_text_to_square_image(values):\n return text_to_square_image(values, image_size=image_size, cut_length=cut_length)\n\n\nsteps_per_epoch = np.ceil(train_indices.shape[0] / BATCH_SIZE)\nsteps_per_epoch_val = np.ceil(valid_indices.shape[0] / BATCH_SIZE)\n\ndataset = build_tf_dataset(\n X[train_indices],\n Y[train_indices],\n image_size,\n fixed_text_to_square_image,\n PREFETCH,\n BATCH_SIZE,\n)\n\ndataset_valid = build_tf_dataset(\n X[valid_indices],\n Y[valid_indices],\n image_size,\n fixed_text_to_square_image,\n PREFETCH,\n BATCH_SIZE,\n)",
"_____no_output_____"
]
],
[
[
"for image, label in dataset.as_numpy_iterator():\n # print(label)\n imshow(image[0])\n break",
"_____no_output_____"
]
],
[
[
"activation = mish\noptimizer = Lookahead(RectifiedAdam(), sync_period=6, slow_step_size=0.5)",
"_____no_output_____"
]
],
[
[
"es = EarlyStopping(\n monitor=\"val_loss\",\n verbose=1,\n mode=\"min\",\n patience=patience,\n restore_best_weights=True,\n)",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.applications.inception_v3 import InceptionV3\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import (\n Dense,\n GlobalAveragePooling2D,\n BatchNormalization,\n Dropout,\n)\nfrom tensorflow.keras import backend as K\n\n# create the base pre-trained model\nbase_model = InceptionV3(weights=\"imagenet\", include_top=False)\n\n# add a global spatial average pooling layer\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\n# let's add a fully-connected layer\nx = Dense(1024, activation=activation, kernel_initializer=\"he_normal\")(x)\nx = Dropout(0.2)(x)\nx = Dense(128, activation=activation, kernel_initializer=\"he_normal\")(x)\nx = Dropout(0.2)(x)\n\n# and a logistic layer -- let's say we have 200 classes\n# predictions = Dense(200, activation='softmax')(x)\npredictions = Dense(2, activation=\"softmax\")(x)\n\n# this is the model we will train\nmodel = Model(inputs=base_model.input, outputs=predictions)\n\n# first: train only the top layers (which were randomly initialized)\n# i.e. freeze all convolutional InceptionV3 layers\nfor layer in base_model.layers:\n layer.trainable = False\n\n# es.set_model(model)\n# compile the model (should be done *after* setting layers to non-trainable)\nmodel.compile(optimizer=optimizer, loss=\"binary_crossentropy\") # , metrics=[\"AUC\"])",
"_____no_output_____"
],
[
"%%time\n# train the model on the new data for a few epochs\nhistory_1 = model.fit(\n dataset, \n #callbacks=[es],\n epochs=epochs_1,\n steps_per_epoch=steps_per_epoch,\n validation_data=dataset_valid,\n validation_steps=steps_per_epoch_val\n)\n# at this point, the top layers are well trained and we can start fine-tuning\n# convolutional layers from inception V3. We will freeze the bottom N layers\n# and train the remaining top layers.",
"Train for 515.0 steps, validate for 65.0 steps\nEpoch 1/2\nWARNING:tensorflow:From /work/.cache/poetry/thc-net-KQLMmzPP-py3.7/lib/python3.7/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1786: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\nInstructions for updating:\nIf using Keras pass *_constraint arguments to layers.\n515/515 [==============================] - 164s 318ms/step - loss: 0.3618 - val_loss: 1.7881\nEpoch 2/2\n515/515 [==============================] - 22s 43ms/step - loss: 0.3341 - val_loss: 1.4349\nCPU times: user 1min 33s, sys: 11.5 s, total: 1min 45s\nWall time: 3min 6s\n"
],
[
"def plot_metric(history, metric):\n # Plot training & validation loss values\n plt.plot(history.history[metric])\n plt.plot(history.history[f\"val_{metric}\"])\n plt.title(f\"Model {metric}\")\n plt.ylabel(f\"{metric}\")\n plt.xlabel(\"Epoch\")\n plt.legend([\"Train\", \"Test\"], loc=\"upper left\")\n plt.show()",
"_____no_output_____"
],
[
"plot_metric(history_1, \"loss\")",
"_____no_output_____"
],
[
"# plot_metric(history_1, \"AUC\")",
"_____no_output_____"
],
[
"# let's visualize layer names and layer indices to see how many layers\n# we should freeze:\nmodel.summary()\n# for i, layer in enumerate(model.layers):\n# print(i, layer.name)",
"Model: \"model_1\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_2 (InputLayer) [(None, None, None, 0 \n__________________________________________________________________________________________________\nconv2d_94 (Conv2D) (None, None, None, 3 864 input_2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_94 (BatchNo (None, None, None, 3 96 conv2d_94[0][0] \n__________________________________________________________________________________________________\nactivation_94 (Activation) (None, None, None, 3 0 batch_normalization_94[0][0] \n__________________________________________________________________________________________________\nconv2d_95 (Conv2D) (None, None, None, 3 9216 activation_94[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_95 (BatchNo (None, None, None, 3 96 conv2d_95[0][0] \n__________________________________________________________________________________________________\nactivation_95 (Activation) (None, None, None, 3 0 batch_normalization_95[0][0] \n__________________________________________________________________________________________________\nconv2d_96 (Conv2D) (None, None, None, 6 18432 activation_95[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_96 (BatchNo (None, None, None, 6 192 conv2d_96[0][0] \n__________________________________________________________________________________________________\nactivation_96 (Activation) (None, None, None, 6 0 batch_normalization_96[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_4 (MaxPooling2D) (None, None, None, 6 0 activation_96[0][0] \n__________________________________________________________________________________________________\nconv2d_97 (Conv2D) (None, None, None, 8 5120 max_pooling2d_4[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_97 (BatchNo (None, None, None, 8 240 conv2d_97[0][0] \n__________________________________________________________________________________________________\nactivation_97 (Activation) (None, None, None, 8 0 batch_normalization_97[0][0] \n__________________________________________________________________________________________________\nconv2d_98 (Conv2D) (None, None, None, 1 138240 activation_97[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_98 (BatchNo (None, None, None, 1 576 conv2d_98[0][0] \n__________________________________________________________________________________________________\nactivation_98 (Activation) (None, None, None, 1 0 batch_normalization_98[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_5 (MaxPooling2D) (None, None, None, 1 0 activation_98[0][0] \n__________________________________________________________________________________________________\nconv2d_102 (Conv2D) (None, None, None, 6 12288 max_pooling2d_5[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_102 (BatchN (None, None, None, 6 192 conv2d_102[0][0] \n__________________________________________________________________________________________________\nactivation_102 (Activation) (None, None, None, 6 0 batch_normalization_102[0][0] \n__________________________________________________________________________________________________\nconv2d_100 (Conv2D) (None, None, None, 4 9216 max_pooling2d_5[0][0] \n__________________________________________________________________________________________________\nconv2d_103 (Conv2D) (None, None, None, 9 55296 activation_102[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_100 (BatchN (None, None, None, 4 144 conv2d_100[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_103 (BatchN (None, None, None, 9 288 conv2d_103[0][0] \n__________________________________________________________________________________________________\nactivation_100 (Activation) (None, None, None, 4 0 batch_normalization_100[0][0] \n__________________________________________________________________________________________________\nactivation_103 (Activation) (None, None, None, 9 0 batch_normalization_103[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_9 (AveragePoo (None, None, None, 1 0 max_pooling2d_5[0][0] \n__________________________________________________________________________________________________\nconv2d_99 (Conv2D) (None, None, None, 6 12288 max_pooling2d_5[0][0] \n__________________________________________________________________________________________________\nconv2d_101 (Conv2D) (None, None, None, 6 76800 activation_100[0][0] \n__________________________________________________________________________________________________\nconv2d_104 (Conv2D) (None, None, None, 9 82944 activation_103[0][0] \n__________________________________________________________________________________________________\nconv2d_105 (Conv2D) (None, None, None, 3 6144 average_pooling2d_9[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_99 (BatchNo (None, None, None, 6 192 conv2d_99[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_101 (BatchN (None, None, None, 6 192 conv2d_101[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_104 (BatchN (None, None, None, 9 288 conv2d_104[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_105 (BatchN (None, None, None, 3 96 conv2d_105[0][0] \n__________________________________________________________________________________________________\nactivation_99 (Activation) (None, None, None, 6 0 batch_normalization_99[0][0] \n__________________________________________________________________________________________________\nactivation_101 (Activation) (None, None, None, 6 0 batch_normalization_101[0][0] \n__________________________________________________________________________________________________\nactivation_104 (Activation) (None, None, None, 9 0 batch_normalization_104[0][0] \n__________________________________________________________________________________________________\nactivation_105 (Activation) (None, None, None, 3 0 batch_normalization_105[0][0] \n__________________________________________________________________________________________________\nmixed0 (Concatenate) (None, None, None, 2 0 activation_99[0][0] \n activation_101[0][0] \n activation_104[0][0] \n activation_105[0][0] \n__________________________________________________________________________________________________\nconv2d_109 (Conv2D) (None, None, None, 6 16384 mixed0[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_109 (BatchN (None, None, None, 6 192 conv2d_109[0][0] \n__________________________________________________________________________________________________\nactivation_109 (Activation) (None, None, None, 6 0 batch_normalization_109[0][0] \n__________________________________________________________________________________________________\nconv2d_107 (Conv2D) (None, None, None, 4 12288 mixed0[0][0] \n__________________________________________________________________________________________________\nconv2d_110 (Conv2D) (None, None, None, 9 55296 activation_109[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_107 (BatchN (None, None, None, 4 144 conv2d_107[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_110 (BatchN (None, None, None, 9 288 conv2d_110[0][0] \n__________________________________________________________________________________________________\nactivation_107 (Activation) (None, None, None, 4 0 batch_normalization_107[0][0] \n__________________________________________________________________________________________________\nactivation_110 (Activation) (None, None, None, 9 0 batch_normalization_110[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_10 (AveragePo (None, None, None, 2 0 mixed0[0][0] \n__________________________________________________________________________________________________\nconv2d_106 (Conv2D) (None, None, None, 6 16384 mixed0[0][0] \n__________________________________________________________________________________________________\nconv2d_108 (Conv2D) (None, None, None, 6 76800 activation_107[0][0] \n__________________________________________________________________________________________________\nconv2d_111 (Conv2D) (None, None, None, 9 82944 activation_110[0][0] \n__________________________________________________________________________________________________\nconv2d_112 (Conv2D) (None, None, None, 6 16384 average_pooling2d_10[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_106 (BatchN (None, None, None, 6 192 conv2d_106[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_108 (BatchN (None, None, None, 6 192 conv2d_108[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_111 (BatchN (None, None, None, 9 288 conv2d_111[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_112 (BatchN (None, None, None, 6 192 conv2d_112[0][0] \n__________________________________________________________________________________________________\nactivation_106 (Activation) (None, None, None, 6 0 batch_normalization_106[0][0] \n__________________________________________________________________________________________________\nactivation_108 (Activation) (None, None, None, 6 0 batch_normalization_108[0][0] \n__________________________________________________________________________________________________\nactivation_111 (Activation) (None, None, None, 9 0 batch_normalization_111[0][0] \n__________________________________________________________________________________________________\nactivation_112 (Activation) (None, None, None, 6 0 batch_normalization_112[0][0] \n__________________________________________________________________________________________________\nmixed1 (Concatenate) (None, None, None, 2 0 activation_106[0][0] \n activation_108[0][0] \n activation_111[0][0] \n activation_112[0][0] \n__________________________________________________________________________________________________\nconv2d_116 (Conv2D) (None, None, None, 6 18432 mixed1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_116 (BatchN (None, None, None, 6 192 conv2d_116[0][0] \n__________________________________________________________________________________________________\nactivation_116 (Activation) (None, None, None, 6 0 batch_normalization_116[0][0] \n__________________________________________________________________________________________________\nconv2d_114 (Conv2D) (None, None, None, 4 13824 mixed1[0][0] \n__________________________________________________________________________________________________\nconv2d_117 (Conv2D) (None, None, None, 9 55296 activation_116[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_114 (BatchN (None, None, None, 4 144 conv2d_114[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_117 (BatchN (None, None, None, 9 288 conv2d_117[0][0] \n__________________________________________________________________________________________________\nactivation_114 (Activation) (None, None, None, 4 0 batch_normalization_114[0][0] \n__________________________________________________________________________________________________\nactivation_117 (Activation) (None, None, None, 9 0 batch_normalization_117[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_11 (AveragePo (None, None, None, 2 0 mixed1[0][0] \n__________________________________________________________________________________________________\nconv2d_113 (Conv2D) (None, None, None, 6 18432 mixed1[0][0] \n__________________________________________________________________________________________________\nconv2d_115 (Conv2D) (None, None, None, 6 76800 activation_114[0][0] \n__________________________________________________________________________________________________\nconv2d_118 (Conv2D) (None, None, None, 9 82944 activation_117[0][0] \n__________________________________________________________________________________________________\nconv2d_119 (Conv2D) (None, None, None, 6 18432 average_pooling2d_11[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_113 (BatchN (None, None, None, 6 192 conv2d_113[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_115 (BatchN (None, None, None, 6 192 conv2d_115[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_118 (BatchN (None, None, None, 9 288 conv2d_118[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_119 (BatchN (None, None, None, 6 192 conv2d_119[0][0] \n__________________________________________________________________________________________________\nactivation_113 (Activation) (None, None, None, 6 0 batch_normalization_113[0][0] \n__________________________________________________________________________________________________\nactivation_115 (Activation) (None, None, None, 6 0 batch_normalization_115[0][0] \n__________________________________________________________________________________________________\nactivation_118 (Activation) (None, None, None, 9 0 batch_normalization_118[0][0] \n__________________________________________________________________________________________________\nactivation_119 (Activation) (None, None, None, 6 0 batch_normalization_119[0][0] \n__________________________________________________________________________________________________\nmixed2 (Concatenate) (None, None, None, 2 0 activation_113[0][0] \n activation_115[0][0] \n activation_118[0][0] \n activation_119[0][0] \n__________________________________________________________________________________________________\nconv2d_121 (Conv2D) (None, None, None, 6 18432 mixed2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_121 (BatchN (None, None, None, 6 192 conv2d_121[0][0] \n__________________________________________________________________________________________________\nactivation_121 (Activation) (None, None, None, 6 0 batch_normalization_121[0][0] \n__________________________________________________________________________________________________\nconv2d_122 (Conv2D) (None, None, None, 9 55296 activation_121[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_122 (BatchN (None, None, None, 9 288 conv2d_122[0][0] \n__________________________________________________________________________________________________\nactivation_122 (Activation) (None, None, None, 9 0 batch_normalization_122[0][0] \n__________________________________________________________________________________________________\nconv2d_120 (Conv2D) (None, None, None, 3 995328 mixed2[0][0] \n__________________________________________________________________________________________________\nconv2d_123 (Conv2D) (None, None, None, 9 82944 activation_122[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_120 (BatchN (None, None, None, 3 1152 conv2d_120[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_123 (BatchN (None, None, None, 9 288 conv2d_123[0][0] \n__________________________________________________________________________________________________\nactivation_120 (Activation) (None, None, None, 3 0 batch_normalization_120[0][0] \n__________________________________________________________________________________________________\nactivation_123 (Activation) (None, None, None, 9 0 batch_normalization_123[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_6 (MaxPooling2D) (None, None, None, 2 0 mixed2[0][0] \n__________________________________________________________________________________________________\nmixed3 (Concatenate) (None, None, None, 7 0 activation_120[0][0] \n activation_123[0][0] \n max_pooling2d_6[0][0] \n__________________________________________________________________________________________________\nconv2d_128 (Conv2D) (None, None, None, 1 98304 mixed3[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_128 (BatchN (None, None, None, 1 384 conv2d_128[0][0] \n__________________________________________________________________________________________________\nactivation_128 (Activation) (None, None, None, 1 0 batch_normalization_128[0][0] \n__________________________________________________________________________________________________\nconv2d_129 (Conv2D) (None, None, None, 1 114688 activation_128[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_129 (BatchN (None, None, None, 1 384 conv2d_129[0][0] \n__________________________________________________________________________________________________\nactivation_129 (Activation) (None, None, None, 1 0 batch_normalization_129[0][0] \n__________________________________________________________________________________________________\nconv2d_125 (Conv2D) (None, None, None, 1 98304 mixed3[0][0] \n__________________________________________________________________________________________________\nconv2d_130 (Conv2D) (None, None, None, 1 114688 activation_129[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_125 (BatchN (None, None, None, 1 384 conv2d_125[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_130 (BatchN (None, None, None, 1 384 conv2d_130[0][0] \n__________________________________________________________________________________________________\nactivation_125 (Activation) (None, None, None, 1 0 batch_normalization_125[0][0] \n__________________________________________________________________________________________________\nactivation_130 (Activation) (None, None, None, 1 0 batch_normalization_130[0][0] \n__________________________________________________________________________________________________\nconv2d_126 (Conv2D) (None, None, None, 1 114688 activation_125[0][0] \n__________________________________________________________________________________________________\nconv2d_131 (Conv2D) (None, None, None, 1 114688 activation_130[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_126 (BatchN (None, None, None, 1 384 conv2d_126[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_131 (BatchN (None, None, None, 1 384 conv2d_131[0][0] \n__________________________________________________________________________________________________\nactivation_126 (Activation) (None, None, None, 1 0 batch_normalization_126[0][0] \n__________________________________________________________________________________________________\nactivation_131 (Activation) (None, None, None, 1 0 batch_normalization_131[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_12 (AveragePo (None, None, None, 7 0 mixed3[0][0] \n__________________________________________________________________________________________________\nconv2d_124 (Conv2D) (None, None, None, 1 147456 mixed3[0][0] \n__________________________________________________________________________________________________\nconv2d_127 (Conv2D) (None, None, None, 1 172032 activation_126[0][0] \n__________________________________________________________________________________________________\nconv2d_132 (Conv2D) (None, None, None, 1 172032 activation_131[0][0] \n__________________________________________________________________________________________________\nconv2d_133 (Conv2D) (None, None, None, 1 147456 average_pooling2d_12[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_124 (BatchN (None, None, None, 1 576 conv2d_124[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_127 (BatchN (None, None, None, 1 576 conv2d_127[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_132 (BatchN (None, None, None, 1 576 conv2d_132[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_133 (BatchN (None, None, None, 1 576 conv2d_133[0][0] \n__________________________________________________________________________________________________\nactivation_124 (Activation) (None, None, None, 1 0 batch_normalization_124[0][0] \n__________________________________________________________________________________________________\nactivation_127 (Activation) (None, None, None, 1 0 batch_normalization_127[0][0] \n__________________________________________________________________________________________________\nactivation_132 (Activation) (None, None, None, 1 0 batch_normalization_132[0][0] \n__________________________________________________________________________________________________\nactivation_133 (Activation) (None, None, None, 1 0 batch_normalization_133[0][0] \n__________________________________________________________________________________________________\nmixed4 (Concatenate) (None, None, None, 7 0 activation_124[0][0] \n activation_127[0][0] \n activation_132[0][0] \n activation_133[0][0] \n__________________________________________________________________________________________________\nconv2d_138 (Conv2D) (None, None, None, 1 122880 mixed4[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_138 (BatchN (None, None, None, 1 480 conv2d_138[0][0] \n__________________________________________________________________________________________________\nactivation_138 (Activation) (None, None, None, 1 0 batch_normalization_138[0][0] \n__________________________________________________________________________________________________\nconv2d_139 (Conv2D) (None, None, None, 1 179200 activation_138[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_139 (BatchN (None, None, None, 1 480 conv2d_139[0][0] \n__________________________________________________________________________________________________\nactivation_139 (Activation) (None, None, None, 1 0 batch_normalization_139[0][0] \n__________________________________________________________________________________________________\nconv2d_135 (Conv2D) (None, None, None, 1 122880 mixed4[0][0] \n__________________________________________________________________________________________________\nconv2d_140 (Conv2D) (None, None, None, 1 179200 activation_139[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_135 (BatchN (None, None, None, 1 480 conv2d_135[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_140 (BatchN (None, None, None, 1 480 conv2d_140[0][0] \n__________________________________________________________________________________________________\nactivation_135 (Activation) (None, None, None, 1 0 batch_normalization_135[0][0] \n__________________________________________________________________________________________________\nactivation_140 (Activation) (None, None, None, 1 0 batch_normalization_140[0][0] \n__________________________________________________________________________________________________\nconv2d_136 (Conv2D) (None, None, None, 1 179200 activation_135[0][0] \n__________________________________________________________________________________________________\nconv2d_141 (Conv2D) (None, None, None, 1 179200 activation_140[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_136 (BatchN (None, None, None, 1 480 conv2d_136[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_141 (BatchN (None, None, None, 1 480 conv2d_141[0][0] \n__________________________________________________________________________________________________\nactivation_136 (Activation) (None, None, None, 1 0 batch_normalization_136[0][0] \n__________________________________________________________________________________________________\nactivation_141 (Activation) (None, None, None, 1 0 batch_normalization_141[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_13 (AveragePo (None, None, None, 7 0 mixed4[0][0] \n__________________________________________________________________________________________________\nconv2d_134 (Conv2D) (None, None, None, 1 147456 mixed4[0][0] \n__________________________________________________________________________________________________\nconv2d_137 (Conv2D) (None, None, None, 1 215040 activation_136[0][0] \n__________________________________________________________________________________________________\nconv2d_142 (Conv2D) (None, None, None, 1 215040 activation_141[0][0] \n__________________________________________________________________________________________________\nconv2d_143 (Conv2D) (None, None, None, 1 147456 average_pooling2d_13[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_134 (BatchN (None, None, None, 1 576 conv2d_134[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_137 (BatchN (None, None, None, 1 576 conv2d_137[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_142 (BatchN (None, None, None, 1 576 conv2d_142[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_143 (BatchN (None, None, None, 1 576 conv2d_143[0][0] \n__________________________________________________________________________________________________\nactivation_134 (Activation) (None, None, None, 1 0 batch_normalization_134[0][0] \n__________________________________________________________________________________________________\nactivation_137 (Activation) (None, None, None, 1 0 batch_normalization_137[0][0] \n__________________________________________________________________________________________________\nactivation_142 (Activation) (None, None, None, 1 0 batch_normalization_142[0][0] \n__________________________________________________________________________________________________\nactivation_143 (Activation) (None, None, None, 1 0 batch_normalization_143[0][0] \n__________________________________________________________________________________________________\nmixed5 (Concatenate) (None, None, None, 7 0 activation_134[0][0] \n activation_137[0][0] \n activation_142[0][0] \n activation_143[0][0] \n__________________________________________________________________________________________________\nconv2d_148 (Conv2D) (None, None, None, 1 122880 mixed5[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_148 (BatchN (None, None, None, 1 480 conv2d_148[0][0] \n__________________________________________________________________________________________________\nactivation_148 (Activation) (None, None, None, 1 0 batch_normalization_148[0][0] \n__________________________________________________________________________________________________\nconv2d_149 (Conv2D) (None, None, None, 1 179200 activation_148[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_149 (BatchN (None, None, None, 1 480 conv2d_149[0][0] \n__________________________________________________________________________________________________\nactivation_149 (Activation) (None, None, None, 1 0 batch_normalization_149[0][0] \n__________________________________________________________________________________________________\nconv2d_145 (Conv2D) (None, None, None, 1 122880 mixed5[0][0] \n__________________________________________________________________________________________________\nconv2d_150 (Conv2D) (None, None, None, 1 179200 activation_149[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_145 (BatchN (None, None, None, 1 480 conv2d_145[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_150 (BatchN (None, None, None, 1 480 conv2d_150[0][0] \n__________________________________________________________________________________________________\nactivation_145 (Activation) (None, None, None, 1 0 batch_normalization_145[0][0] \n__________________________________________________________________________________________________\nactivation_150 (Activation) (None, None, None, 1 0 batch_normalization_150[0][0] \n__________________________________________________________________________________________________\nconv2d_146 (Conv2D) (None, None, None, 1 179200 activation_145[0][0] \n__________________________________________________________________________________________________\nconv2d_151 (Conv2D) (None, None, None, 1 179200 activation_150[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_146 (BatchN (None, None, None, 1 480 conv2d_146[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_151 (BatchN (None, None, None, 1 480 conv2d_151[0][0] \n__________________________________________________________________________________________________\nactivation_146 (Activation) (None, None, None, 1 0 batch_normalization_146[0][0] \n__________________________________________________________________________________________________\nactivation_151 (Activation) (None, None, None, 1 0 batch_normalization_151[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_14 (AveragePo (None, None, None, 7 0 mixed5[0][0] \n__________________________________________________________________________________________________\nconv2d_144 (Conv2D) (None, None, None, 1 147456 mixed5[0][0] \n__________________________________________________________________________________________________\nconv2d_147 (Conv2D) (None, None, None, 1 215040 activation_146[0][0] \n__________________________________________________________________________________________________\nconv2d_152 (Conv2D) (None, None, None, 1 215040 activation_151[0][0] \n__________________________________________________________________________________________________\nconv2d_153 (Conv2D) (None, None, None, 1 147456 average_pooling2d_14[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_144 (BatchN (None, None, None, 1 576 conv2d_144[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_147 (BatchN (None, None, None, 1 576 conv2d_147[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_152 (BatchN (None, None, None, 1 576 conv2d_152[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_153 (BatchN (None, None, None, 1 576 conv2d_153[0][0] \n__________________________________________________________________________________________________\nactivation_144 (Activation) (None, None, None, 1 0 batch_normalization_144[0][0] \n__________________________________________________________________________________________________\nactivation_147 (Activation) (None, None, None, 1 0 batch_normalization_147[0][0] \n__________________________________________________________________________________________________\nactivation_152 (Activation) (None, None, None, 1 0 batch_normalization_152[0][0] \n__________________________________________________________________________________________________\nactivation_153 (Activation) (None, None, None, 1 0 batch_normalization_153[0][0] \n__________________________________________________________________________________________________\nmixed6 (Concatenate) (None, None, None, 7 0 activation_144[0][0] \n activation_147[0][0] \n activation_152[0][0] \n activation_153[0][0] \n__________________________________________________________________________________________________\nconv2d_158 (Conv2D) (None, None, None, 1 147456 mixed6[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_158 (BatchN (None, None, None, 1 576 conv2d_158[0][0] \n__________________________________________________________________________________________________\nactivation_158 (Activation) (None, None, None, 1 0 batch_normalization_158[0][0] \n__________________________________________________________________________________________________\nconv2d_159 (Conv2D) (None, None, None, 1 258048 activation_158[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_159 (BatchN (None, None, None, 1 576 conv2d_159[0][0] \n__________________________________________________________________________________________________\nactivation_159 (Activation) (None, None, None, 1 0 batch_normalization_159[0][0] \n__________________________________________________________________________________________________\nconv2d_155 (Conv2D) (None, None, None, 1 147456 mixed6[0][0] \n__________________________________________________________________________________________________\nconv2d_160 (Conv2D) (None, None, None, 1 258048 activation_159[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_155 (BatchN (None, None, None, 1 576 conv2d_155[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_160 (BatchN (None, None, None, 1 576 conv2d_160[0][0] \n__________________________________________________________________________________________________\nactivation_155 (Activation) (None, None, None, 1 0 batch_normalization_155[0][0] \n__________________________________________________________________________________________________\nactivation_160 (Activation) (None, None, None, 1 0 batch_normalization_160[0][0] \n__________________________________________________________________________________________________\nconv2d_156 (Conv2D) (None, None, None, 1 258048 activation_155[0][0] \n__________________________________________________________________________________________________\nconv2d_161 (Conv2D) (None, None, None, 1 258048 activation_160[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_156 (BatchN (None, None, None, 1 576 conv2d_156[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_161 (BatchN (None, None, None, 1 576 conv2d_161[0][0] \n__________________________________________________________________________________________________\nactivation_156 (Activation) (None, None, None, 1 0 batch_normalization_156[0][0] \n__________________________________________________________________________________________________\nactivation_161 (Activation) (None, None, None, 1 0 batch_normalization_161[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_15 (AveragePo (None, None, None, 7 0 mixed6[0][0] \n__________________________________________________________________________________________________\nconv2d_154 (Conv2D) (None, None, None, 1 147456 mixed6[0][0] \n__________________________________________________________________________________________________\nconv2d_157 (Conv2D) (None, None, None, 1 258048 activation_156[0][0] \n__________________________________________________________________________________________________\nconv2d_162 (Conv2D) (None, None, None, 1 258048 activation_161[0][0] \n__________________________________________________________________________________________________\nconv2d_163 (Conv2D) (None, None, None, 1 147456 average_pooling2d_15[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_154 (BatchN (None, None, None, 1 576 conv2d_154[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_157 (BatchN (None, None, None, 1 576 conv2d_157[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_162 (BatchN (None, None, None, 1 576 conv2d_162[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_163 (BatchN (None, None, None, 1 576 conv2d_163[0][0] \n__________________________________________________________________________________________________\nactivation_154 (Activation) (None, None, None, 1 0 batch_normalization_154[0][0] \n__________________________________________________________________________________________________\nactivation_157 (Activation) (None, None, None, 1 0 batch_normalization_157[0][0] \n__________________________________________________________________________________________________\nactivation_162 (Activation) (None, None, None, 1 0 batch_normalization_162[0][0] \n__________________________________________________________________________________________________\nactivation_163 (Activation) (None, None, None, 1 0 batch_normalization_163[0][0] \n__________________________________________________________________________________________________\nmixed7 (Concatenate) (None, None, None, 7 0 activation_154[0][0] \n activation_157[0][0] \n activation_162[0][0] \n activation_163[0][0] \n__________________________________________________________________________________________________\nconv2d_166 (Conv2D) (None, None, None, 1 147456 mixed7[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_166 (BatchN (None, None, None, 1 576 conv2d_166[0][0] \n__________________________________________________________________________________________________\nactivation_166 (Activation) (None, None, None, 1 0 batch_normalization_166[0][0] \n__________________________________________________________________________________________________\nconv2d_167 (Conv2D) (None, None, None, 1 258048 activation_166[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_167 (BatchN (None, None, None, 1 576 conv2d_167[0][0] \n__________________________________________________________________________________________________\nactivation_167 (Activation) (None, None, None, 1 0 batch_normalization_167[0][0] \n__________________________________________________________________________________________________\nconv2d_164 (Conv2D) (None, None, None, 1 147456 mixed7[0][0] \n__________________________________________________________________________________________________\nconv2d_168 (Conv2D) (None, None, None, 1 258048 activation_167[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_164 (BatchN (None, None, None, 1 576 conv2d_164[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_168 (BatchN (None, None, None, 1 576 conv2d_168[0][0] \n__________________________________________________________________________________________________\nactivation_164 (Activation) (None, None, None, 1 0 batch_normalization_164[0][0] \n__________________________________________________________________________________________________\nactivation_168 (Activation) (None, None, None, 1 0 batch_normalization_168[0][0] \n__________________________________________________________________________________________________\nconv2d_165 (Conv2D) (None, None, None, 3 552960 activation_164[0][0] \n__________________________________________________________________________________________________\nconv2d_169 (Conv2D) (None, None, None, 1 331776 activation_168[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_165 (BatchN (None, None, None, 3 960 conv2d_165[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_169 (BatchN (None, None, None, 1 576 conv2d_169[0][0] \n__________________________________________________________________________________________________\nactivation_165 (Activation) (None, None, None, 3 0 batch_normalization_165[0][0] \n__________________________________________________________________________________________________\nactivation_169 (Activation) (None, None, None, 1 0 batch_normalization_169[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_7 (MaxPooling2D) (None, None, None, 7 0 mixed7[0][0] \n__________________________________________________________________________________________________\nmixed8 (Concatenate) (None, None, None, 1 0 activation_165[0][0] \n activation_169[0][0] \n max_pooling2d_7[0][0] \n__________________________________________________________________________________________________\nconv2d_174 (Conv2D) (None, None, None, 4 573440 mixed8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_174 (BatchN (None, None, None, 4 1344 conv2d_174[0][0] \n__________________________________________________________________________________________________\nactivation_174 (Activation) (None, None, None, 4 0 batch_normalization_174[0][0] \n__________________________________________________________________________________________________\nconv2d_171 (Conv2D) (None, None, None, 3 491520 mixed8[0][0] \n__________________________________________________________________________________________________\nconv2d_175 (Conv2D) (None, None, None, 3 1548288 activation_174[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_171 (BatchN (None, None, None, 3 1152 conv2d_171[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_175 (BatchN (None, None, None, 3 1152 conv2d_175[0][0] \n__________________________________________________________________________________________________\nactivation_171 (Activation) (None, None, None, 3 0 batch_normalization_171[0][0] \n__________________________________________________________________________________________________\nactivation_175 (Activation) (None, None, None, 3 0 batch_normalization_175[0][0] \n__________________________________________________________________________________________________\nconv2d_172 (Conv2D) (None, None, None, 3 442368 activation_171[0][0] \n__________________________________________________________________________________________________\nconv2d_173 (Conv2D) (None, None, None, 3 442368 activation_171[0][0] \n__________________________________________________________________________________________________\nconv2d_176 (Conv2D) (None, None, None, 3 442368 activation_175[0][0] \n__________________________________________________________________________________________________\nconv2d_177 (Conv2D) (None, None, None, 3 442368 activation_175[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_16 (AveragePo (None, None, None, 1 0 mixed8[0][0] \n__________________________________________________________________________________________________\nconv2d_170 (Conv2D) (None, None, None, 3 409600 mixed8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_172 (BatchN (None, None, None, 3 1152 conv2d_172[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_173 (BatchN (None, None, None, 3 1152 conv2d_173[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_176 (BatchN (None, None, None, 3 1152 conv2d_176[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_177 (BatchN (None, None, None, 3 1152 conv2d_177[0][0] \n__________________________________________________________________________________________________\nconv2d_178 (Conv2D) (None, None, None, 1 245760 average_pooling2d_16[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_170 (BatchN (None, None, None, 3 960 conv2d_170[0][0] \n__________________________________________________________________________________________________\nactivation_172 (Activation) (None, None, None, 3 0 batch_normalization_172[0][0] \n__________________________________________________________________________________________________\nactivation_173 (Activation) (None, None, None, 3 0 batch_normalization_173[0][0] \n__________________________________________________________________________________________________\nactivation_176 (Activation) (None, None, None, 3 0 batch_normalization_176[0][0] \n__________________________________________________________________________________________________\nactivation_177 (Activation) (None, None, None, 3 0 batch_normalization_177[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_178 (BatchN (None, None, None, 1 576 conv2d_178[0][0] \n__________________________________________________________________________________________________\nactivation_170 (Activation) (None, None, None, 3 0 batch_normalization_170[0][0] \n__________________________________________________________________________________________________\nmixed9_0 (Concatenate) (None, None, None, 7 0 activation_172[0][0] \n activation_173[0][0] \n__________________________________________________________________________________________________\nconcatenate_2 (Concatenate) (None, None, None, 7 0 activation_176[0][0] \n activation_177[0][0] \n__________________________________________________________________________________________________\nactivation_178 (Activation) (None, None, None, 1 0 batch_normalization_178[0][0] \n__________________________________________________________________________________________________\nmixed9 (Concatenate) (None, None, None, 2 0 activation_170[0][0] \n mixed9_0[0][0] \n concatenate_2[0][0] \n activation_178[0][0] \n__________________________________________________________________________________________________\nconv2d_183 (Conv2D) (None, None, None, 4 917504 mixed9[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_183 (BatchN (None, None, None, 4 1344 conv2d_183[0][0] \n__________________________________________________________________________________________________\nactivation_183 (Activation) (None, None, None, 4 0 batch_normalization_183[0][0] \n__________________________________________________________________________________________________\nconv2d_180 (Conv2D) (None, None, None, 3 786432 mixed9[0][0] \n__________________________________________________________________________________________________\nconv2d_184 (Conv2D) (None, None, None, 3 1548288 activation_183[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_180 (BatchN (None, None, None, 3 1152 conv2d_180[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_184 (BatchN (None, None, None, 3 1152 conv2d_184[0][0] \n__________________________________________________________________________________________________\nactivation_180 (Activation) (None, None, None, 3 0 batch_normalization_180[0][0] \n__________________________________________________________________________________________________\nactivation_184 (Activation) (None, None, None, 3 0 batch_normalization_184[0][0] \n__________________________________________________________________________________________________\nconv2d_181 (Conv2D) (None, None, None, 3 442368 activation_180[0][0] \n__________________________________________________________________________________________________\nconv2d_182 (Conv2D) (None, None, None, 3 442368 activation_180[0][0] \n__________________________________________________________________________________________________\nconv2d_185 (Conv2D) (None, None, None, 3 442368 activation_184[0][0] \n__________________________________________________________________________________________________\nconv2d_186 (Conv2D) (None, None, None, 3 442368 activation_184[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_17 (AveragePo (None, None, None, 2 0 mixed9[0][0] \n__________________________________________________________________________________________________\nconv2d_179 (Conv2D) (None, None, None, 3 655360 mixed9[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_181 (BatchN (None, None, None, 3 1152 conv2d_181[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_182 (BatchN (None, None, None, 3 1152 conv2d_182[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_185 (BatchN (None, None, None, 3 1152 conv2d_185[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_186 (BatchN (None, None, None, 3 1152 conv2d_186[0][0] \n__________________________________________________________________________________________________\nconv2d_187 (Conv2D) (None, None, None, 1 393216 average_pooling2d_17[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_179 (BatchN (None, None, None, 3 960 conv2d_179[0][0] \n__________________________________________________________________________________________________\nactivation_181 (Activation) (None, None, None, 3 0 batch_normalization_181[0][0] \n__________________________________________________________________________________________________\nactivation_182 (Activation) (None, None, None, 3 0 batch_normalization_182[0][0] \n__________________________________________________________________________________________________\nactivation_185 (Activation) (None, None, None, 3 0 batch_normalization_185[0][0] \n__________________________________________________________________________________________________\nactivation_186 (Activation) (None, None, None, 3 0 batch_normalization_186[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_187 (BatchN (None, None, None, 1 576 conv2d_187[0][0] \n__________________________________________________________________________________________________\nactivation_179 (Activation) (None, None, None, 3 0 batch_normalization_179[0][0] \n__________________________________________________________________________________________________\nmixed9_1 (Concatenate) (None, None, None, 7 0 activation_181[0][0] \n activation_182[0][0] \n__________________________________________________________________________________________________\nconcatenate_3 (Concatenate) (None, None, None, 7 0 activation_185[0][0] \n activation_186[0][0] \n__________________________________________________________________________________________________\nactivation_187 (Activation) (None, None, None, 1 0 batch_normalization_187[0][0] \n__________________________________________________________________________________________________\nmixed10 (Concatenate) (None, None, None, 2 0 activation_179[0][0] \n mixed9_1[0][0] \n concatenate_3[0][0] \n activation_187[0][0] \n__________________________________________________________________________________________________\nglobal_average_pooling2d_1 (Glo (None, 2048) 0 mixed10[0][0] \n__________________________________________________________________________________________________\ndense_3 (Dense) (None, 1024) 2098176 global_average_pooling2d_1[0][0] \n__________________________________________________________________________________________________\ndropout_2 (Dropout) (None, 1024) 0 dense_3[0][0] \n__________________________________________________________________________________________________\ndense_4 (Dense) (None, 128) 131200 dropout_2[0][0] \n__________________________________________________________________________________________________\ndropout_3 (Dropout) (None, 128) 0 dense_4[0][0] \n__________________________________________________________________________________________________\ndense_5 (Dense) (None, 2) 258 dropout_3[0][0] \n==================================================================================================\nTotal params: 24,032,418\nTrainable params: 2,229,634\nNon-trainable params: 21,802,784\n__________________________________________________________________________________________________\n"
],
[
"# Let's unfreeze the whole model\nfor layer in model.layers:\n layer.trainable = True\n# Let's build an optimizer\noptimizer = Lookahead(RectifiedAdam(), sync_period=6, slow_step_size=0.5)\nes = EarlyStopping(\n monitor=\"val_loss\",\n verbose=1,\n mode=\"max\",\n patience=patience,\n restore_best_weights=True,\n)\n# We need to recompile the model for these modifications to take effect\nes.set_model(model)\nmodel.compile(optimizer=optimizer, loss=\"binary_crossentropy\") # , metrics=[\"AUC\"])",
"_____no_output_____"
],
[
"%%time\n# we train our model again (this time fine-tuning the top 2 inception blocks\n# alongside the top Dense layers\nhistory_2 = model.fit(\n dataset, \n callbacks=[es],\n epochs=epochs_2,\n steps_per_epoch=steps_per_epoch,\n validation_data=dataset_valid,\n validation_steps=steps_per_epoch_val\n)",
"Train for 515.0 steps, validate for 65.0 steps\nEpoch 1/200\n515/515 [==============================] - 120s 233ms/step - loss: 0.3042 - val_loss: 0.2860\nEpoch 2/200\n515/515 [==============================] - 76s 148ms/step - loss: 0.2871 - val_loss: 0.2850\nEpoch 3/200\n515/515 [==============================] - 78s 151ms/step - loss: 0.2884 - val_loss: 0.2870\nEpoch 4/200\n515/515 [==============================] - 78s 151ms/step - loss: 0.2871 - val_loss: 0.6771\nEpoch 5/200\n515/515 [==============================] - 78s 151ms/step - loss: 0.2824 - val_loss: 0.2890\nEpoch 6/200\n515/515 [==============================] - 79s 154ms/step - loss: 0.2788 - val_loss: 0.2961\nEpoch 7/200\n515/515 [==============================] - 77s 149ms/step - loss: 0.2812 - val_loss: 0.3465\nEpoch 8/200\n515/515 [==============================] - 77s 149ms/step - loss: 0.2848 - val_loss: 0.4543\nEpoch 9/200\n514/515 [============================>.] - ETA: 0s - loss: 0.2840Restoring model weights from the end of the best epoch.\n515/515 [==============================] - 77s 150ms/step - loss: 0.2841 - val_loss: 0.2925\nEpoch 00009: early stopping\nCPU times: user 12min 45s, sys: 1min 5s, total: 13min 50s\nWall time: 12min 20s\n"
],
[
"plot_metric(history_2, \"loss\")",
"_____no_output_____"
],
[
"# plot_metric(history_2, \"AUC\")",
"_____no_output_____"
],
[
"%%time\nvalid_data = preprocess_data(X[valid_indices], fixed_text_to_square_image)",
"(4119, 96, 96, 3)\n108.6064453125\nCPU times: user 2.35 s, sys: 2.05 s, total: 4.4 s\nWall time: 10.8 s\n"
],
[
"%%time\npreds = model.predict(valid_data)\nprint(roc_auc_score(Y[valid_indices], preds[:, 1]))\ndel valid_data\ngc.collect()",
"0.7810644513503227\nCPU times: user 5.59 s, sys: 299 ms, total: 5.89 s\nWall time: 6.23 s\n"
],
[
"%%time\ntest_data = preprocess_data(X[test_indices], fixed_text_to_square_image)",
"(4119, 96, 96, 3)\n108.6064453125\nCPU times: user 2.29 s, sys: 1.86 s, total: 4.14 s\nWall time: 10.3 s\n"
],
[
"preds = model.predict(test_data)\nprint(roc_auc_score(Y[test_indices], preds[:, 1]))\ndel test_data\ngc.collect()",
"0.79967683214928\n"
],
[
"# https://medium.com/google-developer-experts/interpreting-deep-learning-models-for-computer-vision-f95683e23c1d",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"raw",
"code",
"raw",
"code"
] |
[
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"raw"
],
[
"code"
],
[
"raw"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aa7abfd59e0783a16f14a73070b9cd3a180e1c0
| 601,443 |
ipynb
|
Jupyter Notebook
|
notebooks/[explore] ViT v.s. CNN.ipynb
|
hungjinh/galaxyZooNet
|
b18a72ddaaf5ea24377d089d2288546e967dcf5f
|
[
"MIT"
] | 2 |
2021-09-01T17:22:16.000Z
|
2021-09-05T09:06:56.000Z
|
notebooks/[explore] ViT v.s. CNN.ipynb
|
hungjinh/galaxyZooNet
|
b18a72ddaaf5ea24377d089d2288546e967dcf5f
|
[
"MIT"
] | null | null | null |
notebooks/[explore] ViT v.s. CNN.ipynb
|
hungjinh/galaxyZooNet
|
b18a72ddaaf5ea24377d089d2288546e967dcf5f
|
[
"MIT"
] | null | null | null | 746.207196 | 268,156 | 0.945147 |
[
[
[
"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n%config InlineBackend.figure_format='retina'",
"_____no_output_____"
],
[
"dir_cat = './'\n#vit_df = pd.read_csv(dir_cat+'gz2_vit_09172021_0000_predictions.csv')\n#resnet_df = pd.read_csv(dir_cat+'gz2_resnet50_A_predictions.csv')\ndf = pd.read_csv(dir_cat+'gz2_predictions.csv')",
"_____no_output_____"
],
[
"df_vTrT = df[df.vitTresT == 1]\ndf_vTrF = df[df.vitTresF == 1]\ndf_vFrT = df[df.vitFresT == 1]\ndf_vFrF = df[df.vitFresF == 1]",
"_____no_output_____"
],
[
"print(f'Number of galaxies in test set : {len(df)}\\n')\nprint(f'ViT True , resnet True galaxies: {len(df_vTrT)}')\nprint(f'ViT True , resnet False galaxies: {len(df_vTrF)}')\nprint(f'ViT False, resnet True galaxies: {len(df_vFrT)}')\nprint(f'ViT False, resnet False galaxies: {len(df_vFrF)}')\n\ndf.head()",
"Number of galaxies in test set : 31191\n\nViT True , resnet True galaxies: 24009\nViT True , resnet False galaxies: 1116\nViT False, resnet True galaxies: 2683\nViT False, resnet False galaxies: 3383\n"
],
[
"df_stats = df.groupby(['class'])['class'].agg('count').to_frame('count').reset_index()\ndf_stats['test_set'] = df_stats['count']/df_stats['count'].sum()\n\ndf_stats['vitT_resT'] = df_vTrT.groupby('class').size() #/ df_stats['count'].sum()\ndf_stats['vitT_resF'] = df_vTrF.groupby('class').size() #/ df_stats['count'].sum()\ndf_stats['vitF_resT'] = df_vFrT.groupby('class').size() #/ df_stats['count'].sum()\ndf_stats['vitF_resF'] = df_vFrF.groupby('class').size() #/ df_stats['count'].sum()\n\nprint(df_stats)\n###### plot ######\n\n#ax = df_stats.plot.bar(x='class', y=['test_set', 'vitT_resT', 'vitT_resF', 'vitF_resT', 'vitF_resF'], rot=20, color=['gray', 'orange', 'red', 'blue', 'skyblue'])\n#ax = df_stats.plot.bar(x='class', y=['test_set', 'vitT_resT'], rot=20, color=['gray', 'orange', 'red', 'blue', 'skyblue'])\nax = df_stats.plot.bar(x='class', y=['vitT_resF', 'vitF_resT'], rot=20, color=['red', 'blue', 'skyblue'])\n#ax = df_stats.plot.bar(x='class', y=['vitT_resT', 'vitF_resF'], rot=20, color=['orange', 'skyblue'])\n\n\nax.set_xticklabels(['Round','In-between','Cigar-shaped','Edge-on','Barred','UnBarred','Irregular','Merger'])\nax.set_ylabel('class fraction')\nax.set_xlabel('galaxy morphology class')",
" class count test_set vitT_resT vitT_resF vitF_resT vitF_resF\n0 0 6755 0.216569 5961 168 354 272\n1 1 7845 0.251515 6491 285 514 555\n2 2 1471 0.047161 931 80 163 297\n3 3 3295 0.105639 2848 90 165 192\n4 4 4148 0.132987 3119 130 399 500\n5 5 6094 0.195377 4058 262 780 994\n6 6 1176 0.037703 413 73 225 465\n7 7 407 0.013049 188 28 83 108\n"
],
[
"df_vFrT.groupby('class').size()",
"_____no_output_____"
],
[
"df_stats = df.groupby(['class'])['class'].agg('count').to_frame('count').reset_index()\ndf_stats['test_set'] = df_stats['count']/df_stats['count'].sum()\n\ndf_stats['vitT_resT'] = df_vTrT.groupby('class').size() / df_vTrT.groupby('class').size().sum()\ndf_stats['vitT_resF'] = df_vTrF.groupby('class').size() / df_vTrF.groupby('class').size().sum()\ndf_stats['vitF_resT'] = df_vFrT.groupby('class').size() / df_vFrT.groupby('class').size().sum()\ndf_stats['vitF_resF'] = df_vFrF.groupby('class').size() / df_vFrF.groupby('class').size().sum()\n\nprint(df_stats)\n###### plot ######\n\nax = df_stats.plot.bar(x='class', y=['test_set', 'vitT_resT', 'vitT_resF', 'vitF_resT', 'vitF_resF'], rot=20, \n color=['gray', 'orange', 'red', 'blue', 'skyblue'])\n\nax.set_xticklabels(['Round','In-between','Cigar-shaped','Edge-on','Barred','UnBarred','Irregular','Merger'])\nax.set_ylabel('class fraction')\nax.set_xlabel('galaxy morphology class')",
" class count test_set vitT_resT vitT_resF vitF_resT vitF_resF\n0 0 6755 0.216569 0.248282 0.150538 0.131942 0.080402\n1 1 7845 0.251515 0.270357 0.255376 0.191577 0.164056\n2 2 1471 0.047161 0.038777 0.071685 0.060753 0.087792\n3 3 3295 0.105639 0.118622 0.080645 0.061498 0.056754\n4 4 4148 0.132987 0.129910 0.116487 0.148714 0.147798\n5 5 6094 0.195377 0.169020 0.234767 0.290719 0.293822\n6 6 1176 0.037703 0.017202 0.065412 0.083861 0.137452\n7 7 407 0.013049 0.007830 0.025090 0.030936 0.031924\n"
]
],
[
[
"# color, size distributions",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(figsize=(7.2, 5.5))\nplt.rc('font', size=16)\n\n#tag = 'model_g_r'\ntag = 'dered_g_r'\nbins = np.linspace(df[tag].min(), df[tag].max(),80)\n\n\nax.hist(df[tag] , bins=bins, color='lightgray' , label='full test set', density=True)\nax.hist(df_vTrT[tag], bins=bins, color='royalblue' , label=r'ViT $\\bf{T}$ CNN $\\bf{T}$', histtype='step' , lw=2, ls='-.', density=True)\nax.hist(df_vTrF[tag], bins=bins, color='firebrick' , label=r'ViT $\\bf{T}$ CNN $\\bf{F}$', histtype='step', lw=3, density=True)\nax.hist(df_vFrT[tag], bins=bins, color='orange' , label=r'ViT $\\bf{F}$ CNN $\\bf{T}$', histtype='step' , lw=3, ls='--', density=True)\nax.hist(df_vFrF[tag], bins=bins, color='forestgreen', label=r'ViT $\\bf{F}$ CNN $\\bf{F}$', histtype='step', lw=2, ls=':', density=True)\n\n#r\"$\\bf{\" + str(number) + \"}$\"\n\nax.set_xlabel('g-r')\nax.set_ylabel('pdf')\nax.set_xlim(-0.25, 2.2)\n\nax.legend(fontsize=14.5)",
"_____no_output_____"
],
[
"from scipy.stats import ks_2samp\nks_2samp(df_vTrF['dered_g_r'], df_vFrT['dered_g_r'])",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(7.2, 5.5))\nplt.rc('font', size=16)\n\ntag = 'petroR50_r'\nbins = np.linspace(df[tag].min(), df[tag].max(),50)\n\nax.hist(df[tag] , bins=bins, color='lightgray' , label='full test set', density=True)\nax.hist(df_vTrT[tag], bins=bins, color='royalblue' , label=r'ViT $\\bf{T}$ CNN $\\bf{T}$', histtype='step' , lw=2, ls='-.', density=True)\nax.hist(df_vTrF[tag], bins=bins, color='firebrick' , label=r'ViT $\\bf{T}$ CNN $\\bf{F}$', histtype='step', lw=3, density=True)\nax.hist(df_vFrT[tag], bins=bins, color='orange' , label=r'ViT $\\bf{F}$ CNN $\\bf{T}$', histtype='step' , lw=3, ls='--', density=True)\nax.hist(df_vFrF[tag], bins=bins, color='forestgreen', label=r'ViT $\\bf{F}$ CNN $\\bf{F}$', histtype='step', lw=2, ls=':', density=True)\n\n#r\"$\\bf{\" + str(number) + \"}$\"\n\nax.set_xlabel('50% light radius')\nax.set_ylabel('pdf')\nax.set_xlim(0.5, 10)\n\nax.legend(fontsize=14.5)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(7.2, 5.5))\nplt.rc('font', size=16)\n\ntag = 'petroR90_r'\nbins = np.linspace(df[tag].min(), df[tag].max(),50)\n\nax.hist(df[tag] , bins=bins, color='lightgray' , label='full test set', density=True)\nax.hist(df_vTrT[tag], bins=bins, color='royalblue' , label=r'ViT $\\bf{T}$ CNN $\\bf{T}$', histtype='step' , lw=2, ls='-.', density=True)\nax.hist(df_vTrF[tag], bins=bins, color='firebrick' , label=r'ViT $\\bf{T}$ CNN $\\bf{F}$', histtype='step', lw=3, density=True)\nax.hist(df_vFrT[tag], bins=bins, color='orange' , label=r'ViT $\\bf{F}$ CNN $\\bf{T}$', histtype='step' , lw=3, ls='--', density=True)\nax.hist(df_vFrF[tag], bins=bins, color='forestgreen', label=r'ViT $\\bf{F}$ CNN $\\bf{F}$', histtype='step', lw=2, ls=':', density=True)\n\n#r\"$\\bf{\" + str(number) + \"}$\"\n\nax.set_xlabel('90% light radius')\nax.set_ylabel('pdf')\nax.set_xlim(2.5, 25)\n\nax.legend(fontsize=14.5)",
"_____no_output_____"
],
[
"ks_2samp(df_vTrF['petroR90_r'], df_vFrT['petroR90_r'])",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=(7.2, 5.5))\nplt.rc('font', size=16)\n\ntag = 'dered_r'\nbins = np.linspace(df[tag].min(), df[tag].max(),20)\n\nax.hist(df[tag] , bins=bins, color='lightgray' , label='full test set', density=True)\nax.hist(df_vTrT[tag], bins=bins, color='royalblue' , label=r'ViT $\\bf{T}$ CNN $\\bf{T}$', histtype='step' , lw=2, ls='-.', density=True)\nax.hist(df_vTrF[tag], bins=bins, color='firebrick' , label=r'ViT $\\bf{T}$ CNN $\\bf{F}$', histtype='step' , lw=3, density=True)\nax.hist(df_vFrT[tag], bins=bins, color='orange' , label=r'ViT $\\bf{F}$ CNN $\\bf{T}$', histtype='step' , lw=3, ls='--', density=True)\nax.hist(df_vFrF[tag], bins=bins, color='forestgreen', label=r'ViT $\\bf{F}$ CNN $\\bf{F}$', histtype='step' , lw=2, ls=':', density=True)\n\n#r\"$\\bf{\" + str(number) + \"}$\"\n\nax.set_xlabel('r-band (apparent) magnitude')\nax.set_ylabel('pdf')\n#ax.set_xlim(2.5, 25)\n\nax.legend(fontsize=14.5)",
"_____no_output_____"
]
],
[
[
"### check galaxy image",
"_____no_output_____"
]
],
[
[
"dir_image = '/home/hhg/Research/galaxyClassify/catalog/galaxyZoo_kaggle/gz2_images/images'",
"_____no_output_____"
],
[
"galaxyID = 241961\ncurrent_IMG = plt.imread(dir_image+f'/{galaxyID}.jpg')\nplt.imshow(current_IMG)\nplt.axis('off')",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4aa7bd72a60d89ba29e7c40f8a512881b646b56d
| 222,201 |
ipynb
|
Jupyter Notebook
|
WorldCup2018.ipynb
|
TheDiegoFrade/notitiablog.github.io
|
e7bcfc559f21c051635ba3ae7a3708ebffc00489
|
[
"CC-BY-3.0"
] | null | null | null |
WorldCup2018.ipynb
|
TheDiegoFrade/notitiablog.github.io
|
e7bcfc559f21c051635ba3ae7a3708ebffc00489
|
[
"CC-BY-3.0"
] | null | null | null |
WorldCup2018.ipynb
|
TheDiegoFrade/notitiablog.github.io
|
e7bcfc559f21c051635ba3ae7a3708ebffc00489
|
[
"CC-BY-3.0"
] | null | null | null | 195.771806 | 80,228 | 0.887953 |
[
[
[
"from openpyxl import load_workbook\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport plotly.plotly as py\nimport seaborn as sns\nimport jinja2\nfrom bokeh.io import output_notebook\nimport bokeh.palettes\nfrom bokeh.plotting import figure, show, output_file\nfrom bokeh.models import HoverTool, ColumnDataSource, Range1d, LabelSet, Label\nfrom collections import OrderedDict\nfrom bokeh.sampledata.periodic_table import elements\nfrom bokeh.resources import CDN\nfrom bokeh.embed import file_html\nfrom sklearn import preprocessing\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.feature_selection import RFE\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nfrom sklearn.cross_validation import cross_val_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import Ridge\nimport scipy",
"C:\\Users\\diego\\Anaconda3\\lib\\site-packages\\sklearn\\cross_validation.py:41: DeprecationWarning:\n\nThis module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.\n\n"
],
[
"sns.set(style='white')\nsns.set(style='whitegrid', color_codes=True)\n\n\nwb = load_workbook(r'C:\\Users\\diego\\Downloads\\worldcup.xlsx')\n\n#['Hoja1', 'Mundial1994-2014']\n\nwork_sheet = wb['Mundial1994-2014']\n",
"_____no_output_____"
],
[
"df = pd.DataFrame(work_sheet.values)\n\ndf.columns = ['Team1','Goal1','Goal2','Team2','Year','Stage','Goal_Dif','Team1_Res','Team2_Res',\n 'Rank1','Rank2','Dif_Rank','Value1','Value2','Value_Dif','Age1','Age2','Age_Dif','Color1','Color2']\ndf = df.drop(df.index[[0]])\ndf['Match_Info'] = df['Team1'] + ' '+ df['Goal1'].astype(str)+'-'+df['Goal2'].astype(str)+ ' '+ df['Team2']\ndf['y'] = np.where(df['Team1_Res'] == -1, 0, 1)\n\n\ndf_win_lose = df[(df['Team1_Res'] > 0) | (df['Team1_Res'] < 0)]\ndf_value = df[df['Year']>= 2010]\n\ndf_value_win_lose = df_value[(df['Team1_Res'] > 0) | (df_value['Team1_Res'] < 0)]",
"C:\\Users\\diego\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:13: UserWarning:\n\nBoolean Series key will be reindexed to match DataFrame index.\n\n"
],
[
"#Gráfica comparativa Goal_Dif , Dif_Rank\n\ndf_Team1Res_DifRank = df[['Team1_Res','Dif_Rank','Team1','Color1']]\ndf_GoalDif_DifRank = df[['Goal_Dif','Dif_Rank','Team1','Color1']]\n\n\ncolors1 = list(df['Color1'])\n\n\nplt.scatter(df_Team1Res_DifRank['Dif_Rank'],df_Team1Res_DifRank['Team1_Res'],\n s=250, alpha=0.5, c=colors1,edgecolor='#6b0c08',linewidth = 0.75)\nplt.axvline(0, color='black',linestyle=':')\nplt.axhline(0, color='black',linestyle=':')\nplt.suptitle('Win or Lose vs Ranking Difference', weight='bold', fontsize=30)\nplt.title('FIFA World Cups (1994-2014)', weight='bold', fontsize=20)\nplt.show()\n",
"_____no_output_____"
],
[
"plt.scatter(x='Dif_Rank',y='Goal_Dif', data=df_GoalDif_DifRank, marker='o', c=colors1,\n s=250, alpha=0.5)\nplt.axvline(0, color='black',linestyle=':')\nplt.axhline(0, color='black',linestyle=':')\nplt.suptitle('Goal(s) Difference vs Ranking Difference', weight='bold', fontsize=30)\nplt.title('FIFA World Cups (1994-2014)', weight='bold', fontsize=20)\nplt.show()",
"_____no_output_____"
],
[
"#Grafico1\n\ntools = 'pan, wheel_zoom, box_zoom, reset, save'.split(',')\nhover = HoverTool(tooltips=[\n (\"Team\", \"@Team1\"),\n (\"Rank Difference:\", '@Dif_Rank'),\n (\"Team Result\", \"@Team1_Res\"),\n ('Year', '@Year'),\n ('Stage:', '@Stage'),\n ('Match:', '@Match_Info')\n])\n\ntools.append(hover)\n\np = figure(plot_width = 1300, plot_height = 1100, title='Win(1)-Draw(0)-Lose(-1) vs Ranking Difference',\n x_range=Range1d(-100, 100),y_range = Range1d(-1.5,1.5), tools=tools)\n\nsource= ColumnDataSource(df)\n\np.title.text_font_size = '19pt'\np.title_location = 'above'\np.scatter(x='Dif_Rank', y='Team1_Res', size=28,color='Color1' , source=source, fill_alpha=0.6)\np.xaxis[0].axis_label = 'Ranking Difference'\np.xaxis[0].axis_label_text_font_size = '15pt'\np.yaxis[0].axis_label = 'Win(1)-Draw(0)-Lose(-1)'\np.yaxis[0].axis_label_text_font_size = '15pt'\n#labels = LabelSet(x='Dif_Rank', y='Team1_Res', text='Team1', level='glyph',\n# x_offset=8, y_offset=8, source=source, render_mode='canvas', text_align ='center', text_font_size='10pt')\n\n#p.add_layout(labels)\n\noutput_file(\"label.html\", title=\"label.py example\")\n\nshow(p)",
"_____no_output_____"
],
[
"#Grafico2\n\ntools = 'pan, wheel_zoom, box_zoom, reset, save'.split(',')\nhover = HoverTool(tooltips=[\n (\"Team:\", \"@Team1\"),\n (\"Rank Difference:\", '@Dif_Rank'),\n (\"Goal(s) Difference:\", \"@Goal_Dif\"),\n ('Year:', '@Year'),\n ('Stage:', '@Stage'),\n ('Match:', '@Match_Info')\n])\n\ntools.append(hover)\n\np = figure(plot_width = 1000, plot_height = 900, title='Goal(s) Difference vs Ranking Difference',\n x_range=Range1d(-100, 100),y_range = Range1d(-10,10), tools=tools)\n\nsource= ColumnDataSource(df)\n\np.title.text_font_size = '19pt'\np.title_location = 'above'\np.scatter(x='Dif_Rank', y='Goal_Dif', size=28,color='Color1' , source=source, fill_alpha=0.6)\np.xaxis[0].axis_label = 'Ranking Difference'\np.xaxis[0].axis_label_text_font_size = '15pt'\np.yaxis[0].axis_label = 'Goal(s) Difference'\np.yaxis[0].axis_label_text_font_size = '15pt'\n#labels = LabelSet(x='Dif_Rank', y='Team1_Res', text='Team1', level='glyph',\n# x_offset=8, y_offset=8, source=source, render_mode='canvas', text_align ='center', text_font_size='10pt')\n\n\noutput_file(\"label2.html\", title=\"label2.py example\")\n\nshow(p)",
"_____no_output_____"
],
[
"#Grafico3\n\ntools = 'pan, wheel_zoom, box_zoom, reset, save'.split(',')\nhover = HoverTool(tooltips=[\n (\"Team:\", \"@Team1\"),\n (\"Market Value Difference:\", '@Value_Dif'),\n (\"Goal(s) Difference:\", \"@Goal_Dif\"),\n ('Year:', '@Year'),\n ('Stage:', '@Stage'),\n ('Match:', '@Match_Info')\n])\n\ntools.append(hover)\n\np = figure(plot_width = 1000, plot_height = 900, title='Goal(s) Difference vs Team Market Value Difference',\n y_range = Range1d(-10,10), tools=tools)\n\nsource= ColumnDataSource(df_value)\n\np.title.text_font_size = '19pt'\np.title_location = 'above'\np.scatter(x='Value_Dif', y='Goal_Dif', size=28,color='Color1' , source=source, fill_alpha=0.6)\np.xaxis[0].axis_label = 'Team Market Value Difference (Hundred Million USD)'\np.xaxis[0].axis_label_text_font_size = '15pt'\np.yaxis[0].axis_label = 'Goal(s) Difference'\np.yaxis[0].axis_label_text_font_size = '15pt'\n#labels = LabelSet(x='Dif_Rank', y='Team1_Res', text='Team1', level='glyph',\n# x_offset=8, y_offset=8, source=source, render_mode='canvas', text_align ='center', text_font_size='10pt')\n\n\noutput_file(\"label3.html\", title=\"label3.py example\")\n\nshow(p)\n",
"_____no_output_____"
],
[
"#Grafico4\n\ntools = 'pan, wheel_zoom, box_zoom, reset, save'.split(',')\nhover = HoverTool(tooltips=[\n (\"Team:\", \"@Team1\"),\n (\"Market Value Difference:\", '@Value_Dif'),\n (\"Team Result:\", \"@Team1_Res\"),\n ('Year:','@Year'),\n ('Stage:', '@Stage'),\n ('Match:','@Match_Info')])\n\ntools.append(hover)\n\np = figure(plot_width = 1000, plot_height = 900, title='Win(1)-Draw(0)-Lose(-1) vs Team Market Value Difference',\n y_range = Range1d(-1.5,1.5), tools=tools)\n\nsource= ColumnDataSource(df_value)\n\np.title.text_font_size = '19pt'\np.title_location = 'above'\np.scatter(x='Value_Dif', y='Team1_Res', size=28,color='Color1' , source=source, fill_alpha=0.6)\np.xaxis[0].axis_label = 'Team Market Value Difference (Hundred Million USD)'\np.xaxis[0].axis_label_text_font_size = '15pt'\np.yaxis[0].axis_label = 'Win(1)-Draw(0)-Lose(-1)'\np.yaxis[0].axis_label_text_font_size = '15pt'\n#labels = LabelSet(x='Dif_Rank', y='Team1_Res', text='Team1', level='glyph',\n# x_offset=8, y_offset=8, source=source, render_mode='canvas', text_align ='center', text_font_size='10pt')\n\n\noutput_file(\"label4.html\",mode='inline', title=\"label4.py example\")\n\nshow(p)",
"_____no_output_____"
],
[
"#Grafico5\n\ntools = 'pan, wheel_zoom, box_zoom, reset, save'.split(',')\nhover = HoverTool(tooltips=[\n (\"Team\", \"@Team1\"),\n (\"Rank Difference:\", '@Dif_Rank'),\n (\"Team Result\", \"@Team1_Res\"),\n ('Year', '@Year'),\n ('Stage:', '@Stage'),\n ('Match:', '@Match_Info')\n])\n\ntools.append(hover)\n\np = figure(plot_width = 1000, plot_height = 900, title='Win(1)-Lose(-1) vs Ranking Difference',\n x_range=Range1d(-100, 100),y_range = Range1d(-1.5,1.5), tools=tools)\n\nsource = ColumnDataSource(df_value_win_lose)\n\np.title.text_font_size = '19pt'\np.title_location = 'above'\np.scatter(x='Dif_Rank', y='Team1_Res', size=28,color='Color1' , source=source, fill_alpha=0.6)\np.xaxis[0].axis_label = 'Ranking Difference'\np.xaxis[0].axis_label_text_font_size = '15pt'\np.yaxis[0].axis_label = 'Win(1)-Lose(-1)'\np.yaxis[0].axis_label_text_font_size = '15pt'\n#labels = LabelSet(x='Dif_Rank', y='Team1_Res', text='Team1', level='glyph',\n# x_offset=8, y_offset=8, source=source, render_mode='canvas', text_align ='center', text_font_size='10pt')\n\n\n#p.add_layout(labels)\n\noutput_file(\"label5.html\", title=\"label5.py example\")\n\nshow(p)\n",
"_____no_output_____"
],
[
"#Grafico6\n\ntools = 'pan, wheel_zoom, box_zoom, reset, save'.split(',')\nhover = HoverTool(tooltips=[\n (\"Team\", \"@Team1\"),\n (\"Market Value Difference:\", '@Value_Dif'),\n (\"Team Result\", \"@Team1_Res\"),\n ('Year', '@Year'),\n ('Stage:', '@Stage'),\n ('Match:', '@Match_Info')\n])\n\ntools.append(hover)\n\np = figure(plot_width = 1000, plot_height = 900, title='Win(1)-Lose(-1) vs Team Market Value Difference',\n y_range = Range1d(-1.5,1.5), tools=tools)\n\nsource = ColumnDataSource(df_value_win_lose)\n\np.title.text_font_size = '19pt'\np.title_location = 'above'\np.scatter(x='Value_Dif', y='Team1_Res', size=28,color='Color1' , source=source, fill_alpha=0.6)\np.xaxis[0].axis_label = 'Team Market Value Difference (Hundred Million USD)'\np.xaxis[0].axis_label_text_font_size = '15pt'\np.yaxis[0].axis_label = 'Win(1)-Lose(-1)'\np.yaxis[0].axis_label_text_font_size = '15pt'\n#labels = LabelSet(x='Dif_Rank', y='Team1_Res', text='Team1', level='glyph',\n# x_offset=8, y_offset=8, source=source, render_mode='canvas', text_align ='center', text_font_size='10pt')\n\n\n\n\n\n#p.add_layout(labels)\n\noutput_file(\"label6.html\", title=\"label6.py example\")\n\nshow(p)\n",
"_____no_output_____"
],
[
"#Grafico7\n\ntools = 'pan, wheel_zoom, box_zoom, reset, save'.split(',')\nhover = HoverTool(tooltips=[\n (\"Team\", \"@Team1\"),\n (\"Market Value Difference:\", '@Value_Dif'),\n (\"Team Result\", \"@Team1_Res\"),\n ('Year', '@Year'),\n ('Stage:', '@Stage'),\n ('Match:', '@Match_Info')\n])\n\ntools.append(hover)\n\np = figure(plot_width = 1000, plot_height = 900, title='Goal(s) Difference vs Team Market Value Difference',\n y_range = Range1d(-10,10), tools=tools)\n\nsource = ColumnDataSource(df_value_win_lose)\n\np.title.text_font_size = '19pt'\np.title_location = 'above'\np.scatter(x='Value_Dif', y='Goal_Dif', size=28,color='Color1' , source=source, fill_alpha=0.6)\np.xaxis[0].axis_label = 'Team Market Value Difference (Hundred Million USD)'\np.xaxis[0].axis_label_text_font_size = '15pt'\np.yaxis[0].axis_label = 'Goal(s) Difference'\np.yaxis[0].axis_label_text_font_size = '15pt'\n#labels = LabelSet(x='Dif_Rank', y='Team1_Res', text='Team1', level='glyph',\n# x_offset=8, y_offset=8, source=source, render_mode='canvas', text_align ='center', text_font_size='10pt')\n\n\n\n\n\n#p.add_layout(labels)\n\noutput_file(\"label7.html\", title=\"label7.py example\")\n\nshow(p)\n",
"_____no_output_____"
],
[
"#Grafico8\n\ntools = 'pan, wheel_zoom, box_zoom, reset, save'.split(',')\nhover = HoverTool(tooltips=[\n (\"Team\", \"@Team1\"),\n (\"Market Value Difference:\", '@Value_Dif'),\n (\"Team Result\", \"@Team1_Res\"),\n ('Year', '@Year'),\n ('Stage:', '@Stage'),\n ('Match:', '@Match_Info')\n])\n\ntools.append(hover)\n\np = figure(plot_width = 1000, plot_height = 900, title='Goal(s) Difference vs Ranking Difference',\n y_range = Range1d(-10,10), tools=tools)\n\nsource = ColumnDataSource(df_value_win_lose)\n\np.title.text_font_size = '19pt'\np.title_location = 'above'\np.scatter(x='Dif_Rank', y='Goal_Dif', size=28,color='Color1' , source=source, fill_alpha=0.6)\np.xaxis[0].axis_label = 'Ranking Difference'\np.xaxis[0].axis_label_text_font_size = '15pt'\np.yaxis[0].axis_label = 'Goal(s Difference)'\np.yaxis[0].axis_label_text_font_size = '15pt'\n#labels = LabelSet(x='Dif_Rank', y='Team1_Res', text='Team1', level='glyph',\n# x_offset=8, y_offset=8, source=source, render_mode='canvas', text_align ='center', text_font_size='10pt')\n\n#p.add_layout(labels)\n\noutput_file(\"label8.html\", title=\"label8.py example\")\n\nshow(p)\n",
"_____no_output_____"
],
[
"#Linear Regression World Cup-Transfer Market Value\n\n#Predict variable desired target 1 means win, -1 means lose\n\n#Data Exploration\n\n\ntrain, test = train_test_split(df_value_win_lose, test_size=0.20, random_state=99)\n\nX_train = train[['Value_Dif']]\ny_train = train[['y']]\n\nX_test = test[['Value_Dif']]\ny_test = test[['y']]\n\n#Usar si son más de una variable independiente\n#data_final = df_value_win_lose[['y','Value_Dif']]\n#X = data_final['Value_Dif']\n#y = data_final['y']\n\n\n#Choose Data- tienen que ser más de 1 variable independiente\n#logreg = LogisticRegression()\n\n#rfe = RFE(logreg, 1)\n#rfe = rfe.fit(data_final['Value_Dif'], data_final['y'])\n\n#Split Data Set\n#split = int(0.7*len(data_final))\n\n#X_train, X_test, y_train, y_test = X[:split],X[split:],y[:split], y[split:]\n\n#Fit Model- mas de 1 variable\n#model = LogisticRegression()\n#model = model.fit(X_train, y_train)\nmodel = LogisticRegression()\nmodel = model.fit(X_train, y_train)\n#Predict Probabilities\nprobability = model.predict_proba(X_test)\nprint(probability)\n\n#Predict class labels\npredicted = model.predict(X_test)\nprint(len(predicted))\nprint(len(y_test))\n\n#Evaluate the model\n #Confusion Matrix\nprint(metrics.confusion_matrix(y_test,predicted))\n\nprint(metrics.classification_report(y_test, predicted))\n\n#Model Accuracy\nprint(model.score(X_test,y_test))\n\n#Cross Validation\nValue_Dif = df_value_win_lose['Value_Dif']\nValue_Dif = np.array(Value_Dif).reshape(-1,1)\n\ncross_val = cross_val_score(LogisticRegression(), Value_Dif, df_value_win_lose['y'],\n scoring='accuracy', cv=10)\nprint(cross_val)\nprint(cross_val.mean())",
"[[0.57947171 0.42052829]\n [0.21710208 0.78289792]\n [0.3771423 0.6228577 ]\n [0.31314871 0.68685129]\n [0.66201459 0.33798541]\n [0.19145558 0.80854442]\n [0.23390157 0.76609843]\n [0.77414109 0.22585891]\n [0.40991326 0.59008674]\n [0.70636746 0.29363254]\n [0.08758699 0.91241301]\n [0.40386222 0.59613778]\n [0.6205644 0.3794356 ]\n [0.45878582 0.54121418]\n [0.89264119 0.10735881]\n [0.53412901 0.46587099]\n [0.33097288 0.66902712]\n [0.28595816 0.71404184]\n [0.60041285 0.39958715]\n [0.18656114 0.81343886]\n [0.23409364 0.76590636]]\n21\n21\n[[ 6 3]\n [ 2 10]]\n precision recall f1-score support\n\n 0 0.75 0.67 0.71 9\n 1 0.77 0.83 0.80 12\n\navg / total 0.76 0.76 0.76 21\n\n0.7619047619047619\n[0.63636364 0.45454545 0.63636364 0.72727273 0.81818182 0.54545455\n 0.6 0.77777778 0.77777778 1. ]\n0.6973737373737374\n"
],
[
"#Create Strategy Using the model\n\nplt.scatter(X_test, y_test, color='black')\nplt.scatter(X_test, predicted, color='blue', linewidth=3, alpha=0.4)\nplt.xlabel(\"Team Value Difference\")\nplt.ylabel(\"Team Result Win(1) Lose(0)\")\nplt.show()",
"_____no_output_____"
],
[
"#Segundo Modelo\ntrain, test = train_test_split(df, test_size=0.20, random_state=99)\n\nX_train = train[['Dif_Rank']]\ny_train = train[['y']]\n\nX_test = test[['Dif_Rank']]\ny_test = test[['y']]\n\n#Polynomial and Ridge model alternative en caso de que no sea Logistic Regression\n#pol = make_pipeline(PolynomialFeatures(6), Ridge())\n#pol.fit(X_train,y_train)\n\n\nmodel = LogisticRegression()\nmodel = model.fit(X_train, y_train)\n#Predict Probabilities\nprobability = model.predict_proba(X_test)\nprint(probability)\n\n#Predict class labels\npredicted = model.predict(X_test)\nprint(len(predicted))\nprint(len(y_test))\n\n#Evaluate the model\n #Confusion Matrix\nprint(metrics.confusion_matrix(y_test,predicted))\n\nprint(metrics.classification_report(y_test, predicted))\n\n#Model Accuracy\nprint(model.score(X_test, y_test))\n\n#Cross Validation\nDif_Rank = df_value_win_lose['Dif_Rank']\nDif_Rank = np.array(Dif_Rank).reshape(-1,1)\n\ncross_val = cross_val_score(LogisticRegression(), Dif_Rank, df_value_win_lose['y'],\n scoring='accuracy', cv=10)\nprint(cross_val)\nprint(cross_val.mean())\n\nplt.scatter(X_test, y_test, color='black')\nplt.scatter(X_test, predicted, color='blue', linewidth=3, alpha=0.4)\nplt.xlabel(\"Team Ranking Difference\")\nplt.ylabel(\"Team Result Win(1) Lose(0)\")\nplt.show()\n",
"[[0.25983425 0.74016575]\n [0.7159766 0.2840234 ]\n [0.12563353 0.87436647]\n [0.21530189 0.78469811]\n [0.45404667 0.54595333]\n [0.35078695 0.64921305]\n [0.22055167 0.77944833]\n [0.2258926 0.7741074 ]\n [0.15528951 0.84471049]\n [0.19521531 0.80478469]\n [0.38661472 0.61338528]\n [0.19521531 0.80478469]\n [0.2258926 0.7741074 ]\n [0.42371352 0.57628648]\n [0.14737874 0.85262126]\n [0.10096409 0.89903591]\n [0.37211093 0.62788907]\n [0.43882295 0.56117705]\n [0.51551854 0.48448146]\n [0.67694559 0.32305441]\n [0.27185659 0.72814341]\n [0.12563353 0.87436647]\n [0.43882295 0.56117705]\n [0.69681578 0.30318422]\n [0.16780106 0.83219894]\n [0.18110453 0.81889547]\n [0.14737874 0.85262126]\n [0.15937318 0.84062682]\n [0.25395408 0.74604592]\n [0.5840266 0.4159734 ]\n [0.24816237 0.75183763]\n [0.41621015 0.58378985]\n [0.33688902 0.66311098]\n [0.37933587 0.62066413]\n [0.20507618 0.79492382]\n [0.47703538 0.52296462]\n [0.5001218 0.4998782 ]\n [0.33688902 0.66311098]\n [0.35783382 0.64216618]\n [0.2842216 0.7157784 ]\n [0.4013225 0.5986775 ]\n [0.19042128 0.80957872]\n [0.33688902 0.66311098]\n [0.43125224 0.56874776]\n [0.52320771 0.47679229]\n [0.25983425 0.74016575]\n [0.37933587 0.62066413]\n [0.15528951 0.84471049]\n [0.4087454 0.5912546 ]\n [0.21530189 0.78469811]\n [0.4693568 0.5306432 ]\n [0.4616927 0.5383073 ]\n [0.18110453 0.81889547]\n [0.54619487 0.45380513]\n [0.23684702 0.76315298]\n [0.2258926 0.7741074 ]\n [0.35078695 0.64921305]\n [0.36494268 0.63505732]\n [0.13980427 0.86019573]\n [0.32326755 0.67673245]\n [0.45404667 0.54595333]\n [0.35078695 0.64921305]\n [0.64943493 0.35056507]\n [0.29052967 0.70947033]\n [0.29052967 0.70947033]\n [0.2842216 0.7157784 ]\n [0.2258926 0.7741074 ]\n [0.25983425 0.74016575]\n [0.34380456 0.65619544]\n [0.65641524 0.34358476]\n [0.04942342 0.95057658]\n [0.14354992 0.85645008]\n [0.19042128 0.80957872]\n [0.37933587 0.62066413]]\n74\n74\n[[ 6 23]\n [ 4 41]]\n precision recall f1-score support\n\n 0 0.60 0.21 0.31 29\n 1 0.64 0.91 0.75 45\n\navg / total 0.62 0.64 0.58 74\n\n0.6351351351351351\n[0.72727273 0.54545455 0.81818182 0.72727273 0.90909091 0.72727273\n 0.6 0.88888889 0.88888889 1. ]\n0.7832323232323233\n"
],
[
"#Polynomial Ridge En caso de que no sea Logistic Regression\n#y_pol = pol.predict(X_test)\n#plt.scatter(X_test, y_test, color='black')\n#plt.scatter(X_test, y_pol, color='blue')\n#plt.xlabel(\"Team Ranking Difference\")\n#plt.ylabel(\"Team Result Win(1) Lose(0)\")\n#plt.show()\n",
"_____no_output_____"
],
[
"#Tercer Modelo Age-Rank\n#Fit Model- mas de 1 variable\n#model = LogisticRegression()\n#model = model.fit(X_train, y_train)\n\n\ntrain, test = train_test_split(df_value_win_lose, test_size=0.20, random_state=99)\n\nX_train = train[['Age_Dif','Dif_Rank']]\ny_train = train[['y']]\n\nX_test = test[['Age_Dif','Dif_Rank']]\ny_test = test[['y']]\n\nmodel = LogisticRegression()\nmodel = model.fit(X_train, y_train)\n#Predict Probabilities\nprobability = model.predict_proba(X_test)\nprint(probability)\n\n#Predict class labels\npredicted = model.predict(X_test)\nprint(len(predicted))\nprint(len(y_test))\n\n#Evaluate the model\n #Confusion Matrix\nprint(metrics.confusion_matrix(y_test,predicted))\n\nprint(metrics.classification_report(y_test, predicted))\n\n#Model Accuracy\nprint(model.score(X_test,y_test))\n\n#Cross Validation\nIndep_Var = df_value_win_lose[['Dif_Rank','Age_Dif']]\n\ncross_val = cross_val_score(LogisticRegression(), Indep_Var, df_value_win_lose['y'],\n scoring='accuracy', cv=10)\nprint(cross_val)\nprint(cross_val.mean())\n",
"[[0.83641041 0.16358959]\n [0.38015027 0.61984973]\n [0.35174158 0.64825842]\n [0.2205888 0.7794112 ]\n [0.83296221 0.16703779]\n [0.13755873 0.86244127]\n [0.4578505 0.5421495 ]\n [0.58367203 0.41632797]\n [0.18251261 0.81748739]\n [0.73095139 0.26904861]\n [0.24000707 0.75999293]\n [0.23182501 0.76817499]\n [0.652026 0.347974 ]\n [0.65324789 0.34675211]\n [0.60818204 0.39181796]\n [0.48370911 0.51629089]\n [0.32281642 0.67718358]\n [0.60182337 0.39817663]\n [0.59413992 0.40586008]\n [0.19161788 0.80838212]\n [0.39211785 0.60788215]]\n21\n21\n[[ 7 2]\n [ 2 10]]\n precision recall f1-score support\n\n 0 0.78 0.78 0.78 9\n 1 0.83 0.83 0.83 12\n\navg / total 0.81 0.81 0.81 21\n\n0.8095238095238095\n[0.72727273 0.54545455 0.72727273 0.72727273 0.90909091 0.72727273\n 0.6 0.88888889 0.77777778 1. ]\n0.763030303030303\n"
],
[
"#Mejorar el modelo\n\n# from sklearn.svm import SVR\n#\n# regr_more_features = LogisticRegression()\n# regr_more_features.fit(X_train, y_train)\n# y_pred_more_features = regr_more_features.predict(X_test)\n# print(\"Mean squared error: %.2f\" % metrics.mean_squared_error(y_test, y_pred_more_features))\n# print('Variance score: %.2f' % metrics.r2_score(y_test, y_pred_more_features))\n#\n# pol_more_features = make_pipeline(PolynomialFeatures(4), Ridge())\n# pol_more_features.fit(X_train, y_train)\n# y_pol_more_features = pol_more_features.predict(X_test)\n# print(\"Mean squared error: %.2f\" % metrics.mean_squared_error(y_test, y_pol_more_features))\n# print('Variance score: %.2f' % metrics.r2_score(y_test, y_pol_more_features))\n#\n# svr_rbf_more_features = SVR(kernel='rbf', gamma=1e-3, C=100, epsilon=0.1)\n# svr_rbf_more_features.fit(X_train, y_train.values.ravel())\n# y_rbf_more_features = svr_rbf_more_features.predict(X_test)\n# print(\"Mean squared error: %.2f\" % metrics.mean_squared_error(y_test, y_rbf_more_features))\n# print('Variance score: %.2f' % metrics.r2_score(y_test, y_rbf_more_features))\n\n\n\n#print(test[['Team1','Team2','y', 'Age_Dif', 'Value_Dif', 'Dif_Rank', 'Result_Prediction_RBF','Error_Percentage']].nlargest(4, columns='Error_Percentage'))\n",
"_____no_output_____"
],
[
"#Modelo Final\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.datasets import make_regression\n#Generate DataSet\ntrain, test = train_test_split(df_value_win_lose, test_size=0.20, random_state=99)\n\nX_train = train[['Age_Dif','Dif_Rank']]\ny_train = train[['y']]\n\nX_test = test[['Age_Dif','Dif_Rank']]\ny_test = test[['y']]\n\n#Fit Final Model\nmodel = LogisticRegression()\nmodel = model.fit(X_train,y_train)\n\n#New instances where we do not want answers\n\nwork_sheet2018 = wb['Mundial2018']\n\ndata2018 = pd.DataFrame(work_sheet2018.values)\n\ndata2018.columns = ['Team1','Team2','Year','Stage','Rank1','Rank2','Dif_Rank','Value1','Value2','Value_Dif','Age1','Age2','Age_Dif']\n\ndata2018 = data2018.drop(data2018.index[[0]])\n\n#New Instances which we do not know the answer\nXnew = data2018[['Age_Dif','Dif_Rank']]\n\n#Make Predictions\ny_predicted_WC2018 = model.predict(Xnew)\nprobability2018 = model.predict_proba(Xnew)\n\n\n\n#show the inputs and predicted outputs\n#writer = pd.ExcelWriter('/Users/juancarlos/ProbabilidadMundial2018.xlsx')\n#print(pd.DataFrame(y_predicted_WC2018))\n#probability2018 = pd.DataFrame(probability2018)\n",
"_____no_output_____"
],
[
"#probability2018.to_excel(writer,'Sheet1')\n#writer.save()\n\n\n#Calculadora de Probabilidades\n\nCalculadora_Prob = wb['Calculadora2']\n\ndf_calculadora = pd.DataFrame(Calculadora_Prob.values)\ndf_calculadora.columns = ['num','Team1','Team2','Year','Rank1','Rank2','Dif_Rank','Age1','Age2','Age_Dif']\n\ndf_calculadora = df_calculadora.drop(df_calculadora.index[[0]])\n\n#New Data to predict\nxnew_calc = df_calculadora[['Age_Dif','Dif_Rank']]\ny_predict_calc = model.predict(xnew_calc)\nprob_calc = model.predict_proba(xnew_calc)\n\nprint(y_predict_calc)\nprint(prob_calc)\n\n# #show the inputs and predicted outputs\n# writer = pd.ExcelWriter('/Users/juancarlos/ProbabilidadMundial2018-2.xlsx')\n# print(pd.DataFrame(y_predict_calc))\n# y_predict_calc= pd.DataFrame(y_predict_calc)\n#\n# y_predict_calc.to_excel(writer,'Sheet1')\n# writer.save()\n#\n# writer = pd.ExcelWriter('/Users/juancarlos/ProbabilidadMundial2018-1.xlsx')\n# print(pd.DataFrame(prob_calc))\n# prob_calc= pd.DataFrame(prob_calc)\n#\n# prob_calc.to_excel(writer,'Sheet1')\n# writer.save()",
"[0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 1 1\n 0 1 1 1 0 1 1 0 0 1 1 1 0 0 0 1 0 1 1 0 0 1 1 1 1 1 0 0 0 0 1 0 1 1 0 0 1\n 1 0 0 1 0 1 0 0 0 1 0 1 1 0 0 0 1 1 1 1 1 1 0 1 1 0 1 1 1 0 1 1 0 0 1 1 1\n 0 0 0 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 0 0 1 1 1 1 1 1 1 0 1\n 1 1 0 1 1 1 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 0 1 1 0 0 1 1 1\n 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1\n 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 1 0 1 0 0 1 1 0 0 1 0\n 1 0 0 0 1 0 1 1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 1 1 0 1 1 0 0 1 1 1 0 0 0 1 0\n 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 1 1 1 1 0 0 0\n 0 0 1 0 1 0 0 0 1 0 0 1 0 0 0 0 0 1 0 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 0 1 1\n 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 1 0 0 0 1 1 1 1 0 1 0 0 0 1 0 1 1 0 0 1 1 0 0 1 1 0 0 0 1 0 1 1 0 0 0\n 1 1 1 1 0 0 0 0 0 1 0 1 0 0 0 1 1 0 0 1 0 0 0 0 1 0 1 1 0 0 0 1 1 1 1 1 1\n 1 0 1 1 0 1 1 1 0 1 1 0 0 1 1 1 0 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 1\n 1 1 0 1 1 0 0 1 1 1 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 0 1 1 1 0 1 1 0\n 0 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1 1 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 1 0 0 0 0\n 0 0 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 0\n 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 1 1 0\n 1 1 1 0 1 1 0 0 1 1 1 0 0 0 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1\n 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 0 0 1 1 0 1 1 0 0 1 1 0 0 1 1 1 0\n 0 0 1 0 1 1 0 0 1 1 1 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]\n[[0.88441691 0.11558309]\n [0.84497 0.15503 ]\n [0.90667829 0.09332171]\n ...\n [0.91618871 0.08381129]\n [0.78407028 0.21592972]\n [0.49999 0.50001 ]]\n"
]
],
[
[
"Predicciones por equipos con su probabilidad: 1=Triunfo, 0=derrota. Lista de probabilidad abajo.\n",
"_____no_output_____"
]
]
] |
[
"code",
"markdown"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
4aa7be9768ccb752dc0bf4e284f9d900cda0bf53
| 85,728 |
ipynb
|
Jupyter Notebook
|
S2/RITAL/RI/TME2/RI-pyterrier-3-2022.ipynb
|
hanzopgp/MasterArtificialIntelligencePTs
|
075aadbe3f7a36d596d547d93604cee748015485
|
[
"MIT"
] | null | null | null |
S2/RITAL/RI/TME2/RI-pyterrier-3-2022.ipynb
|
hanzopgp/MasterArtificialIntelligencePTs
|
075aadbe3f7a36d596d547d93604cee748015485
|
[
"MIT"
] | null | null | null |
S2/RITAL/RI/TME2/RI-pyterrier-3-2022.ipynb
|
hanzopgp/MasterArtificialIntelligencePTs
|
075aadbe3f7a36d596d547d93604cee748015485
|
[
"MIT"
] | null | null | null | 46.040816 | 1,549 | 0.63467 |
[
[
[
"# Modèle ColBERT\n\nOn s'intéresse ici au modèle ColBERT, qui propose ...",
"_____no_output_____"
]
],
[
[
"!pip install --upgrade python-terrier\n!pip install --upgrade git+https://github.com/terrierteam/pyterrier_colbert",
"Requirement already satisfied: python-terrier in c:\\users\\karna\\anaconda3\\lib\\site-packages (0.8.0)\nRequirement already satisfied: dill in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (0.3.4)\nRequirement already satisfied: statsmodels in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (0.13.0)\nRequirement already satisfied: nptyping in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (1.4.4)\nRequirement already satisfied: ir-measures>=0.2.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (0.2.3)\nRequirement already satisfied: pandas in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (1.4.1)\nRequirement already satisfied: ir-datasets>=0.3.2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (0.5.0)\nRequirement already satisfied: matchpy in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (0.5.5)\nRequirement already satisfied: requests in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (2.27.1)\nRequirement already satisfied: sklearn in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (0.0)\nRequirement already satisfied: jinja2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (2.11.3)\nRequirement already satisfied: tqdm in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (4.62.3)\nRequirement already satisfied: pyjnius~=1.3.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (1.3.0)\nRequirement already satisfied: deprecation in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (2.1.0)\nRequirement already satisfied: more-itertools in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (8.12.0)\nRequirement already satisfied: wget in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (3.2)\nRequirement already satisfied: numpy in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (1.21.2)\nRequirement already satisfied: joblib in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (1.1.0)\nRequirement already satisfied: scipy in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (1.7.3)\nRequirement already satisfied: chest in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier) (0.2.3)\nRequirement already satisfied: pyautocorpus>=0.1.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier) (0.1.8)\nRequirement already satisfied: trec-car-tools>=2.5.4 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier) (2.6)\nRequirement already satisfied: warc3-wet>=0.2.3 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier) (0.2.3)\nRequirement already satisfied: beautifulsoup4>=4.4.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier) (4.10.0)\nRequirement already satisfied: ijson>=3.1.3 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier) (3.1.4)\nRequirement already satisfied: lxml>=4.5.2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier) (4.7.1)\nRequirement already satisfied: zlib-state>=0.1.3 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier) (0.1.5)\nRequirement already satisfied: lz4>=3.1.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier) (4.0.0)\nRequirement already satisfied: pyyaml>=5.3.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier) (6.0)\nRequirement already satisfied: warc3-wet-clueweb09>=0.2.5 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier) (0.2.5)\nRequirement already satisfied: soupsieve>1.2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from beautifulsoup4>=4.4.1->ir-datasets>=0.3.2->python-terrier) (2.3.1)\nRequirement already satisfied: pytrec-eval-terrier==0.5.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-measures>=0.2.0->python-terrier) (0.5.1)\nRequirement already satisfied: pyndeval>=0.0.2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-measures>=0.2.0->python-terrier) (0.0.2)\nRequirement already satisfied: cwl-eval>=1.0.10 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-measures>=0.2.0->python-terrier) (1.0.10)\nRequirement already satisfied: six>=1.7.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from pyjnius~=1.3.0->python-terrier) (1.16.0)\nRequirement already satisfied: cython in c:\\users\\karna\\anaconda3\\lib\\site-packages (from pyjnius~=1.3.0->python-terrier) (0.29.25)\nRequirement already satisfied: certifi>=2017.4.17 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from requests->python-terrier) (2021.10.8)\nRequirement already satisfied: charset-normalizer~=2.0.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from requests->python-terrier) (2.0.4)\nRequirement already satisfied: idna<4,>=2.5 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from requests->python-terrier) (3.3)\nRequirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from requests->python-terrier) (1.26.7)\nRequirement already satisfied: colorama in c:\\users\\karna\\anaconda3\\lib\\site-packages (from tqdm->python-terrier) (0.4.4)\nRequirement already satisfied: cbor>=1.0.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from trec-car-tools>=2.5.4->ir-datasets>=0.3.2->python-terrier) (1.0.0)\nRequirement already satisfied: heapdict in c:\\users\\karna\\anaconda3\\lib\\site-packages (from chest->python-terrier) (1.0.1)\nRequirement already satisfied: packaging in c:\\users\\karna\\anaconda3\\lib\\site-packages (from deprecation->python-terrier) (21.3)\nRequirement already satisfied: MarkupSafe>=0.23 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from jinja2->python-terrier) (1.1.1)\nRequirement already satisfied: multiset<3.0,>=2.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from matchpy->python-terrier) (2.1.1)\nRequirement already satisfied: typish>=1.7.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from nptyping->python-terrier) (1.9.3)\nRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from packaging->deprecation->python-terrier) (3.0.4)\nRequirement already satisfied: python-dateutil>=2.8.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from pandas->python-terrier) (2.8.2)\nRequirement already satisfied: pytz>=2020.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from pandas->python-terrier) (2021.3)\nRequirement already satisfied: scikit-learn in c:\\users\\karna\\anaconda3\\lib\\site-packages (from sklearn->python-terrier) (1.0.2)\nRequirement already satisfied: threadpoolctl>=2.0.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from scikit-learn->sklearn->python-terrier) (2.2.0)\nRequirement already satisfied: patsy>=0.5.2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from statsmodels->python-terrier) (0.5.2)\nCollecting git+https://github.com/terrierteam/pyterrier_colbert\n Cloning https://github.com/terrierteam/pyterrier_colbert to c:\\users\\karna\\appdata\\local\\temp\\pip-req-build-jp89wy2z\n Resolved https://github.com/terrierteam/pyterrier_colbert to commit cce6d55a2a869ae354af1930bcd5eff6ced80657\nCollecting ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT\n Cloning https://github.com/cmacdonald/ColBERT.git (to revision v0.2) to c:\\users\\karna\\appdata\\local\\temp\\pip-install-mrj34hd5\\colbert_21d2128cda2748c9a92657287d05468a\n Resolved https://github.com/cmacdonald/ColBERT.git to commit f90dc0415655e2c5a0d616100c2e8610a5424686\nRequirement already satisfied: python-terrier>=0.5.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from pyterrier-colbert==0.0.1) (0.8.0)\nRequirement already satisfied: pandas in c:\\users\\karna\\anaconda3\\lib\\site-packages (from pyterrier-colbert==0.0.1) (1.4.1)\nRequirement already satisfied: torch>=1.6.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from pyterrier-colbert==0.0.1) (1.10.2)\nRequirement already satisfied: deprecation in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (2.1.0)\nRequirement already satisfied: numpy in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (1.21.2)\nRequirement already satisfied: sklearn in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.0)\nRequirement already satisfied: more-itertools in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (8.12.0)\nRequirement already satisfied: chest in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.2.3)\nRequirement already satisfied: statsmodels in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.13.0)\nRequirement already satisfied: wget in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (3.2)\nRequirement already satisfied: dill in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.3.4)\nRequirement already satisfied: jinja2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (2.11.3)\nRequirement already satisfied: matchpy in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.5.5)\nRequirement already satisfied: scipy in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (1.7.3)\nRequirement already satisfied: nptyping in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (1.4.4)\nRequirement already satisfied: joblib in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (1.1.0)\nRequirement already satisfied: pyjnius~=1.3.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (1.3.0)\nRequirement already satisfied: ir-datasets>=0.3.2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.5.0)\nRequirement already satisfied: ir-measures>=0.2.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.2.3)\nRequirement already satisfied: tqdm in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (4.62.3)\nRequirement already satisfied: requests in c:\\users\\karna\\anaconda3\\lib\\site-packages (from python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (2.27.1)\nRequirement already satisfied: lxml>=4.5.2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (4.7.1)\nRequirement already satisfied: lz4>=3.1.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (4.0.0)\nRequirement already satisfied: warc3-wet>=0.2.3 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.2.3)\nRequirement already satisfied: ijson>=3.1.3 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (3.1.4)\nRequirement already satisfied: zlib-state>=0.1.3 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.1.5)\nRequirement already satisfied: trec-car-tools>=2.5.4 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (2.6)\nRequirement already satisfied: pyyaml>=5.3.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (6.0)\nRequirement already satisfied: warc3-wet-clueweb09>=0.2.5 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.2.5)\nRequirement already satisfied: pyautocorpus>=0.1.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.1.8)\nRequirement already satisfied: beautifulsoup4>=4.4.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-datasets>=0.3.2->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (4.10.0)\nRequirement already satisfied: soupsieve>1.2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from beautifulsoup4>=4.4.1->ir-datasets>=0.3.2->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (2.3.1)\nRequirement already satisfied: cwl-eval>=1.0.10 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-measures>=0.2.0->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (1.0.10)\nRequirement already satisfied: pytrec-eval-terrier==0.5.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-measures>=0.2.0->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.5.1)\nRequirement already satisfied: pyndeval>=0.0.2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ir-measures>=0.2.0->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.0.2)\nRequirement already satisfied: cython in c:\\users\\karna\\anaconda3\\lib\\site-packages (from pyjnius~=1.3.0->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.29.25)\nRequirement already satisfied: six>=1.7.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from pyjnius~=1.3.0->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (1.16.0)\nRequirement already satisfied: certifi>=2017.4.17 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from requests->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (2021.10.8)\nRequirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from requests->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (1.26.7)\nRequirement already satisfied: charset-normalizer~=2.0.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from requests->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (2.0.4)\nRequirement already satisfied: idna<4,>=2.5 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from requests->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (3.3)\nRequirement already satisfied: typing-extensions in c:\\users\\karna\\anaconda3\\lib\\site-packages (from torch>=1.6.0->pyterrier-colbert==0.0.1) (4.0.1)\nRequirement already satisfied: colorama in c:\\users\\karna\\anaconda3\\lib\\site-packages (from tqdm->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.4.4)\nRequirement already satisfied: cbor>=1.0.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from trec-car-tools>=2.5.4->ir-datasets>=0.3.2->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (1.0.0)\nRequirement already satisfied: heapdict in c:\\users\\karna\\anaconda3\\lib\\site-packages (from chest->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (1.0.1)\nCollecting transformers==3.0.2\n Using cached transformers-3.0.2-py3-none-any.whl (769 kB)\nRequirement already satisfied: ujson in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (4.0.2)\nCollecting mlflow\n Using cached mlflow-1.24.0-py3-none-any.whl (16.5 MB)\nRequirement already satisfied: tensorboard in c:\\users\\karna\\anaconda3\\lib\\site-packages (from ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (2.4.1)\nRequirement already satisfied: packaging in c:\\users\\karna\\anaconda3\\lib\\site-packages (from transformers==3.0.2->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (21.3)\nCollecting tokenizers==0.8.1.rc1\n Using cached tokenizers-0.8.1rc1-cp38-cp38-win_amd64.whl (1.9 MB)\nRequirement already satisfied: regex!=2019.12.17 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from transformers==3.0.2->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (2021.8.3)\nCollecting sentencepiece!=0.1.92\n Using cached sentencepiece-0.1.96-cp38-cp38-win_amd64.whl (1.1 MB)\nCollecting sacremoses\n Using cached sacremoses-0.0.47-py2.py3-none-any.whl (895 kB)\nRequirement already satisfied: filelock in c:\\users\\karna\\anaconda3\\lib\\site-packages (from transformers==3.0.2->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (3.4.2)\nRequirement already satisfied: MarkupSafe>=0.23 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from jinja2->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (1.1.1)\nRequirement already satisfied: multiset<3.0,>=2.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from matchpy->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (2.1.1)\nCollecting docker>=4.0.0\n Using cached docker-5.0.3-py2.py3-none-any.whl (146 kB)\nCollecting querystring-parser\n Using cached querystring_parser-1.2.4-py2.py3-none-any.whl (7.9 kB)\nRequirement already satisfied: importlib-metadata!=4.7.0,>=3.7.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (4.10.1)\nRequirement already satisfied: cloudpickle in c:\\users\\karna\\anaconda3\\lib\\site-packages (from mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (2.0.0)\nRequirement already satisfied: sqlalchemy in c:\\users\\karna\\anaconda3\\lib\\site-packages (from mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (1.4.27)\nCollecting sqlparse>=0.3.1\n Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB)\nRequirement already satisfied: click>=7.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (8.0.3)\nCollecting prometheus-flask-exporter\n Using cached prometheus_flask_exporter-0.19.0-py3-none-any.whl (18 kB)\nRequirement already satisfied: Flask in c:\\users\\karna\\anaconda3\\lib\\site-packages (from mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (1.1.2)\nCollecting gitpython>=2.1.0\n Using cached GitPython-3.1.27-py3-none-any.whl (181 kB)\nRequirement already satisfied: pytz in c:\\users\\karna\\anaconda3\\lib\\site-packages (from mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (2021.3)\nRequirement already satisfied: protobuf>=3.7.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (3.15.6)\nCollecting databricks-cli>=0.8.7\n Using cached databricks_cli-0.16.4-py3-none-any.whl\nCollecting alembic\n Using cached alembic-1.7.6-py3-none-any.whl (210 kB)\nRequirement already satisfied: entrypoints in c:\\users\\karna\\anaconda3\\lib\\site-packages (from mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (0.3)\nCollecting waitress\n Using cached waitress-2.1.0-py3-none-any.whl (56 kB)\nRequirement already satisfied: tabulate>=0.7.7 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from databricks-cli>=0.8.7->mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (0.8.9)\nRequirement already satisfied: websocket-client>=0.32.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from docker>=4.0.0->mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (1.3.1)\nCollecting pywin32==227\n Using cached pywin32-227-cp38-cp38-win_amd64.whl (9.1 MB)\nCollecting gitdb<5,>=4.0.1\n Using cached gitdb-4.0.9-py3-none-any.whl (63 kB)\nRequirement already satisfied: smmap<6,>=3.0.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from gitdb<5,>=4.0.1->gitpython>=2.1.0->mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (5.0.0)\nRequirement already satisfied: zipp>=0.5 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from importlib-metadata!=4.7.0,>=3.7.0->mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (3.7.0)\nCollecting importlib-resources\n Using cached importlib_resources-5.4.0-py3-none-any.whl (28 kB)\nCollecting Mako\n Using cached Mako-1.1.6-py2.py3-none-any.whl (75 kB)\nRequirement already satisfied: greenlet!=0.4.17 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from sqlalchemy->mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (1.1.1)\nRequirement already satisfied: Werkzeug>=0.15 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from Flask->mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (2.0.2)\nRequirement already satisfied: itsdangerous>=0.24 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from Flask->mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (2.0.1)\nRequirement already satisfied: typish>=1.7.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from nptyping->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (1.9.3)\nRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from packaging->transformers==3.0.2->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (3.0.4)\nRequirement already satisfied: python-dateutil>=2.8.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from pandas->pyterrier-colbert==0.0.1) (2.8.2)\nRequirement already satisfied: prometheus-client in c:\\users\\karna\\anaconda3\\lib\\site-packages (from prometheus-flask-exporter->mlflow->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (0.12.0)\nRequirement already satisfied: scikit-learn in c:\\users\\karna\\anaconda3\\lib\\site-packages (from sklearn->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (1.0.2)\nRequirement already satisfied: threadpoolctl>=2.0.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from scikit-learn->sklearn->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (2.2.0)\nRequirement already satisfied: patsy>=0.5.2 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from statsmodels->python-terrier>=0.5.0->pyterrier-colbert==0.0.1) (0.5.2)\nRequirement already satisfied: grpcio>=1.24.3 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (1.32.0)\nRequirement already satisfied: markdown>=2.6.8 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (3.3.4)\nRequirement already satisfied: absl-py>=0.4 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (0.12.0)\nRequirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (0.4.4)\nRequirement already satisfied: wheel>=0.26 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (0.37.1)\nRequirement already satisfied: setuptools>=41.0.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (58.0.4)\nRequirement already satisfied: tensorboard-plugin-wit>=1.6.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (1.8.0)\nRequirement already satisfied: google-auth<2,>=1.6.3 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (1.28.0)\nRequirement already satisfied: cachetools<5.0,>=2.0.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from google-auth<2,>=1.6.3->tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (4.2.1)\nRequirement already satisfied: rsa<5,>=3.1.4 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from google-auth<2,>=1.6.3->tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (4.7.2)\nRequirement already satisfied: pyasn1-modules>=0.2.1 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from google-auth<2,>=1.6.3->tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (0.2.8)\nRequirement already satisfied: requests-oauthlib>=0.7.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (1.3.0)\nRequirement already satisfied: pyasn1<0.5.0,>=0.4.6 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (0.4.8)\nRequirement already satisfied: oauthlib>=3.0.0 in c:\\users\\karna\\anaconda3\\lib\\site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard->ColBERT@ git+https://github.com/cmacdonald/[email protected]#egg=ColBERT->pyterrier-colbert==0.0.1) (3.1.0)\nBuilding wheels for collected packages: pyterrier-colbert, ColBERT\n Building wheel for pyterrier-colbert (setup.py): started\n Building wheel for pyterrier-colbert (setup.py): finished with status 'done'\n Created wheel for pyterrier-colbert: filename=pyterrier_colbert-0.0.1-py3-none-any.whl size=25581 sha256=fb32aa4af1f6a78141f16a55bbcc02b4fac9901b3b4509ff1b6c662d465e1fee\n Stored in directory: C:\\Users\\karna\\AppData\\Local\\Temp\\pip-ephem-wheel-cache-7reko5yo\\wheels\\fe\\9e\\da\\f1c140008c49435e410215dcfd1d8f84d7e867de986c5f1625\n Building wheel for ColBERT (setup.py): started\n Building wheel for ColBERT (setup.py): finished with status 'done'\n Created wheel for ColBERT: filename=ColBERT-0.2.0-py3-none-any.whl size=48926 sha256=cf1972826b9c4b588c2a14628eb1c1b7f7ebf722ab280ba203621ba87fd7f245\n Stored in directory: C:\\Users\\karna\\AppData\\Local\\Temp\\pip-ephem-wheel-cache-7reko5yo\\wheels\\a3\\25\\89\\4a78e5c94ec1dfd826f4320ddda521cea960d9c48f90e4191b\nSuccessfully built pyterrier-colbert ColBERT\nInstalling collected packages: pywin32, Mako, importlib-resources, gitdb, waitress, tokenizers, sqlparse, sentencepiece, sacremoses, querystring-parser, prometheus-flask-exporter, gitpython, docker, databricks-cli, alembic, transformers, mlflow, ColBERT, pyterrier-colbert\n Attempting uninstall: pywin32\n Found existing installation: pywin32 302\n Uninstalling pywin32-302:\n Successfully uninstalled pywin32-302\n Rolling back uninstall of pywin32\n Moving to c:\\users\\karna\\anaconda3\\lib\\site-packages\\__pycache__\\pythoncom.cpython-38.pyc\n from C:\\Users\\karna\\AppData\\Local\\Temp\\pip-uninstall-qnlo7_z1\\pythoncom.cpython-38.pyc\n Moving to c:\\users\\karna\\anaconda3\\lib\\site-packages\\adodbapi\n from C:\\Users\\karna\\anaconda3\\Lib\\site-packages\\~dodbapi\n Moving to c:\\users\\karna\\anaconda3\\lib\\site-packages\\isapi\n from C:\\Users\\karna\\anaconda3\\Lib\\site-packages\\~sapi\n Moving to c:\\users\\karna\\anaconda3\\lib\\site-packages\\pythoncom.py\n from C:\\Users\\karna\\AppData\\Local\\Temp\\pip-uninstall-8fl51696\\pythoncom.py\n Moving to c:\\users\\karna\\anaconda3\\lib\\site-packages\\pythonwin\n from C:\\Users\\karna\\anaconda3\\Lib\\site-packages\\~ythonwin\n Moving to c:\\users\\karna\\anaconda3\\lib\\site-packages\\pywin32-302-py3.8.egg-info\n from C:\\Users\\karna\\anaconda3\\Lib\\site-packages\\~ywin32-302-py3.8.egg-info\n Moving to c:\\users\\karna\\anaconda3\\lib\\site-packages\\win32\\lib\\\n from C:\\Users\\karna\\anaconda3\\Lib\\site-packages\\win32\\~ib\n Moving to c:\\users\\karna\\anaconda3\\lib\\site-packages\\win32com\n from C:\\Users\\karna\\anaconda3\\Lib\\site-packages\\~in32com\n Moving to c:\\users\\karna\\anaconda3\\lib\\site-packages\\win32comext\n from C:\\Users\\karna\\anaconda3\\Lib\\site-packages\\~in32comext\n"
],
[
"#initialisation pyterrier\nimport pyterrier as pt\nif not pt.started():\n pt.init()",
"terrier-assemblies 5.6 jar-with-dependencies not found, downloading to C:\\Users\\karna\\.pyterrier...\nDone\nterrier-python-helper 0.0.6 jar not found, downloading to C:\\Users\\karna\\.pyterrier...\nDone\n"
],
[
"#récupération du dataset covid19\ndataset = pt.datasets.get_dataset('irds:cord19/trec-covid')\ntopics = dataset.get_topics(variant='description')\nqrels = dataset.get_qrels()\n\n#construction de l'index\nimport os\n\ncord19 = pt.datasets.get_dataset('irds:cord19/trec-covid')\npt_index_path = './terrier_cord19'\n\nif not os.path.exists(pt_index_path + \"/data.properties\"):\n # create the index, using the IterDictIndexer indexer \n indexer = pt.index.IterDictIndexer(pt_index_path)\n\n # we give the dataset get_corpus_iter() directly to the indexer\n # while specifying the fields to index and the metadata to record\n index_ref = indexer.index(cord19.get_corpus_iter(), \n fields=('abstract',), \n meta=('docno',))\n\nelse:\n # if you already have the index, use it.\n index_ref = pt.IndexRef.of(pt_index_path + \"/data.properties\")\n\nindex = pt.IndexFactory.of(index_ref)\n\n\nimport os\n\nif not os.path.exists(\"terrier_index.zip\"):\n !wget http://www.dcs.gla.ac.uk/~craigm/ecir2021-tutorial/terrier_index.zip\n !unzip -j terrier_index.zip -d terrier_index\n\nindex_ref = pt.IndexRef.of(\"./terrier_index/data.properties\")\nindex = pt.IndexFactory.of(index_ref)",
"_____no_output_____"
]
],
[
[
"## chargement du modèle ColBERT",
"_____no_output_____"
]
],
[
[
"import pyterrier_colbert.ranking\ncolbert_factory = pyterrier_colbert.ranking.ColBERTFactory(\n \"http://www.dcs.gla.ac.uk/~craigm/colbert.dnn.zip\", None, None)\ncolbert = colbert_factory.text_scorer(doc_attr='abstract')",
"_____no_output_____"
]
],
[
[
"Exécution des requêtes du dataset et calcul des métriques",
"_____no_output_____"
]
],
[
[
"br = pt.BatchRetrieve(index) % 100\npipeline = br >> pt.text.get_text(dataset, 'abstract') >> colbert\npt.Experiment(\n [br, pipeline],\n topics,\n qrels,\n names=['DPH', 'DPH >> ColBERT'],\n eval_metrics=[\"map\", \"ndcg\", 'ndcg_cut.10', 'P.10', 'mrt']\n)",
"_____no_output_____"
]
],
[
[
"on souhaite ici visualiser les résultats du modèle, et surtout visualiser l'attention calculée sur le texte.",
"_____no_output_____"
]
],
[
[
"res = pipeline(topics.iloc[:1])\nres.merge(dataset.get_qrels(), how='left').head()",
"_____no_output_____"
]
],
[
[
"le premier document est pertinent pour la requête q0. Nous observons ci-dessous la carte d'attention associée au calcul du score : ",
"_____no_output_____"
]
],
[
[
"text = dataset.irds_ref().docs_store().get('4dtk1kyh').abstract[:300] + '...' # truncate text\ncolbert_factory.explain_text('what is the origin of covid 19', text)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aa7f2300b60bee634d73879385ba096a67d89a2
| 8,147 |
ipynb
|
Jupyter Notebook
|
05-reinforcement-learning/01-intro-to-reinforcement-learning.ipynb
|
HarryGuapo/intro-to-deep-learning
|
cbeb764c4280025b0be7b2186f7ea5c11b579b59
|
[
"Unlicense"
] | 143 |
2019-05-10T01:23:59.000Z
|
2022-02-24T07:12:40.000Z
|
05-reinforcement-learning/01-intro-to-reinforcement-learning.ipynb
|
HarryGuapo/intro-to-deep-learning
|
cbeb764c4280025b0be7b2186f7ea5c11b579b59
|
[
"Unlicense"
] | 6 |
2019-10-23T16:17:13.000Z
|
2020-06-05T13:18:14.000Z
|
05-reinforcement-learning/01-intro-to-reinforcement-learning.ipynb
|
HarryGuapo/intro-to-deep-learning
|
cbeb764c4280025b0be7b2186f7ea5c11b579b59
|
[
"Unlicense"
] | 87 |
2019-05-14T17:52:43.000Z
|
2022-02-09T15:31:21.000Z
| 60.348148 | 552 | 0.692157 |
[
[
[
"# Intro to Reinforcement Learning\n\nReinforcement learning requires us to model our problem using the following two constructs:\n\n* An agent, the thing that makes decisions.\n* An environment, the world which encodes what decisions can be made, and the impact of those decisions. \n\nThe environment contains all the possible states, knows all the actions that can be taken from each state, and knows when rewards should be given and what the magnitude of those rewards should be. An agent gets this information from the environment by exploring and learns from experience which states provide the best rewards. Rewards slowly percolate outward to neighboring states iteratively, which helps the agent make decisions over longer time horizons.\n\n## The Agent/Environment Interface\n\n\n\n> Image Source: [Reinforcement Learning:An Introduction](http://incompleteideas.net/book/bookdraft2017nov5.pdf)\n",
"_____no_output_____"
],
[
"Reinforcement learning typically takes place over a number of episodes—which are rougly analogous to an epoch. In most situations for RL, there are some \"terminal\" states within the environment which indicate the end of an episode. In games for example, this happens when the game ends. For example when Mario gets killed or reaches the end of the level. Or in chess when someone is put into checkmate or conceeds. An episode ends when an agent reaches one of these terminal states.\n\nAn episode is compirsed of the agent making a series of decisions until it reaches one of these terminal states. Sometimes engineers may choose to terminate an episode after a maximum number of decisions, especially if there is a strong chance that the agent will never reach a terminal state. \n\n## Markov Decsion Processes\n\nFormally, the problems that reinforcement learning is best at solving are modeled by Markov Decision Processes (MDP). MDPs are a special kind of graph that are similar to State Machines. MDPs have two kinds of nodes, states and actions. From any given state an agent can select from only the available actions, those actions will take an agent to another state. These transitions from actions to states are frequently stochastic—meaning taking a particular action might lead you to one of several states based on some probabilistic function. \n\nTransitions from state to state can be associated with a reward but they are not required to be. Many MDPs have terminal states, but those are not formally required either.\n\n\n\n> Image Source: [Wikimedia commons, public domain](https://commons.wikimedia.org/wiki/File:Markov_Decision_Process_example.png)\n\nThis MDP has 3 states (larger green nodes S0, S1, S2), each state has exactly 2 actions available (smaller red nodes, a0, a1), and two transitions have rewards (from S2a1 -> S0 has -1 reward, from S1a0 -> S0 has +5 reward). ",
"_____no_output_____"
],
[
"## Finding a Policy\n\nThe reinforcment learning algorithm we're going to focus on (Q-Learning) is a \"policy based\" agent. This means, it's goal is to discover which decision is the \"best\" decision to make at any given state. Sometimes, this goal is a little naive, for example if the state-spaces is evolving in real time, it may not be possible to determine a \"best\" policy. In the above MDP, though, there IS an optimal policy... What is it?",
"_____no_output_____"
],
[
"### Optimal Policy For the Above:\n\nThe only way to gain a positive reward is to take the transition S1a0 -> S0. That gives us +5 70% of the time. \n\nGetting to S1 requires a risk though: the only way to get to S1 is by taking a1 from S2, which has a 30% chance of landing us back at S0 with a -1 reward. \n\nWe can easily oscilate infinitely between S0 and S2 with zero reward by taking only S0a1, S0a0, and S2a0 repeatedly. So the question is: is the risk worth the reward? \n\nSay we're in S1, we can get +5 70% of the time by taking a0. That's an expected value of 3.5 if our policy is always take action a0. If we're in S2, then, we can get an expected value of 3.5 30% of the time, and a -1 30% of the time by always taking action a1: \n\n`(.3 * 3.5) + (.3 * -1) = 1.05 - .3 = .75`\n\nSo intiutively we should go ahead and take the risky action to gain the net-positive reward. **But wait!** Both of our actions are *self-referential* and might lead us back to the original state... how do we account for that? \n\nFor the mathematical purists, we can use something called the Bellman Optimality Equation. Intuitively, the Bellman optimality equation expresses the fact that the value of a state under an optimal policy must equal the expected return for the best action from that state:\n\nFor the value of states:\n\n\n\nFor the state-action pairs:\n\n\n\n> For a more complete treatment of these equations, see [Chapter 3.6 of this book](http://incompleteideas.net/book/bookdraft2017nov5.pdf)\n\nSeveral bits of notation were just introduced:\n\n* The Discount Factor (γ) — some value between 0 and 1, which is required for convergance.\n* The expected return (Gt) — the value we want to optimize.\n* The table of state-action pairs (Q) — these are the values of being in a state and taking a given action.\n* The table of state values (V*) — these are based on the Q-values from the Q-table based on taking the best action.\n* The policy is represented by π — our policy is what our agent thinks is the best action\n* S and S' both represent states, the current state (S) and the next state (S') for any given state-action pair.\n* r represents a reward for a given transition.\n\nSolving this series of equations is computationally unrealistic for most problems of any real size. It is an iterative process that will only converge if the discount factor λ is between 0 and 1, and even then often it converges slowly. The most common algorithm for solving the Bellman equations directly is called Value Iteration, and it is much like what we did above, but we'd apply that logic repeatedly, for every state-action pair, and we'd have to apply a discount factor to the expected values we computed.\n\nValue iteration is never used in practice. Instead we use Q-learning to experimentally explore states, essentially we attempt to partially solve the above Bellman equations. For a more complete treatment of value iteration, see the book linked above. \n",
"_____no_output_____"
],
[
"In my opinion, it is much easier, and much more helpful to see Q-Learning in action than it is to pour over the dense and confusing mathematical notation above. Q-Learning is actually wonderfully intuitive when you take a step back from the math. ",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4aa7f420abf3792260c5ae6b7a74cceb35d5335e
| 4,123 |
ipynb
|
Jupyter Notebook
|
ipynb/Hungary-Budapest.ipynb
|
RobertRosca/oscovida.github.io
|
d609949076e3f881e38ec674ecbf0887e9a2ec25
|
[
"CC-BY-4.0"
] | null | null | null |
ipynb/Hungary-Budapest.ipynb
|
RobertRosca/oscovida.github.io
|
d609949076e3f881e38ec674ecbf0887e9a2ec25
|
[
"CC-BY-4.0"
] | null | null | null |
ipynb/Hungary-Budapest.ipynb
|
RobertRosca/oscovida.github.io
|
d609949076e3f881e38ec674ecbf0887e9a2ec25
|
[
"CC-BY-4.0"
] | null | null | null | 28.832168 | 170 | 0.512976 |
[
[
[
"# Hungary: Budapest\n\n* Homepage of project: https://oscovida.github.io\n* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Hungary-Budapest.ipynb)",
"_____no_output_____"
]
],
[
[
"import datetime\nimport time\n\nstart = datetime.datetime.now()\nprint(f\"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}\")",
"_____no_output_____"
],
[
"%config InlineBackend.figure_formats = ['svg']\nfrom oscovida import *",
"_____no_output_____"
],
[
"overview(country=\"Hungary\", region=\"Budapest\");",
"_____no_output_____"
],
[
"# load the data\ncases, deaths, region_label = get_region_hungary(county=\"Budapest\")\n\n# compose into one table\ntable = compose_dataframe_summary(cases, deaths)\n\n# show tables with up to 500 rows\npd.set_option(\"max_rows\", 500)\n\n# display the table\ntable",
"_____no_output_____"
]
],
[
[
"# Explore the data in your web browser\n\n- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Hungary-Budapest.ipynb)\n- and wait (~1 to 2 minutes)\n- Then press SHIFT+RETURN to advance code cell to code cell\n- See http://jupyter.org for more details on how to use Jupyter Notebook",
"_____no_output_____"
],
[
"# Acknowledgements:\n\n- Johns Hopkins University provides data for countries\n- Robert Koch Institute provides data for within Germany\n- Open source and scientific computing community for the data tools\n- Github for hosting repository and html files\n- Project Jupyter for the Notebook and binder service\n- The H2020 project Photon and Neutron Open Science Cloud ([PaNOSC](https://www.panosc.eu/))\n\n--------------------",
"_____no_output_____"
]
],
[
[
"print(f\"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and \"\n f\"deaths at {fetch_deaths_last_execution()}.\")",
"_____no_output_____"
],
[
"# to force a fresh download of data, run \"clear_cache()\"",
"_____no_output_____"
],
[
"print(f\"Notebook execution took: {datetime.datetime.now()-start}\")\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
4aa80ad84134bf7ad45cf07a6afebeacd6278f9f
| 35,724 |
ipynb
|
Jupyter Notebook
|
hw_wordrelatedness.ipynb
|
ebbingcasa/cs224u
|
d491b93ecb12a523bfbeb84230a5a3510493c448
|
[
"Apache-2.0"
] | null | null | null |
hw_wordrelatedness.ipynb
|
ebbingcasa/cs224u
|
d491b93ecb12a523bfbeb84230a5a3510493c448
|
[
"Apache-2.0"
] | null | null | null |
hw_wordrelatedness.ipynb
|
ebbingcasa/cs224u
|
d491b93ecb12a523bfbeb84230a5a3510493c448
|
[
"Apache-2.0"
] | null | null | null | 34.284069 | 494 | 0.601416 |
[
[
[
"# Homework and bake-off: Word relatedness",
"_____no_output_____"
]
],
[
[
"__author__ = \"Christopher Potts\"\n__version__ = \"CS224u, Stanford, Spring 2021\"",
"_____no_output_____"
]
],
[
[
"## Contents\n\n1. [Overview](#Overview)\n1. [Set-up](#Set-up)\n1. [Development dataset](#Development-dataset)\n 1. [Vocabulary](#Vocabulary)\n 1. [Score distribution](#Score-distribution)\n 1. [Repeated pairs](#Repeated-pairs)\n1. [Evaluation](#Evaluation)\n1. [Error analysis](#Error-analysis)\n1. [Homework questions](#Homework-questions)\n 1. [PPMI as a baseline [0.5 points]](#PPMI-as-a-baseline-[0.5-points])\n 1. [Gigaword with LSA at different dimensions [0.5 points]](#Gigaword-with-LSA-at-different-dimensions-[0.5-points])\n 1. [t-test reweighting [2 points]](#t-test-reweighting-[2-points])\n 1. [Pooled BERT representations [1 point]](#Pooled-BERT-representations-[1-point])\n 1. [Learned distance functions [2 points]](#Learned-distance-functions-[2-points])\n 1. [Your original system [3 points]](#Your-original-system-[3-points])\n1. [Bake-off [1 point]](#Bake-off-[1-point])\n1. [Submission Instruction](#Submission-Instruction)",
"_____no_output_____"
],
[
"## Overview\n\nWord similarity and relatedness datasets have long been used to evaluate distributed representations. This notebook provides code for conducting such analyses with a new word relatedness datasets. It consists of word pairs, each with an associated human-annotated relatedness score. \n\nThe evaluation metric for each dataset is the [Spearman correlation coefficient $\\rho$](https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient) between the annotated scores and your distances, as is standard in the literature.\n\nThis homework ([questions at the bottom of this notebook](#Homework-questions)) asks you to write code that uses the count matrices in `data/vsmdata` to create and evaluate some baseline models. The final question asks you to create your own original system for this task, using any data you wish. This accounts for 9 of the 10 points for this assignment.\n\nFor the associated bake-off, we will distribute a new dataset, and you will evaluate your original system (no additional training or tuning allowed!) on that datasets and submit your predictions. Systems that enter will receive the additional homework point, and systems that achieve the top score will receive an additional 0.5 points.",
"_____no_output_____"
],
[
"## Set-up",
"_____no_output_____"
]
],
[
[
"from collections import defaultdict\nimport csv\nimport itertools\nimport numpy as np\nimport os\nimport pandas as pd\nimport random\nfrom scipy.stats import spearmanr\n\nimport vsm\nimport utils",
"_____no_output_____"
],
[
"utils.fix_random_seeds()",
"_____no_output_____"
],
[
"VSM_HOME = os.path.join('data', 'vsmdata')\n\nDATA_HOME = os.path.join('data', 'wordrelatedness')",
"_____no_output_____"
]
],
[
[
"## Development dataset",
"_____no_output_____"
],
[
"You can use development dataset freely, since our bake-off evalutions involve a new test set.",
"_____no_output_____"
]
],
[
[
"dev_df = pd.read_csv(\n os.path.join(DATA_HOME, \"cs224u-wordrelatedness-dev.csv\"))",
"_____no_output_____"
]
],
[
[
"The dataset consists of word pairs with scores:",
"_____no_output_____"
]
],
[
[
"dev_df.head()",
"_____no_output_____"
]
],
[
[
"This gives the number of word pairs in the data:",
"_____no_output_____"
]
],
[
[
"dev_df.shape[0]",
"_____no_output_____"
]
],
[
[
"The test set will contain 1500 word pairs with scores of the same type. No word pair in the development set appears in the test set, but some of the individual words are repeated in the test set.",
"_____no_output_____"
],
[
"### Vocabulary",
"_____no_output_____"
],
[
"The full vocabulary in the dataframe can be extracted as follows:",
"_____no_output_____"
]
],
[
[
"dev_vocab = set(dev_df.word1.values) | set(dev_df.word2.values)",
"_____no_output_____"
],
[
"len(dev_vocab)",
"_____no_output_____"
]
],
[
[
"The vocabulary for the bake-off test is different – it is partly overlapping with the above. If you want to be sure ahead of time that your system has a representation for every word in the dev and test sets, then you can check against the vocabularies of any of the VSMs in `data/vsmdata` (which all have the same vocabulary). For example:",
"_____no_output_____"
]
],
[
[
"task_index = pd.read_csv(\n os.path.join(VSM_HOME, 'yelp_window5-scaled.csv.gz'),\n usecols=[0], index_col=0)\n\nfull_task_vocab = list(task_index.index)",
"_____no_output_____"
],
[
"len(full_task_vocab)",
"_____no_output_____"
]
],
[
[
"If you can process every one of those words, then you are all set. Alternatively, you can wait to see the test set and make system adjustments to ensure that you can process all those words. This is fine as long as you are not tuning your predictions.",
"_____no_output_____"
],
[
"### Score distribution",
"_____no_output_____"
],
[
"All the scores fall in $[0, 1]$, and the dataset skews towards words with low scores, meaning low relatedness:",
"_____no_output_____"
]
],
[
[
"ax = dev_df.plot.hist().set_xlabel(\"Relatedness score\")",
"_____no_output_____"
]
],
[
[
"### Repeated pairs",
"_____no_output_____"
],
[
"The development data has some word pairs with multiple distinct scores in it. Here we create a `pd.Series` that contains these word pairs:",
"_____no_output_____"
]
],
[
[
"repeats = dev_df.groupby(['word1', 'word2']).apply(lambda x: x.score.var())\n\nrepeats = repeats[repeats > 0].sort_values(ascending=False)\n\nrepeats.name = 'score variance'",
"_____no_output_____"
],
[
"repeats.shape[0]",
"_____no_output_____"
]
],
[
[
"The `pd.Series` is sorted with the highest variance items at the top:",
"_____no_output_____"
]
],
[
[
"repeats.head()",
"_____no_output_____"
]
],
[
[
"Since this is development data, it is up to you how you want to handle these repeats. The test set has no repeated pairs in it.",
"_____no_output_____"
],
[
"## Evaluation",
"_____no_output_____"
],
[
"Our evaluation function is `vsm.word_relatedness_evaluation`. Its arguments:\n \n1. A relatedness dataset `pd.DataFrame` – e.g., `dev_df` as given above.\n1. A VSM `pd.DataFrame` – e.g., `giga5` or some transformation thereof, or a GloVe embedding space, or something you have created on your own. The function checks that you can supply a representation for every word in `dev_df` and raises an exception if you can't.\n1. Optionally a `distfunc` argument, which defaults to `vsm.cosine`.\n\nThe function returns a tuple:\n\n1. A copy of `dev_df` with a new column giving your predictions.\n1. The Spearman $\\rho$ value (our primary score).\n\nImportant note: Internally, `vsm.word_relatedness_evaluation` uses `-distfunc(x1, x2)` as its score, where `x1` and `x2` are vector representations of words. This is because the scores in our data are _positive_ relatedness scores, whereas we are assuming that `distfunc` is a _distance_ function.\n\nHere's a simple illustration using one of our count matrices:",
"_____no_output_____"
]
],
[
[
"count_df = pd.read_csv(\n os.path.join(VSM_HOME, \"giga_window5-scaled.csv.gz\"), index_col=0)",
"_____no_output_____"
],
[
"count_pred_df, count_rho = vsm.word_relatedness_evaluation(dev_df, count_df)",
"_____no_output_____"
],
[
"count_rho",
"_____no_output_____"
],
[
"count_pred_df.head()",
"_____no_output_____"
]
],
[
[
"It's instructive to compare this against a truly random system, which we can create by simply having a custom distance function that returns a random number in [0, 1] for each example, making no use of the VSM itself:",
"_____no_output_____"
]
],
[
[
"def random_scorer(x1, x2):\n \"\"\"`x1` and `x2` are vectors, to conform to the requirements\n of `vsm.word_relatedness_evaluation`, but this function just\n returns a random number in [0, 1].\"\"\"\n return random.random()",
"_____no_output_____"
],
[
"random_pred_df, random_rho = vsm.word_relatedness_evaluation(\n dev_df, count_df, distfunc=random_scorer)\n\nrandom_rho",
"_____no_output_____"
]
],
[
[
"This is a truly baseline system!",
"_____no_output_____"
],
[
"## Error analysis\n\nFor error analysis, we can look at the words with the largest delta between the gold score and the distance value in our VSM. We do these comparisons based on ranks, just as with our primary metric (Spearman $\\rho$), and we normalize both rankings so that they have a comparable number of levels.",
"_____no_output_____"
]
],
[
[
"def error_analysis(pred_df):\n pred_df = pred_df.copy()\n pred_df['relatedness_rank'] = _normalized_ranking(pred_df.prediction)\n pred_df['score_rank'] = _normalized_ranking(pred_df.score)\n pred_df['error'] = abs(pred_df['relatedness_rank'] - pred_df['score_rank'])\n return pred_df.sort_values('error')\n\n\ndef _normalized_ranking(series):\n ranks = series.rank(method='dense')\n return ranks / ranks.sum()",
"_____no_output_____"
]
],
[
[
"Best predictions:",
"_____no_output_____"
]
],
[
[
"error_analysis(count_pred_df).head()",
"_____no_output_____"
]
],
[
[
"Worst predictions:",
"_____no_output_____"
]
],
[
[
"error_analysis(count_pred_df).tail()",
"_____no_output_____"
]
],
[
[
"## Homework questions\n\nPlease embed your homework responses in this notebook, and do not delete any cells from the notebook. (You are free to add as many cells as you like as part of your responses.)",
"_____no_output_____"
],
[
"### PPMI as a baseline [0.5 points]",
"_____no_output_____"
],
[
"The insight behind PPMI is a recurring theme in word representation learning, so it is a natural baseline for our task. This question asks you to write code for conducting such experiments.\n\nYour task: write a function called `run_giga_ppmi_baseline` that does the following:\n\n1. Reads the Gigaword count matrix with a window of 20 and a flat scaling function into a `pd.DataFrame`, as is done in the VSM notebooks. The file is `data/vsmdata/giga_window20-flat.csv.gz`, and the VSM notebooks provide examples of the needed code.\n1. Reweights this count matrix with PPMI.\n1. Evaluates this reweighted matrix using `vsm.word_relatedness_evaluation` on `dev_df` as defined above, with `distfunc` set to the default of `vsm.cosine`.\n1. Returns the return value of this call to `vsm.word_relatedness_evaluation`.\n\nThe goal of this question is to help you get more familiar with the code in `vsm` and the function `vsm.word_relatedness_evaluation`.\n\nThe function `test_run_giga_ppmi_baseline` can be used to test that you've implemented this specification correctly.",
"_____no_output_____"
]
],
[
[
"def run_giga_ppmi_baseline():\n pass\n ##### YOUR CODE HERE\n\n",
"_____no_output_____"
],
[
"def test_run_giga_ppmi_baseline(func):\n \"\"\"`func` should be `run_giga_ppmi_baseline\"\"\"\n pred_df, rho = func()\n rho = round(rho, 3)\n expected = 0.586\n assert rho == expected, \\\n \"Expected rho of {}; got {}\".format(expected, rho)",
"_____no_output_____"
],
[
"if 'IS_GRADESCOPE_ENV' not in os.environ:\n test_run_giga_ppmi_baseline(run_giga_ppmi_baseline)",
"_____no_output_____"
]
],
[
[
"### Gigaword with LSA at different dimensions [0.5 points]",
"_____no_output_____"
],
[
"We might expect PPMI and LSA to form a solid pipeline that combines the strengths of PPMI with those of dimensionality reduction. However, LSA has a hyper-parameter $k$ – the dimensionality of the final representations – that will impact performance. This problem asks you to create code that will help you explore this approach.\n\nYour task: write a wrapper function `run_ppmi_lsa_pipeline` that does the following:\n\n1. Takes as input a count `pd.DataFrame` and an LSA parameter `k`.\n1. Reweights the count matrix with PPMI.\n1. Applies LSA with dimensionality `k`.\n1. Evaluates this reweighted matrix using `vsm.word_relatedness_evaluation` with `dev_df` as defined above. The return value of `run_ppmi_lsa_pipeline` should be the return value of this call to `vsm.word_relatedness_evaluation`.\n\nThe goal of this question is to help you get a feel for how LSA can contribute to this problem. \n\nThe function `test_run_ppmi_lsa_pipeline` will test your function on the count matrix in `data/vsmdata/giga_window20-flat.csv.gz`.",
"_____no_output_____"
]
],
[
[
"def run_ppmi_lsa_pipeline(count_df, k):\n pass\n ##### YOUR CODE HERE\n\n",
"_____no_output_____"
],
[
"def test_run_ppmi_lsa_pipeline(func):\n \"\"\"`func` should be `run_ppmi_lsa_pipeline`\"\"\"\n giga20 = pd.read_csv(\n os.path.join(VSM_HOME, \"giga_window20-flat.csv.gz\"), index_col=0)\n pred_df, rho = func(giga20, k=10)\n rho = round(rho, 3)\n expected = 0.545\n assert rho == expected,\\\n \"Expected rho of {}; got {}\".format(expected, rho)",
"_____no_output_____"
],
[
"if 'IS_GRADESCOPE_ENV' not in os.environ:\n test_run_ppmi_lsa_pipeline(run_ppmi_lsa_pipeline)",
"_____no_output_____"
]
],
[
[
"### t-test reweighting [2 points]",
"_____no_output_____"
],
[
"The t-test statistic can be thought of as a reweighting scheme. For a count matrix $X$, row index $i$, and column index $j$:\n\n$$\\textbf{ttest}(X, i, j) = \n\\frac{\n P(X, i, j) - \\big(P(X, i, *)P(X, *, j)\\big)\n}{\n\\sqrt{(P(X, i, *)P(X, *, j))}\n}$$\n\nwhere $P(X, i, j)$ is $X_{ij}$ divided by the total values in $X$, $P(X, i, *)$ is the sum of the values in row $i$ of $X$ divided by the total values in $X$, and $P(X, *, j)$ is the sum of the values in column $j$ of $X$ divided by the total values in $X$.\n\nYour task: implement this reweighting scheme. You can use `test_ttest_implementation` below to check that your implementation is correct. You do not need to use this for any evaluations, though we hope you will be curious enough to do so!",
"_____no_output_____"
]
],
[
[
"def ttest(df):\n pass\n ##### YOUR CODE HERE\n\n",
"_____no_output_____"
],
[
"def test_ttest_implementation(func):\n \"\"\"`func` should be `ttest`\"\"\"\n X = pd.DataFrame([\n [1., 4., 3., 0.],\n [2., 43., 7., 12.],\n [5., 6., 19., 0.],\n [1., 11., 1., 4.]])\n actual = np.array([\n [ 0.04655, -0.01337, 0.06346, -0.09507],\n [-0.11835, 0.13406, -0.20846, 0.10609],\n [ 0.16621, -0.23129, 0.38123, -0.18411],\n [-0.0231 , 0.0563 , -0.14549, 0.10394]])\n predicted = func(X)\n assert np.array_equal(predicted.round(5), actual), \\\n \"Your ttest result is\\n{}\".format(predicted.round(5))",
"_____no_output_____"
],
[
"if 'IS_GRADESCOPE_ENV' not in os.environ:\n test_ttest_implementation(ttest)",
"_____no_output_____"
]
],
[
[
"### Pooled BERT representations [1 point]",
"_____no_output_____"
],
[
"The notebook [vsm_04_contextualreps.ipynb](vsm_04_contextualreps.ipynb) explores methods for deriving static vector representations of words from the contextual representations given by models like BERT and RoBERTa. The methods are due to [Bommasani et al. 2020](https://www.aclweb.org/anthology/2020.acl-main.431). The simplest of these methods involves processing the words as independent texts and pooling the sub-word representations that result, using a function like mean or max.\n\nYour task: write a function `evaluate_pooled_bert` that will enable exploration of this approach. The function should do the following:\n\n1. Take as its arguments (a) a word relatedness `pd.DataFrame` `rel_df` (e.g., `dev_df`), (b) a `layer` index (see below), and (c) a `pool_func` value (see below).\n1. Set up a BERT tokenizer and BERT model based on `'bert-base-uncased'`.\n1. Use `vsm.create_subword_pooling_vsm` to create a VSM (a `pd.DataFrame`) with the user's values for `layer` and `pool_func`.\n1. Return the return value of `vsm.word_relatedness_evaluation` using this new VSM, evaluated on `rel_df` with `distfunc` set to its default value.\n\nThe function `vsm.create_subword_pooling_vsm` does the heavy-lifting. Your task is really just to put these pieces together. The result will be the start of a flexible framework for seeing how these methods do on our task. \n\nThe function `test_evaluate_pooled_bert` can help you obtain the design we are seeking.",
"_____no_output_____"
]
],
[
[
"from transformers import BertModel, BertTokenizer\n\ndef evaluate_pooled_bert(rel_df, layer, pool_func):\n bert_weights_name = 'bert-base-uncased'\n\n # Initialize a BERT tokenizer and BERT model based on\n # `bert_weights_name`:\n ##### YOUR CODE HERE\n\n\n # Get the vocabulary from `rel_df`:\n ##### YOUR CODE HERE\n\n\n # Use `vsm.create_subword_pooling_vsm` with the user's arguments:\n ##### YOUR CODE HERE\n\n # Return the results of the relatedness evalution:\n ##### YOUR CODE HERE\n",
"_____no_output_____"
],
[
"def test_evaluate_pooled_bert(func):\n import torch\n rel_df = pd.DataFrame([\n {'word1': 'porcupine', 'word2': 'capybara', 'score': 0.6},\n {'word1': 'antelope', 'word2': 'springbok', 'score': 0.5},\n {'word1': 'llama', 'word2': 'camel', 'score': 0.4},\n {'word1': 'movie', 'word2': 'play', 'score': 0.3}])\n layer = 2\n pool_func = vsm.max_pooling\n pred_df, rho = evaluate_pooled_bert(rel_df, layer, pool_func)\n rho = round(rho, 2)\n expected_rho = 0.40\n assert rho == expected_rho, \\\n \"Expected rho={}; got rho={}\".format(expected_rho, rho)",
"_____no_output_____"
],
[
"if 'IS_GRADESCOPE_ENV' not in os.environ:\n test_evaluate_pooled_bert(evaluate_pooled_bert)",
"_____no_output_____"
]
],
[
[
"### Learned distance functions [2 points]",
"_____no_output_____"
],
[
"The presentation thus far leads one to assume that the `distfunc` argument used in the experiments will be a standard vector distance function like `vsm.cosine` or `vsm.euclidean`. However, the framework itself simply requires that this function map two fixed-dimensional vectors to a real number. This opens up a world of possibilities. This question asks you to dip a toe in these waters.\n\nYour task: write a function `run_knn_score_model` for models in this class. The function should:\n\n1. Take as its arguments (a) a VSM dataframe `vsm_df`, (b) a relatedness dataset (e.g., `dev_df`), and (c) a `test_size` value between 0.0 and 1.0 that can be passed directly to `train_test_split` (see below).\n1. Create a feature matrix `X`: each word pair in `dev_df` should be represented by the concatenation of the vectors for word1 and word2 from `vsm_df`.\n1. Create a score vector `y`, which is just the `score` column in `dev_df`.\n1. Split the dataset `(X, y)` into train and test portions using [sklearn.model_selection.train_test_split](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html).\n1. Train an [sklearn.neighbors.KNeighborsRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsRegressor.html#sklearn.neighbors.KNeighborsRegressor) model on the train split from step 4, with default hyperparameters.\n1. Return the value of the `score` method of the trained `KNeighborsRegressor` model on the test split from step 4.\n\nThe functions `test_knn_feature_matrix` and `knn_represent` will help you test the crucial representational aspects of this.\n\nNote: if you decide to apply this approach to our task as part of an original system, recall that `vsm.create_subword_pooling_vsm` returns `-d` where `d` is the value computed by `distfunc`, since it assumes that `distfunc` is a distance value of some kind rather than a relatedness/similarity value. Since most regression models will return positive scores for positive associations, you will probably want to undo this by having your `distfunc` return the negative of its value.",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsRegressor\n\ndef run_knn_score_model(vsm_df, dev_df, test_size=0.20):\n pass\n\n # Complete `knn_feature_matrix` for this step.\n ##### YOUR CODE HERE\n\n\n # Get the values of the 'score' column in `dev_df`\n # and store them in a list or array `y`.\n ##### YOUR CODE HERE\n\n\n # Use `train_test_split` to split (X, y) into train and\n # test protions, with `test_size` as the test size.\n ##### YOUR CODE HERE\n\n\n # Instantiate a `KNeighborsRegressor` with default arguments:\n ##### YOUR CODE HERE\n\n # Fit the model on the training data:\n ##### YOUR CODE HERE\n\n\n # Return the value of `score` for your model on the test split\n # you created above:\n ##### YOUR CODE HERE\n\n\ndef knn_feature_matrix(vsm_df, rel_df):\n pass\n # Complete `knn_represent` and use it to create a feature\n # matrix `np.array`:\n ##### YOUR CODE HERE\n\n\ndef knn_represent(word1, word2, vsm_df):\n pass\n # Use `vsm_df` to get vectors for `word1` and `word2`\n # and concatenate them into a single vector:\n ##### YOUR CODE HERE\n\n",
"_____no_output_____"
],
[
"def test_knn_feature_matrix(func):\n rel_df = pd.DataFrame([\n {'word1': 'w1', 'word2': 'w2', 'score': 0.1},\n {'word1': 'w1', 'word2': 'w3', 'score': 0.2}])\n vsm_df = pd.DataFrame([\n [1, 2, 3.],\n [4, 5, 6.],\n [7, 8, 9.]], index=['w1', 'w2', 'w3'])\n expected = np.array([\n [1, 2, 3, 4, 5, 6.],\n [1, 2, 3, 7, 8, 9.]])\n result = func(vsm_df, rel_df)\n assert np.array_equal(result, expected), \\\n \"Your `knn_feature_matrix` returns: {}\\nWe expect: {}\".format(\n result, expected)\n\ndef test_knn_represent(func):\n vsm_df = pd.DataFrame([\n [1, 2, 3.],\n [4, 5, 6.],\n [7, 8, 9.]], index=['w1', 'w2', 'w3'])\n result = func('w1', 'w3', vsm_df)\n expected = np.array([1, 2, 3, 7, 8, 9.])\n assert np.array_equal(result, expected), \\\n \"Your `knn_represent` returns: {}\\nWe expect: {}\".format(\n result, expected)",
"_____no_output_____"
],
[
"if 'IS_GRADESCOPE_ENV' not in os.environ:\n test_knn_represent(knn_represent)\n test_knn_feature_matrix(knn_feature_matrix)",
"_____no_output_____"
]
],
[
[
"### Your original system [3 points]\n\nThis question asks you to design your own model. You can of course include steps made above (ideally, the above questions informed your system design!), but your model should not be literally identical to any of the above models. Other ideas: retrofitting, autoencoders, GloVe, subword modeling, ... \n\nRequirements:\n\n1. Your system must work with `vsm.word_relatedness_evaluation`. You are free to specify the VSM and the value of `distfunc`.\n\n1. Your code must be self-contained, so that we can work with your model directly in your homework submission notebook. If your model depends on external data or other resources, please submit a ZIP archive containing these resources along with your submission.\n\nIn the cell below, please provide a brief technical description of your original system, so that the teaching team can gain an understanding of what it does. This will help us to understand your code and analyze all the submissions to identify patterns and strategies. We also ask that you report the best score your system got during development, just to help us understand how systems performed overall.",
"_____no_output_____"
]
],
[
[
"# PLEASE MAKE SURE TO INCLUDE THE FOLLOWING BETWEEN THE START AND STOP COMMENTS:\n# 1) Textual description of your system.\n# 2) The code for your original system.\n# 3) The score achieved by your system in place of MY_NUMBER.\n# With no other changes to that line.\n# You should report your score as a decimal value <=1.0\n# PLEASE MAKE SURE NOT TO DELETE OR EDIT THE START AND STOP COMMENTS\n\n# NOTE: MODULES, CODE AND DATASETS REQUIRED FOR YOUR ORIGINAL SYSTEM\n# SHOULD BE ADDED BELOW THE 'IS_GRADESCOPE_ENV' CHECK CONDITION. DOING\n# SO ABOVE THE CHECK MAY CAUSE THE AUTOGRADER TO FAIL.\n\n# START COMMENT: Enter your system description in this cell.\n# My peak score was: MY_NUMBER\nif 'IS_GRADESCOPE_ENV' not in os.environ:\n pass\n\n# STOP COMMENT: Please do not remove this comment.",
"_____no_output_____"
]
],
[
[
"## Bake-off [1 point]\n\nFor the bake-off, you simply need to evaluate your original system on the file \n\n`vsmdata/cs224u-wordrelatedness-bakeoff-test-unlabeled.csv`\n\nThis contains only word pairs (no scores), so `vsm.word_relatedness_evaluation` will simply make predictions without doing any scoring. Use that function to make predictions with your original system, store the resulting `pred_df` to a file, and then upload the file as your bake-off submission.\n\nThe following function should be used to conduct this evaluation:",
"_____no_output_____"
]
],
[
[
"def create_bakeoff_submission(\n vsm_df,\n distfunc,\n output_filename=\"cs224u-wordrelatedness-bakeoff-entry.csv\"):\n\n test_df = pd.read_csv(\n os.path.join(DATA_HOME, \"cs224u-wordrelatedness-test-unlabeled.csv\"))\n\n pred_df, _ = vsm.word_relatedness_evaluation(test_df, vsm_df, distfunc=distfunc)\n\n pred_df.to_csv(output_filename)",
"_____no_output_____"
]
],
[
[
"For example, if `count_df` were the VSM for my system, and I wanted my distance function to be `vsm.euclidean`, I would do",
"_____no_output_____"
]
],
[
[
"create_bakeoff_submission(count_df, vsm.euclidean)",
"_____no_output_____"
]
],
[
[
"This creates a file `cs224u-wordrelatedness-bakeoff-entry.csv` in the current directory. That file should be uploaded as-is. Please do not change its name.\n\nOnly one upload per team is permitted, and you should do no tuning of your system based on what you see in `pred_df` – you should not study that file in anyway, beyond perhaps checking that it contains what you expected it to contain. The upload function will do some additional checking to ensure that your file is well-formed.\n\nPeople who enter will receive the additional homework point, and people whose systems achieve the top score will receive an additional 0.5 points. We will test the top-performing systems ourselves, and only systems for which we can reproduce the reported results will win the extra 0.5 points.\n\nLate entries will be accepted, but they cannot earn the extra 0.5 points.",
"_____no_output_____"
],
[
"## Submission Instruction\n\nSubmit the following files to gradescope submission\n\n- Please do not change the file name as described below\n- `hw_wordrelatedness.ipynb` (this notebook)\n- `cs224u-wordrelatedness-bakeoff-entry.csv` (bake-off output)\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
4aa810d4b85b6bdd5a9688eb4cc708e44769d0e8
| 65,085 |
ipynb
|
Jupyter Notebook
|
applications/microglia_analysis.ipynb
|
theislab/scCODA_reproducibility
|
15b5f4a7ef1d8b3a287e63019ed3007d5d5081d4
|
[
"MIT"
] | 5 |
2021-01-24T19:45:28.000Z
|
2022-03-15T12:13:34.000Z
|
applications/microglia_analysis.ipynb
|
theislab/scCODA_reproducibility
|
15b5f4a7ef1d8b3a287e63019ed3007d5d5081d4
|
[
"MIT"
] | 1 |
2022-03-31T14:40:07.000Z
|
2022-03-31T14:40:07.000Z
|
applications/microglia_analysis.ipynb
|
theislab/scCODA_reproducibility
|
15b5f4a7ef1d8b3a287e63019ed3007d5d5081d4
|
[
"MIT"
] | 1 |
2020-12-19T05:23:12.000Z
|
2020-12-19T05:23:12.000Z
| 79.858896 | 27,215 | 0.656926 |
[
[
[
"# Analysis of Microglia data\n",
"_____no_output_____"
]
],
[
[
"# Setup\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n\nfrom sccoda.util import comp_ana as mod\nfrom sccoda.util import cell_composition_data as dat\nfrom sccoda.model import other_models as om",
"_____no_output_____"
]
],
[
[
"Load and format data: \n\n4 control samples, 2 samples for other conditions each; 8 cell types",
"_____no_output_____"
]
],
[
[
"cell_counts = pd.read_csv(\"../../sccoda_benchmark_data/cell_count_microglia_AD_WT_location.csv\", index_col=0)\n# Sort values such that wild type is considered the base category\nprint(cell_counts)\n\ndata_cer = dat.from_pandas(cell_counts.loc[cell_counts[\"location\"] == \"cerebellum\"], \n covariate_columns=[\"mouse_type\", \"location\", \"replicate\"])\ndata_cor = dat.from_pandas(cell_counts.loc[cell_counts[\"location\"] == \"cortex\"], \n covariate_columns=[\"mouse_type\", \"location\", \"replicate\"])",
" mouse_type location replicate microglia 1 microglia 2 microglia 3\n0 AD cerebellum mouse1 709 5 2\n1 AD cerebellum mouse2 715 7 6\n2 AD cortex mouse1 834 19 59\n3 AD cortex mouse2 794 16 100\n4 WT cerebellum mouse1 449 3 2\n5 WT cerebellum mouse2 424 3 4\n6 WT cortex mouse1 412 0 0\n7 WT cortex mouse2 581 1 1\n"
]
],
[
[
"Plot data:",
"_____no_output_____"
]
],
[
[
"# Count data to ratios\ncounts = cell_counts.iloc[:, 3:]\nrowsum = np.sum(counts, axis=1)\n\nratios = counts.div(rowsum, axis=0)\nratios[\"mouse_type\"] = cell_counts[\"mouse_type\"]\nratios[\"location\"] = cell_counts[\"location\"]\n\n# Make boxplots\nfig, ax = plt.subplots(figsize=(12,5), ncols=3)\ndf = pd.melt(ratios, id_vars=['location', \"mouse_type\"], value_vars=ratios.columns[:3])\ndf = df.sort_values([\"location\", \"mouse_type\"], ascending=[True, False])\nprint(df)\nsns.set_context('notebook')\nsns.set_style('ticks')\nfor i in range(3):\n d = sns.boxplot(x='location', y = 'value', hue=\"mouse_type\",\n data=df.loc[df[\"variable\"]==f\"microglia {i+1}\"], fliersize=1,\n palette='Blues', ax=ax[i])\n\n d.set_ylabel('Proportion')\n loc, labels = plt.xticks()\n d.set_xlabel('Location')\n d.set_title(f\"microglia {i+1}\")\nplt.legend(bbox_to_anchor=(1.33, 1), borderaxespad=0., title=\"Condition\")\n\n# plt.savefig(plot_path + \"haber_boxes_blue.svg\", format=\"svg\", bbox_inches=\"tight\")\n# plt.savefig(plot_path + \"haber_boxes_blue.png\", format=\"png\", bbox_inches=\"tight\")\n\nplt.show()",
" location mouse_type variable value\n4 cerebellum WT microglia 1 0.988987\n5 cerebellum WT microglia 1 0.983759\n12 cerebellum WT microglia 2 0.006608\n13 cerebellum WT microglia 2 0.006961\n20 cerebellum WT microglia 3 0.004405\n21 cerebellum WT microglia 3 0.009281\n0 cerebellum AD microglia 1 0.990223\n1 cerebellum AD microglia 1 0.982143\n8 cerebellum AD microglia 2 0.006983\n9 cerebellum AD microglia 2 0.009615\n16 cerebellum AD microglia 3 0.002793\n17 cerebellum AD microglia 3 0.008242\n6 cortex WT microglia 1 1.000000\n7 cortex WT microglia 1 0.996569\n14 cortex WT microglia 2 0.000000\n15 cortex WT microglia 2 0.001715\n22 cortex WT microglia 3 0.000000\n23 cortex WT microglia 3 0.001715\n2 cortex AD microglia 1 0.914474\n3 cortex AD microglia 1 0.872527\n10 cortex AD microglia 2 0.020833\n11 cortex AD microglia 2 0.017582\n18 cortex AD microglia 3 0.064693\n19 cortex AD microglia 3 0.109890\n"
]
],
[
[
"Analyze cerebellum data:\nApply scCODA for every cell type set as the reference.\n\nWe see no credible effects at the 0.2 FDR level.",
"_____no_output_____"
]
],
[
[
"# Use this formula to make a wild type -> treated comparison, not the other way\nformula = \"C(mouse_type, levels=['WT', 'AD'])\"\n\n\n# cerebellum\nres_cer = []\neffects_cer = pd.DataFrame(index=data_cer.var.index.copy(),\n columns=data_cer.var.index.copy())\neffects_cer.index.rename(\"cell type\", inplace=True)\neffects_cer.columns.rename(\"reference\", inplace=True)\n\nfor ct in data_cer.var.index:\n print(f\"Reference: {ct}\")\n \n model = mod.CompositionalAnalysis(data=data_cer, formula=formula, reference_cell_type=ct)\n results = model.sample_hmc()\n _, effect_df = results.summary_prepare(est_fdr=0.2)\n res_cer.append(results)\n effects_cer[ct] = effect_df.loc[:, \"Final Parameter\"].array\n ",
"Reference: microglia 1\nWARNING:tensorflow:7 out of the last 7 calls to <function CompositionalModel.sampling.<locals>.sample_mcmc at 0x7fb786b398b0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nMCMC sampling finished. (57.881 sec)\nAcceptance rate: 46.8%\nReference: microglia 2\nWARNING:tensorflow:8 out of the last 8 calls to <function CompositionalModel.sampling.<locals>.sample_mcmc at 0x7fb783ddc280> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nMCMC sampling finished. (54.892 sec)\nAcceptance rate: 54.0%\nReference: microglia 3\nWARNING:tensorflow:9 out of the last 9 calls to <function CompositionalModel.sampling.<locals>.sample_mcmc at 0x7fb786b21dc0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nMCMC sampling finished. (55.403 sec)\nAcceptance rate: 54.8%\n"
],
[
"# Column: Reference category\n# Row: Effect\nprint(effects_cer)",
"reference microglia 1 microglia 2 microglia 3\ncell type \nmicroglia 1 0.0 0.0 0.0\nmicroglia 2 0.0 0.0 0.0\nmicroglia 3 0.0 0.0 0.0\n"
],
[
"for x in res_cer:\n print(x.summary_extended())\n ",
"Compositional Analysis summary (extended):\n\nData: 4 samples, 3 cell types\nReference index: 0\nFormula: C(mouse_type, levels=['WT', 'AD'])\nSpike-and-slab threshold: 1.000\n\nMCMC Sampling: Sampled 20000 chain states (5000 burnin samples) in 57.881 sec. Acceptance rate: 46.8%\n\nIntercepts:\n Final Parameter HDI 3% HDI 97% SD Expected Sample\nCell Type \nmicroglia 1 7.764 5.162 10.527 1.532 574.413721\nmicroglia 2 2.878 0.289 5.662 1.528 4.337725\nmicroglia 3 2.663 0.004 5.440 1.528 3.498555\n\n\nEffects:\n Final Parameter HDI 3% \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.0 0.000 \n microglia 2 0.0 -0.605 \n microglia 3 0.0 -0.836 \n\n HDI 97% SD \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.000 0.000 \n microglia 2 0.862 0.256 \n microglia 3 0.744 0.272 \n\n Inclusion probability \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.000000 \n microglia 2 0.444333 \n microglia 3 0.456533 \n\n Expected Sample \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 574.413721 \n microglia 2 4.337725 \n microglia 3 3.498555 \n\n log2-fold change \nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.0 \n microglia 2 0.0 \n microglia 3 0.0 \nNone\nCompositional Analysis summary (extended):\n\nData: 4 samples, 3 cell types\nReference index: 1\nFormula: C(mouse_type, levels=['WT', 'AD'])\nSpike-and-slab threshold: 1.000\n\nMCMC Sampling: Sampled 20000 chain states (5000 burnin samples) in 54.892 sec. Acceptance rate: 54.0%\n\nIntercepts:\n Final Parameter HDI 3% HDI 97% SD Expected Sample\nCell Type \nmicroglia 1 7.669 5.026 10.177 1.389 574.334813\nmicroglia 2 2.806 0.254 5.376 1.383 4.438039\nmicroglia 3 2.562 -0.037 5.027 1.376 3.477148\n\n\nEffects:\n Final Parameter HDI 3% \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.0 -0.529 \n microglia 2 0.0 0.000 \n microglia 3 0.0 -0.858 \n\n HDI 97% SD \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.564 0.186 \n microglia 2 0.000 0.000 \n microglia 3 0.686 0.270 \n\n Inclusion probability \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.426267 \n microglia 2 0.000000 \n microglia 3 0.471267 \n\n Expected Sample \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 574.334813 \n microglia 2 4.438039 \n microglia 3 3.477148 \n\n log2-fold change \nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.0 \n microglia 2 0.0 \n microglia 3 0.0 \nNone\nCompositional Analysis summary (extended):\n\nData: 4 samples, 3 cell types\nReference index: 2\nFormula: C(mouse_type, levels=['WT', 'AD'])\nSpike-and-slab threshold: 1.000\n\nMCMC Sampling: Sampled 20000 chain states (5000 burnin samples) in 55.403 sec. Acceptance rate: 54.8%\n\nIntercepts:\n Final Parameter HDI 3% HDI 97% SD Expected Sample\nCell Type \nmicroglia 1 7.702 5.209 10.327 1.382 574.541547\nmicroglia 2 2.806 0.266 5.313 1.368 4.295519\nmicroglia 3 2.576 0.155 5.206 1.377 3.412934\n\n\nEffects:\n Final Parameter HDI 3% \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.0 -0.607 \n microglia 2 0.0 -0.719 \n microglia 3 0.0 0.000 \n\n HDI 97% SD \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.623 0.199 \n microglia 2 0.851 0.261 \n microglia 3 0.000 0.000 \n\n Inclusion probability \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.392733 \n microglia 2 0.448600 \n microglia 3 0.000000 \n\n Expected Sample \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 574.541547 \n microglia 2 4.295519 \n microglia 3 3.412934 \n\n log2-fold change \nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.0 \n microglia 2 0.0 \n microglia 3 0.0 \nNone\n"
]
],
[
[
"Now with cortex data:\n\nWe see credible effects on all cell types, depending on the reference.\nOnly the effects on microglia 2 and 3 when using the other one as the reference are not considered credible at the 0.2 FDR level.",
"_____no_output_____"
]
],
[
[
"# cortex\nres_cor = []\neffects_cor = pd.DataFrame(index=data_cor.var.index.copy(),\n columns=data_cor.var.index.copy())\neffects_cor.index.rename(\"cell type\", inplace=True)\neffects_cor.columns.rename(\"reference\", inplace=True)\n\nfor ct in data_cer.var.index:\n print(f\"Reference: {ct}\")\n \n model = mod.CompositionalAnalysis(data=data_cor, formula=formula, reference_cell_type=ct)\n results = model.sample_hmc()\n _, effect_df = results.summary_prepare(est_fdr=0.2)\n res_cor.append(results)\n effects_cor[ct] = effect_df.loc[:, \"Final Parameter\"].array\n ",
"Reference: microglia 1\nZero counts encountered in data! Added a pseudocount of 0.5.\nMCMC sampling finished. (55.426 sec)\nAcceptance rate: 46.1%\nReference: microglia 2\nZero counts encountered in data! Added a pseudocount of 0.5.\nWARNING:tensorflow:5 out of the last 5 calls to <function CompositionalModel.sampling.<locals>.sample_mcmc at 0x7fb787772d30> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nMCMC sampling finished. (54.388 sec)\nAcceptance rate: 43.3%\nReference: microglia 3\nZero counts encountered in data! Added a pseudocount of 0.5.\nWARNING:tensorflow:6 out of the last 6 calls to <function CompositionalModel.sampling.<locals>.sample_mcmc at 0x7fb77370ad30> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for more details.\nMCMC sampling finished. (53.308 sec)\nAcceptance rate: 51.2%\n"
],
[
"# Column: Reference category\n# Row: Effect\neffects_cor.index.name = \"cell type\"\neffects_cor.columns.name = \"reference\"\nprint(effects_cor)",
"reference microglia 1 microglia 2 microglia 3\ncell type \nmicroglia 1 0.000000 -2.807754 -3.563174\nmicroglia 2 1.692587 0.000000 0.000000\nmicroglia 3 2.892039 0.000000 0.000000\n"
],
[
"for x in res_cor:\n print(x.summary_extended())",
"Compositional Analysis summary (extended):\n\nData: 4 samples, 3 cell types\nReference index: 0\nFormula: C(mouse_type, levels=['WT', 'AD'])\nSpike-and-slab threshold: 0.775\n\nMCMC Sampling: Sampled 20000 chain states (5000 burnin samples) in 55.426 sec. Acceptance rate: 46.1%\n\nIntercepts:\n Final Parameter HDI 3% HDI 97% SD Expected Sample\nCell Type \nmicroglia 1 4.956 2.549 7.503 1.443 697.133635\nmicroglia 2 -0.312 -1.982 1.239 0.872 3.592963\nmicroglia 3 -0.263 -1.888 1.494 0.902 3.773403\n\n\nEffects:\n Final Parameter HDI 3% \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.0 0.000 \n microglia 2 0.0 -0.126 \n microglia 3 0.0 0.005 \n\n HDI 97% SD \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.000 0.000 \n microglia 2 3.350 1.124 \n microglia 3 4.452 1.307 \n\n Inclusion probability \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.000000 \n microglia 2 0.775667 \n microglia 3 0.949200 \n\n Expected Sample \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 697.133635 \n microglia 2 3.592963 \n microglia 3 3.773403 \n\n log2-fold change \nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.0 \n microglia 2 0.0 \n microglia 3 0.0 \nNone\nCompositional Analysis summary (extended):\n\nData: 4 samples, 3 cell types\nReference index: 1\nFormula: C(mouse_type, levels=['WT', 'AD'])\nSpike-and-slab threshold: 0.964\n\nMCMC Sampling: Sampled 20000 chain states (5000 burnin samples) in 54.388 sec. Acceptance rate: 43.3%\n\nIntercepts:\n Final Parameter HDI 3% HDI 97% SD Expected Sample\nCell Type \nmicroglia 1 7.179 3.893 9.571 1.459 701.514298\nmicroglia 2 0.769 -1.140 2.249 0.922 1.154008\nmicroglia 3 1.231 -1.185 3.451 1.220 1.831694\n\n\nEffects:\n Final Parameter HDI 3% \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 -2.807754 -4.611 \n microglia 2 0.000000 0.000 \n microglia 3 0.000000 -0.314 \n\n HDI 97% SD \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 -1.021 1.103 \n microglia 2 0.000 0.000 \n microglia 3 3.212 1.041 \n\n Inclusion probability \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.964333 \n microglia 2 0.000000 \n microglia 3 0.554200 \n\n Expected Sample \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 658.082454 \n microglia 2 17.940914 \n microglia 3 28.476632 \n\n log2-fold change \nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 -0.092204 \n microglia 2 3.958528 \n microglia 3 3.958528 \nNone\nCompositional Analysis summary (extended):\n\nData: 4 samples, 3 cell types\nReference index: 2\nFormula: C(mouse_type, levels=['WT', 'AD'])\nSpike-and-slab threshold: 0.999\n\nMCMC Sampling: Sampled 20000 chain states (5000 burnin samples) in 53.308 sec. Acceptance rate: 51.2%\n\nIntercepts:\n Final Parameter HDI 3% HDI 97% SD Expected Sample\nCell Type \nmicroglia 1 8.219 6.046 10.315 1.142 702.147344\nmicroglia 2 1.154 -0.829 3.006 0.996 0.599981\nmicroglia 3 2.226 0.347 3.908 1.002 1.752675\n\n\nEffects:\n Final Parameter HDI 3% \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 -3.563174 -4.852 \n microglia 2 0.000000 -2.393 \n microglia 3 0.000000 0.000 \n\n HDI 97% SD \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 -2.196 0.717 \n microglia 2 1.493 0.773 \n microglia 3 0.000 0.000 \n\n Inclusion probability \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 0.999867 \n microglia 2 0.435533 \n microglia 3 0.000000 \n\n Expected Sample \\\nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 630.033512 \n microglia 2 18.990662 \n microglia 3 55.475827 \n\n log2-fold change \nCovariate Cell Type \nC(mouse_type, levels=['WT', 'AD'])[T.AD] microglia 1 -0.156345 \n microglia 2 4.984229 \n microglia 3 4.984229 \nNone\n"
]
],
[
[
"For validataion, apply ancom to the same dataset.\nWe see also no changes for the cerebellum data, and change in all microglia types for the cortex data.",
"_____no_output_____"
]
],
[
[
"cer_ancom = data_cer.copy()\ncer_ancom.obs = cer_ancom.obs.rename(columns={\"mouse_type\": \"x_0\"})\nancom_cer = om.AncomModel(cer_ancom)\nancom_cer.fit_model(alpha=0.2)\nprint(ancom_cer.ancom_out)\n\ncor_ancom = data_cor.copy()\ncor_ancom.obs = cor_ancom.obs.rename(columns={\"mouse_type\": \"x_0\"})\ncor_ancom.X = cor_ancom.X + 0.5\nancom_cor = om.AncomModel(cor_ancom)\nancom_cor.fit_model(alpha=0.2)\nprint(ancom_cor.ancom_out)",
"( W Reject null hypothesis\nmicroglia 1 0 False\nmicroglia 2 0 False\nmicroglia 3 0 False, Percentile 0.0 25.0 50.0 75.0 100.0 0.0 25.0 50.0 75.0 \\\nGroup AD AD AD AD AD WT WT WT WT \nmicroglia 1 709.0 710.5 712.0 713.5 715.0 424.0 430.25 436.5 442.75 \nmicroglia 2 5.0 5.5 6.0 6.5 7.0 3.0 3.00 3.0 3.00 \nmicroglia 3 2.0 3.0 4.0 5.0 6.0 2.0 2.50 3.0 3.50 \n\nPercentile 100.0 \nGroup WT \nmicroglia 1 449.0 \nmicroglia 2 3.0 \nmicroglia 3 4.0 )\n( W Reject null hypothesis\nmicroglia 1 2 True\nmicroglia 2 2 True\nmicroglia 3 2 True, Percentile 0.0 25.0 50.0 75.0 100.0 0.0 25.0 50.0 \\\nGroup AD AD AD AD AD WT WT WT \nmicroglia 1 794.5 804.50 814.5 824.50 834.5 412.5 454.75 497.0 \nmicroglia 2 16.5 17.25 18.0 18.75 19.5 0.5 0.75 1.0 \nmicroglia 3 59.5 69.75 80.0 90.25 100.5 0.5 0.75 1.0 \n\nPercentile 75.0 100.0 \nGroup WT WT \nmicroglia 1 539.25 581.5 \nmicroglia 2 1.25 1.5 \nmicroglia 3 1.25 1.5 )\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aa8119ce053fe13561bee12607f13cbfebe47ec
| 345,205 |
ipynb
|
Jupyter Notebook
|
Law-of-Large-Numbers/Law_of_Large_Numbers.ipynb
|
npinak/Python-Projects
|
6e6463f4fde175fde60c9cca045e3c114b854505
|
[
"MIT"
] | 1 |
2021-10-16T16:22:14.000Z
|
2021-10-16T16:22:14.000Z
|
Law-of-Large-Numbers/Law_of_Large_Numbers.ipynb
|
npinak/Python-Projects
|
6e6463f4fde175fde60c9cca045e3c114b854505
|
[
"MIT"
] | null | null | null |
Law-of-Large-Numbers/Law_of_Large_Numbers.ipynb
|
npinak/Python-Projects
|
6e6463f4fde175fde60c9cca045e3c114b854505
|
[
"MIT"
] | null | null | null | 76.474302 | 92,790 | 0.619499 |
[
[
[
"# A project that shows the law of large numbers\n",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport numpy as np \nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"# **Generating a population of random numbers**",
"_____no_output_____"
]
],
[
[
"# Creating 230,000 random numbers in a 1/f distribution\n\n\nrandint = np.logspace(np.log10(0.001),np.log10(100),230000)\n\nfdist = np.zeros(230000)\n\nfor i in range(len(randint)):\n fdist[i] = 1/randint[i]\n if fdist[i]< 0:\n print(fdist[i])\n\nfdist[:40]",
"_____no_output_____"
],
[
"# Only taking every 1000th entry in fdist\nfdist1000 = fdist[0::1000]\n\nfdist1000[:40]",
"_____no_output_____"
],
[
"#Sorting the array in descending order\nfdist1000[::-1].sort()\nfdist1000[1]",
"_____no_output_____"
],
[
"#Creating the index\nindex = np.zeros(len(fdist1000))\n\nfor i in range(len(fdist1000)):\n index[i] = i+1\n\nindex[:40]",
"_____no_output_____"
],
[
"# Graphing the random numbers \n\nplt.plot(index,fdist1000, 'go--')\nplt.xlabel('Sample')\nplt.ylabel('Data Value')\nplt.show()",
"_____no_output_____"
],
[
"# Shuffling fdist1000\n\nshuffledist = fdist1000.copy()\n\nnp.random.shuffle(shuffledist)\n\nplt.plot(index,shuffledist, 'go')\nplt.xlabel('Sample')\nplt.ylabel('Data Value')\nplt.show()",
"_____no_output_____"
]
],
[
[
"# **Monte Carlo sampling**",
"_____no_output_____"
]
],
[
[
"### Randomly selecting 50 of the 230000 data points. Finding the mean. Repeat this 500 times. ###\n\n\nmean = np.zeros(500)\n\nfor i in range(len(mean)):\n fifty = np.random.choice(fdist, size=50, replace=False)\n mean[i] = np.mean(fifty) \n\nmean[:100]\n",
"_____no_output_____"
],
[
"# Calculating the real average \n\nrealmean = sum(fdist)/len(fdist)\n\nprint(realmean)",
"86.85982410100492\n"
],
[
"# Creating the index for mean to plot\nmeanindex = np.zeros(len(mean))\n\nfor i in range(len(mean)):\n meanindex[i] = i+1\n\nmeanindex[:40]\n",
"_____no_output_____"
],
[
"# Plotting the Monte-Carlo sampling \n\nplt.plot(meanindex,mean, 'ko',markerfacecolor='c' , label = 'Sample Means')\nplt.axhline(y=realmean, color='r', linewidth='3', linestyle='-', label = 'True Mean')\nplt.xlabel('Sample Number')\nplt.ylabel('Mean Value')\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"# **Cumulative averaging**",
"_____no_output_____"
]
],
[
[
"# Cumulative average of all sample means\n\ncumemean = np.zeros(500)\ncumesum = np.zeros(500)\nlength = len(mean)\n\nfor i in range(length):\n cumesum[i] = np.sum(mean[:i+1])\n #if i == 0:\n #cumemean[i] = cumesum[i]/(i+1)\n #else:\n cumemean[i] = cumesum[i] / (i+1)\n\n",
"_____no_output_____"
],
[
"# Creating the index for cumulative mean to plot\ncumemeanindex = np.zeros(len(cumemean))\n\nfor i in range(len(cumemean)):\n cumemeanindex[i] = i+1\n\ncumemeanindex[-1]",
"_____no_output_____"
],
[
"# Plotting of the Cumulative Average\n\nplt.plot(cumemeanindex,cumemean, 'bo',markerfacecolor='w' , label = 'Cumulative Averages')\nplt.axhline(y=realmean, color='r', linewidth='3', linestyle='-', label = 'True Mean')\nplt.xlabel('Sample Number')\nplt.ylabel('Mean Value')\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"### Computing the square divergence for each point. Repeating 100 times ###\n\ndfdivergence = pd.DataFrame(cumemean, columns = ['Original Cumulative Mean Run 1'])\n",
"_____no_output_____"
],
[
"# Finding the square divergence from mean (realmean) for the first run\n\ndivergence1 = (dfdivergence[\"Original Cumulative Mean Run 1\"] - realmean)**2",
"_____no_output_____"
],
[
"divergence1[:20]",
"_____no_output_____"
],
[
"dfdivergence['Square Divergence 1'] = divergence1",
"_____no_output_____"
],
[
"dfdivergence\n",
"_____no_output_____"
],
[
"dfmeans = pd.DataFrame()\n\nfor i in range(99):\n dfmeans[i] = np.zeros(500)\n\n",
"_____no_output_____"
],
[
"# (Sampling 50 random point 500 times) for 100 runs. \nfor i in range(99):\n for j in range(500):\n dffifty = np.random.choice(fdist, size=50, replace=False)\n tempmean = np.mean(dffifty) \n dfmeans.at[j, i] = tempmean\n",
"_____no_output_____"
],
[
"dfmeans[:5]",
"_____no_output_____"
],
[
"dfcumemean = pd.DataFrame()\ndfcumesum = pd.DataFrame()\n\n\ndfcumesum = dfmeans.cumsum(axis=0) # Finding the cumulative sum down each column\n\n\n\n",
"_____no_output_____"
],
[
"dfcumesum",
"_____no_output_____"
],
[
"for i in range(99):\n for j in range(500):\n dfcumemean.at[j,i] = dfcumesum.at[j,i]/(j+1) # Finding the cumulative mean down each column\n",
"_____no_output_____"
],
[
"dfcumemean",
"_____no_output_____"
],
[
"for i in range(99):\n dfdivergence['Square Divergence' + ' ' + str(i+2)] = (dfcumemean[i] - realmean)**2 # finding the divergence down each column",
"_____no_output_____"
],
[
"dfdivergence[:4]",
"_____no_output_____"
],
[
"dfdivergence = dfdivergence.drop(['Original Cumulative Mean Run 1'], axis=1)\n\ndfdivergence[:4]",
"_____no_output_____"
],
[
"dfdivergence.plot(figsize = (12,7), legend=False) # This plot shows the divergence from the real mean for 100 runs of cumulative averaging. \nplt.ylim([-10,500])\nplt.ylabel('Square Divergence from True Mean')\nplt.xlabel('Sample Number')\n\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aa81a4f67747ccf36c8ff04a771eedf182e660d
| 605,879 |
ipynb
|
Jupyter Notebook
|
docs/source/notebooks/GLM-robust-with-outlier-detection.ipynb
|
rsumner31/pymc3-23
|
539c0fc04c196679a1cdcbf4bc2dbea4dee10080
|
[
"Apache-2.0"
] | 1 |
2019-03-01T02:47:20.000Z
|
2019-03-01T02:47:20.000Z
|
docs/source/notebooks/GLM-robust-with-outlier-detection.ipynb
|
rsumner31/pymc3-23
|
539c0fc04c196679a1cdcbf4bc2dbea4dee10080
|
[
"Apache-2.0"
] | 1 |
2019-08-17T06:58:38.000Z
|
2019-08-17T06:58:38.000Z
|
docs/source/notebooks/GLM-robust-with-outlier-detection.ipynb
|
rsumner31/pymc3-23
|
539c0fc04c196679a1cdcbf4bc2dbea4dee10080
|
[
"Apache-2.0"
] | null | null | null | 687.717367 | 207,664 | 0.935408 |
[
[
[
"# GLM: Robust Regression with Outlier Detection\n\n**A minimal reproducable example of Robust Regression with Outlier Detection using Hogg 2010 Signal vs Noise method.**\n\n+ This is a complementary approach to the Student-T robust regression as illustrated in Thomas Wiecki's notebook in the [PyMC3 documentation](http://pymc-devs.github.io/pymc3/GLM-robust/), that approach is also compared here.\n+ This model returns a robust estimate of linear coefficients and an indication of which datapoints (if any) are outliers.\n+ The likelihood evaluation is essentially a copy of eqn 17 in \"Data analysis recipes: Fitting a model to data\" - [Hogg 2010](http://arxiv.org/abs/1008.4686).\n+ The model is adapted specifically from Jake Vanderplas' [implementation](http://www.astroml.org/book_figures/chapter8/fig_outlier_rejection.html) (3rd model tested).\n+ The dataset is tiny and hardcoded into this Notebook. It contains errors in both the x and y, but we will deal here with only errors in y.\n\n\n**Note:**\n\n+ Python 3.4 project using latest available [PyMC3](https://github.com/pymc-devs/pymc3)\n+ Developed using [ContinuumIO Anaconda](https://www.continuum.io/downloads) distribution on a Macbook Pro 3GHz i7, 16GB RAM, OSX 10.10.5.\n+ During development I've found that 3 data points are always indicated as outliers, but the remaining ordering of datapoints by decreasing outlier-hood is slightly unstable between runs: the posterior surface appears to have a small number of solutions with similar probability. \n+ Finally, if runs become unstable or Theano throws weird errors, try clearing the cache `$> theano-cache clear` and rerunning the notebook.\n\n\n**Package Requirements (shown as a conda-env YAML):**\n```\n$> less conda_env_pymc3_examples.yml\n\nname: pymc3_examples\n channels:\n - defaults\n dependencies:\n - python=3.4\n - ipython\n - ipython-notebook\n - ipython-qtconsole\n - numpy\n - scipy\n - matplotlib\n - pandas\n - seaborn\n - patsy \n - pip\n\n$> conda env create --file conda_env_pymc3_examples.yml\n\n$> source activate pymc3_examples\n\n$> pip install --process-dependency-links git+https://github.com/pymc-devs/pymc3\n\n```",
"_____no_output_____"
],
[
"## Setup",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nimport warnings\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom scipy import optimize\nimport pymc3 as pm\nimport theano as thno\nimport theano.tensor as T \n\n# configure some basic options\nsns.set(style=\"darkgrid\", palette=\"muted\")\npd.set_option('display.notebook_repr_html', True)\nplt.rcParams['figure.figsize'] = 12, 8\nnp.random.seed(0)",
"_____no_output_____"
]
],
[
[
"### Load and Prepare Data",
"_____no_output_____"
],
[
"We'll use the Hogg 2010 data available at https://github.com/astroML/astroML/blob/master/astroML/datasets/hogg2010test.py\n\nIt's a very small dataset so for convenience, it's hardcoded below",
"_____no_output_____"
]
],
[
[
"#### cut & pasted directly from the fetch_hogg2010test() function\n## identical to the original dataset as hardcoded in the Hogg 2010 paper\n\ndfhogg = pd.DataFrame(np.array([[1, 201, 592, 61, 9, -0.84],\n [2, 244, 401, 25, 4, 0.31],\n [3, 47, 583, 38, 11, 0.64],\n [4, 287, 402, 15, 7, -0.27],\n [5, 203, 495, 21, 5, -0.33],\n [6, 58, 173, 15, 9, 0.67],\n [7, 210, 479, 27, 4, -0.02],\n [8, 202, 504, 14, 4, -0.05],\n [9, 198, 510, 30, 11, -0.84],\n [10, 158, 416, 16, 7, -0.69],\n [11, 165, 393, 14, 5, 0.30],\n [12, 201, 442, 25, 5, -0.46],\n [13, 157, 317, 52, 5, -0.03],\n [14, 131, 311, 16, 6, 0.50],\n [15, 166, 400, 34, 6, 0.73],\n [16, 160, 337, 31, 5, -0.52],\n [17, 186, 423, 42, 9, 0.90],\n [18, 125, 334, 26, 8, 0.40],\n [19, 218, 533, 16, 6, -0.78],\n [20, 146, 344, 22, 5, -0.56]]),\n columns=['id','x','y','sigma_y','sigma_x','rho_xy'])\n\n\n## for convenience zero-base the 'id' and use as index\ndfhogg['id'] = dfhogg['id'] - 1\ndfhogg.set_index('id', inplace=True)\n\n## standardize (mean center and divide by 1 sd)\ndfhoggs = (dfhogg[['x','y']] - dfhogg[['x','y']].mean(0)) / dfhogg[['x','y']].std(0)\ndfhoggs['sigma_y'] = dfhogg['sigma_y'] / dfhogg['y'].std(0)\ndfhoggs['sigma_x'] = dfhogg['sigma_x'] / dfhogg['x'].std(0)\n\n## create xlims ylims for plotting\nxlims = (dfhoggs['x'].min() - np.ptp(dfhoggs['x'])/5\n ,dfhoggs['x'].max() + np.ptp(dfhoggs['x'])/5)\nylims = (dfhoggs['y'].min() - np.ptp(dfhoggs['y'])/5\n ,dfhoggs['y'].max() + np.ptp(dfhoggs['y'])/5)\n\n## scatterplot the standardized data\ng = sns.FacetGrid(dfhoggs, size=8)\n_ = g.map(plt.errorbar, 'x', 'y', 'sigma_y', 'sigma_x', marker=\"o\", ls='')\n_ = g.axes[0][0].set_ylim(ylims)\n_ = g.axes[0][0].set_xlim(xlims)\n\nplt.subplots_adjust(top=0.92)\n_ = g.fig.suptitle('Scatterplot of Hogg 2010 dataset after standardization', fontsize=16)",
"_____no_output_____"
]
],
[
[
"**Observe**: \n\n+ Even judging just by eye, you can see these datapoints mostly fall on / around a straight line with positive gradient\n+ It looks like a few of the datapoints may be outliers from such a line",
"_____no_output_____"
],
[
"## Create Conventional OLS Model",
"_____no_output_____"
],
[
"The *linear model* is really simple and conventional:\n\n$$\\bf{y} = \\beta^{T} \\bf{X} + \\bf{\\sigma}$$\n\nwhere: \n\n$\\beta$ = coefs = $\\{1, \\beta_{j \\in X_{j}}\\}$ \n$\\sigma$ = the measured error in $y$ in the dataset `sigma_y`",
"_____no_output_____"
],
[
"### Define model\n\n**NOTE:**\n+ We're using a simple linear OLS model with Normally distributed priors so that it behaves like a ridge regression",
"_____no_output_____"
]
],
[
[
"with pm.Model() as mdl_ols:\n \n ## Define weakly informative Normal priors to give Ridge regression\n b0 = pm.Normal('b0_intercept', mu=0, sd=100)\n b1 = pm.Normal('b1_slope', mu=0, sd=100)\n \n ## Define linear model\n yest = b0 + b1 * dfhoggs['x']\n \n ## Use y error from dataset, convert into theano variable\n sigma_y = thno.shared(np.asarray(dfhoggs['sigma_y'],\n dtype=thno.config.floatX), name='sigma_y')\n\n ## Define Normal likelihood\n likelihood = pm.Normal('likelihood', mu=yest, sd=sigma_y, observed=dfhoggs['y'])\n",
"_____no_output_____"
]
],
[
[
"### Sample",
"_____no_output_____"
]
],
[
[
"with mdl_ols:\n ## take samples\n traces_ols = pm.sample(2000, tune=1000)",
"Auto-assigning NUTS sampler...\nInitializing NUTS using ADVI...\nAverage Loss = 168.87: 4%|▍ | 7828/200000 [00:00<00:09, 19595.48it/s]\nConvergence archived at 9500\nInterrupted at 9,500 [4%]: Average Loss = 237.62\n100%|██████████| 3000/3000 [00:00<00:00, 3118.55it/s]\n"
]
],
[
[
"### View Traces\n\n**NOTE**: I'll 'burn' the traces to only retain the final 1000 samples",
"_____no_output_____"
]
],
[
[
"_ = pm.traceplot(traces_ols[-1000:], figsize=(12,len(traces_ols.varnames)*1.5),\n lines={k: v['mean'] for k, v in pm.df_summary(traces_ols[-1000:]).iterrows()})",
"_____no_output_____"
]
],
[
[
"**NOTE:** We'll illustrate this OLS fit and compare to the datapoints in the final plot",
"_____no_output_____"
],
[
"---\n\n---",
"_____no_output_____"
],
[
"## Create Robust Model: Student-T Method",
"_____no_output_____"
],
[
"I've added this brief section in order to directly compare the Student-T based method exampled in Thomas Wiecki's notebook in the [PyMC3 documentation](http://pymc-devs.github.io/pymc3/GLM-robust/)\n\nInstead of using a Normal distribution for the likelihood, we use a Student-T, which has fatter tails. In theory this allows outliers to have a smaller mean square error in the likelihood, and thus have less influence on the regression estimation. This method does not produce inlier / outlier flags but is simpler and faster to run than the Signal Vs Noise model below, so a comparison seems worthwhile.\n\n**Note:** we'll constrain the Student-T 'degrees of freedom' parameter `nu` to be an integer, but otherwise leave it as just another stochastic to be inferred: no need for prior knowledge.",
"_____no_output_____"
],
[
"### Define Model",
"_____no_output_____"
]
],
[
[
"with pm.Model() as mdl_studentt:\n \n ## Define weakly informative Normal priors to give Ridge regression\n b0 = pm.Normal('b0_intercept', mu=0, sd=100)\n b1 = pm.Normal('b1_slope', mu=0, sd=100)\n \n ## Define linear model\n yest = b0 + b1 * dfhoggs['x']\n \n ## Use y error from dataset, convert into theano variable\n sigma_y = thno.shared(np.asarray(dfhoggs['sigma_y'],\n dtype=thno.config.floatX), name='sigma_y')\n \n ## define prior for Student T degrees of freedom\n nu = pm.Uniform('nu', lower=1, upper=100)\n\n ## Define Student T likelihood\n likelihood = pm.StudentT('likelihood', mu=yest, sd=sigma_y, nu=nu,\n observed=dfhoggs['y'])\n",
"_____no_output_____"
]
],
[
[
"### Sample",
"_____no_output_____"
]
],
[
[
"with mdl_studentt: \n ## take samples\n traces_studentt = pm.sample(2000, tune=1000)",
"Auto-assigning NUTS sampler...\nInitializing NUTS using ADVI...\nAverage Loss = 41.822: 8%|▊ | 15829/200000 [00:01<00:14, 13016.12it/s]\nConvergence archived at 16100\nInterrupted at 16,100 [8%]: Average Loss = 83.741\n100%|██████████| 3000/3000 [00:02<00:00, 1441.38it/s]\n"
]
],
[
[
"#### View Traces",
"_____no_output_____"
]
],
[
[
"_ = pm.traceplot(traces_studentt[-1000:],\n figsize=(12,len(traces_studentt.varnames)*1.5),\n lines={k: v['mean'] for k, v in pm.df_summary(traces_studentt[-1000:]).iterrows()})",
"_____no_output_____"
]
],
[
[
"**Observe:**\n\n+ Both parameters `b0` and `b1` show quite a skew to the right, possibly this is the action of a few samples regressing closer to the OLS estimate which is towards the left\n+ The `nu` parameter seems very happy to stick at `nu = 1`, indicating that a fat-tailed Student-T likelihood has a better fit than a thin-tailed (Normal-like) Student-T likelihood.\n+ The inference sampling also ran very quickly, almost as quickly as the conventional OLS\n\n\n**NOTE:** We'll illustrate this Student-T fit and compare to the datapoints in the final plot",
"_____no_output_____"
],
[
"---\n\n---",
"_____no_output_____"
],
[
"## Create Robust Model with Outliers: Hogg Method",
"_____no_output_____"
],
[
"Please read the paper (Hogg 2010) and Jake Vanderplas' code for more complete information about the modelling technique.\n\nThe general idea is to create a 'mixture' model whereby datapoints can be described by either the linear model (inliers) or a modified linear model with different mean and larger variance (outliers).\n\n\nThe likelihood is evaluated over a mixture of two likelihoods, one for 'inliers', one for 'outliers'. A Bernouilli distribution is used to randomly assign datapoints in N to either the inlier or outlier groups, and we sample the model as usual to infer robust model parameters and inlier / outlier flags:\n\n$$\n\\mathcal{logL} = \\sum_{i}^{i=N} log \\left[ \\frac{(1 - B_{i})}{\\sqrt{2 \\pi \\sigma_{in}^{2}}} exp \\left( - \\frac{(x_{i} - \\mu_{in})^{2}}{2\\sigma_{in}^{2}} \\right) \\right] + \\sum_{i}^{i=N} log \\left[ \\frac{B_{i}}{\\sqrt{2 \\pi (\\sigma_{in}^{2} + \\sigma_{out}^{2})}} exp \\left( - \\frac{(x_{i}- \\mu_{out})^{2}}{2(\\sigma_{in}^{2} + \\sigma_{out}^{2})} \\right) \\right]\n$$\n\nwhere: \n$\\bf{B}$ is Bernoulli-distibuted $B_{i} \\in [0_{(inlier)},1_{(outlier)}]$\n\n",
"_____no_output_____"
],
[
"### Define model",
"_____no_output_____"
]
],
[
[
"def logp_signoise(yobs, is_outlier, yest_in, sigma_y_in, yest_out, sigma_y_out):\n '''\n Define custom loglikelihood for inliers vs outliers. \n NOTE: in this particular case we don't need to use theano's @as_op \n decorator because (as stated by Twiecki in conversation) that's only \n required if the likelihood cannot be expressed as a theano expression.\n We also now get the gradient computation for free.\n ''' \n \n # likelihood for inliers\n pdfs_in = T.exp(-(yobs - yest_in + 1e-4)**2 / (2 * sigma_y_in**2)) \n pdfs_in /= T.sqrt(2 * np.pi * sigma_y_in**2)\n logL_in = T.sum(T.log(pdfs_in) * (1 - is_outlier))\n\n # likelihood for outliers\n pdfs_out = T.exp(-(yobs - yest_out + 1e-4)**2 / (2 * (sigma_y_in**2 + sigma_y_out**2))) \n pdfs_out /= T.sqrt(2 * np.pi * (sigma_y_in**2 + sigma_y_out**2))\n logL_out = T.sum(T.log(pdfs_out) * is_outlier)\n\n return logL_in + logL_out",
"_____no_output_____"
],
[
"with pm.Model() as mdl_signoise:\n \n ## Define weakly informative Normal priors to give Ridge regression\n b0 = pm.Normal('b0_intercept', mu=0, sd=10, testval=pm.floatX(0.1))\n b1 = pm.Normal('b1_slope', mu=0, sd=10, testval=pm.floatX(1.))\n \n ## Define linear model\n yest_in = b0 + b1 * dfhoggs['x']\n\n ## Define weakly informative priors for the mean and variance of outliers\n yest_out = pm.Normal('yest_out', mu=0, sd=100, testval=pm.floatX(1.))\n sigma_y_out = pm.HalfNormal('sigma_y_out', sd=100, testval=pm.floatX(1.))\n\n ## Define Bernoulli inlier / outlier flags according to a hyperprior \n ## fraction of outliers, itself constrained to [0,.5] for symmetry\n frac_outliers = pm.Uniform('frac_outliers', lower=0., upper=.5)\n is_outlier = pm.Bernoulli('is_outlier', p=frac_outliers, shape=dfhoggs.shape[0], \n testval=np.random.rand(dfhoggs.shape[0]) < 0.2)\n \n ## Extract observed y and sigma_y from dataset, encode as theano objects\n yobs = thno.shared(np.asarray(dfhoggs['y'], dtype=thno.config.floatX), name='yobs')\n sigma_y_in = thno.shared(np.asarray(dfhoggs['sigma_y'], dtype=thno.config.floatX), \n name='sigma_y_in')\n \n ## Use custom likelihood using DensityDist\n likelihood = pm.DensityDist('likelihood', logp_signoise,\n observed={'yobs': yobs, 'is_outlier': is_outlier,\n 'yest_in': yest_in, 'sigma_y_in': sigma_y_in,\n 'yest_out': yest_out, 'sigma_y_out': sigma_y_out})",
"_____no_output_____"
]
],
[
[
"### Sample",
"_____no_output_____"
]
],
[
[
"with mdl_signoise:\n ## two-step sampling to create Bernoulli inlier/outlier flags\n step1 = pm.Metropolis([frac_outliers, yest_out, sigma_y_out, b0, b1])\n step2 = pm.step_methods.BinaryGibbsMetropolis([is_outlier])\n\n ## take samples\n traces_signoise = pm.sample(20000, step=[step1, step2], tune=10000, progressbar=True)",
"100%|██████████| 30000/30000 [00:59<00:00, 505.40it/s]\n"
]
],
[
[
"### View Traces",
"_____no_output_____"
]
],
[
[
"traces_signoise[-10000:]['b0_intercept']",
"_____no_output_____"
],
[
"_ = pm.traceplot(traces_signoise[-10000:], figsize=(12,len(traces_signoise.varnames)*1.5),\n lines={k: v['mean'] for k, v in pm.df_summary(traces_signoise[-1000:]).iterrows()})",
"_____no_output_____"
]
],
[
[
"**NOTE:**\n\n+ During development I've found that 3 datapoints id=[1,2,3] are always indicated as outliers, but the remaining ordering of datapoints by decreasing outlier-hood is unstable between runs: the posterior surface appears to have a small number of solutions with very similar probability.\n+ The NUTS sampler seems to work okay, and indeed it's a nice opportunity to demonstrate a custom likelihood which is possible to express as a theano function (thus allowing a gradient-based sampler like NUTS). However, with a more complicated dataset, I would spend time understanding this instability and potentially prefer using more samples under Metropolis-Hastings.",
"_____no_output_____"
],
[
"---\n\n---",
"_____no_output_____"
],
[
"## Declare Outliers and Compare Plots",
"_____no_output_____"
],
[
"### View ranges for inliers / outlier predictions",
"_____no_output_____"
],
[
"At each step of the traces, each datapoint may be either an inlier or outlier. We hope that the datapoints spend an unequal time being one state or the other, so let's take a look at the simple count of states for each of the 20 datapoints.",
"_____no_output_____"
]
],
[
[
"outlier_melt = pd.melt(pd.DataFrame(traces_signoise['is_outlier', -1000:],\n columns=['[{}]'.format(int(d)) for d in dfhoggs.index]),\n var_name='datapoint_id', value_name='is_outlier')\nax0 = sns.pointplot(y='datapoint_id', x='is_outlier', data=outlier_melt,\n kind='point', join=False, ci=None, size=4, aspect=2)\n\n_ = ax0.vlines([0,1], 0, 19, ['b','r'], '--')\n\n_ = ax0.set_xlim((-0.1,1.1))\n_ = ax0.set_xticks(np.arange(0, 1.1, 0.1))\n_ = ax0.set_xticklabels(['{:.0%}'.format(t) for t in np.arange(0,1.1,0.1)])\n\n_ = ax0.yaxis.grid(True, linestyle='-', which='major', color='w', alpha=0.4)\n_ = ax0.set_title('Prop. of the trace where datapoint is an outlier')\n_ = ax0.set_xlabel('Prop. of the trace where is_outlier == 1')",
"_____no_output_____"
]
],
[
[
"**Observe**:\n\n+ The plot above shows the number of samples in the traces in which each datapoint is marked as an outlier, expressed as a percentage.\n+ In particular, 3 points [1, 2, 3] spend >=95% of their time as outliers\n+ Contrastingly, points at the other end of the plot close to 0% are our strongest inliers.\n+ For comparison, the mean posterior value of `frac_outliers` is ~0.35, corresponding to roughly 7 of the 20 datapoints. You can see these 7 datapoints in the plot above, all those with a value >50% or thereabouts.\n+ However, only 3 of these points are outliers >=95% of the time. \n+ See note above regarding instability between runs.\n\nThe 95% cutoff we choose is subjective and arbitrary, but I prefer it for now, so let's declare these 3 to be outliers and see how it looks compared to Jake Vanderplas' outliers, which were declared in a slightly different way as points with means above 0.68.",
"_____no_output_____"
],
[
"### Declare outliers\n\n**Note:**\n+ I will declare outliers to be datapoints that have value == 1 at the 5-percentile cutoff, i.e. in the percentiles from 5 up to 100, their values are 1. \n+ Try for yourself altering cutoff to larger values, which leads to an objective ranking of outlier-hood.",
"_____no_output_____"
]
],
[
[
"cutoff = 5\ndfhoggs['outlier'] = np.percentile(traces_signoise[-1000:]['is_outlier'],cutoff, axis=0)\ndfhoggs['outlier'].value_counts()",
"_____no_output_____"
]
],
[
[
"### Posterior Prediction Plots for OLS vs StudentT vs SignalNoise",
"_____no_output_____"
]
],
[
[
"g = sns.FacetGrid(dfhoggs, size=8, hue='outlier', hue_order=[True,False],\n palette='Set1', legend_out=False)\n\nlm = lambda x, samp: samp['b0_intercept'] + samp['b1_slope'] * x\n\npm.plot_posterior_predictive_glm(traces_ols[-1000:],\n eval=np.linspace(-3, 3, 10), lm=lm, samples=200, color='#22CC00', alpha=.2)\n\npm.plot_posterior_predictive_glm(traces_studentt[-1000:], lm=lm,\n eval=np.linspace(-3, 3, 10), samples=200, color='#FFA500', alpha=.5)\n\npm.plot_posterior_predictive_glm(traces_signoise[-1000:], lm=lm,\n eval=np.linspace(-3, 3, 10), samples=200, color='#357EC7', alpha=.3)\n\n_ = g.map(plt.errorbar, 'x', 'y', 'sigma_y', 'sigma_x', marker=\"o\", ls='').add_legend()\n\n_ = g.axes[0][0].annotate('OLS Fit: Green\\nStudent-T Fit: Orange\\nSignal Vs Noise Fit: Blue',\n size='x-large', xy=(1,0), xycoords='axes fraction',\n xytext=(-160,10), textcoords='offset points')\n_ = g.axes[0][0].set_ylim(ylims)\n_ = g.axes[0][0].set_xlim(xlims)",
"_____no_output_____"
]
],
[
[
"**Observe**:\n\n+ The posterior preditive fit for:\n + the **OLS model** is shown in **Green** and as expected, it doesn't appear to fit the majority of our datapoints very well, skewed by outliers\n + the **Robust Student-T model** is shown in **Orange** and does appear to fit the 'main axis' of datapoints quite well, ignoring outliers\n + the **Robust Signal vs Noise model** is shown in **Blue** and also appears to fit the 'main axis' of datapoints rather well, ignoring outliers.\n \n \n+ We see that the **Robust Signal vs Noise model** also yields specific estimates of _which_ datapoints are outliers:\n + 17 'inlier' datapoints, in **Blue** and\n + 3 'outlier' datapoints shown in **Red**.\n + From a simple visual inspection, the classification seems fair, and agrees with Jake Vanderplas' findings.\n \n \n+ Overall, it seems that:\n + the **Signal vs Noise model** behaves as promised, yielding a robust regression estimate and explicit labelling of inliers / outliers, but\n + the **Signal vs Noise model** is quite complex and whilst the regression seems robust and stable, the actual inlier / outlier labelling seems slightly unstable\n + if you simply want a robust regression without inlier / outlier labelling, the **Student-T model** may be a good compromise, offering a simple model, quick sampling, and a very similar estimate.",
"_____no_output_____"
],
[
"---",
"_____no_output_____"
],
[
"Example originally contributed by Jonathan Sedar 2015-12-21 [github.com/jonsedar](https://github.com/jonsedar)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
4aa81ccc474a3529d922827fea4823899dd2f658
| 9,421 |
ipynb
|
Jupyter Notebook
|
6_google_trace/VMFuzzyPrediction/.ipynb_checkpoints/SoftMax-checkpoint.ipynb
|
nguyenthieu95/machine_learning
|
40595a003815445a7a9fef7e8925f71d19f8fa30
|
[
"MIT"
] | 1 |
2017-12-30T20:10:07.000Z
|
2017-12-30T20:10:07.000Z
|
6_google_trace/VMFuzzyPrediction/.ipynb_checkpoints/SoftMax-checkpoint.ipynb
|
ThieuNv/machine_learning
|
40595a003815445a7a9fef7e8925f71d19f8fa30
|
[
"MIT"
] | null | null | null |
6_google_trace/VMFuzzyPrediction/.ipynb_checkpoints/SoftMax-checkpoint.ipynb
|
ThieuNv/machine_learning
|
40595a003815445a7a9fef7e8925f71d19f8fa30
|
[
"MIT"
] | 1 |
2019-12-23T15:30:16.000Z
|
2019-12-23T15:30:16.000Z
| 44.438679 | 1,112 | 0.587199 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4aa85388e21b803b81b6f72e3e45f0926dda5508
| 5,701 |
ipynb
|
Jupyter Notebook
|
homecredit/Tensorflow04_w+b+l.ipynb
|
ChenyangShi/ChenyangShi.github.io
|
07518c6c69bac92fef24634f759d9deee7ef3b82
|
[
"MIT"
] | null | null | null |
homecredit/Tensorflow04_w+b+l.ipynb
|
ChenyangShi/ChenyangShi.github.io
|
07518c6c69bac92fef24634f759d9deee7ef3b82
|
[
"MIT"
] | null | null | null |
homecredit/Tensorflow04_w+b+l.ipynb
|
ChenyangShi/ChenyangShi.github.io
|
07518c6c69bac92fef24634f759d9deee7ef3b82
|
[
"MIT"
] | null | null | null | 28.792929 | 131 | 0.529907 |
[
[
[
"import pandas as pd\nimport numpy as np\nimport gc\nimport time\n\ndf=pd.read_csv(\"df.csv\")",
"_____no_output_____"
],
[
"train_df = df[df['TARGET'].notnull()]\ntest_df = df[df['TARGET'].isnull()]\ndel df\ngc.collect()\nfeats = [f for f in train_df.columns if f not in ['TARGET','SK_ID_CURR','SK_ID_BUREAU','SK_ID_PREV','index']]\n\nX = train_df[feats]\ny = train_df['TARGET']\n\ntotal = X.isnull().sum().sort_values(ascending = False)\npercent = (X.isnull().sum() / X.isnull().count()*100).sort_values(ascending = False)\nmissing_X = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\n\nL=missing_X[missing_X['Total']==0]\nL1=L.reset_index().values\nnomiss_feats=[]\nfor e in range(0, L.shape[0]):\n nomiss_feats.append(L1[e][0])\n\ndel missing_X\ndel L\ndel L1\ngc.collect()\n\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\n\nfor f in X.columns:\n if f in nomiss_feats:\n X[f] = scaler.fit_transform(X[f].values.reshape(-1,1))\n \ny = scaler.fit_transform(y.values.reshape(-1,1))\n\ndel nomiss_feats\ngc.collect()\n\nX = X.fillna(value = 0)\n\n# split data\nfrom sklearn.model_selection import train_test_split\nX_train, X_valid, y_train, y_valid = train_test_split(X, y,test_size=0.2)#, random_state=42)\n\nprint (X_train.shape)\nprint (X_valid.shape)\nprint (y_train.shape)\nprint (y_valid.shape)",
"_____no_output_____"
],
[
"# Build and run model\nimport tensorflow as tf\nITERATIONS = 40000\nLEARNING_RATE = 1e-4\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n \ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n# Let's train the model\nfeature_count = X_train.shape[1]\nx = tf.placeholder('float', shape=[None, feature_count], name='x')\ny_ = tf.placeholder('float', shape=[None, 1], name='y_')\n\nprint(x.get_shape())\n\nnodes = 20\n\nw1 = weight_variable([feature_count, nodes])\nb1 = bias_variable([nodes])\nl1 = tf.nn.relu(tf.matmul(x, w1) + b1)\n\nw2 = weight_variable([nodes, 1])\nb2 = bias_variable([1])\ny = tf.nn.sigmoid(tf.matmul(l1, w2) + b2)\n\ncross_entropy = -tf.reduce_mean(y_*tf.log(tf.maximum(0.00001, y)) + (1.0 - y_)*tf.log(tf.maximum(0.00001, 1.0-y)))\nreg = 0.01 * (tf.reduce_mean(tf.square(w1)) + tf.reduce_mean(tf.square(w2)))\n\npredict = (y > 0.5)\n\ncorrect_prediction = tf.equal(predict, (y_ > 0.5))\n\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))\n \n \n\ntrain_step = tf.train.AdamOptimizer(LEARNING_RATE).minimize(cross_entropy + reg)\n\ninit = tf.initialize_all_variables()\n\nsess = tf.Session()\nsess.run(init)\n\nfor i in range(ITERATIONS):\n feed={x:X_train, y_:y_train}\n sess.run(train_step, feed_dict=feed)\n if i % 1000 == 0 or i == ITERATIONS-1:\n print('{} {} {:.2f}%'.format(i, sess.run(cross_entropy, feed_dict=feed), sess.run(accuracy, feed_dict=feed)*100.0))\n",
"_____no_output_____"
],
[
"T = test_df[feats]\n\ntotal = T.isnull().sum().sort_values(ascending = False)\npercent = (T.isnull().sum() / T.isnull().count()*100).sort_values(ascending = False)\nmissing_T = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\n\nL2=missing_T[missing_T['Total']==0]\nL3=L2.reset_index().values\nnomiss_feats=[]\nfor e in range(0, L2.shape[0]):\n nomiss_feats.append(L3[e][0])\n \ndel missing_T\ndel L2\ndel L3\ngc.collect()\n\nfrom sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\n\nfor f in T.columns:\n if f in nomiss_feats:\n T[f] = scaler.fit_transform(T[f].values.reshape(-1,1))\n \ndel nomiss_feats\ngc.collect()\n\nT",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
4aa853dfd169db8f93a97445f627c5c3e5fba5bb
| 6,225 |
ipynb
|
Jupyter Notebook
|
07-weights-exercise-solutions.ipynb
|
grochmal/nnag
|
3d833a2e5f42566070ed041c5cfd037922b6ab70
|
[
"MIT"
] | 1 |
2019-09-13T16:21:25.000Z
|
2019-09-13T16:21:25.000Z
|
07-weights-exercise-solutions.ipynb
|
grochmal/nnag
|
3d833a2e5f42566070ed041c5cfd037922b6ab70
|
[
"MIT"
] | null | null | null |
07-weights-exercise-solutions.ipynb
|
grochmal/nnag
|
3d833a2e5f42566070ed041c5cfd037922b6ab70
|
[
"MIT"
] | null | null | null | 27.914798 | 107 | 0.503454 |
[
[
[
"# Demystifying Neural Networks \n\n---",
"_____no_output_____"
],
[
"# Exercises - ANN Weights\n\nWe will generate matrices that can be used as an ANN.\n\nYou can generate matrices with any function from `numpy.random`.\nYou can provide a tuple to the `size=` parameter to get an array\nof that shape. For example, `np.random.normal(0, 1, (3, 6))`\ngenerates a matrix of 3 rows and 6 columns.",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
]
],
[
[
"#### 1. Generate the following matrices with values from the normal distribution\n\nA) $A_{2 \\times 3}$\n\nB) $B_{7 \\times 5}$",
"_____no_output_____"
]
],
[
[
"A = np.random.normal(0, 1, (2, 3))\nB = np.random.normal(0, 1, (7, 5))\nprint(A)\nprint(B)",
"[[ 0.41368386 -0.46197109 -0.31394177]\n [-0.76525426 -0.12080901 -1.15777574]]\n[[-1.24587997 0.9302691 2.48813365 0.02748313 -2.26752876]\n [-0.6345608 0.91266004 1.07964376 -0.27285384 0.58175895]\n [ 1.11946317 0.75285805 1.0308717 1.50849316 -1.07940968]\n [ 0.69269657 1.19468001 1.1692544 -0.88120546 0.55920565]\n [-1.57520478 0.04654562 1.06973026 1.78777095 -0.99759735]\n [-0.30326333 0.42675967 -1.58884367 -0.91625 -0.20531768]\n [-0.30970048 -0.44785164 -1.25832689 -0.87159608 2.22253136]]\n"
]
],
[
[
"#### 2. Generate matrices of the same size as the used in the `pytorch` network\n\n$$\nW_{25 \\times 8}, W_{B\\: 25 \\times 1},\nW'_{10 \\times 25}, W'_{B\\: 10 \\times 1},\nW'_{2 \\times 10}, W'_{B\\: 2 \\times 1}\n$$",
"_____no_output_____"
]
],
[
[
"W = np.random.normal(0, 1, (25, 8))\nW_B = np.random.normal(0, 1, (25, 1))\nWx = np.random.normal(0, 1, (10, 25))\nWx_B = np.random.normal(0, 1, (10, 1))\nWxx = np.random.normal(0, 1, (2, 10))\nWxx_B = np.random.normal(0, 1, (2, 1))\n\nweights = [W, W_B, Wx, Wx_B, Wxx, Wxx_B]\nprint([x.shape for x in weights])",
"[(25, 8), (25, 1), (10, 25), (10, 1), (2, 10), (2, 1)]\n"
]
],
[
[
"---\n\nWeight generation is a big topic in ANN research.\nWe will use one well accepted way of generating ways but there are plethora of others.\n\nThe way we will generate weight matrices is to:\nIf we need to generate a matrix of size $p \\times n$,\nwe take all values for the matrix from the normal distribution\nwith mean and standard deviation as:\n\n$$\n\\mu = 0 \\\\\n\\sigma = \\frac{1}{n + p}\n$$\n\nIn `numpy` the mean argument is `loc=` and standard deviation is called `scale=`",
"_____no_output_____"
],
[
"#### 3. Generate the same matrices as above but use the distribution describe above, then evaluate\n\n$$\nX = \\left[\n\\begin{matrix}\n102.50781 & 58.88243 & 0.46532 & -0.51509 & 1.67726 & 14.86015 & 10.57649 & 127.39358 \\\\\n142.07812 & 45.28807 & -0.32033 & 0.28395 & 5.37625 & 29.00990 & 6.07627 & 37.83139 \\\\\n138.17969 & 51.52448 & -0.03185 & 0.04680 & 6.33027 & 31.57635 & 5.15594 & 26.14331 \\\\\n\\end{matrix}\n\\right]\n$$\n\n(These are the first three rows in the pulsar dataset)\n\n$$\n\\hat{Y}_{2 \\times 3} = tanh(W''_{2 \\times 10} \\times\n tanh(W'_{10 \\times 25} \\times\n tanh(W_{25 \\times 8} \\times X^T + W_{B\\: 25 \\times 1})\n + W'_{B\\: 10 \\times 1})\n+ W''_{B\\: 2 \\times 1})\n$$",
"_____no_output_____"
]
],
[
[
"X = np.array([\n [102.50781, 58.88243, 0.46532, -0.51509, 1.67726, 14.86015, 10.57649, 127.39358],\n [142.07812, 45.28807, -0.32033, 0.28395, 5.37625, 29.00990, 6.07627, 37.83139],\n [138.17969, 51.52448, -0.03185, 0.04680, 6.33027, 31.57635, 5.15594, 26.14331],\n])\nW = np.random.normal(0, 1/(8+25), (25, 8))\nW_B = np.random.normal(0, 1/(25+1), (25, 1))\nWx = np.random.normal(0, 1/(10+25), (10, 25))\nWx_B = np.random.normal(0, 1/(10+1), (10, 1))\nWxx = np.random.normal(0, 1/(2+10), (2, 10))\nWxx_B = np.random.normal(0, 1/(2+1), (2, 1));",
"_____no_output_____"
],
[
"Y_hat = np.tanh(Wxx @ np.tanh(Wx @ np.tanh(W @ X.T + W_B) + Wx_B) + Wxx_B)\nprint(Y_hat.T)",
"[[-0.36091669 0.03487534]\n [-0.38056382 0.04280491]\n [-0.38015046 0.04409401]]\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
4aa85ac246e262938dc74e5352382d7f01cb0e9b
| 672 |
ipynb
|
Jupyter Notebook
|
copycat-spark/src/main/jupyter/copycat-on-terabyte-runs.ipynb
|
chatnoir-eu/chatnoir-copycat
|
505fa7fab0cd53994177aff1f6284ba6a282734a
|
[
"MIT"
] | 3 |
2021-07-14T01:45:09.000Z
|
2022-01-31T03:33:24.000Z
|
copycat-spark/src/main/jupyter/copycat-on-terabyte-runs.ipynb
|
chatnoir-eu/chatnoir-copycat
|
505fa7fab0cd53994177aff1f6284ba6a282734a
|
[
"MIT"
] | 1 |
2021-05-08T11:57:17.000Z
|
2021-05-08T11:57:17.000Z
|
copycat-spark/src/main/jupyter/copycat-on-terabyte-runs.ipynb
|
chatnoir-eu/copycat
|
505fa7fab0cd53994177aff1f6284ba6a282734a
|
[
"MIT"
] | null | null | null | 19.2 | 89 | 0.556548 |
[
[
[
"# CopyCat: Example Usage on the Terabyte Runs\n\n- Terabyte has much impact, hence I show it here in contrast to argsme and robust04",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown"
]
] |
4aa869876e484df7742aab6b27807b3f00eaf2cc
| 2,934 |
ipynb
|
Jupyter Notebook
|
notebooks/Plan.ipynb
|
hanialshater/The-Dauntless-ML-Book
|
aa1819ddad5f28428a75d8ab9a1ee3da6406e8e8
|
[
"MIT"
] | null | null | null |
notebooks/Plan.ipynb
|
hanialshater/The-Dauntless-ML-Book
|
aa1819ddad5f28428a75d8ab9a1ee3da6406e8e8
|
[
"MIT"
] | null | null | null |
notebooks/Plan.ipynb
|
hanialshater/The-Dauntless-ML-Book
|
aa1819ddad5f28428a75d8ab9a1ee3da6406e8e8
|
[
"MIT"
] | null | null | null | 26.917431 | 207 | 0.580777 |
[
[
[
"### Part 1: Awake to your true power\nit is all about avoiding brught force \n* chapter 1: ML is a database (avoid ML BF, you can answer varius kind of questions not only regression, you put schema ask questions, bayesian, what is ml, how i get into AI secondery school, etc.)\n* chapter 2: Optimization algorithms \n* chapter 3: The dauntless algorithms\n",
"_____no_output_____"
],
[
"Part 2: Became a data hacker\n* chapter 1: Baysian modeling examples\n* chapter 2: Data analyics examples\n* chapter 3: Mixture models\n* chapter 4: Latent variable models\n* chapter 5: time series \n* chapter 6: the model zoo",
"_____no_output_____"
],
[
"### Part 2.5: Became a problem solving master (optimization, meta-heuristics)\n",
"_____no_output_____"
],
[
"### Part 3: Face your worst nightmares \n* chapter 1: Show me the money! (construct dataset from noisy heuriscs)\n* chapter 2: Learn with limited lables (simi-supervised)\n Learn from synthetic\n* chapter 3: What we are talking about (explainable ML)",
"_____no_output_____"
]
],
[
[
"### Part 4: Arm your self\n* chapter 1: Neural networks architectures\n* chapter 2: Techniques: Few shot learning\n* chapter : Imatation learning, reinfrocement learning\n* chapter 3: NN index \n* chapter 4: Graph neural networks",
"_____no_output_____"
],
[
"### Part 5: Become a trickster\n* chapter 1: Alpha zero\n* chapter 2: Algorithm configuration",
"_____no_output_____"
],
[
"### To be considered\n* chapter 4: Optimize with experimentation (Bandits, GP, TS, BNN, Tree based for speed, etc.)\n* Applications: QU, learning2rank\n* causality and econometrics\n* bayesian none parametrics\n* advances in certain fields\n* knowladge graph, atomic, etc\n* ML systems (docker, k8s, sagemaker, etc.)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
4aa86e62b6c78217882a0c4cd9ef184b62de36f7
| 37,495 |
ipynb
|
Jupyter Notebook
|
courses/machine_learning/asl/open_project/document_processing/notebooks/document_processing.ipynb
|
KayvanShah1/training-data-analyst
|
3f778a57b8e6d2446af40ca6063b2fd9c1b4bc88
|
[
"Apache-2.0"
] | 6,140 |
2016-05-23T16:09:35.000Z
|
2022-03-30T19:00:46.000Z
|
courses/machine_learning/asl/open_project/document_processing/notebooks/document_processing.ipynb
|
KayvanShah1/training-data-analyst
|
3f778a57b8e6d2446af40ca6063b2fd9c1b4bc88
|
[
"Apache-2.0"
] | 1,384 |
2016-07-08T22:26:41.000Z
|
2022-03-24T16:39:43.000Z
|
courses/machine_learning/asl/open_project/document_processing/notebooks/document_processing.ipynb
|
KayvanShah1/training-data-analyst
|
3f778a57b8e6d2446af40ca6063b2fd9c1b4bc88
|
[
"Apache-2.0"
] | 5,110 |
2016-05-27T13:45:18.000Z
|
2022-03-31T18:40:42.000Z
| 29.805246 | 802 | 0.545433 |
[
[
[
"# Document Processing with AutoML and Vision API",
"_____no_output_____"
],
[
"## Problem Statement\nFormally the brief for this Open Project could be stated as follows: Given a collection of varying pdf/png documents containing similar information, create a pipeline that will extract relevant entities from the documents and store the entities in a standardized, easily accessible format. \n\nThe data for this project is contained in the Cloud Storage bucket [gs://document-processing/patent_dataset.zip](https://storage.googleapis.com/document-processing/patent_dataset.zip). The file [gs://document-processing/ground_truth.csv](https://storage.googleapis.com/document-processing/ground_truth.csv) contains hand-labeled fields extracted from the patents. \nThe labels in the ground_truth.csv file are filename, category, publication_date, classification_1, classification_2, application_number, filing_date, priority, representative, applicant, inventor, titleFL, titleSL, abstractFL, and publication_number\n\nHere is an example of two different patent formats:",
"_____no_output_____"
],
[
"<table><tr>\n<td> <img src=\"eu_patent.png\" alt=\"Drawing\" style=\"width: 600px;\"/> </td>\n<td> <img src=\"us_patent.png\" alt=\"Drawing\" style=\"width: 600px;\"/> </td>\n</tr></table>",
"_____no_output_____"
],
[
"### Flexible Solution\nThere are many possible ways to develop a solution to this task which allows students to touch on various functionality and GCP tools that we discuss during the ASL, including the Vision API, AutoML Vision, BigQuery, Tensorflow, Cloud Composer, PubSub. \n\nFor students more interested in modeling with Tensorflow, they could build a classification model from scratch to regcognize the various type of document formats at hand. Knowing the document format (e.g. US or EU patents as in the example above), relevant entities can then be extracted using the Vision API and some basic regex extactors. It might also be possible to train a [conditional random field in Tensorflow](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/crf) to learn how to tag and extract relevant entities from text and the given labels, instead of writing regex-based entity extractors for each document class. \n\nStudents more interested in productionization could work to use Cloud Functions to automate the extraction pipeline. Or incorporate PubSub so that when a new document is uploaded to a specific GCS bucket it is parsed and the entities uploaded to a BigQuery table. \n\nBelow is a solution outline that uses the Vision API and AutoML, uploading the extracted entities to a table in BigQuery. ",
"_____no_output_____"
],
[
"## Install AutoML package",
"_____no_output_____"
],
[
"**Caution:** Run the following command and **restart the kernel** afterwards.",
"_____no_output_____"
]
],
[
[
"!pip freeze | grep google-cloud-automl==0.1.2 || pip install --upgrade google-cloud-automl==0.1.2",
"google-cloud-automl==0.1.2\r\n"
]
],
[
[
"## Set the correct environment variables",
"_____no_output_____"
],
[
"The following variables should be updated according to your own enviroment:\n",
"_____no_output_____"
]
],
[
[
"PROJECT_ID = \"asl-open-projects\"\nSERVICE_ACCOUNT = \"entity-extractor\"\nZONE = \"us-central1\"\nAUTOML_MODEL_ID = \"ICN6705037528556716784\"",
"_____no_output_____"
]
],
[
[
"The following variables are computed from the one you set above, and should\nnot be modified:",
"_____no_output_____"
]
],
[
[
"import os\n\nPWD = os.path.abspath(os.path.curdir)\n\nSERVICE_KEY_PATH = os.path.join(PWD, \"{0}.json\".format(SERVICE_ACCOUNT))\nSERVICE_ACCOUNT_EMAIL=\"{0}@{1}.iam.gserviceaccount.com\".format(SERVICE_ACCOUNT, PROJECT_ID)\n\n# Exporting the variables into the environment to make them available to all the subsequent cells\nos.environ[\"PROJECT_ID\"] = PROJECT_ID\nos.environ[\"SERVICE_ACCOUNT\"] = SERVICE_ACCOUNT\nos.environ[\"SERVICE_KEY_PATH\"] = SERVICE_KEY_PATH\nos.environ[\"SERVICE_ACCOUNT_EMAIL\"] = SERVICE_ACCOUNT_EMAIL\nos.environ[\"ZONE\"] = ZONE",
"_____no_output_____"
]
],
[
[
"## Switching the right project and zone",
"_____no_output_____"
]
],
[
[
"%%bash\ngcloud config set project $PROJECT_ID\ngcloud config set compute/region $ZONE",
"Updated property [core/project].\nUpdated property [compute/region].\n"
]
],
[
[
"## Create a service account",
"_____no_output_____"
]
],
[
[
"%%bash\ngcloud iam service-accounts list | grep $SERVICE_ACCOUNT ||\ngcloud iam service-accounts create $SERVICE_ACCOUNT",
" [email protected]\n"
]
],
[
[
"## Grant service account project ownership ",
"_____no_output_____"
],
[
"TODO: We should ideally restrict the permissions to AutoML and Vision roles only",
"_____no_output_____"
]
],
[
[
"%%bash\ngcloud projects add-iam-policy-binding $PROJECT_ID \\\n --member \"serviceAccount:$SERVICE_ACCOUNT_EMAIL\" \\\n --role \"roles/owner\"",
"bindings:\n- members:\n - serviceAccount:[email protected]\n - user:[email protected]\n - user:[email protected]\n role: roles/automl.admin\n- members:\n - serviceAccount:[email protected]\n role: roles/automl.editor\n- members:\n - serviceAccount:[email protected]\n role: roles/automl.serviceAgent\n- members:\n - serviceAccount:[email protected]\n role: roles/ml.admin\n- members:\n - serviceAccount:[email protected]\n - user:[email protected]\n - user:[email protected]\n role: roles/owner\n- members:\n - serviceAccount:[email protected]\n role: roles/serviceusage.serviceUsageAdmin\n- members:\n - serviceAccount:service-171999062104@sourcerepo-service-accounts.iam.gserviceaccount.com\n role: roles/sourcerepo.serviceAgent\n- members:\n - serviceAccount:[email protected]\n role: roles/storage.admin\netag: BwV_ubbP9N0=\nversion: 1\n"
]
],
[
[
"## Create service account keys if not existing",
"_____no_output_____"
]
],
[
[
"%%bash\ntest -f $SERVICE_KEY_PATH || \ngcloud iam service-accounts keys create $SERVICE_KEY_PATH \\\n --iam-account $SERVICE_ACCOUNT_EMAIL\n\necho \"Service key: $(ls $SERVICE_KEY_PATH)\"",
"Service key: /content/datalab/clones/document-processing/notebooks/entity-extractor.json\n"
]
],
[
[
"## Make the key available to google clients for authentication",
"_____no_output_____"
]
],
[
[
"os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = SERVICE_KEY_PATH",
"_____no_output_____"
]
],
[
[
"## Implement a document classifier with AutoML",
"_____no_output_____"
],
[
"Here is a simple wrapper around an already trained AutoML model trained directly\nfrom the cloud console on the various document types:",
"_____no_output_____"
]
],
[
[
"from google.cloud import automl_v1beta1 as automl\n\nclass DocumentClassifier:\n \n def __init__(self, project_id, model_id, zone):\n self.client = automl.PredictionServiceClient()\n self.model = self.client.model_path(project_id, zone, model_id)\n\n def __call__(self, filename):\n with open(filename, 'rb') as fp:\n image = fp.read()\n payload = {\n 'image': {\n 'image_bytes': image\n }\n }\n response = self.client.predict(self.model, payload)\n predicted_class = response.payload[0].display_name\n return predicted_class",
"_____no_output_____"
]
],
[
[
"Let's see how to use that `DocumentClassifier`:",
"_____no_output_____"
]
],
[
[
"classifier = DocumentClassifier(PROJECT_ID, AUTOML_MODEL_ID, ZONE)\n\neu_image_label = classifier(\"./eu_patent.png\")\nus_image_label = classifier(\"./us_patent.png\")\n\nprint(\"EU patent inferred label:\", eu_image_label)\nprint(\"US patent inferred label:\", us_image_label)",
"EU patent inferred label: eu\nUS patent inferred label: us\n"
]
],
[
[
"## Implement a document parser with Vision API",
"_____no_output_____"
],
[
"Documentation:\n* https://cloud.google.com/vision/docs/base64\n* https://stackoverflow.com/questions/49918950/response-400-from-google-vision-api-ocr-with-a-base64-string-of-specified-image\n",
"_____no_output_____"
],
[
"Here is a simple class wrapping calls to the OCR capabilities of Cloud Vision:",
"_____no_output_____"
]
],
[
[
"!pip freeze | grep google-api-python-client==1.7.7 || pip install --upgrade google-api-python-client==1.7.7",
"google-api-python-client==1.7.7\r\n"
],
[
"import base64\nfrom googleapiclient.discovery import build\n\nclass DocumentParser:\n def __init__(self):\n self.client = build('vision', 'v1')\n \n def __call__(self, filename):\n with open(filename, 'rb') as fp:\n image = fp.read() \n encoded_image = base64.b64encode(image).decode('UTF-8')\n payload = {\n 'requests': [{\n 'image': {\n 'content': encoded_image\n },\n 'features': [{\n 'type': 'TEXT_DETECTION',\n }]\n }],\n }\n request = self.client.images().annotate(body=payload)\n response = request.execute(num_retries=3)\n return response['responses'][0]['textAnnotations'][0]['description']",
"_____no_output_____"
]
],
[
[
"Let's now see how to use our `DocumentParser`:",
"_____no_output_____"
]
],
[
[
"parser = DocumentParser()\n\neu_patent_text = parser(\"./eu_patent.png\")\nus_patent_text = parser(\"./us_patent.png\")\n\nprint(eu_patent_text)",
"(19)\nEuropäisches\nPatentamt\n0\nEuropean\nPatent Office\nOffice européen\ndes brevets\nEP 3 399 652 A1\n(12)\nEUROPEAN PATENT APPLICATION\n(43) Date of publication:\n(51) Int Cl.:\n07.11.2018 Bulletin 2018/45\nH04B 117107 (2011.01)H04B 117073 (2011.01)\n(21) Application number: 18180150.7\n(22) Date of filing: 24.06.2009\n(84) Designated Contracting States\n. YEE, Nathan, D.\nAT BE BG CH CY CZ DE DK EE ES FI FR GB GR\nHR HU IE IS IT LI LT LU LV MC MK MT NL NO PL\nPT RO SE SI SK TR\nSan Diego, CA 92121-1714 (US)\nSUBRAHMANYA, Parvathanathaln\nSan Diego, CA 92121-1714 (US)\n(30) Priority: 25.06.2008 US 146232\n(74) Representative: Wegner, Hans\nBardehle Pagenberg Partnerschaft mbB\nPatentanwälte, Rechtsanwälte\nPrinzregentenplatz 7\n81675 München (DE)\n(62) Document number(s) of the earlier application(s) in\naccordance with Art. 76 EPC:\n09770969.5/2311 196\n(71) Applicant: QUALCOMM Incorporated\nSan Diego, CA 92121-1714 (US)\nRemarks:\nThis application was filed on 27-06-2018 as a\ndivisional application to the application mentioned\nunder INID code 62\n(72) Inventors:\nSHEN, Qiang\nSan Diego, CA 92121-1714 (US)\n(54)\nMETHODS AND APPARATUS FOR COMMON CHANNEL CANCELLATION IN WIRELESS\nCOMMUNICATIONS\n(57) A mobile station that is configured to perform\ncommon channel cancellation may include a parameter\nestimation unit that is configured to estimate parameters\nfor generating a common channel error. The mobile sta\ntion may also include a common channel generation unit\nthat is configured to generate the common channel error\nbased on the parameters. The mobile station may also\ninclude an adder that is configured to subtract the com\nmon channel error from received data samples\n700\n702\nEstimate parameters for generating a common channel error\n704\nGenerate the common channel error based on the parameters\n706\nSubtract the common channel error from received data samples\nFIG. 7\nPrinted by Jouve, 75001 PARIS (FR)\n\n"
]
],
[
[
"# Implement the rule-based extractors for each document categories",
"_____no_output_____"
],
[
"For each patent type, we now want to write a simple function that takes the \ntext extracted by the OCR system above and extract the name and date of the patent.\n\nWe will write two rule base extractors, one for each type of patent (us or eu), each of\nwhich will yield a PatentInfo object collecting the extracted object into a `nametuple` instance.",
"_____no_output_____"
]
],
[
[
"from collections import namedtuple\n\nPatentInfo = namedtuple('PatentInfo', ['filename', 'category', 'date', 'number'])",
"_____no_output_____"
]
],
[
[
"Here are two helper functions for text splitting and pattern matching:",
"_____no_output_____"
]
],
[
[
"!pip freeze | grep pandas==0.23.4 || pip install --upgrade pandas==0.23.4",
"pandas==0.23.4\r\n"
],
[
"import pandas as pd\nimport re\n\n\ndef split_text_into_lines(text, sep=\"\\(..\\)\"):\n lines = [line.strip() for line in re.split(sep, text)]\n return lines\n\n\ndef extract_pattern_from_lines(lines, pattern):\n \"\"\"Extracts the first line from `text` with a matching `pattern`.\n \"\"\"\n lines = pd.Series(lines)\n mask = lines.str.contains(pattern)\n return lines[mask].values[0] if mask.any() else None",
"_____no_output_____"
]
],
[
[
"### European patent extractor",
"_____no_output_____"
]
],
[
[
"def extract_info_from_eu_patent(filename, text):\n lines = split_text_into_lines(text)\n\n category = \"eu\"\n \n number_paragraph = extract_pattern_from_lines(lines, \"EP\")\n number_lines = number_paragraph.split('\\n')\n number = extract_pattern_from_lines(number_lines, 'EP') \n \n date_paragraph = extract_pattern_from_lines(lines, 'Date of filing:')\n date = date_paragraph.replace(\"Date of filing:\", \"\").strip()\n \n return PatentInfo(\n filename=filename,\n category=category,\n date=date,\n number=number\n )",
"_____no_output_____"
],
[
"eu_patent_info = extract_info_from_eu_patent(\"./eu_patent.png\", eu_patent_text)\neu_patent_info",
"_____no_output_____"
]
],
[
[
"### US patent extractor",
"_____no_output_____"
]
],
[
[
"def extract_info_from_us_patent(filename, text):\n lines = split_text_into_lines(text)\n\n category = \"us\"\n \n number_paragraph = extract_pattern_from_lines(lines, \"Patent No.:\")\n number = number_paragraph.replace(\"Patent No.:\", \"\").strip()\n \n date_paragraph = extract_pattern_from_lines(lines, \"Date of Patent:\")\n date = date_paragraph.split('\\n')[-1]\n \n return PatentInfo(\n filename=filename,\n category=category,\n date=date,\n number=number\n )",
"_____no_output_____"
],
[
"us_patent_info = extract_info_from_us_patent(\"./us_patent.png\", us_patent_text)\nus_patent_info",
"_____no_output_____"
]
],
[
[
"## Tie all together into a DocumentExtractor",
"_____no_output_____"
]
],
[
[
"class DocumentExtractor:\n def __init__(self, classifier, parser):\n self.classifier = classifier\n self.parser = parser\n\n def __call__(self, filename):\n\n text = self.parser(filename)\n label = self.classifier(filename)\n \n if label == 'eu':\n info = extract_info_from_eu_patent(filename, text)\n elif label == 'us':\n info = extract_info_from_us_patent(filename, text)\n else:\n raise ValueError\n \n return info",
"_____no_output_____"
],
[
"extractor = DocumentExtractor(classifier, parser)\n\neu_patent_info = extractor(\"./eu_patent.png\")\nus_patent_info = extractor(\"./us_patent.png\")\n\nprint(eu_patent_info)\nprint(us_patent_info)",
"PatentInfo(filename='./eu_patent.png', category='eu', date='24.06.2009', number='EP 3 399 652 A1')\nPatentInfo(filename='./us_patent.png', category='us', date='Nov. 27, 2018', number='US 10,142,913 B2')\n"
]
],
[
[
"## Upload found entites to BigQuery\nStart by adding a dataset called patents to the current project",
"_____no_output_____"
]
],
[
[
"!pip freeze | grep google-cloud-bigquery==1.8.1 || pip install google-cloud-bigquery==1.8.1",
"google-cloud-bigquery==1.8.1\r\n"
]
],
[
[
"Check to see if the dataset called \"patents\" exists in the current project. If not, create it. ",
"_____no_output_____"
]
],
[
[
"from google.cloud import bigquery\n\n\nclient = bigquery.Client()\n\n# Collect datasets and project information\ndatasets = list(client.list_datasets())\nproject = client.project\n\n# Create a list of the datasets. If the 'patents' dataset \n# does not exist, then create it.\nif datasets:\n all_datasets = []\n for dataset in datasets:\n all_datasets.append(dataset.dataset_id)\nelse:\n print('{} project does not contain any datasets.'.format(project))\n\nif datasets and 'patents' in all_datasets:\n print('The dataset \"patents\" already exists in project {}.'.format(project))\nelse:\n dataset_id = 'patents'\n dataset_ref = client.dataset(dataset_id)\n\n # Construct a Dataset object.\n dataset = bigquery.Dataset(dataset_ref)\n\n # Specify the geographic location where the dataset should reside.\n dataset.location = \"US\"\n\n # Send the dataset to the API for creation.\n dataset = client.create_dataset(dataset) # API request\n print('The dataset \"patents\" was created in project {}.'.format(project))",
"The dataset \"patents\" already exists in project asl-open-projects.\n"
]
],
[
[
"Upload the extracted entities to a table called \"found_entities\" in the \"patents\" dataset.\n\nStart by creating an empty table in the patents dataset.",
"_____no_output_____"
]
],
[
[
"# Create an empty table in the patents dataset and define schema\ndataset_ref = client.dataset('patents')\n\nschema = [\n bigquery.SchemaField('filename', 'STRING', mode='NULLABLE'),\n bigquery.SchemaField('category', 'STRING', mode='NULLABLE'),\n bigquery.SchemaField('date', 'STRING', mode='NULLABLE'),\n bigquery.SchemaField('number', 'STRING', mode='NULLABLE'),\n]\ntable_ref = dataset_ref.table('found_entities')\ntable = bigquery.Table(table_ref, schema=schema)\ntable = client.create_table(table) # API request\n\nassert table.table_id == 'found_entities'",
"_____no_output_____"
],
[
"def upload_to_bq(patent_info, dataset_id, table_id):\n \"\"\"Appends the information extracted in patent_info into the \n dataset_id:table_id in BigQuery.\n patent_info should be a namedtuple as created above and should\n have components matching the schema set up for the table\n \"\"\"\n table_ref = client.dataset(dataset_id).table(table_id)\n table = client.get_table(table_ref) # API request\n\n rows_to_insert = [tuple(patent_info._asdict().values())]\n\n errors = client.insert_rows(table, rows_to_insert) # API request\n\n assert errors == []",
"_____no_output_____"
],
[
"upload_to_bq(eu_patent_info, 'patents', 'found_entities')\nupload_to_bq(us_patent_info, 'patents', 'found_entities')",
"_____no_output_____"
]
],
[
[
"### Examine the resuts in BigQuery. \nWe can now query the BigQuery table to see what values have been uploaded.",
"_____no_output_____"
]
],
[
[
"%load_ext google.cloud.bigquery",
"_____no_output_____"
],
[
"%%bigquery\nSELECT\n *\nFROM `asl-open-projects.patents.found_entities`",
"_____no_output_____"
]
],
[
[
"We can also look at the resulting entities in a dataframe. ",
"_____no_output_____"
]
],
[
[
"dataset_id = 'patents'\ntable_id = 'found_entities'\n\nsql = \"\"\"\nSELECT\n *\nFROM\n `{}.{}.{}`\nLIMIT 10\n\"\"\".format(project, dataset_id, table_id)\n\ndf = client.query(sql).to_dataframe()\ndf.head()",
"_____no_output_____"
]
],
[
[
"## Pipeline Evaluation",
"_____no_output_____"
],
[
"TODO: We should include some section on how to evaluate the performance of the extractor. Here we can use the ground_truth table and explore different kinds of string metrics (e.g. Levenshtein distance) to measure accuracy of the entity extraction.",
"_____no_output_____"
],
[
"## Clean up",
"_____no_output_____"
],
[
"To remove the table \"found_entities\" from the \"patents\" dataset created above.",
"_____no_output_____"
]
],
[
[
"dataset_id = 'patents'\ntable_id = 'found_entities'\n\ntables = list(client.list_tables(dataset_id)) # API request(s)\n\nif tables:\n num_tables = len(tables)\n all_tables = []\n for _ in range(num_tables):\n all_tables.append(tables[_].table_id)\n print('These tables were found in the {} dataset: {}'.format(dataset_id,all_tables))\n if table_id in all_tables:\n table_ref = client.dataset(dataset_id).table(table_id)\n client.delete_table(table_ref) # API request\n print('Table {} was deleted from dataset {}.'.format(table_id, dataset_id))\nelse:\n print('{} dataset does not contain any tables.'.format(dataset_id))",
"These tables were found in the patents dataset: ['found_entities', 'ground_truth']\nTable found_entities was deleted from dataset patents.\n"
]
],
[
[
"### The next cells will remove the patents dataset and all of its tables. Not recommended as I recently uploaded a talbe of 'ground_truth' for entities in the files",
"_____no_output_____"
],
[
"To remove the \"patents\" dataset and all of its tables.",
"_____no_output_____"
]
],
[
[
"'''\nclient = bigquery.Client()\n# Collect datasets and project information\ndatasets = list(client.list_datasets())\nproject = client.project\n\nif datasets:\n all_datasets = []\n for dataset in datasets:\n all_datasets.append(dataset.dataset_id)\n if 'patents' in all_datasets:\n # Delete the dataset \"patents\" and its contents\n dataset_id = 'patents'\n dataset_ref = client.dataset(dataset_id)\n client.delete_dataset(dataset_ref, delete_contents=True)\n print('Dataset {} deleted from project {}.'.format(dataset_id, project))\n else: print('{} project does not contain the \"patents\" datasets.'.format(project))\nelse:\n print('{} project does not contain any datasets.'.format(project))\n'''",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
4aa8a4d67e7bdd9267e8586c3962a0b00b5e0bc1
| 26,275 |
ipynb
|
Jupyter Notebook
|
notebooks/1.xx-sfb-try-mediawikis-recentchanges-api.ipynb
|
bhrdj/predwikt
|
f27066fe2308f918abc9fdace93dcdc4fa75173b
|
[
"MIT"
] | null | null | null |
notebooks/1.xx-sfb-try-mediawikis-recentchanges-api.ipynb
|
bhrdj/predwikt
|
f27066fe2308f918abc9fdace93dcdc4fa75173b
|
[
"MIT"
] | null | null | null |
notebooks/1.xx-sfb-try-mediawikis-recentchanges-api.ipynb
|
bhrdj/predwikt
|
f27066fe2308f918abc9fdace93dcdc4fa75173b
|
[
"MIT"
] | null | null | null | 28.715847 | 134 | 0.457812 |
[
[
[
"# Try MediaWiki's RecentChanges API",
"_____no_output_____"
],
[
"## Setup",
"_____no_output_____"
],
[
"### imports",
"_____no_output_____"
]
],
[
[
"import pandas as pd, dateutil.parser as dp\nimport os, requests, datetime, time, json\nfrom sseclient import SSEClient as EventSource",
"_____no_output_____"
]
],
[
[
"### define function ```get_rc```",
"_____no_output_____"
]
],
[
[
"def get_rc(rc_list:list, params:dict, url: str, sesh) -> str:\n '''\n Inputs: rc_list: list to be populated with recentchanges jsons\n params: dictionary of parameters for the API request\n this fn expects at least these parameters:\n 'rcprop' : 'timestamp|ids', (more is okay)\n 'action' : 'query',\n 'rcdir' : 'newer',\n 'format' : 'json',\n 'list' : 'recentchanges',\n url: API url (designates which wiki)\n sesh: requests session\n Outputs: timestamp of latest \n '''\n raw_output= sesh.get(url=url, params=params)\n json_data = raw_output.json()\n recent_changes = json_data['query']['recentchanges']\n rc_list.append(recent_changes)\n timestamps = [rc['timestamp'] for rc in recent_changes]\n timestamps = sorted(map(dp.isoparse, timestamps))\n ts = timestamps[-3]\n return ts.strftime('%Y-%m-%dT%H:%M:%SZ')\n",
"_____no_output_____"
]
],
[
[
"## Collect 500 recent changes",
"_____no_output_____"
],
[
"### get ```rc_list```",
"_____no_output_____"
],
[
"#### initialize requests session",
"_____no_output_____"
]
],
[
[
"sesh = requests.Session()",
"_____no_output_____"
]
],
[
[
"#### set parameters",
"_____no_output_____"
]
],
[
[
"rc_list=[]\nurl = 'https://en.wikipedia.org/w/api.php'\nparams = {\n 'rcstart' : '2021-10-20T00:30:01Z',\n 'rcnamespace' : '0',\n 'rcshow' : '!bot',\n 'rclimit' : '50',\n \n 'rcprop': 'user|userid|timestamp|title|ids|sizes',\n \n 'action' : 'query',\n 'rcdir' : 'newer',\n 'format' : 'json',\n 'list' : 'recentchanges',\n}\n\n# Dictionary keys that output from these parameters:\n['timestamp', 'type', 'title', 'anon', 'rcid', 'ns', 'revid', 'pageid', 'user', 'userid', 'oldlen', 'old_revid', 'newlen'];",
"_____no_output_____"
]
],
[
[
"#### populate rc_list",
"_____no_output_____"
]
],
[
[
"for i in range(10):\n latest_timestamp = get_rc(rc_list, params, url, sesh)\n params['rcstart'] = latest_timestamp\n print(f'{i} {latest_timestamp}')\n time.sleep(.5)",
"0 2022-01-29T11:08:54Z\n1 2022-01-29T11:09:35Z\n2 2022-01-29T11:10:19Z\n3 2022-01-29T11:10:59Z\n4 2022-01-29T11:11:42Z\n5 2022-01-29T11:12:29Z\n6 2022-01-29T11:13:16Z\n7 2022-01-29T11:13:58Z\n8 2022-01-29T11:14:22Z\n9 2022-01-29T11:14:36Z\n"
]
],
[
[
"### peek at ```rc_list```",
"_____no_output_____"
],
[
"#### check dimensions of nested list",
"_____no_output_____"
]
],
[
[
"len(rc_list), len(rc_list[0]), len(rc_list[0][0])",
"_____no_output_____"
]
],
[
[
"#### look at one JSON element of nested list",
"_____no_output_____"
]
],
[
[
"rc_list[0][0]",
"_____no_output_____"
]
],
[
[
"#### timestamp of latest recentchanges record",
"_____no_output_____"
]
],
[
[
"latest_timestamp",
"_____no_output_____"
]
],
[
[
"### flatten rc_list to get unique_jsons",
"_____no_output_____"
],
[
"#### flatten",
"_____no_output_____"
]
],
[
[
"# flatten the jsons\nall_jsons = [item for sublist in rc_list for item in sublist]\n# remove jsons with duplicate rcid's\nall_rcids = {j['rcid']:i for i,j in enumerate(all_jsons)}\nunique_jsons = [all_jsons[i] for i in all_rcids.values()]",
"_____no_output_____"
]
],
[
[
"#### make dataframe",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame.from_records(unique_jsons)",
"_____no_output_____"
]
],
[
[
"#### peek at jsons as dataframe",
"_____no_output_____"
]
],
[
[
"df",
"_____no_output_____"
],
[
"# df.to_csv('../data/interim/2021-10-20T00:30:01Z_2021-10-20T01:39:40Z.csv')",
"_____no_output_____"
]
],
[
[
"## Build SQL schema for import into database",
"_____no_output_____"
],
[
"### This is for postgreSQL; <mark>(Update for MySQL)</mark>",
"_____no_output_____"
],
[
"#### make \"create table\" query",
"_____no_output_____"
]
],
[
[
"sql_create_table = \"\"\"\nDROP TABLE IF EXISTS data_raw;\n\nCREATE TABLE data_raw(\n row_index SERIAL,\n time_string char varying(25),\n unix_time bigint,\n instance char varying(35),\n product char varying(5),\n username char varying(35),\n event char varying(100),\n attributes text\n);\n\"\"\"",
"_____no_output_____"
]
],
[
[
"#### connect to database",
"_____no_output_____"
]
],
[
[
"try:\n conn = psycopg2.connect(\"host=\"+dbhost+\" dbname=\"+dbname+\" user=\"+dbuname+\" password=\"+dbpassword)\n cur = conn.cursor()\nexcept:\n print('Database connection error - check creds')",
"_____no_output_____"
]
],
[
[
"#### create table and import data",
"_____no_output_____"
]
],
[
[
"cur.execute(sql_create_table)\nsql_import = \"COPY data_raw(time_string,unix_time,instance,product,username,event,attributes) FROM STDIN DELIMITER E'\\t';\"\ncur.copy_expert(sql_import, open('jira_clean.tsv', \"r\",encoding=\"utf8\"))\nconn.commit()",
"_____no_output_____"
]
],
[
[
"#### update table to have date ",
"_____no_output_____"
]
],
[
[
"sql_calc_table = \"\"\"\nDROP TABLE IF EXISTS data_prep;\n\nCREATE TABLE data_prep as (\n select \n row_index\n , to_timestamp(time_string,'YYYY-MM-DD HH24:MI,MS')::timestamp without time zone as time_parsed\n , unix_time\n , instance\n , username\n , event\n , attributes\n from\n data_raw\n);\n\"\"\"\ncur.execute(sql_calc_table)\nconn.commit()",
"_____no_output_____"
]
],
[
[
"#### SQLAlchemy",
"_____no_output_____"
]
],
[
[
"# Finally, let's instantiate a SQL alchemy engine, so we can pass results sets into pandas and evaluate them here \nconnection_str = 'postgresql+psycopg2://'+dbuname+':'+dbpassword+'@'+dbhost+':'+dbport+'/'+dbname\ntry:\n engine1 = sqlalchemy.create_engine(connection_str)\n conn1 = engine1.connect()\nexcept:\n print('Database connection error - check creds')\nengine1.table_names() # Confirm connection and tables are present as expect",
"_____no_output_____"
]
],
[
[
"#### More detailed requests from wikipedia",
"_____no_output_____"
]
],
[
[
"import requests\nrequests_session = requests.Session()\nurl = 'https://en.wikipedia.org/w/api.php'\nparams = {\n 'rcstart' : '2021-10-20T00:30:01Z',\n 'rcdir' : 'newer',\n 'rcnamespace' : '0',\n 'format' : 'json',\n 'rcprop': 'user|userid|comment|flags|timestamp|title|ids|sizes|redirect|tags|loginfo',\n 'list' : 'recentchanges',\n 'action' : 'query',\n 'rclimit' : '50',\n 'rcshow' : '!bot'\n}",
"_____no_output_____"
],
[
"fields = ['anon', 'comment', 'logaction', 'logid', 'logparams', \n 'logtype', 'minor', 'new', 'newlen', 'ns', \n 'old_revid', 'oldlen', 'pageid', 'rcid', 'redirect', \n 'revid', 'tags', 'tagstags', 'timestamp', 'title', \n 'type', 'user', 'userid']\nlen(fields);",
"_____no_output_____"
],
[
"# List of wikipedias is used to filter wikipedia edits out from other wiki projects\nwkps = pd.read_csv('../data/external/wikipedias.csv').assign(code=lambda x: x.abbrev + 'wiki')\nwkps.columns",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"raw",
"markdown",
"raw",
"markdown",
"raw",
"markdown",
"raw",
"markdown",
"raw",
"markdown",
"raw"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"raw"
],
[
"markdown"
],
[
"raw"
],
[
"markdown"
],
[
"raw"
],
[
"markdown"
],
[
"raw"
],
[
"markdown"
],
[
"raw"
],
[
"markdown"
],
[
"raw",
"raw",
"raw"
]
] |
4aa8b698aa4d0507ee1415d76354ff59b936738f
| 3,018 |
ipynb
|
Jupyter Notebook
|
guinea.ipynb
|
andersle/seirmodel
|
0a42a18d595bdaebea0f046aea77c550a62ceecd
|
[
"MIT"
] | null | null | null |
guinea.ipynb
|
andersle/seirmodel
|
0a42a18d595bdaebea0f046aea77c550a62ceecd
|
[
"MIT"
] | null | null | null |
guinea.ipynb
|
andersle/seirmodel
|
0a42a18d595bdaebea0f046aea77c550a62ceecd
|
[
"MIT"
] | null | null | null | 22.029197 | 105 | 0.535123 |
[
[
[
"SEIR model for the 2014 outbreak in Guinea.\nNumbers are taken from: [this article](10.1371/currents.outbreaks.91afb5e0f279e7f29e7056095255b288)",
"_____no_output_____"
]
],
[
[
"%matplotlib notebook\nimport dateutil.parser\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nfrom model import run_model\nfrom plotting import (\n plot_model_and_raw_data,\n plot_model_evolution,\n plot_model_evolution_item,\n)\nplt.style.use('seaborn-notebook')",
"_____no_output_____"
],
[
"raw = pd.read_csv('data/ebola_guinea.csv')\nraw['Date'] = [dateutil.parser.parse(i) for i in raw['Date'].values]",
"_____no_output_____"
],
[
"time_zero = dateutil.parser.parse('2 Dec 2013')\n\nparameters = {\n 'infectiousness': 5.61,\n 'incubation': 5.3,\n 'r0': 1.5011,\n 'fatality': 0.74,\n 'kappa': 0.0023,\n 'tau': 0,\n 'time_zero': time_zero,\n}\n\nparameters['beta_0'] = parameters['r0'] / parameters['infectiousness']\nparameters",
"_____no_output_____"
],
[
"population = 12 * 10**6\ninitial_values = [population, 0, 1, 0, 0, 1]\ntime_span = [0, 350]",
"_____no_output_____"
],
[
"result, _, time_date, model = run_model(time_span, parameters, initial_values)",
"_____no_output_____"
],
[
"plot_model_and_raw_data(\n time_date,\n model,\n raw,\n max_model_date=dateutil.parser.parse('01 Sep 2014')\n)",
"_____no_output_____"
],
[
"plot_model_evolution(time_date, model)",
"_____no_output_____"
],
[
"plot_model_evolution_item(time_date, model, 'infected')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aa8d3bdc2cd923ab426dd84920fab9de3d0af77
| 158,071 |
ipynb
|
Jupyter Notebook
|
module2-wrangle-ml-datasets/LS_DS_232.ipynb
|
ArmandoSep/DS-Unit-2-Applied-Modeling
|
e94815618e7e550bde0147b9b0f61ac5e8ee706b
|
[
"MIT"
] | null | null | null |
module2-wrangle-ml-datasets/LS_DS_232.ipynb
|
ArmandoSep/DS-Unit-2-Applied-Modeling
|
e94815618e7e550bde0147b9b0f61ac5e8ee706b
|
[
"MIT"
] | null | null | null |
module2-wrangle-ml-datasets/LS_DS_232.ipynb
|
ArmandoSep/DS-Unit-2-Applied-Modeling
|
e94815618e7e550bde0147b9b0f61ac5e8ee706b
|
[
"MIT"
] | null | null | null | 41.630498 | 14,490 | 0.422671 |
[
[
[
"<a href=\"https://colab.research.google.com/github/ArmandoSep/DS-Unit-2-Applied-Modeling/blob/master/module2-wrangle-ml-datasets/LS_DS_232.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"Lambda School Data Science\n\n*Unit 2, Sprint 3, Module 2*\n\n---\n",
"_____no_output_____"
],
[
"# Wrangle ML datasets \n- Explore tabular data for supervised machine learning\n- Join relational data for supervised machine learning",
"_____no_output_____"
],
[
"# Explore tabular data for superviesd machine learning 🍌",
"_____no_output_____"
],
[
"Wrangling your dataset is often the most challenging and time-consuming part of the modeling process.\n\nIn today's lesson, we’ll work with a dataset of [3 Million Instacart Orders, Open Sourced](https://tech.instacart.com/3-million-instacart-orders-open-sourced-d40d29ead6f2)!\n\nLet’s get set up:",
"_____no_output_____"
]
],
[
[
"# Download data\nimport requests\n\ndef download(url):\n filename = url.split('/')[-1]\n print(f'Downloading {url}')\n r = requests.get(url)\n with open(filename, 'wb') as f:\n f.write(r.content)\n print(f'Downloaded {filename}')\n\ndownload('https://s3.amazonaws.com/instacart-datasets/instacart_online_grocery_shopping_2017_05_01.tar.gz')",
"Downloading https://s3.amazonaws.com/instacart-datasets/instacart_online_grocery_shopping_2017_05_01.tar.gz\nDownloaded instacart_online_grocery_shopping_2017_05_01.tar.gz\n"
],
[
"# Uncompress data\nimport tarfile\ntarfile.open('instacart_online_grocery_shopping_2017_05_01.tar.gz').extractall()",
"_____no_output_____"
],
[
"# Change directory to where the data was uncompressed\n%cd instacart_2017_05_01",
"/content/instacart_2017_05_01\n"
],
[
"# Print the csv filenames\nfrom glob import glob\nfor filename in glob('*.csv'):\n print(filename)",
"aisles.csv\norder_products__train.csv\ndepartments.csv\norder_products__prior.csv\nproducts.csv\norders.csv\n"
],
[
"# For each csv file, look at its shape & head\nimport pandas as pd\nfrom IPython.display import display\n\ndef preview(): \n for filename in glob('*.csv'):\n df = pd.read_csv(filename)\n print('\\n', filename, df.shape)\n display(df.head())\n",
"_____no_output_____"
],
[
"preview()",
"\n aisles.csv (134, 2)\n"
]
],
[
[
"### The original task was complex ...\n\n[The Kaggle competition said,](https://www.kaggle.com/c/instacart-market-basket-analysis/data):\n\n> The dataset for this competition is a relational set of files describing customers' orders over time. The goal of the competition is to predict which products will be in a user's next order.\n\n> orders.csv: This file tells to which set (prior, train, test) an order belongs. You are predicting reordered items only for the test set orders.\n\nEach row in the submission is an order_id from the test set, followed by product_id(s) predicted to be reordered.\n\n> sample_submission.csv: \n```\norder_id,products\n17,39276 29259\n34,39276 29259\n137,39276 29259\n182,39276 29259\n257,39276 29259\n```",
"_____no_output_____"
],
[
"### ... but we can simplify!\n\nSimplify the question, from \"Which products will be reordered?\" (Multi-class, [multi-label](https://en.wikipedia.org/wiki/Multi-label_classification) classification) to **\"Will customers reorder this one product?\"** (Binary classification)\n\nWhich product? How about **the most frequently ordered product?**\n",
"_____no_output_____"
],
[
"### Questions:\n\n- What is the most frequently ordered product?\n- How often is this product included in a customer's next order?\n- Which customers have ordered this product before?\n- How can we get a subset of data, just for these customers?\n- What features can we engineer? We want to predict, will these customers reorder this product on their next order?",
"_____no_output_____"
],
[
"## Follow Along\n### What was the most frequently ordered product?",
"_____no_output_____"
]
],
[
[
"order_products__train = pd.read_csv('order_products__train.csv')\norder_products__train.head()",
"_____no_output_____"
],
[
"order_products__train['product_id'].value_counts()",
"_____no_output_____"
],
[
"# Group by example\ntemp = order_products__train.sort_values(by='product_id',\n ascending=False).head()\ntemp",
"_____no_output_____"
],
[
"temp.groupby('product_id').count()",
"_____no_output_____"
],
[
"order_products__train.groupby('product_id').order_id.count().sort_values(\n ascending=False\n)",
"_____no_output_____"
],
[
"# Product 24852 was ordered almsot 20k times.\n# Read the products table to see what product is it\n\nproducts = pd.read_csv('products.csv')\nproducts.head()",
"_____no_output_____"
],
[
"products[products.product_id==24852]",
"_____no_output_____"
],
[
"# On -> the common column\ntrain = pd.merge(order_products__train, products, how='inner', on='product_id')",
"_____no_output_____"
],
[
"train.head()",
"_____no_output_____"
],
[
"train['product_name'].value_counts()",
"_____no_output_____"
]
],
[
[
"### How often are bananas included in a customer's next order?\n\nThere are [three sets of data](https://gist.github.com/jeremystan/c3b39d947d9b88b3ccff3147dbcf6c6b):\n\n> \"prior\": orders prior to that users most recent order (3.2m orders) \n\"train\": training data supplied to participants (131k orders) \n\"test\": test data reserved for machine learning competitions (75k orders)\n\nCustomers' next orders are in the \"train\" and \"test\" sets. (The \"prior\" set has the orders prior to the most recent orders.)\n\nWe can't use the \"test\" set here, because we don't have its labels (only Kaggle & Instacart have them), so we don't know what products were bought in the \"test\" set orders.\n\nSo, we'll use the \"train\" set. It currently has one row per product_id and multiple rows per order_id.\n\nBut we don't want that. Instead we want one row per order_id, with a binary column: \"Did the order include bananas?\"\n\nLet's wrangle!",
"_____no_output_____"
]
],
[
[
"train.head()",
"_____no_output_____"
],
[
"# Goal: 'Yes, they orderer no bananas'.\n\ntrain['bananas'] = train['product_name'] == 'Banana'",
"_____no_output_____"
],
[
"train.head()",
"_____no_output_____"
],
[
"# How ofen are banans included in the customer's next order? Is this true\n\ntrain['bananas'].value_counts(normalize=True)",
"_____no_output_____"
],
[
"# Let's use group by to simply our data down to bananas only\n# .any() -> if there is at least one True boolean, it will return True\n\ntrain_wrangled = train.groupby('order_id')['bananas'].any().reset_index()\ntrain_wrangled.head()",
"_____no_output_____"
],
[
"train_wrangled['bananas'].value_counts(normalize=True)",
"_____no_output_____"
],
[
"# What is the most common hour of the day that bananas are ordered?\n# What about the common hour for any order?\n\nimport numpy as np\n\ntrain[train['bananas']]",
"_____no_output_____"
],
[
"# What other table do we need? Orders:\n\norders = pd.read_csv('orders.csv')\norders.head()",
"_____no_output_____"
],
[
"# What hour of the day most typical to place an order?\n\norders['order_hour_of_day'].value_counts(normalize=True)",
"_____no_output_____"
]
],
[
[
"# Join relational data for supervised machine learning",
"_____no_output_____"
],
[
"## Overview\nOften, you’ll need to join data from multiple relational tables before you’re ready to fit your models.",
"_____no_output_____"
],
[
"### Which customers have ordered this product before?\n\n- Customers are identified by `user_id`\n- Products are identified by `product_id`\n\nDo we have a table with both these id's? (If not, how can we combine this information?)",
"_____no_output_____"
]
],
[
[
"banana_order_id = train[train['bananas']].order_id\nbanana_order_id",
"_____no_output_____"
],
[
"orders[orders['order_id'].isin(banana_order_id)]",
"_____no_output_____"
],
[
"# Most typical hour for people who bought bananas\nbanana_orders = orders[orders['order_id'].isin(banana_order_id)]\nbanana_orders['order_hour_of_day'].value_counts(normalize=True)\n",
"_____no_output_____"
],
[
"banana_orders.head()",
"_____no_output_____"
],
[
"# Double check that we did things right, and that order 1492625 has a banana\n\ntrain[train['order_id'] == 1492625]",
"_____no_output_____"
]
],
[
[
"## Follow Along",
"_____no_output_____"
],
[
"### How can we get a subset of data, just for these customers?\n\nWe want *all* the orders from customers who have *ever* bought bananas.\n\n(And *none* of the orders from customers who have *never* bought bananas.)",
"_____no_output_____"
]
],
[
[
"# We did this above,\n# note that this wasn't a merget directly\n# but instead reused past merges and sliced a df by id",
"_____no_output_____"
]
],
[
[
"### What features can we engineer? We want to predict, will these customers reorder bananas on their next order?",
"_____no_output_____"
]
],
[
[
"# Is there a differece in average order size in bana orders vs. not?\n# We know that it's about -10 items/order in general\n# Number of items/order could be an interesting feature\n\norders.head()",
"_____no_output_____"
],
[
"train.head()",
"_____no_output_____"
],
[
"product_order_counts = train.groupby(['order_id']).count()['product_id']\nproduct_order_counts",
"_____no_output_____"
],
[
"product_order_counts.describe()",
"_____no_output_____"
],
[
"import seaborn as sns\n\nsns.distplot(product_order_counts);",
"_____no_output_____"
],
[
"# Number of items in an order where bananas where purchased\nbanana_orders_counts = train[train['order_id'].isin(banana_order_id)].groupby(\n ['order_id']).count()['product_id']\nbanana_orders_counts.mean()",
"_____no_output_____"
],
[
"banana_orders_counts.describe()",
"_____no_output_____"
],
[
"sns.distplot(banana_orders_counts);",
"_____no_output_____"
]
],
[
[
"## Challenge\n\n**Continue to clean and explore your data.** Can you **engineer features** to help predict your target? For the evaluation metric you chose, what score would you get just by guessing? Can you **make a fast, first model** that beats guessing?\n\nWe recommend that you use your portfolio project dataset for all assignments this sprint. But if you aren't ready yet, or you want more practice, then use the New York City property sales dataset today. Follow the instructions in the assignment notebook. [Here's a video walkthrough](https://youtu.be/pPWFw8UtBVg?t=584) you can refer to if you get stuck or want hints!",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
4aa8d85299ba42bddd23568faf1c72d559388feb
| 110,980 |
ipynb
|
Jupyter Notebook
|
Scraping_demo.ipynb
|
nithishr/meetup_scraping
|
bf21080dabe1e6a6d83db4de1de54dcdc62bbfc9
|
[
"MIT"
] | null | null | null |
Scraping_demo.ipynb
|
nithishr/meetup_scraping
|
bf21080dabe1e6a6d83db4de1de54dcdc62bbfc9
|
[
"MIT"
] | 2 |
2020-03-24T15:34:16.000Z
|
2020-03-30T20:08:59.000Z
|
Scraping_demo.ipynb
|
nithishr/meetup_scraping
|
bf21080dabe1e6a6d83db4de1de54dcdc62bbfc9
|
[
"MIT"
] | null | null | null | 47.488233 | 395 | 0.400433 |
[
[
[
"## HTML Essentials",
"_____no_output_____"
]
],
[
[
"%%html\n<html>\n <head>\n <title>Page Title</title>\n </head>\n <body>\n <h1>This is a Heading</h1>\n <p>This is a paragraph.</p>\n <a href=\"https://www.w3schools.com/\">This is a link to tutorials</a>\n </body>\n</html>",
"_____no_output_____"
]
],
[
[
"## CSS Classes",
"_____no_output_____"
]
],
[
[
"%%html\n<p class=\"center medium\">This paragraph refers to two classes.</p>",
"_____no_output_____"
]
],
[
[
"### Simple Beautiful Soup Example",
"_____no_output_____"
]
],
[
[
"html_string = r\"\"\"<html>\n <head>\n <title>Page Title</title>\n </head>\n <body>\n <h1>This is a Heading</h1>\n <p>This is a paragraph.</p>\n <a href=\"https://www.w3schools.com/\">This is a link to tutorials</a>\n </body>\n</html>\"\"\"",
"_____no_output_____"
],
[
"from bs4 import BeautifulSoup",
"_____no_output_____"
],
[
"html_soup = BeautifulSoup(html_string, 'html.parser')",
"_____no_output_____"
],
[
"html_soup.head.text",
"_____no_output_____"
],
[
"html_soup.a.get('href')",
"_____no_output_____"
]
],
[
[
"### Requests & Responses",
"_____no_output_____"
]
],
[
[
"import requests",
"_____no_output_____"
],
[
"response = requests.get('https://www.bundes-telefonbuch.de/nuernberg/firma/karosseriefachbetrieb-hofer-tb1150222')",
"_____no_output_____"
],
[
"print(response.status_code)",
"200\n"
],
[
"print(response.text)",
"<!DOCTYPE html>\n<html lang=\"de\">\n<head>\n <meta charset=\"utf-8\"/>\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"/>\n<title>Karosseriefachbetrieb Hofer in 90431, Nürnberg</title>\n<meta name=\"description\" content=\" ✓ Karosseriefachbetrieb Hofer ⌂ Hans-Bunte-Str. 47, 90431 Nürnberg. 3 Bilder, Telefonnummer und Anschrift finden Sie im Bundestelefonbuch.\"/>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>\n<meta name=\"google-site-verification\" content=\"3OBXd2NBPoTz5Mxt-TZqneKf3PLYXGnZ9QDvEJUnH4w\"/>\n<meta name=\"msvalidate.01\" content=\"5571DC1344E41A655D0D4C965A626E77\"/> <!-- Bing -->\n<script type=\"text/javascript\">window.___gcfg = {lang: 'de'}</script>\n<script src=\"https://apis.google.com/js/platform.js\" async defer></script>\n<meta name=\"robots\" content=\"index,follow,archive\"/>\n <link rel=\"canonical\" href=\"https://www.bundes-telefonbuch.de/nuernberg/firma/karosseriefachbetrieb-hofer-tb1150222\"/>\n\n\n\n<!-- Begin Cookie Consent plugin by Silktide - http://silktide.com/cookieconsent -->\n<script type=\"text/javascript\">\n window.cookieconsent_options = {\n \"message\": \"Ich stimme zu, dass diese Seite Cookies für Analysen, personalisierte Inhalte und Werbung verwendet. \",\n \"dismiss\": \"Ok\",\n \"learnMore\": \"Mehr erfahren\",\n \"link\": \"https://www.bundes-telefonbuch.de/infos/datenschutzhinweis#5\",\n \"theme\": \"dark-top\"\n };\n</script>\n\n<script type=\"text/javascript\"\n src=\"//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/1.0.9/cookieconsent.min.js\"></script>\n<!-- End Cookie Consent plugin -->\n\n<!-- Facebook Share Information -->\n<meta property=\"og:type\" content=\"website\"/>\n<meta property=\"og:site_name\" content=\"BundesTelefonbuch\"/>\n<meta property=\"fb:app_id\" content=\"445350842203770\"/>\n<meta property=\"og:url\" content=\"https://www.bundes-telefonbuch.de/nuernberg/firma/karosseriefachbetrieb-hofer-tb1150222\"/>\n<meta property=\"og:title\" content=\"Karosseriefachbetrieb Hofer in 90431, Nürnberg\"/>\n<meta property=\"og:description\" content=\" ✓ Karosseriefachbetrieb Hofer ⌂ Hans-Bunte-Str. 47, 90431 Nürnberg. 3 Bilder, Telefonnummer und Anschrift finden Sie im Bundestelefonbuch.\"/>\n<meta property=\"og:image\" content=\"https://www.bundes-telefonbuch.de/img/logo_dialo_400x400.png\"/>\n<!-- Facebook Share Information -->\n\n\n<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css\">\n\n\n<link rel=\"icon\" type=\"image/x-icon\" href=\"https://www.bundes-telefonbuch.de/favicon.ico\"/>\n<link rel=\"apple-touch-icon\" sizes=\"180x180\" href=\"https://www.bundes-telefonbuch.de/apple-touch-icon.png\">\n<link rel=\"icon\" type=\"image/png\" href=\"https://www.bundes-telefonbuch.de/favicon-32x32.png\" sizes=\"32x32\">\n<link rel=\"icon\" type=\"image/png\" href=\"https://www.bundes-telefonbuch.de/favicon-16x16.png\" sizes=\"16x16\">\n<link rel=\"manifest\" href=\"https://www.bundes-telefonbuch.de/manifest.json\">\n<link rel=\"mask-icon\" href=\"https://www.bundes-telefonbuch.de/safari-pinned-tab.svg\" color=\"#c4091d\">\n<meta name=\"theme-color\" content=\"#ffffff\">\n\n\n<script src=\"https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyCIviOgBC4_EmAjKmfpLVo_FKR6OAUY2y0\"></script>\n\n<script type=\"text/javascript\" src=\"https://www.bundes-telefonbuch.de/js/head_all.js?1498638616\"></script>\n\n<script type=\"text/javascript\">\n \n (function (w) {\n w['Login'] = w['Login'] || {};\n w['Login'].loginUrl = \"https://www.bundes-telefonbuch.de/user/loginPopup\"\n }(window));\n</script>\n\n\n\n<script type=\"text/javascript\">\n var onloadCallback = function () {\n $('.g-recaptcha').each(function (index, el) {\n grecaptcha.render(el, {\n 'sitekey': '6Ld0RAoTAAAAAFji0CujiR0oPoPiDYZQvh21l715',\n 'theme': 'light'\n });\n });\n };\n </script>\n<script type=\"text/javascript\">\n // getScript workaround for IE\n jQuery.extend({\n getScript: function (url, callback) {\n var head = document.getElementsByTagName(\"head\")[0];\n var script = document.createElement(\"script\");\n var done = false; // Handle Script loading\n\n script.src = url;\n script.onload = script.onreadystatechange = function () { // Attach handlers for all browsers\n if (!done && (!this.readyState || this.readyState === \"loaded\" || this.readyState === \"complete\")) {\n done = true;\n if (callback) {\n callback();\n }\n script.onload = script.onreadystatechange = null; // Handle memory leak in IE\n }\n };\n\n head.appendChild(script);\n return undefined; // We handle everything using the script element injection\n }\n });\n</script>\n\n<script type=\"text/javascript\">\n if (window.location.hash && window.location.hash == '#_=_') {\n if (window.history && history.pushState) window.history.pushState(\"\", document.title, window.location.pathname);\n else window.location.hash = '';\n }\n\n \n $(document).ready(function () {\n if (window.location.hash == '#imageUploadForm') {\n CompanyAjaxLoad.toggleFromNavigation('navigation_images', 'imageUploadForm', true, false);\n }\n\n if ($('#companyAdvert').height() > 200) {\n $('#map-canvas').height($('#companyAdvert').height());\n }\n\n var windowWidth = $(window).width();\n if (windowWidth <= 768) { //for iPad & smaller devices\n $('.panel-collapse').removeClass('in');\n }\n\n $('.fb-page').attr('data-width', $('.fb-page').parent().width());\n\n $('textarea').each(function () {\n autoresizeTextarea(this);\n });\n });\n\n $(function () {\n $('[data-toggle=\"tooltip\"]').tooltip({html: true});\n $('textarea').keyup(function () {\n autoresizeTextarea(this);\n });\n });\n\n function loadDatePicker($noStartDate, $id) {\n if ($id != null) {\n $field = $id;\n } else {\n $field = '.form-control.date';\n }\n if ($noStartDate == false) {\n $($field).datepicker({\n format: \"dd.mm.yyyy\",\n weekStart: 1,\n startDate: \"08.05.2018\",\n clearBtn: true,\n language: \"de\",\n calendarWeeks: true,\n autoclose: true\n });\n } else {\n $($field).datepicker({\n format: \"dd.mm.yyyy\",\n weekStart: 1,\n startDate: \"07.11.2017\",\n clearBtn: true,\n language: \"de\",\n calendarWeeks: true,\n autoclose: true\n });\n }\n }\n\n</script>\n\n <script type=\"text/javascript\">\n loadGoogleMap('map-canvas', [{\"latitude\":\"49.4482515\",\"longitude\":\"11.0442206\",\"address\":\"<span class=\\\"bold\\\">Karosseriefachbetrieb Hofer<\\/span><br\\/>Hans-Bunte-Str. 47, 90431 Nürnberg\",\"icon\":\"marker\",\"color\":\"red\"}], null, false, false);\n </script>\n\n<script type=\"text/javascript\" charset=\"utf-8\">\n (function (G, o, O, g, L, e) {\n G[g] = G[g] || function () {\n (G[g]['q'] = G[g]['q'] || []).push(arguments)\n }, G[g]['t'] = 1 * new Date;\n L = o.createElement(O), e = o.getElementsByTagName(O)[0];\n L.async = 1;\n L.src = '//www.google.com/adsense/search/async-ads.js';\n e.parentNode.insertBefore(L, e)\n })(window, document, 'script', '_googCsa');\n</script>\n\n<script type='text/javascript'>\n \n var googletag = googletag || {};\n googletag.cmd = googletag.cmd || [];\n (function () {\n var gads = document.createElement('script');\n gads.async = true;\n gads.type = 'text/javascript';\n var useSSL = 'https:' == document.location.protocol;\n gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js';\n var node = document.getElementsByTagName('script')[0];\n node.parentNode.insertBefore(gads, node);\n })();\n\n googletag.cmd.push(function () {\n \n googletag.defineSlot('/2492971/BTb.de_Detailseiten_Top_Leaderboard', [728, 90], 'gpt-ad-leader-top').addService(googletag.pubads());\n googletag.defineSlot('/2492971/BTb.de_Detailseiten_Leaderboard', [728, 90], 'gpt-ad-leader').addService(googletag.pubads());\n googletag.defineSlot('/2492971/BTb.de_Detailseiten_Medium_Rectangle', [300, 250], 'gpt-ad-rectangle1').addService(googletag.pubads());\n googletag.defineSlot('/2492971/BTb.de_Detailseiten_Wide_Skyscraper', [160, 600], 'gpt-ad-skyscraper').addService(googletag.pubads());\n googletag.defineSlot('/2492971/BTb.de_Detailseiten_Firmendetailseite_Medium_Rectangle_Bilder', [300, 250], 'gpt-ad-rectangle2').addService(googletag.pubads());\n googletag.defineSlot('/2492971/BTb.de_Detailseiten_Large_Mobile_Banner', [325, 120], 'gpt-ad-mobile-top').addService(googletag.pubads());\n\n googletag.enableServices();\n });\n </script>\n\n<script type='text/javascript'>\n function getLocation() {\n $('#myLocation').toggleClass(\"active\");\n var output = document.getElementById(\"geoMsg\");\n var nav = window.navigator, $btn = $('#searchButton'), t = $btn.html();\n\n function successCallback(position) {\n $btn.enableButton(t);\n $('#geoMsg').html(\"\");\n $('#whereLat').val(position.coords.latitude);\n $('#whereLng').val(position.coords.longitude);\n\n $('#where').val(\"Mein Standort\");\n $('#where').attr('readonly', 'readonly');\n }\n\n function errorCallback(error) {\n $btn.enableButton(t);\n var message = \"\";\n switch (error.code) {\n case error.PERMISSION_DENIED:\n message = \"<i class='fa fa-times-circle-o'></i> <strong class='bold text-white'>Keine Berechtigung zur Ermittlung des Standorts.</span>\";\n break;\n case error.POSITION_UNAVAILABLE:\n message = \"<i class='fa fa-times-circle-o'></i> <span class='bold text-white'>Keine Positionsermittlung möglich.</span>\";\n break;\n case error.PERMISSION_DENIED_TIMEOUT:\n message = \"<i class='fa fa-times-circle-o'></i> <span class='bold text-white'>Fehler: Ermittlung des Standorts dauerte zu lange.</span>\";\n break;\n }\n output.innerHTML = message;\n }\n\n if (nav != null) {\n var geoloc = nav.geolocation;\n if (geoloc != null) {\n output.innerHTML = \"<i class='fa fa-question-circle-o'></i> <span class='bold text-white'>Koordinaten werden ermittelt.</span>\";\n if ($('#myLocation').hasClass('active')) {\n $btn.disableButton(t);\n geoloc.getCurrentPosition(successCallback, errorCallback);\n } else {\n $('#where').removeAttr('readonly');\n $('#where').val('');\n $('#whereLat').val('');\n $('#whereLng').val('');\n output.innerHTML = \"\";\n }\n }\n else {\n output.innerHTML = \"<i class='fa fa-times-circle-o'></i> <strong class='bold text-white'>Es ist ein Fehler unterlaufen. Überprüfen Sie, ob ihr GPS aktiviert ist bzw. ob ihr Browser diese Funktion unterstützt.</span>\";\n return;\n }\n }\n else {\n output.innerHTML = \"<i class='fa fa-times-circle-o'></i> <strong class='bold text-white'>Es ist ein Fehler unterlaufen. Überprüfen Sie, ob ihr GPS aktiviert ist bzw. ob ihr Browser diese Funktion unterstützt.</span>\";\n return;\n }\n }\n\n function removeLocation() {\n $('#myLocation').toggleClass(\"active\");\n var output = document.getElementById(\"geoMsg\");\n\n $('#where').removeAttr('readonly');\n $('#where').val('');\n $('#whereLat').val('');\n $('#whereLng').val('');\n output.innerHTML = \"\";\n }\n\n function positionSlidercontroll(id) {\n var carouselFiftyPercent = (($('#' + id).height() - 20) - ($('#' + id + ' .btn').height() / 2)) / 2;\n $('#' + id + ' .btn').css('top', carouselFiftyPercent);\n }\n</script>\n <link rel=\"shortcut icon\" href=\"/favicon.ico\"/>\n\n</head>\n<body itemscope=\"itemscope\" itemtype=\"http://schema.org/WebPage\"\n id=\"https://www.bundes-telefonbuch.de/nuernberg/firma/karosseriefachbetrieb-hofer-tb1150222\">\n\n<!--[if lt IE 7]>\n<p class=\"browsehappy\">You are using an <span class=\"bold\">outdated</span> browser. Please <a\n href=\"http://browsehappy.com/\">upgrade\n your browser</a> to improve your experience.</p>\n<![endif]-->\n\n<div id=\"page\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.bundes-telefonbuch.de/css/header.min.css?1498638616\" />\n<script> </script>\n <div class=\"hidden-xs container\">\n <div id=\"gpt-ad-leader-top\" class=\"leader pull-right\">\n <script type='text/javascript'>\n\t\t\t\t\t\tgoogletag.cmd.push(function() {\n\t\t\t\t\t\t\tgoogletag.display('gpt-ad-leader-top');\n\t\t\t\t\t\t});\n </script>\n </div>\n </div>\n <div class=\"container\">\n <div class=\"row pull-right\">\n <div class='col-md-2 skyscraper hidden-xs hidden-sm hidden-md'>\n <div id=\"skyscraper\">\n <div id=\"gpt-ad-skyscraper\">\n <script type='text/javascript'>\n googletag.cmd.push(function () {\n googletag.display('gpt-ad-skyscraper');\n });\n </script>\n </div>\n </div>\n </div>\n </div>\n </div>\n <script type=\"text/javascript\">\n $(document).ready(function () {\n var offset = $('.skyscraper').offset();\n $('.skyscraper').affix({\n offset: {\n top: offset.top\n }\n });\n });\n </script>\n <div class=\"container pageContent\">\n \n\n <header>\n <div class=\"row\">\n <nav class=\"header navbar navbar-default\">\n <div class=\"container-fluid\">\n <!-- Brand and toggle get grouped for better mobile display -->\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle collapsed text-white\" data-toggle=\"collapse\"\n data-target=\"#navigationList\">\n <span class=\"sr-only\">Navigation</span>\n <i class=\"fa fa-2x fa-bars\"></i>\n </button>\n <button type=\"button\" class=\"navbar-toggle collapsed text-white\" data-toggle=\"collapse\"\n data-target=\"#search\">\n <span class=\"sr-only\">Suchen</span>\n <i class=\"fa fa-2x fa-search\"></i>\n </button>\n <div class=\"visible-xs\">\n <a class=\"noPaddingMargin\" href=\"https://www.bundes-telefonbuch.de/\">\n <img src=\"https://www.bundes-telefonbuch.de/img/logo_bundestelefonbuch_200_60.png\" alt=\"Bundestelefonbuch Logo\" width=\"200px\" height=\"60px\" /> </a>\n </div>\n </div>\n\n <!-- Collect the nav links, forms, and other content for toggling -->\n <div class=\"row\">\n <div class=\"collapse navbar-collapse\" id=\"navigationList\">\n <div class=\"col-sm-3 col-md-4 col-lg-6 hidden-xs noPaddingMargin\">\n <div class=\"pull-left\">\n <a class=\"noPaddingMargin logo\" href=\"https://www.bundes-telefonbuch.de/\">\n <img src=\"https://www.bundes-telefonbuch.de/img/logo_btb_340_114.png\" class=\"img-responsive\" alt=\"Bundestelefonbuch Logo\" /> </a>\n </div>\n <div class=\"hidden-md hidden-sm pull-left phonebook\">\n Partner von <br/>\n\n <div class=\"linkPhonebook\">\n <a href=\"http://www.dastelefonbuch.de/\" target=\"_blank\" rel=\"nofollow\">\n <img src=\"https://www.bundes-telefonbuch.de/img/logo_das_telefonbuch_deutschland.jpg\" class=\"img-responsive\" alt=\"Telefonbuch Deutschland Logo\" /> </a>\n </div>\n </div>\n </div>\n <div class=\"col-sm-9 col-md-8 col-lg-6 noPaddingMargin\">\n <ul class=\"nav navbar-nav navbar-right lead marginTop30\">\n <li >\n <a href=\"https://www.bundes-telefonbuch.de/firma/grund-eintrag\" class=\"text-decorationNone\" title=\"Firma eintragen\">\n <i class=\"fa fa-plus-circle text-success\"></i>\n Firma eintragen </a>\n </li>\n \n \n\n<li style=\"width:132px\" id=\"userMenuPlaceholder\"></li>\n\n<script type=\"text/javascript\">\n jQuery(document).ready(function($) {\n $.get('/usermenu.do', {}, function(html) {\n $('#userMenuPlaceholder').replaceWith(html);\n });\n }(jQuery));\n</script> </ul>\n\n <ul class=\"nav navbar-nav navbar-right lead marginRightMinus15\">\n <li >\n <a href=\"https://www.bundes-telefonbuch.de/branchenbuch-deutschland\" class=\"text-decorationNone\" title=\"Branchenbuch\">\n <i class=\"fa fa-book text-danger\"></i>\n Branchenbuch </a>\n </li>\n <li >\n <a href=\"https://www.bundes-telefonbuch.de/a\" class=\"text-decorationNone\" title=\"Lokale Suche\">\n <i class=\"fa fa-globe text-danger\"></i>\n Lokale Suche </a>\n </li>\n <li >\n <a href=\"https://www.bundes-telefonbuch.de/lieblingslisten\" class=\"text-decorationNone\" title=\"LieblingsListen\">\n <i class=\"fa fa-thumb-tack text-danger\"></i>\n LieblingsListen </a>\n </li>\n </ul>\n </div>\n </div><!-- /.navbar-collapse -->\n </div>\n <div class=\"row\">\n <div class=\"collapse navbar navbar-collapse gray-dark search\"\n id=\"search\">\n \n\n<div itemscope itemtype=\"http://schema.org/WebSite\">\n <meta itemprop=\"url\" content=\"https://www.bundes-telefonbuch.de\"/>\n <form id=\"searchForm\" role=\"form\" method=\"post\"\n action=\"/suche\"\n itemprop=\"potentialAction\" itemscope itemtype=\"http://schema.org/SearchAction\">\n <div class=\"col-sm-1\"></div>\n <div class=\"col-sm-4 marginBottom20\">\n <meta itemprop=\"target\" content=\"https://www.bundes-telefonbuch.de/suche?what={what}\"/>\n <div class=\"input-group-lg search-wrapper-what\">\n <input itemprop=\"query-input\" type=\"text\" required=\"\" class=\"form-control search-box-what\" name=\"what\"\n placeholder=\"Was?\" id=\"what\" value=\"\"\n onkeyup=\"showSearchClearIcon(this, 'search-wrapper-what', 'close-icon-what', 'input-group');\">\n <span class=\"input-group-btn close-icon-what\" style=\"display:none;\"\n onclick=\"clearSearch(this, 'search-box-what', 'search-wrapper-what', 'input-group');\">\n <button type=\"button\"\n class=\"btn btn-default btn-input paddingTop5 gray-lighter\"\n title=\"Suche zurücksetzen\">\n <i class=\"fa fa-2x fa-times text-gray-darker\"></i>\n </button>\n </span>\n </div>\n </div>\n\n <div class=\"col-sm-4 marginBottom20\">\n <div class=\"input-group input-group-lg search-wrapper-where\">\n <input type=\"text\" class=\"form-control search-box-where\" name=\"where\" placeholder=\"Wo?\"\n onclick=\"removeLocation();\"\n id=\"where\"\n onkeyup=\"showSearchClearIcon(this, 'search-wrapper-where', 'close-icon-where', '');\">\n\n <span class=\"input-group-btn close-icon-where\" style=\"display:none;\"\n onclick=\"clearSearch(this, 'search-box-where', 'search-wrapper-where', '');\">\n <button type=\"button\"\n class=\"btn btn-default btn-input paddingTop5 gray-lighter\"\n title=\"Suche zurücksetzen\">\n <i class=\"fa fa-2x fa-times text-gray-darker\"></i>\n </button>\n </span>\n <span class=\"input-group-btn\">\n <button type=\"button\"\n class=\"btn btn-default btn-input paddingTop5\"\n name=\"myLocation\" id=\"myLocation\" onclick=\"getLocation();\"\n title=\"Meinen aktuellen Standort ermitteln\">\n <i class=\"fa fa-2x fa-map-marker text-danger\"></i>\n </button>\n </span>\n </div>\n\n <div id=\"geoMsg\"></div>\n </div>\n <div class=\"col-sm-2\">\n <input type=\"hidden\" name=\"whereLat\" id=\"whereLat\" value=\"\"/>\n <input type=\"hidden\" name=\"whereLng\" id=\"whereLng\" value=\"\"/>\n <button type=\"submit\" class=\"btn btn-danger btn-lg btn-block btn-search bold\" id=\"searchButton\">\n <i class=\"fa fa-search hidden-sm\"></i> Suchen </button>\n </div>\n </form>\n</div>\n\n<script type=\"text/javascript\">\n if ($(window).width() <= 768) { //for iPad & smaller devices\n if ($('.search-box-what').val()) {\n $('.search-wrapper-what').addClass('input-group');\n $('.close-icon-what').show();\n }\n\n if ($('.search-box-where').val()) {\n $('.close-icon-where').show();\n }\n }\n\n /* $('.search-box').keyup(function () {\n var t = $(this);\n $('.close-icon').toggle(Boolean(t.val()));\n if (Boolean(t.val())) {\n $('.search-wrapper').addClass('input-group');\n } else {\n $('.search-wrapper').removeClass('input-group');\n }\n });\n\n $('.close-icon').click(function () {\n $('.search-box').val('').focus();\n $('.search-wrapper').removeClass('input-group');\n $(this).hide();\n });\n */\n</script> </div>\n </div>\n </div><!-- /.container-fluid -->\n </nav>\n </div>\n <div class=\"row\">\n <div class=\"hidden-sm hidden-md hidden-lg\">\n <div class=\"mobileGap\"></div>\n </div>\n </div>\n </header>\n <div id=\"gpt-ad-mobile-top\" class=\"visible-xs mobileBanner\">\n <script type='text/javascript'>\n googletag.cmd.push(function () {\n googletag.display('gpt-ad-mobile-top');\n });\n </script>\n <br/>\n </div>\n \n<div id=\"qwertzuiop\">\n <script type=\"text/javascript\">\n jQuery(document).ready(function () {\n $('#qwertzuiop').load('/office.do?u=&c=13478898');\n });\n </script>\n</div> <div id=\"content\">\n <div class=\"hidden-xs\">\n <div class=\"row\">\n <ol itemprop=\"breadcrumb\" class=\"breadcrumb\">\n <li>\n <a href=\"/\" rel=\"follow\">Startseite</a>\n </li>\n <li>\n <a href=\"/suche/firma\" rel=\"follow\">Firma</a>\n </li>\n <li>\n <a href=\"/suche/firma/nuernberg\" rel=\"follow\">Firma in Nürnberg</a>\n </li>\n <li class=\"active\">\n Karosseriefachbetrieb Hofer </li>\n </ol>\n </div>\n </div>\n <div class=\"row\">\n <div id=\"flashSessionOutput\" class=\"noMargin\"></div>\n <script type=\"text/javascript\">\n jQuery(document).ready(function ($) {\n outputFlashSession();\n }(jQuery));\n </script>\n </div>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://www.bundes-telefonbuch.de/css/content.min.css?1502787592\" />\n<script> </script>\n \n\n<div itemscope=\"\" itemtype=\"http://schema.org/LocalBusiness\">\n <div class=\"row\">\n <div class=\"col-sm-12\" id=\"pageHeader\">\n \n<div class=\"page-header\">\n <div class=\"row\">\n \n \n \n <div class=\"col-xs-12\">\n <meta itemprop=\"name\" content=\"Karosseriefachbetrieb Hofer\">\n <h1 class=\"noMarginTop\">\n <i class=\"fa fa-check-square-o text-success\" data-placement=\"top\" data-toggle=\"tooltip\"\n title=\"Karosseriefachbetrieb Hofer ist verifiziert. Die Richtigkeit der eingetragenen Firmendaten wurde von Karosseriefachbetrieb Hofer bestätigt und die Inhaberschaft von Bundestelefonbuch überprüft.\"></i>\n Karosseriefachbetrieb Hofer </h1>\n\n <div class=\"text-gray-darker\">\n Firma, 90431 Nürnberg </div>\n </div>\n </div>\n</div>\n\n\n\n </div>\n </div>\n <div class=\"row\">\n <div class='col-sm-12 col-lg-8 rwpLeader'>\n \n <script type=\"text/javascript\">\n jQuery(document).ready(function () {\n Payment.banner.checkDetailRival('/payment.do', 13478898, 'adPackageBanner', '', 'null');\n });\n </script>\n <div id=\"adPackageBannerContainer\" class=\"hidden-xs\">\n <div id=\"adPackageBanner\" class=\"positionRelative\"></div>\n </div>\n\n \n\n </div>\n \n\n\n\n <div class='col-sm-4 detail-navigation'>\n <nav class=\"header navbar navbar-default navbar-detail-page\" role=\"navigation\">\n <div class=\"container-fluid\">\n \n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle collapsed btn btn-danger\" data-toggle=\"collapse\"\n data-target=\"#navigationDetailList\">\n <span class=\"sr-only\">Menü</span>\n <i class=\"fa fa-bars\"></i> Menü\n </button>\n </div>\n\n \n <div class=\"row\">\n <div class=\"collapse navbar-collapse\" id=\"navigationDetailList\">\n <ul class=\"nav\">\n \n \n \n \n \n <li class=\"btn-block\"> <div class=\"btn btn-block btn-lg text-left btn-navigation\">\n <div data-toggle=\"tooltip\" data-placement=\"bottom\"\n title=\"Dieser Firmeneintrag wurde uns von Das Telefonbuch angeliefert. Für Änderungen wenden Sie sich bitte an den regional zuständigen Verlag.\"\n class=\"btn-block\">\n <i class=\"fa fa-2x fa-pencil\"></i> Firmeneintrag bearbeiten </div>\n </div>\n </li> \n <li class=\"btn-block btn-navigation\">\n <div class=\"btn btn-block btn-lg text-left \"\n id=\"navigation_detailRating\">\n <a href=\"/nuernberg/firma/karosseriefachbetrieb-hofer-tb1150222/bewertungen#createReviewForm\" title=\"Bewertung schreiben\" class=\"btn-block\">\n <i class=\"fa fa-2x fa-thumbs-o-up\"></i>\n Bewertung schreiben <span class=\"pull-right marginTop5\"><i class=\"fa fa-caret-right\"></i></span>\n </a>\n </div>\n </li>\n \n \n \n <li class=\"btn-block btn-navigation\">\n <div class=\"btn btn-block btn-lg text-left \"\n id=\"navigation_images\">\n <a href=\"/nuernberg/firma/karosseriefachbetrieb-hofer-tb1150222#imageUploadForm\" onclick=\" CompanyAjaxLoad.toggleFromNavigation('navigation_images', 'imageUploadForm', true, false);\" title=\"Bild zur Firma hochladen\" class=\"btn-block\">\n <i class=\"fa fa-2x fa-file-image-o\"></i>\n Bild zur Firma hochladen <span class=\"pull-right marginTop5\"><i class=\"fa fa-caret-right\"></i></span>\n </a>\n </div>\n </li>\n \n \n <li class=\"btn-block btn-navigation\">\n <div class=\"btn btn-block btn-lg text-left \"\n id=\"navigation_bookmark\">\n <a href=\"/nuernberg/firma/karosseriefachbetrieb-hofer-tb1150222/merklisten\" title=\"LieblingsListen (0)\" class=\"btn-block\">\n <i class=\"fa fa-2x fa-thumb-tack\"></i>\n LieblingsListen (0) <span class=\"pull-right marginTop5\"><i class=\"fa fa-caret-right\"></i></span>\n </a>\n </div>\n </li>\n \n \n <li class=\"btn-block btn-navigation\">\n <div class=\"btn btn-block btn-lg text-left \"\n id=\"navigation_map\">\n <a href=\"/nuernberg/firma/karosseriefachbetrieb-hofer-tb1150222#karte\" onclick=\"CompanyAjaxLoad.getAdditionalCompanyInfo('companyMap', '13478898', 'karte', true, 'map');\" title=\"Route berechnen\" class=\"btn-block\">\n <i class=\"fa fa-2x fa-map-marker\"></i>\n Route berechnen <span class=\"pull-right marginTop5\"><i class=\"fa fa-caret-right\"></i></span>\n </a>\n </div>\n </li>\n\n \n \n <li class=\"btn-block btn-navigation\">\n <div class=\"btn btn-block btn-lg btn-success text-left\"\n id=\"navigation_companyRequest\"\n data-toggle=\"modal\" data-target=\"#sendLead\">\n <i class=\"fa fa-2x fa-paper-plane\"></i> Anfrage an die Firma senden <span class=\"pull-right\"><i class=\"fa fa-caret-right\"></i></span>\n </div>\n </li>\n \n \n <li class=\"btn-block btn-navigation\">\n <div class=\"btn btn-block btn-lg text-left\">\n <div data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"Dieser Firmeneintrag wurde uns von Das Telefonbuch angeliefert. Für Änderungen wenden Sie sich bitte an den regional zuständigen Verlag.\" class=\"btn-block\">\n <i class=\"fa fa-2x fa-building\"></i>\n Ihre Firma? </div>\n </div>\n </li>\n </ul>\n </div>\n </div>\n </div>\n </nav>\n </div>\n\n \n <div class=\"modal fade\" id=\"sendLead\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"sendLeadLabel\">\n <div class=\"modal-dialog modal-lg\" role=\"document\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span\n aria-hidden=\"true\">×</span></button>\n <h4 class=\"modal-title\" id=\"sendLeadLabel\">Anfrage senden</h4>\n </div>\n <div class=\"modal-body\">\n <div id=\"leadMessage\"></div>\n <form id=\"sendLead-form\" method=\"post\" role=\"form\" onSubmit=\"lead.send("sendLead-form", "sendLead", "leadMessage");return false\">\n <div class=\"content\">\n <div class=\"row\">\n \n <div class=\"col-sm-12 \">\n <span class=\"bold\">Ihre Nachricht <span class=\"text-danger\">*</span>\n </span>\n <br/>\n \n <div class=\" \">\n \n \n <textarea id=\"message\" name=\"message\" class=\"form-control \" data-required=\"true\" required=\"required\"></textarea> \n </div>\n\n \n </div>\n </div>\n </div>\n <div class=\"content\">\n <div class=\"row\">\n \n <div class=\"col-sm-12 \">\n <label>\n <input type=\"checkbox\" id=\"leadQuestionNews\" name=\"leadQuestionNews\" required=\"required\" data-required=\"true\" /> <span class=\"bold col-bottom\">Ich bin einverstanden, dass meine E-Mail-Adresse an das Unternehmen weitergegeben wird, um meine Anfrage zu bearbeiten. </span>\n </label>\n\n </div>\n </div>\n </div>\n <input type=\"hidden\" id=\"companyId\" name=\"companyId\" value=\"13478898\" /> <input type=\"hidden\" id=\"productId\" name=\"productId\" /> <input type=\"hidden\" id=\"formIdent\" name=\"formIdent\" value=\"lead\" /> \n \n<div class=\"content\">\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <p> (Mit * gekennzeichnete Felder sind Pflichtfelder)</p>\n </div>\n </div>\n</div>\n\n \n \n \n\n \n<div class=\"content form-login\">\n \n<input type=\"hidden\" class=\"csrf-token\" name=\"csrf_token\" value=\"7P9VPKbagvLoyiJ\"/> <input type=\"hidden\" id=\"companyId\" name=\"companyId\" value=\"13478898\" /> <input type=\"hidden\" id=\"productId\" name=\"productId\" /> <input type=\"hidden\" id=\"formIdent\" name=\"formIdent\" value=\"lead\" /> \n <div class=\"row\">\n \n\n<div class=\"col-xs-12 form-login-actions\">\n <p class=\"bold\">Bitte loggen Sie sich zunächst ein.</p>\n\n <div class=\"gray-light\">\n <div class=\"row\">\n <div class=\"col-sm-6\">\n <div class=\"content\">\n <p>Ich habe bereits ein Benutzerkonto</p>\n <a href=\"#\" onclick=\"Login.popup(this); return false\" class=\"btn btn-lg btn-warning btn-block\">Jetzt einloggen</a>\n \n <input type=\"checkbox\" style=\"display:none\" name=\"returnBlock\" class=\"form-login-returnBlock\" required/>\n </div>\n </div>\n <div class=\"col-sm-6 loginFormBorderLeft form-login-register\">\n <div class=\"content\">\n <p>Ich habe noch kein Benutzerkonto</p>\n\n <div class=\"form-group\">\n <label for=\"formLoginlead\" class=\"control-label\">E-Mail <span\n class=\"text-danger\">*</span></label>\n <input type=\"email\" name=\"formLoginEmail\" id=\"formLoginlead\"\n class=\"form-control form-login-email\"\n onkeyup=\"Login.checkForSend($('#formLoginlead'))\"\n onchange=\"Login.checkForSend($('#formLoginlead'))\"\n onblur=\"Login.checkForSend($('#formLoginlead'))\"\n value=\"[email protected]\" required/>\n </div>\n <div class=\"form-group\">\n \n\n<script type=\"text/javascript\">\n grecaptcha.render('recaptcha-lead', {\n 'sitekey': '6Ld0RAoTAAAAAFji0CujiR0oPoPiDYZQvh21l715',\n 'theme': 'light'\n });\n </script> <div id=\"recaptcha-lead\" class=\"g-recaptcha\"></div>\n </div>\n <p class=\"text-center\">oder</p>\n <script>\n function facebookStatusCallback(response) {\n if (response.status === 'connected') {\n FB.api('/me', function (res) {\n Login.facebookRegister({'auth': response, 'profile': res});\n });\n }\n }\n</script>\n\n\n\n \n<button type=\"button\" class=\"btn btn-block btn-default btn-lg col-middle facebook-login-button marginBottom5\"\n onclick=\"Social.loginByFacebookStep1(this, '445350842203770', 'public_profile,email', 'Jetzt mit Facebook anmelden');\">\n <i class=\"fa fa-facebook-square fa-2x\"></i> Registrierung per Facebook\n</button>\n\n \n<p>Eine Verbindung zu Facebook wird erst hergestellt, wenn Sie auf die oben angezeigte Schaltfläche klicken. Weitere Informationen: <a rel=\"nofollow\" href=\"/infos/datenschutzhinweis\" target=\"_blank\">Datenschutzhinweis</a></p> <br/>\n <div>\n <label>\n <input type=\"checkbox\" class=\"form-login-terms\" name=\"terms\" required/>\n <span style=\"vertical-align:text-bottom\">\n Ich akzeptiere die\n <a href=\"/allgemeine-geschaeftsbedingungen\"\n target=\"_blank\">AGB</a>\n <span class=\"text-danger\">*</span>\n </span>\n </label>\n </div>\n\n <div style=\"display:none\">\n <label>\n <input type=\"checkbox\" name=\"newsletter\"\n checked=\"checked\" />\n <span style=\"vertical-align:text-bottom\">Angebote und Neuigkeiten per E-Mail erhalten</span>\n </label>\n </div>\n </div>\n </div>\n </div>\n </div>\n</div> <br/>\n\n <div class=\"form-login-submit\"></div>\n <br/>\n\n <div class=\"col-xs-12 form-login-submit\">\n <input type=\"submit\" value=\"Senden\" class=\"btn btn-lg btn-warning btn-block\" textClass=\"bold\" /> </div>\n </div>\n</div>\n\n<script type=\"text/javascript\">\n $('.form-login-submit').hide();\n Login.showRegister($('.form-login-actions'));\n </script>\n </form> </div>\n </div>\n </div>\n </div>\n \n <div class=\"col-sm-8\">\n <div class=\"eyeCatcherTbDetailRow\">\n <div id=\"companyAdvert\">\n <div class=\"eyeCatcherTbDetail\">\n <p class=\"eyeCatcherTb\">\n <img src=\"/img/telefonbuch_logo_eyecatcher.png\" alt=\"Telefonbuch Anzeige\" title=\"Telefonbuch Anzeige\"/>\n </p>\n <a href=\"http://www.hofer-n.de\" target=\"_blank\" rel=\"nofollow\" class=\"detail-homepage\">\n <img src=\"https://www.bundes-telefonbuch.de/anzeige/13478898\" id=\"companyAdvert\"\n alt=\"Firmenanzeige Karosseriefachbetrieb Hofer\" title=\"Firmenanzeige Karosseriefachbetrieb Hofer\"/>\n </a>\n </div>\n </div>\n </div>\n\n \n\n \n<div class=\"content marginBottom17\">\n \n <table class=\"table\">\n <tr>\n <td><span class=\"bold\">Adresse</span></td>\n <td>\n <div itemprop=\"address\" itemscope itemtype=\"http://schema.org/PostalAddress\" class=\"detail-address\">\n <span itemprop=\"streetAddress\">\n Hans-Bunte-Str. 47 </span>\n <br/>\n <span itemprop=\"postalCode\">90431</span>\n <span itemprop=\"addressLocality\">Nürnberg</span>\n </div>\n </td>\n </tr>\n <tr>\n <td><span class=\"bold\">Telefonnummer</span></td>\n <td>\n <span itemprop=\"telephone\" class=\"detail-phone\">\n <a href=\"tel:+49 911314947\"\n rel=\"nofollow\">(0911) 314947</a>\n </span>\n </td>\n </tr>\n <tr>\n <td><span class=\"bold\">Faxnummer</span></td>\n <td>\n <span itemprop=\"faxNumber\" class=\"detail-fax\">\n (0911) 318106 </span>\n </td>\n </tr>\n <tr>\n <td><span class=\"bold\">Homepage</span></td>\n <td><span itemprop=\"url\">\n <a href=\"http://www.hofer-n.de\" target=\"_blank\" rel=\"nofollow\"\n class=\"detail-homepage\" >\n www.hofer-n.de </a>\n </span>\n </td>\n </tr>\n <tr>\n <td><span class=\"bold\">E-Mail</span></td>\n <td>\n <span itemprop=\"email\">\n <a href=\"mailto:[email protected]\" class=\"detail-email\">[email protected]</a>\n </span>\n </td>\n </tr>\n \n \n \n <tr>\n <td><span class=\"bold\">Eingetragen seit:</span></td>\n <td>08.09.2017</td>\n </tr>\n <tr>\n <td><span class=\"bold\">Aktualisiert am:</span></td>\n <td>08.09.2017, 07:59</td>\n </tr>\n \n </table>\n</div> <div id=\"memoryList\" class=\"content\">\n <button type=\"button\" id=\"buttonAddToMemoryList\" class=\"btn btn-danger\" onclick=\"Mem.add(this, 13478898)\">Zu LieblingsListe hinzufügen</button>\n\n <div id=\"memoryAddContainer\"></div>\n </div>\n <div id=\"additionalCompanyInfo\"></div>\n <div class=\"panel panel-default\">\n <div class=\"panel-heading\"><h2 class=\"panel-title\">Unternehmensbeschreibung</h2></div>\n <div class=\"panel-body\">\n <div itemprop=\"description\">\n <p class=\"description\"></p>\n </div>\n </div>\n</div>\n\n \n<div class=\"panel panel-default\">\n <div class=\"panel-body\">\n <div id=\"imageSlider\" class=\"carousel slide height350\" data-ride=\"carousel\">\n \n <ol class=\"carousel-indicators\">\n <li data-target=\"#imageSlider\" data-slide-to=\"0\"\n class=\"active\"></li>\n <li data-target=\"#imageSlider\" data-slide-to=\"1\"\n class=\"\"></li>\n <li data-target=\"#imageSlider\" data-slide-to=\"2\"\n class=\"\"></li>\n <li data-target=\"#imageSlider\" data-slide-to=\"3\" class=\"\">\n </li>\n </ol>\n\n \n <div class=\"carousel-inner\" role=\"listbox\">\n <div class=\"item active text-center\" itemscope\n itemtype=\"http://schema.org/ImageObject\">\n <div class=\"carousel-caption\" itemprop=\"name\"><h3></h3></div>\n <img src=\"https://ies.v4all.de/v244/TB/0122/1/4201/48644201_460x310px.png\" data-holder-rendered=\"true\"\n alt=\"Bild von Karosseriefachbetrieb Hofer in Nürnberg - 1\" title=\"Bild von Karosseriefachbetrieb Hofer in Nürnberg - 1\" class=\"carousel-image\" itemprop=\"contentUrl\"/>\n </div>\n <div class=\"item text-center\" itemscope\n itemtype=\"http://schema.org/ImageObject\">\n <div class=\"carousel-caption\" itemprop=\"name\"><h3></h3></div>\n <img src=\"https://ies.v4all.de/v244/TB/0122/2/1332/41501332_460x310px.png\" data-holder-rendered=\"true\"\n alt=\"Bild von Karosseriefachbetrieb Hofer in Nürnberg - 2\" title=\"Bild von Karosseriefachbetrieb Hofer in Nürnberg - 2\" class=\"carousel-image\" itemprop=\"contentUrl\"/>\n </div>\n <div class=\"item text-center\" itemscope\n itemtype=\"http://schema.org/ImageObject\">\n <div class=\"carousel-caption\" itemprop=\"name\"><h3></h3></div>\n <img src=\"https://ies.v4all.de/v244/TB/0122/7/0667/43650667_460x310px.png\" data-holder-rendered=\"true\"\n alt=\"Bild von Karosseriefachbetrieb Hofer in Nürnberg - 3\" title=\"Bild von Karosseriefachbetrieb Hofer in Nürnberg - 3\" class=\"carousel-image\" itemprop=\"contentUrl\"/>\n </div>\n <div class=\"item\">\n <div class=\"carousel-caption\">\n Anzeige von Google\n </div>\n <div class=\"carousel-image\" style=\"width:300px;height:250px;\">\n <div class=\"content rectangleContainer2\">\n <div id=\"gpt-ad-rectangle2\" class=\"rectangle\">\n <script type='text/javascript'>\n googletag.cmd.push(function () {\n googletag.display('gpt-ad-rectangle2');\n });\n </script>\n </div>\n </div>\n\n\n <script type='text/javascript'>\n $(document).ready(function () {\n var leaderWidth = $('.rectangleContainer2').parent().width();\n if (leaderWidth < 300) {\n $('.rectangleContainer2').hide()\n } else {\n $('.rectangleContainer2').show()\n }\n });\n </script>\n </div>\n </div>\n </div>\n\n \n <a class=\"left carousel-control\" href=\"#imageSlider\" role=\"button\" data-slide=\"prev\">\n <span class=\"glyphicon-chevron-left btn btn-block btn-danger\"><i class=\"fa fa-chevron-left\"></i></span>\n <span class=\"sr-only\">Previous</span>\n </a>\n <a class=\"right carousel-control\" href=\"#imageSlider\" role=\"button\" data-slide=\"next\">\n <span class=\"glyphicon-chevron-right btn btn-block btn-danger\"><i class=\"fa fa-chevron-right\"></i></span>\n <span class=\"sr-only\">Next</span>\n </a>\n </div>\n <br/>\n\n <div class=\"text-right\">\n <a href=\"#imageUploadForm\" title=\"Bild zur Firma hochladen\" class=\"btn btn-danger\"\n onclick=\"$('#imageUploadForm').toggle();$('html,body').scrollTop($(this));\">\n Bild zur Firma hochladen </a>\n </div>\n </div>\n</div>\n<script type='text/javascript'>\n positionSlidercontroll('imageSlider');\n</script> <div id=\"imageUploadForm\" style=\"display:none\" >\n <div class=\"panel panel-default\">\n <div class=\"panel-heading\">\n <h2 class=\"panel-title\">\n Bilder hochladen zu Karosseriefachbetrieb Hofer </h2>\n </div>\n <div class=\"panel-body\">\n \n \n <form action=\"/nuernberg/firma/karosseriefachbetrieb-hofer-tb1150222#imageUploadForm\" method=\"post\" role=\"form\" enctype=\"multipart/form-data\">\n <div class=\"content\">\n <div class=\"row\">\n \n\n<style>\n .btn-file {\n position: relative;\n color: black;\n }\n\n .btn-file input[type=file] {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n opacity: 0;\n }\n\n #imageUploadCropContainer {\n display: none;\n }\n\n .upload-msg {\n text-align: center;\n padding: 50px;\n font-size: 22px;\n color: #aaa;\n width: 300px;\n height: 300px;\n margin: 10px auto;\n border: 1px solid #aaa;\n }\n\n .croppie-container {\n padding: 10px 0px;\n }\n</style>\n\n<div class=\"row\">\n <div class=\"col-sm-12\">\n <a class=\"btn btn-default btn-file\">\n <span>Bild auswählen</span>\n <input type=\"file\" id=\"file\" name=\"file\" class=\"form-control\" data-required=\"true\" accept=\"image/jpeg,image/png\" data-max-size=\"5000000\" /> </a>\n </div>\n <div class=\"col-sm-12\">\n <div class=\"upload-msg\">\n Bitte wählen Sie ein Bild aus. </div>\n <div id=\"imageUploadCropContainer\"></div>\n </div>\n <div class=\"col-sm-12\">\n <table>\n <tr>\n <td class=\"col-middle\">\n <i class=\"fa fa-3x fa-info-circle text-gray\"></i>\n </td>\n <td class=\"col-middle\">\n Bildformat jpg und png möglich </td>\n </tr>\n <tr>\n <td class=\"col-middle\">\n <i class=\"fa fa-3x fa-info-circle text-gray\"></i>\n </td>\n <td class=\"col-middle\">\n Bildgröße bis 5MB, mindestens 400x400, maximal 2000x2000 Pixel </td>\n </tr>\n </table>\n <br/>\n </div>\n</div>\n\n<script type=\"text/javascript\">\n jQuery(function () {\n var $container = $('#imageUploadCropContainer'), $form = $container.parents('form'), $uploadCrop;\n\n function readFile(input) {\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n reader.onload = function (e) {\n $uploadCrop.croppie('bind', {url: e.target.result});\n $container.show();\n $('.upload-msg').hide();\n };\n reader.readAsDataURL(input.files[0]);\n }\n }\n\n $uploadCrop = $container.croppie({\n viewport: {width: 250, height: 250, type: 'square'},\n boundary: {width: 300, height: 300}\n });\n\n $('#' + 'file').on('change', function () {\n readFile(this);\n });\n $form.on('submit', function (ev) {\n image = $('#imageUploadCropContainer img');\n if (image.width() > 1999 || image.height() > 1999) {\n alert('Das Bild ist zu groß. Bitte verwenden Sie ein Bild mit maximal 2000x2000 Pixel.');\n $uploadCrop.croppie('destroy');\n $uploadCrop = $container.croppie({\n viewport: {width: 250, height: 250, type: 'square'},\n boundary: {width: 300, height: 300}\n });\n $container.hide();\n $('.upload-msg').show();\n } else {\n if (image.width() > 0 || image.height() > 0) {\n $uploadCrop.croppie('result', {\n type: 'canvas',\n size: 'original'\n }).then(function (resp) {\n $('#croppedImage').val(resp);\n $form.unbind('submit').submit();\n });\n } else {\n $form.unbind('submit').submit();\n }\n }\n\n return false;\n });\n });\n</script>\n </div>\n </div>\n \n <div class=\"content\">\n <div class=\"row\">\n \n <div class=\"col-sm-12 \">\n <span class=\"bold\">Bildbeschreibung <span class=\"text-danger\">*</span>\n </span>\n <br/>\n \n <div class=\" \">\n \n \n <textarea id=\"text\" name=\"text\" class=\"form-control \" data-description=\"Bitte ergänzen Sie das Bild mit einer Textbeschreibung und dem Firmennamen (z.&nbsp;B. 'Produktionshalle der Muster GmbH in Musterstadt')\" data-required=\"true\" required=\"required\"></textarea> \n </div>\n\n \n </div>\n <div class=\"col-sm-12\">\n <div class=\"form-group form-help\">\n <table>\n <tr>\n <td class=\"col-middle\">\n <i class=\"fa fa-3x fa-info-circle text-gray\"></i>\n </td>\n <td class=\"col-middle\">\n Bitte ergänzen Sie das Bild mit einer Textbeschreibung und dem Firmennamen (z. B. 'Produktionshalle der Muster GmbH in Musterstadt') </td>\n </tr>\n </table>\n </div>\n </div>\n </div>\n </div>\n\n \n<div class=\"content\">\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <p> (Mit * gekennzeichnete Felder sind Pflichtfelder)</p>\n </div>\n </div>\n</div>\n\n \n \n \n\n \n<div class=\"content form-login\">\n \n<input type=\"hidden\" class=\"csrf-token\" name=\"csrf_token\" value=\"7P9VPKbagvLoyiJ\"/> <input type=\"hidden\" id=\"formIdent\" name=\"formIdent\" value=\"imageUpload\" /> <input type=\"hidden\" id=\"mediaType\" name=\"mediaType\" /> <input type=\"hidden\" id=\"croppedImage\" name=\"croppedImage\" value=\"\" /> \n <div class=\"row\">\n \n\n<div class=\"col-xs-12 form-login-actions\">\n <p class=\"bold\">Das Hochladen von Bildern ist kostenlos, Sie benötigen lediglich ein Benutzerkonto.</p>\n\n <div class=\"gray-light\">\n <div class=\"row\">\n <div class=\"col-sm-6\">\n <div class=\"content\">\n <p>Ich habe bereits ein Benutzerkonto</p>\n <a href=\"#\" onclick=\"Login.popup(this); return false\" class=\"btn btn-lg btn-warning btn-block\">Jetzt einloggen</a>\n \n <input type=\"checkbox\" style=\"display:none\" name=\"returnBlock\" class=\"form-login-returnBlock\" required/>\n </div>\n </div>\n <div class=\"col-sm-6 loginFormBorderLeft form-login-register\">\n <div class=\"content\">\n <p>Ich habe noch kein Benutzerkonto</p>\n\n <div class=\"form-group\">\n <label for=\"formLoginimage\" class=\"control-label\">E-Mail <span\n class=\"text-danger\">*</span></label>\n <input type=\"email\" name=\"formLoginEmail\" id=\"formLoginimage\"\n class=\"form-control form-login-email\"\n onkeyup=\"Login.checkForSend($('#formLoginimage'))\"\n onchange=\"Login.checkForSend($('#formLoginimage'))\"\n onblur=\"Login.checkForSend($('#formLoginimage'))\"\n value=\"[email protected]\" required/>\n </div>\n <div class=\"form-group\">\n \n\n<script type=\"text/javascript\">\n grecaptcha.render('recaptcha-image', {\n 'sitekey': '6Ld0RAoTAAAAAFji0CujiR0oPoPiDYZQvh21l715',\n 'theme': 'light'\n });\n </script> <div id=\"recaptcha-image\" class=\"g-recaptcha\"></div>\n </div>\n <p class=\"text-center\">oder</p>\n <script>\n function facebookStatusCallback(response) {\n if (response.status === 'connected') {\n FB.api('/me', function (res) {\n Login.facebookRegister({'auth': response, 'profile': res});\n });\n }\n }\n</script>\n\n\n\n \n<button type=\"button\" class=\"btn btn-block btn-default btn-lg col-middle facebook-login-button marginBottom5\"\n onclick=\"Social.loginByFacebookStep1(this, '445350842203770', 'public_profile,email', 'Jetzt mit Facebook anmelden');\">\n <i class=\"fa fa-facebook-square fa-2x\"></i> Registrierung per Facebook\n</button>\n\n \n<p>Eine Verbindung zu Facebook wird erst hergestellt, wenn Sie auf die oben angezeigte Schaltfläche klicken. Weitere Informationen: <a rel=\"nofollow\" href=\"/infos/datenschutzhinweis\" target=\"_blank\">Datenschutzhinweis</a></p> <br/>\n <div>\n <label>\n <input type=\"checkbox\" class=\"form-login-terms\" name=\"terms\" required/>\n <span style=\"vertical-align:text-bottom\">\n Ich akzeptiere die\n <a href=\"/allgemeine-geschaeftsbedingungen\"\n target=\"_blank\">AGB</a>\n <span class=\"text-danger\">*</span>\n </span>\n </label>\n </div>\n\n <div style=\"\">\n <label>\n <input type=\"checkbox\" name=\"newsletter\"\n />\n <span style=\"vertical-align:text-bottom\">Angebote und Neuigkeiten per E-Mail erhalten</span>\n </label>\n </div>\n </div>\n </div>\n </div>\n </div>\n</div> <br/>\n\n <div class=\"form-login-submit\"></div>\n <br/>\n\n <div class=\"col-xs-12 form-login-submit\">\n <input type=\"submit\" value=\"Senden\" class=\"btn btn-lg btn-warning btn-block\" textClass=\"bold\" /> </div>\n </div>\n</div>\n\n<script type=\"text/javascript\">\n $('.form-login-submit').hide();\n Login.showRegister($('.form-login-actions'));\n </script>\n </form> </div>\n</div>\n\n<script type=\"text/javascript\" src=\"https://www.bundes-telefonbuch.de/js/rating.js\"></script>\n </div>\n \n <div class=\"panel panel-default\">\n <div class=\"panel-heading\">\n <h2 class=\"panel-title\">\n <a data-toggle=\"collapse\" data-parent=\"#accordion\" href=\"#companyCategories\" class=\"btn-block\">\n Mit diesem Eintrag verknüpfte Branchen und Keywords <span class=\"pull-right\"><i class=\"fa fa-caret-down\"></i></span>\n </a>\n </h2>\n </div>\n <div id=\"companyCategories\" class=\"panel-collapse collapse in\">\n <div class=\"panel-body\">\n <div class=\"margin_10\">\n <h3>Branche</h3>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg\" rel=\"follow\">\n <span class=\"value-category\">Firma</span>\n in Nürnberg </a>\n </div>\n \n \n <div class=\"margin_10\">\n <h3>Stichwörter</h3>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/aachener-muenchener\" rel=\"follow\">Aachener Münchener</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/auto-reparatur\" rel=\"follow\">Auto-Reparatur</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/autolackiererei\" rel=\"follow\">Autolackiererei</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/autolackierung\" rel=\"follow\">Autolackierung</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/cosmos\" rel=\"follow\">Cosmos</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/fahrzeuglackierungen\" rel=\"follow\">Fahrzeuglackierungen</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/gothar\" rel=\"follow\">Gothar</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/huk\" rel=\"follow\">HUK</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/karosserie\" rel=\"follow\">Karosserie</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/karosseriearbeiten\" rel=\"follow\">Karosseriearbeiten</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/karosseriefachbetrieb\" rel=\"follow\">Karosseriefachbetrieb</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/karosserieinstandsetzung\" rel=\"follow\">Karosserieinstandsetzung</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/kfz-unfall\" rel=\"follow\">Kfz-Unfall</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/lackiererei\" rel=\"follow\">Lackiererei</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/lackierfachbetrieb\" rel=\"follow\">Lackierfachbetrieb</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/lackierung\" rel=\"follow\">Lackierung</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/rahmen-richtbank\" rel=\"follow\">Rahmen-Richtbank</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/unfallinstandsetzung\" rel=\"follow\">Unfallinstandsetzung</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/unfallschaden\" rel=\"follow\">Unfallschaden</a>\n <a class=\"label label-default\" href=\"/suche/firma/nuernberg/vhv\" rel=\"follow\">VHV</a>\n </div>\n </div>\n </div>\n</div>\n\n\n </div>\n <div class=\"col-sm-4\">\n <div class=\"content rectangleContainer1\">\n <div id=\"gpt-ad-rectangle1\" class=\"rectangle\">\n <script type='text/javascript'>\n googletag.cmd.push(function () {\n googletag.display('gpt-ad-rectangle1');\n });\n </script>\n </div>\n </div>\n\n <script type='text/javascript'>\n $(document).ready(function () {\n var leaderWidth = $('.rectangleContainer1').parent().width();\n if (leaderWidth < 300) {\n $('.rectangleContainer1').hide()\n } else {\n $('.rectangleContainer1').show()\n }\n });\n </script>\n <div class=\"panel panel-default similarCompany\">\n <div class=\"panel-heading\">\n <h2 class=\"panel-title\">\n <a data-toggle=\"collapse\" data-parent=\"#accordion\" href=\"#similarCompany\" class=\"btn-block\">\n Ähnliche Firmen in der Nähe <span class=\"pull-right\"><i class=\"fa fa-caret-down\"></i></span>\n </a>\n </h2>\n </div>\n <div id=\"similarCompany\" class=\"panel-collapse collapse in\">\n <div class=\"panel-body\">\n <table>\n <tr>\n <td><i class=\"fa fa-2x fa-map-marker text-danger\"></i></td>\n <td class=\"text-right width60\">0.8 km</td>\n <td><a href=\"/nuernberg/firma/mchamed-kairi-bvg901000188\">Mchamed Kairi, Nürnberg</a></td>\n </tr>\n <tr>\n <td><i class=\"fa fa-2x fa-map-marker text-danger\"></i></td>\n <td class=\"text-right width60\">1.2 km</td>\n <td><a href=\"/nuernberg/firma/biegel-kurt-bvg014703840\">Biegel, Kurt, Nürnberg</a></td>\n </tr>\n <tr>\n <td><i class=\"fa fa-2x fa-map-marker text-danger\"></i></td>\n <td class=\"text-right width60\">1.2 km</td>\n <td><a href=\"/nuernberg/firma/geisler-guenther-bvg014705800\">Geisler Günther, Nürnberg</a></td>\n </tr>\n <tr>\n <td><i class=\"fa fa-2x fa-map-marker text-danger\"></i></td>\n <td class=\"text-right width60\">1.5 km</td>\n <td><a href=\"/nuernberg/firma/service-centrum-nordbayern-frank-hernik-it-dienstleistung-bvg901629662\">Service-Centrum Nordbayern Frank Hernik IT-Dienstleistung, Nürnberg</a></td>\n </tr>\n <tr>\n <td><i class=\"fa fa-2x fa-map-marker text-danger\"></i></td>\n <td class=\"text-right width60\">1.7 km</td>\n <td><a href=\"/nuernberg/firma/hagen-haarpraxis-bvg150879861\">Hagen Haarpraxis, Nürnberg</a></td>\n </tr>\n </table>\n \n </div>\n </div>\n</div>\n <div class=\"panel panel-default\">\n <div class=\"panel-heading\">\n <h2 class=\"panel-title\">\n <a data-toggle=\"collapse\" data-parent=\"#accordion\" href=\"#companySeoText\" class=\"btn-block\">\n Information zum Firmeneintrag <span class=\"pull-right\"><i class=\"fa fa-caret-down\"></i></span>\n </a>\n\n </h2>\n </div>\n <div id=\"companySeoText\" class=\"panel-collapse collapse in\">\n <div class=\"panel-body\">\n <div itemprop=\"description\">\n <p>\n Hier sehen Sie das <strong>Profil des Unternehmens Karosseriefachbetrieb Hofer in Nürnberg</strong> <br/>\n Auf Bundestelefonbuch ist dieser Eintrag seit dem 08.09.2017. Die Daten für das Verzeichnis wurden zuletzt am 08.09.2017, 07:59 geändert. Die Firma ist der Branche Firma in Nürnberg zugeordnet. </p>\n <p>Notiz:\n Ergänzen Sie den Firmeneintrag mit weiteren Angaben oder schreiben Sie eine Bewertung und teilen Sie Ihre Erfahrung zum Anbieter Karosseriefachbetrieb Hofer in Nürnberg mit. </p>\n </div>\n </div>\n </div>\n</div>\n\n </div>\n </div>\n</div>\n \n<script type=\"text/javascript\">\n\tswitch (window.location.hash) {\n\t\tcase '#karte':\n\t\t\tCompanyAjaxLoad.getAdditionalCompanyInfo('companyMap', '13478898', window.location.hash, true, 'map');\n\t\t\tbreak;\n\t\tcase '#termin-o-reservierung-vereinbaren':\n\t\t\tCompanyAjaxLoad.toggleFromNavigation('navigation_appointment', 'termin-o-reservierung-vereinbaren', true, true);\n\t\t\tbreak;\n\t\tcase '#firma-uebernehmen':\n\t\t\tCompanyAjaxLoad.getAdditionalCompanyInfo('companyClaim', '13478898', window.location.hash, true, 'claim');\n\t\t\tbreak;\n\t\tdefault:\n \t\t\tbreak;\n\t}\n\n\t$(document).ajaxComplete(function() {\n\t\t$('#additionalCompanyInfo .panel').switchClass(\"panel-default\", \"panel-danger\", 1500, \"easeInQuad\");\n\t\tsetTimeout(function() {\n\t\t\t$('#additionalCompanyInfo .panel').switchClass(\"panel-danger\", \"panel-default\", 1500, \"easeOutQuad\");\n\t\t}, 3000);\n\t});\n</script> <div class=\"row\">\n <div class='col-sm-8'>\n <div class=\"item\">\n <div class=\"content\">\n <div class=\"hidden-xs marginBottom20 leaderContainer\">\n <div id=\"gpt-ad-leader\" class=\"leaderBottom text-center\">\n <script type='text/javascript'>\n googletag.cmd.push(function () {\n googletag.display('gpt-ad-leader');\n });\n </script>\n </div>\n </div>\n <div class=\"visible-xs\"></div>\n\n \n \n <script type='text/javascript'>\n $(document).ready(function () {\n var leaderWidth = $('.leaderContainer').parent().width();\n if (leaderWidth < 728) {\n $('.leaderContainer').hide()\n } else {\n $('.leaderContainer').show()\n }\n });\n </script>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n\n <footer>\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <div class=\"text-center\">\n <br/>\n <p>\n \n <a href=\"/faq\">Häufig gestellte Fragen</a> |\n <a rel=\"nofollow\" href=\"/kontakt\">Kontakt</a> |\n <a href=\"https://www.bundes-telefonbuch.de/blog/\" target=\"_blank\">Blog</a> |\n <a href=\"/firma/kostenlos-eintragen\">Firma eintragen</a> |\n <br/>\n <a rel=\"nofollow\" href=\"/infos/nutzungsbedingungen\">Nutzungsbedingungen</a> |\n <a rel=\"nofollow\" href=\"/infos/datenschutzhinweis\">Datenschutzhinweis</a> |\n <a rel=\"nofollow\" href=\"/infos/agb\">AGB</a> |\n <a rel=\"nofollow\" href=\"/infos/impressum\">Impressum von Bundestelefonbuch</a> <br/>© BVV Bundesverzeichnis Verlag GmbH & Co. KG - Auskunft mit Telefonnummer und Bewertung\n </p>\n </div>\n </div>\n </div>\n </div>\n</footer>\n\n <script type=\"text/javascript\">\n \n window.document.cookie = \"companyId=13478898; path=/\"\n </script>\n\n<div id=\"fb-root\"></div>\n\n\n\n\n\n<script>\n (function(i, s, o, g, r, a, m) {\n i['GoogleAnalyticsObject'] = r;\n i[r] = i[r] || function() {\n (i[r].q = i[r].q || []).push(arguments)\n }, i[r].l = 1 * new Date();\n a = s.createElement(o), m = s.getElementsByTagName(o)[0];\n a.async = 1;\n a.src = g;\n m.parentNode.insertBefore(a, m)\n })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');\n\n ga('create', 'UA-4947670-1', 'auto');\n ga('set', 'anonymizeIp', true);\n ga('send', 'pageview');\n</script>\n\n\n<script type=\"text/javascript\" src=\"https://script.ioam.de/iam.js\"></script>\n<script type=\"text/javascript\">\n var iam_data = {\n \"st\": \"dastelef\",\n \"cp\": \"TBBUND20\",\n \"sv\": \"in\"\n };\n iom.c(iam_data);\n</script>\n\n<script src=\"https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit\" async defer></script></div>\n\n<script type=\"text/javascript\">\n var Confirmation = (function ($) {\n var my = {'facebookCallback': null};\n\n my.registerFacebookCallback = function (cb) {\n my.facebookCallback = cb;\n };\n\n my.isConfirmed = function (by, data) {\n var email, accountname, token;\n\n if (by === 'facebook') {\n email = data.profile.email;\n accountname = data.profile.name;\n token = data.auth.authResponse.accessToken;\n $('.facebook-authinfo').val(JSON.stringify(data.auth.authResponse));\n\n if (typeof my.facebookCallback === 'function') {\n my.facebookCallback(data.auth, data.profile);\n }\n } else {\n if (by === 'twitter') {\n email = 'not_send';\n accountname = 'not_send';\n token = 'private';\n } else {\n return;\n }\n }\n\n $('.confirm-option').hide();\n $('.confirm-info').show().children(':nth-child(2)').html('Bestätigung erfolgt über ' + by.charAt(0).toUpperCase() + by.slice(1));\n $('.privemail').val(email);\n $('.accountname').val(accountname);\n $('.accesstoken').val(token);\n $('.confirmMethod').val(by);\n $('.captchaAnswer').val('1234');\n };\n\n my.listener = function (event) {\n if (event.data === 'dialo_twitter_confirm_ok') {\n my.isConfirmed('twitter');\n }\n };\n\n return my;\n }(jQuery));\n\n if (window.addEventListener) {\n addEventListener(\"message\", function (e) {\n if (Confirmation) {\n Confirmation.listener(e);\n }\n if (Login) {\n Login.listener(e);\n }\n }, false)\n } else {\n attachEvent(\"onmessage\", function (e) {\n if (Confirmation) {\n Confirmation.listener(e);\n }\n if (Login) {\n Login.listener(e);\n }\n })\n }\n\n \n jQuery(window).load(function () {\n \n $('.image-defer').each(function () {\n $(this).attr('src', $(this).data('src'));\n });\n })\n</script>\n\n<script type=\"text/javascript\" src=\"https://www.bundes-telefonbuch.de/js/foot_all.js?1498638616\"></script>\n\n</body>\n</html>\n\n"
]
],
[
[
"### Beautiful Soup",
"_____no_output_____"
]
],
[
[
"entry_soup = BeautifulSoup(response.text,'html.parser')",
"_____no_output_____"
],
[
"name = entry_soup.h1.text.strip()\nprint(name)",
"Karosseriefachbetrieb Hofer\n"
],
[
"address_div = entry_soup.find('div', {'class':'detail-address'})\nprint(address_div.text)\naddress_div.stripped_strings",
"\n\n Hans-Bunte-Str. 47 \n\n90431\nNürnberg\n\n"
],
[
"address_parts = list(address_div.stripped_strings)\nprint(address_parts)\naddress = ' '.join(address_parts)\nprint(address)",
"['Hans-Bunte-Str. \\xa047', '90431', 'Nürnberg']\nHans-Bunte-Str. 47 90431 Nürnberg\n"
],
[
"email = entry_soup.find('a',{'class':'detail-email'}).get('href')\nprint(email)",
"mailto:[email protected]\n"
],
[
"website = entry_soup.find('a',{'class':'detail-homepage'}).get('href')\nprint(website)",
"http://www.hofer-n.de\n"
],
[
"tel = entry_soup.find('span', {'class':'detail-fax'}).text.strip()\nfax = entry_soup.find('span', {'class':'detail-phone'}).text.strip()\nprint(tel, fax)",
"(0911) 318106 (0911) 314947\n"
]
],
[
[
"## Create Scrapy Project ",
"_____no_output_____"
]
],
[
[
"scrapy startproject yellow_pages",
"_____no_output_____"
],
[
"cd yellow_pages\nscrapy genspider telefonbuch bundes-telefonbuch.de",
"_____no_output_____"
]
],
[
[
"## Scrapy Shell for debugging",
"_____no_output_____"
]
],
[
[
"scrapy shell 'www.bundes-telefonbuch.de'",
"_____no_output_____"
]
],
[
[
"### Scrapy: Fill Out Forms",
"_____no_output_____"
]
],
[
[
"fetch(scrapy.FormRequest.from_response(response, formid='searchForm', formdata={'what':'auto', 'where':'Muenchen'}))",
"_____no_output_____"
],
[
"response.css('div.companyBox')",
"_____no_output_____"
],
[
"results_soup = BeautifulSoup(response.text,'html.parser')",
"_____no_output_____"
],
[
"results_soup.prettify()",
"_____no_output_____"
]
],
[
[
"### Extract entries",
"_____no_output_____"
]
],
[
[
"entry = results_soup.find('div',{'class':'companyBox'})",
"_____no_output_____"
],
[
"entries = result_soup.find_all('div', {'class':'companyBox'})\nlen(entries)",
"_____no_output_____"
]
],
[
[
"### Paging",
"_____no_output_____"
]
],
[
[
"paging = result_soup.find('div',{'id':'pagination'})",
"_____no_output_____"
],
[
"pages = paging.find_all('a')\nlen(pages)",
"_____no_output_____"
],
[
"next_page = None\nfor page in pages:\n if page.text.strip()=='∨':\n next_page = page.get('href')\n break",
"_____no_output_____"
],
[
"start_urls = ['http://bundes-telefonbuch.de/']\nif next_page:\n next_page = start_urls[0] + next_page\nprint(next_page)",
"_____no_output_____"
]
],
[
[
"### Get the details of the entry",
"_____no_output_____"
]
],
[
[
"entry_url = entry.a.get('href')\nfetch(scrapy.http.Request(start_urls[0] + entry_url))",
"_____no_output_____"
],
[
"entry_soup = BeautifulSoup(response.text,'html.parser')",
"_____no_output_____"
],
[
"name = entry_soup.h1.text.strip()\nprint(name)",
"_____no_output_____"
],
[
"address_div = entry_soup.find('div', {'class':'detail-address'})\nprint(address_div.text)\nprint(address_div.stripped_strings)",
"_____no_output_____"
],
[
"address_parts = list(address_div.stripped_strings)\nprint(address_parts)\naddress = ' '.join(address_parts)\nprint(address)",
"_____no_output_____"
],
[
"email = entry_soup.find('a',{'class':'detail-email'}).get('href')\nprint(email)",
"_____no_output_____"
],
[
"website = entry_soup.find('a',{'class':'detail-homepage'}).get('href')\nprint(website)",
"_____no_output_____"
],
[
"tel = entry_soup.find('span', {'class':'detail-fax'}).text.strip()\nfax = entry_soup.find('span', {'class':'detail-phone'}).text.strip()\nprint(tel, fax)",
"_____no_output_____"
]
],
[
[
"## Run crawler",
"_____no_output_____"
]
],
[
[
"scrapy crawl telefonbuch -a sector=\"Auto\" -a city=\"Muenchen\" -o \"Auto_Muenchen.csv\"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aa8f03e99e6edf583765afab5d14af0daec8199
| 77,307 |
ipynb
|
Jupyter Notebook
|
docs/new/test.ipynb
|
SanstyleLab/pytorch-book
|
d615ddade989559dfeaf8e765d294e1616af320a
|
[
"Apache-2.0"
] | 1 |
2021-11-05T01:25:28.000Z
|
2021-11-05T01:25:28.000Z
|
docs/new/test.ipynb
|
SanstyleLab/pytorch-book
|
d615ddade989559dfeaf8e765d294e1616af320a
|
[
"Apache-2.0"
] | null | null | null |
docs/new/test.ipynb
|
SanstyleLab/pytorch-book
|
d615ddade989559dfeaf8e765d294e1616af320a
|
[
"Apache-2.0"
] | null | null | null | 568.433824 | 74,442 | 0.951738 |
[
[
[
"import sys\n\nroot = '../..'\nsys.path.extend([f'{root}/apps'])",
"_____no_output_____"
],
[
"from pathlib import Path\nfrom test_op import Test",
"_____no_output_____"
],
[
"model_name = 'CSA-256'\n\n## 模型参数\nalpha = 1\nbeta = 0.8\n\nfine_size = 256\n\ncheckpoints_dir = 'D:/BaiduNetdiskWorkspace/result'\nsave_dir = \"D:/BaiduNetdiskWorkspace/result/measure\"\ngpu_ids = [0]\nwhich_epoch = -1",
"_____no_output_____"
],
[
"test = Test(fine_size)",
"_____no_output_____"
],
[
"for image, name, mask in test:\n for epoch in range(50, 120):\n model = test.model(alpha, beta,\n checkpoints_dir, gpu_ids,\n which_epoch=epoch)\n test.run(epoch, image, name, mask, model, save_dir)\n break\n break\n",
"initialize network with normal\ninitialize network with normal\nLoading pre-trained network!\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code"
]
] |
4aa8f055b0c2b86ad8747c47d48a0c12757ec7bc
| 354,659 |
ipynb
|
Jupyter Notebook
|
7-TimeSeries/2-ARIMA/working/notebook.ipynb
|
turhancan97/ML-For-Beginners
|
8bc4c7d4e355ea816322c83c67770600ba5bc77e
|
[
"MIT"
] | null | null | null |
7-TimeSeries/2-ARIMA/working/notebook.ipynb
|
turhancan97/ML-For-Beginners
|
8bc4c7d4e355ea816322c83c67770600ba5bc77e
|
[
"MIT"
] | null | null | null |
7-TimeSeries/2-ARIMA/working/notebook.ipynb
|
turhancan97/ML-For-Beginners
|
8bc4c7d4e355ea816322c83c67770600ba5bc77e
|
[
"MIT"
] | null | null | null | 261.547935 | 163,150 | 0.898776 |
[
[
[
"# Time series forecasting with ARIMA\n\nIn this notebook, we demonstrate how to:\n- prepare time series data for training an ARIMA time series forecasting model\n- implement a simple ARIMA model to forecast the next HORIZON steps ahead (time *t+1* through *t+HORIZON*) in the time series\n- evaluate the model \n\n\nThe data in this example is taken from the GEFCom2014 forecasting competition<sup>1</sup>. It consists of 3 years of hourly electricity load and temperature values between 2012 and 2014. The task is to forecast future values of electricity load. In this example, we show how to forecast one time step ahead, using historical load data only.\n\n<sup>1</sup>Tao Hong, Pierre Pinson, Shu Fan, Hamidreza Zareipour, Alberto Troccoli and Rob J. Hyndman, \"Probabilistic energy forecasting: Global Energy Forecasting Competition 2014 and beyond\", International Journal of Forecasting, vol.32, no.3, pp 896-913, July-September, 2016.",
"_____no_output_____"
]
],
[
[
"import os\nimport warnings\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport datetime as dt\nimport math\n\nfrom pandas.plotting import autocorrelation_plot\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\nfrom sklearn.preprocessing import MinMaxScaler\nfrom common.utils import load_data, mape\nfrom IPython.display import Image\n\n%matplotlib inline\npd.options.display.float_format = '{:,.2f}'.format\nnp.set_printoptions(precision=2)\nwarnings.filterwarnings(\"ignore\") # specify to ignore warning messages",
"_____no_output_____"
],
[
"energy = load_data('./data')[['load']]\nenergy.head(10)",
"_____no_output_____"
],
[
"energy.plot(y='load', subplots=True, figsize=(15, 8), fontsize=12)\nplt.xlabel('timestamp', fontsize=12)\nplt.ylabel('load', fontsize=12)\nplt.show()",
"_____no_output_____"
],
[
"train_start_dt = '2014-11-01 00:00:00'\ntest_start_dt = '2014-12-30 00:00:00'",
"_____no_output_____"
],
[
"energy[(energy.index < test_start_dt) & (energy.index >= train_start_dt)][['load']].rename(columns={'load':'train'}) \\\n .join(energy[test_start_dt:][['load']].rename(columns={'load':'test'}), how='outer') \\\n .plot(y=['train', 'test'], figsize=(15, 8), fontsize=12)\nplt.xlabel('timestamp', fontsize=12)\nplt.ylabel('load', fontsize=12)\nplt.show()",
"_____no_output_____"
],
[
"energy[(energy.index < test_start_dt) & (energy.index >= train_start_dt)][['load']].rename(columns={'load':'train'})",
"_____no_output_____"
],
[
"energy[test_start_dt:][['load']].rename(columns={'load':'test'})",
"_____no_output_____"
],
[
"train = energy.copy()[(energy.index >= train_start_dt) & (energy.index < test_start_dt)][['load']]\ntest = energy.copy()[energy.index >= test_start_dt][['load']]\n\nprint('Training data shape: ', train.shape)\nprint('Test data shape: ', test.shape)",
"Training data shape: (1416, 1)\nTest data shape: (48, 1)\n"
],
[
"scaler = MinMaxScaler()\ntrain['load'] = scaler.fit_transform(train)\ntrain.head(10)",
"_____no_output_____"
],
[
"energy[(energy.index >= train_start_dt) & (energy.index < test_start_dt)][['load']].rename(columns={'load':'original load'}).plot.hist(bins=100, fontsize=12)\ntrain.rename(columns={'load':'scaled load'}).plot.hist(bins=100, fontsize=12)\nplt.show()",
"_____no_output_____"
],
[
"test['load'] = scaler.transform(test)\ntest.head()",
"_____no_output_____"
],
[
"# Specify the number of steps to forecast ahead\nHORIZON = 3\nprint('Forecasting horizon:', HORIZON, 'hours')",
"Forecasting horizon: 3 hours\n"
],
[
"order = (4, 1, 0)\nseasonal_order = (1, 1, 0, 24)\n\nmodel = SARIMAX(endog=train, order=order, seasonal_order=seasonal_order)\nresults = model.fit()\n\nprint(results.summary())",
" SARIMAX Results \n==========================================================================================\nDep. Variable: load No. Observations: 1416\nModel: SARIMAX(4, 1, 0)x(1, 1, 0, 24) Log Likelihood 3477.240\nDate: Wed, 16 Mar 2022 AIC -6942.480\nTime: 13:09:45 BIC -6911.053\nSample: 11-01-2014 HQIC -6930.728\n - 12-29-2014 \nCovariance Type: opg \n==============================================================================\n coef std err z P>|z| [0.025 0.975]\n------------------------------------------------------------------------------\nar.L1 0.8405 0.016 52.187 0.000 0.809 0.872\nar.L2 -0.5218 0.034 -15.372 0.000 -0.588 -0.455\nar.L3 0.1530 0.044 3.458 0.001 0.066 0.240\nar.L4 -0.0783 0.036 -2.173 0.030 -0.149 -0.008\nar.S.L24 -0.2335 0.024 -9.758 0.000 -0.280 -0.187\nsigma2 0.0004 8.32e-06 47.351 0.000 0.000 0.000\n===================================================================================\nLjung-Box (L1) (Q): 0.05 Jarque-Bera (JB): 1464.29\nProb(Q): 0.82 Prob(JB): 0.00\nHeteroskedasticity (H): 0.84 Skew: 0.14\nProb(H) (two-sided): 0.07 Kurtosis: 8.02\n===================================================================================\n\nWarnings:\n[1] Covariance matrix calculated using the outer product of gradients (complex-step).\n"
],
[
"test_shifted = test.copy()\n\nfor t in range(1, HORIZON):\n test_shifted['load+'+str(t)] = test_shifted['load'].shift(-t, freq='H')\n\ntest_shifted = test_shifted.dropna(how='any')\ntest_shifted.head(5)",
"_____no_output_____"
],
[
"%%time\ntraining_window = 720 # dedicate 30 days (720 hours) for training\n\ntrain_ts = train['load']\ntest_ts = test_shifted\n\nhistory = [x for x in train_ts]\nhistory = history[(-training_window):]\n\npredictions = list()\n\norder = (2, 1, 0)\nseasonal_order = (1, 1, 0, 24)\n\nfor t in range(test_ts.shape[0]):\n model = SARIMAX(endog=history, order=order, seasonal_order=seasonal_order)\n model_fit = model.fit()\n yhat = model_fit.forecast(steps = HORIZON)\n predictions.append(yhat)\n obs = list(test_ts.iloc[t])\n # move the training window\n history.append(obs[0])\n history.pop(0)\n print(test_ts.index[t])\n print(t+1, ': predicted =', yhat, 'expected =', obs)",
"2014-12-30 00:00:00\n1 : predicted = [0.32 0.29 0.28] expected = [0.32945389435989236, 0.2900626678603402, 0.2739480752014323]\n2014-12-30 01:00:00\n2 : predicted = [0.3 0.29 0.3 ] expected = [0.2900626678603402, 0.2739480752014323, 0.26812891674127126]\n2014-12-30 02:00:00\n3 : predicted = [0.27 0.28 0.32] expected = [0.2739480752014323, 0.26812891674127126, 0.3025962399283795]\n2014-12-30 03:00:00\n4 : predicted = [0.28 0.32 0.42] expected = [0.26812891674127126, 0.3025962399283795, 0.40823634735899716]\n2014-12-30 04:00:00\n5 : predicted = [0.3 0.39 0.54] expected = [0.3025962399283795, 0.40823634735899716, 0.5689346463742166]\n2014-12-30 05:00:00\n6 : predicted = [0.4 0.55 0.67] expected = [0.40823634735899716, 0.5689346463742166, 0.6799462846911368]\n2014-12-30 06:00:00\n7 : predicted = [0.57 0.68 0.75] expected = [0.5689346463742166, 0.6799462846911368, 0.7309758281110115]\n2014-12-30 07:00:00\n8 : predicted = [0.68 0.75 0.8 ] expected = [0.6799462846911368, 0.7309758281110115, 0.7511190689346463]\n2014-12-30 08:00:00\n9 : predicted = [0.75 0.8 0.82] expected = [0.7309758281110115, 0.7511190689346463, 0.7636526410026856]\n2014-12-30 09:00:00\n10 : predicted = [0.76 0.78 0.78] expected = [0.7511190689346463, 0.7636526410026856, 0.7381378692927483]\n2014-12-30 10:00:00\n11 : predicted = [0.76 0.75 0.74] expected = [0.7636526410026856, 0.7381378692927483, 0.7188898836168307]\n2014-12-30 11:00:00\n12 : predicted = [0.77 0.76 0.75] expected = [0.7381378692927483, 0.7188898836168307, 0.7090420769919425]\n2014-12-30 12:00:00\n13 : predicted = [0.7 0.68 0.69] expected = [0.7188898836168307, 0.7090420769919425, 0.7081468218442255]\n2014-12-30 13:00:00\n14 : predicted = [0.72 0.73 0.76] expected = [0.7090420769919425, 0.7081468218442255, 0.7385854968666068]\n2014-12-30 14:00:00\n15 : predicted = [0.71 0.73 0.86] expected = [0.7081468218442255, 0.7385854968666068, 0.8478066248880931]\n2014-12-30 15:00:00\n16 : predicted = [0.73 0.85 0.97] expected = [0.7385854968666068, 0.8478066248880931, 0.9516562220232765]\n2014-12-30 16:00:00\n17 : predicted = [0.87 0.99 0.97] expected = [0.8478066248880931, 0.9516562220232765, 0.934198746642793]\n2014-12-30 17:00:00\n18 : predicted = [0.94 0.92 0.86] expected = [0.9516562220232765, 0.934198746642793, 0.8876454789615038]\n2014-12-30 18:00:00\n19 : predicted = [0.94 0.89 0.82] expected = [0.934198746642793, 0.8876454789615038, 0.8294538943598924]\n2014-12-30 19:00:00\n20 : predicted = [0.88 0.82 0.71] expected = [0.8876454789615038, 0.8294538943598924, 0.7197851387645477]\n2014-12-30 20:00:00\n21 : predicted = [0.83 0.72 0.58] expected = [0.8294538943598924, 0.7197851387645477, 0.5747538048343777]\n2014-12-30 21:00:00\n22 : predicted = [0.72 0.58 0.47] expected = [0.7197851387645477, 0.5747538048343777, 0.4592658907788718]\n2014-12-30 22:00:00\n23 : predicted = [0.58 0.47 0.39] expected = [0.5747538048343777, 0.4592658907788718, 0.3858549686660697]\n2014-12-30 23:00:00\n24 : predicted = [0.46 0.38 0.34] expected = [0.4592658907788718, 0.3858549686660697, 0.34377797672336596]\n2014-12-31 00:00:00\n25 : predicted = [0.38 0.34 0.33] expected = [0.3858549686660697, 0.34377797672336596, 0.32542524619516544]\n2014-12-31 01:00:00\n26 : predicted = [0.36 0.34 0.34] expected = [0.34377797672336596, 0.32542524619516544, 0.33034914950760963]\n2014-12-31 02:00:00\n27 : predicted = [0.32 0.32 0.35] expected = [0.32542524619516544, 0.33034914950760963, 0.3706356311548791]\n2014-12-31 03:00:00\n28 : predicted = [0.32 0.36 0.47] expected = [0.33034914950760963, 0.3706356311548791, 0.470008952551477]\n2014-12-31 04:00:00\n29 : predicted = [0.37 0.48 0.65] expected = [0.3706356311548791, 0.470008952551477, 0.6145926589077886]\n2014-12-31 05:00:00\n30 : predicted = [0.48 0.64 0.75] expected = [0.470008952551477, 0.6145926589077886, 0.7247090420769919]\n2014-12-31 06:00:00\n31 : predicted = [0.63 0.73 0.79] expected = [0.6145926589077886, 0.7247090420769919, 0.786034019695613]\n2014-12-31 07:00:00\n32 : predicted = [0.71 0.76 0.79] expected = [0.7247090420769919, 0.786034019695613, 0.8012533572068039]\n2014-12-31 08:00:00\n33 : predicted = [0.79 0.82 0.83] expected = [0.786034019695613, 0.8012533572068039, 0.7994628469113696]\n2014-12-31 09:00:00\n34 : predicted = [0.82 0.83 0.81] expected = [0.8012533572068039, 0.7994628469113696, 0.780214861235452]\n2014-12-31 10:00:00\n35 : predicted = [0.8 0.78 0.76] expected = [0.7994628469113696, 0.780214861235452, 0.7587287376902416]\n2014-12-31 11:00:00\n36 : predicted = [0.77 0.75 0.74] expected = [0.780214861235452, 0.7587287376902416, 0.7367949865711727]\n2014-12-31 12:00:00\n37 : predicted = [0.77 0.76 0.76] expected = [0.7587287376902416, 0.7367949865711727, 0.7188898836168307]\n2014-12-31 13:00:00\n38 : predicted = [0.75 0.75 0.78] expected = [0.7367949865711727, 0.7188898836168307, 0.7273948075201431]\n2014-12-31 14:00:00\n39 : predicted = [0.73 0.75 0.87] expected = [0.7188898836168307, 0.7273948075201431, 0.8299015219337511]\n2014-12-31 15:00:00\n40 : predicted = [0.74 0.85 0.96] expected = [0.7273948075201431, 0.8299015219337511, 0.909579230080573]\n2014-12-31 16:00:00\n41 : predicted = [0.83 0.94 0.93] expected = [0.8299015219337511, 0.909579230080573, 0.855863921217547]\n2014-12-31 17:00:00\n42 : predicted = [0.94 0.93 0.88] expected = [0.909579230080573, 0.855863921217547, 0.7721575649059982]\n2014-12-31 18:00:00\n43 : predicted = [0.87 0.82 0.77] expected = [0.855863921217547, 0.7721575649059982, 0.7023276633840643]\n2014-12-31 19:00:00\n44 : predicted = [0.79 0.73 0.63] expected = [0.7721575649059982, 0.7023276633840643, 0.6195165622202325]\n2014-12-31 20:00:00\n45 : predicted = [0.7 0.59 0.46] expected = [0.7023276633840643, 0.6195165622202325, 0.5425246195165621]\n2014-12-31 21:00:00\n46 : predicted = [0.6 0.47 0.36] expected = [0.6195165622202325, 0.5425246195165621, 0.4735899731423454]\nWall time: 2min 29s\n"
],
[
"eval_df = pd.DataFrame(predictions, columns=['t+'+str(t) for t in range(1, HORIZON+1)])\neval_df['timestamp'] = test.index[0:len(test.index)-HORIZON+1]\neval_df = pd.melt(eval_df, id_vars='timestamp', value_name='prediction', var_name='h')\neval_df['actual'] = np.array(np.transpose(test_ts)).ravel()\neval_df[['prediction', 'actual']] = scaler.inverse_transform(eval_df[['prediction', 'actual']])\neval_df.head()",
"_____no_output_____"
],
[
"if(HORIZON > 1):\n eval_df['APE'] = (eval_df['prediction'] - eval_df['actual']).abs() / eval_df['actual']\n print(eval_df.groupby('h')['APE'].mean())",
"h\nt+1 0.01\nt+2 0.01\nt+3 0.02\nName: APE, dtype: float64\n"
],
[
"print('One step forecast MAPE: ', (mape(eval_df[eval_df['h'] == 't+1']['prediction'], eval_df[eval_df['h'] == 't+1']['actual']))*100, '%')",
"One step forecast MAPE: 0.5569378541927237 %\n"
],
[
"print('Multi-step forecast MAPE: ', mape(eval_df['prediction'], eval_df['actual'])*100, '%')",
"Multi-step forecast MAPE: 1.1467232100858318 %\n"
],
[
" if(HORIZON == 1):\n ## Plotting single step forecast\n eval_df.plot(x='timestamp', y=['actual', 'prediction'], style=['r', 'b'], figsize=(15, 8))\n\nelse:\n ## Plotting multi step forecast\n plot_df = eval_df[(eval_df.h=='t+1')][['timestamp', 'actual']]\n for t in range(1, HORIZON+1):\n plot_df['t+'+str(t)] = eval_df[(eval_df.h=='t+'+str(t))]['prediction'].values\n\n fig = plt.figure(figsize=(15, 8))\n ax = plt.plot(plot_df['timestamp'], plot_df['actual'], color='r', linewidth=4.0)\n ax = fig.add_subplot(111)\n for t in range(1, HORIZON+1):\n x = plot_df['timestamp'][(t-1):]\n y = plot_df['t+'+str(t)][0:len(x)]\n ax.plot(x, y, color='blue', linewidth=4*math.pow(.9,t), alpha=math.pow(0.8,t))\n\n ax.legend(loc='best')\n\nplt.xlabel('timestamp', fontsize=12)\nplt.ylabel('load', fontsize=12)\nplt.show()",
"No artists with labels found to put in legend. Note that artists whose label start with an underscore are ignored when legend() is called with no argument.\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aa9100775f5574b5a60b70dded8987b555194a5
| 3,109 |
ipynb
|
Jupyter Notebook
|
examples/bqplot.ipynb
|
martinRenou/ipysheet
|
4b96dd63db9ac1203381be52ca329d8d91daaa2d
|
[
"MIT"
] | 495 |
2017-11-09T05:33:26.000Z
|
2022-03-20T07:33:21.000Z
|
examples/bqplot.ipynb
|
giswqs/ipysheet
|
89a80c4299f15810d665b9a4d68f18739c66c339
|
[
"MIT"
] | 171 |
2018-01-12T09:44:03.000Z
|
2022-03-25T06:02:19.000Z
|
examples/bqplot.ipynb
|
giswqs/ipysheet
|
89a80c4299f15810d665b9a4d68f18739c66c339
|
[
"MIT"
] | 69 |
2018-01-13T18:19:07.000Z
|
2022-02-18T20:06:41.000Z
| 42.589041 | 1,174 | 0.59762 |
[
[
[
"import numpy as np\nfrom traitlets import link\nfrom ipywidgets import HBox\nimport bqplot.pyplot as plt\nfrom ipysheet import sheet, cell, column\n\nsize = 18\nscale = 100.\nnp.random.seed(0)\nx_data = np.arange(size)\ny_data = np.cumsum(np.random.randn(size) * scale)\n\nfig = plt.figure()\naxes_options = {'x': {'label': 'Date', 'tick_format': '%m/%d'},\n 'y': {'label': 'Price', 'tick_format': '0.0f'}}\n\nscatt = plt.scatter(x_data, y_data, colors=['red'], stroke='black')\nfig.layout.width = '70%'\n\nsheet1 = sheet(rows=size, columns=2)\nx_column = column(0, x_data)\ny_column = column(1, y_data)\n\nlink((scatt, 'x'), (x_column, 'value'))\nlink((scatt, 'y'), (y_column, 'value'))\n\nHBox((fig, sheet1))",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
4aa915cb4953bab3892093de6956fd34fc21cec6
| 101,252 |
ipynb
|
Jupyter Notebook
|
Univ AI GHF 01/Geoffrey3.ipynb
|
swapniljha001/CodingNotes
|
3096a185caa746cdd0bf7ba4508753ede13a5347
|
[
"MIT"
] | null | null | null |
Univ AI GHF 01/Geoffrey3.ipynb
|
swapniljha001/CodingNotes
|
3096a185caa746cdd0bf7ba4508753ede13a5347
|
[
"MIT"
] | null | null | null |
Univ AI GHF 01/Geoffrey3.ipynb
|
swapniljha001/CodingNotes
|
3096a185caa746cdd0bf7ba4508753ede13a5347
|
[
"MIT"
] | null | null | null | 35.778092 | 267 | 0.288626 |
[
[
[
"\n# Import Python libraries.",
"_____no_output_____"
]
],
[
[
"#Importing required libraries\n!sudo pip install --upgrade xgboost\nimport numpy as np\nimport pandas as pd\n# import matplotlib.pyplot as plt\n# %matplotlib inline\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.preprocessing import LabelEncoder\nfrom xgboost import XGBClassifier\nfrom sklearn.metrics import classification_report\nfrom sklearn.preprocessing import StandardScaler",
"Requirement already up-to-date: xgboost in /usr/local/lib/python3.7/dist-packages (1.3.3)\nRequirement already satisfied, skipping upgrade: scipy in /usr/local/lib/python3.7/dist-packages (from xgboost) (1.4.1)\nRequirement already satisfied, skipping upgrade: numpy in /usr/local/lib/python3.7/dist-packages (from xgboost) (1.19.5)\n"
],
[
"#importing required objects and instantiating them\n# log_reg = LogisticRegression()\nlab = LabelEncoder()\n# mpld3.enable_notebook()\n# plt.rcParams['figure.figsize'] = [15, 10]\nxgbc = XGBClassifier(use_label_encoder=False)\nscaler = StandardScaler()",
"_____no_output_____"
]
],
[
[
"# Import Training Dataset",
"_____no_output_____"
]
],
[
[
"#Obtaining the data\ndataset = pd.read_csv(\"Training Data.csv\")",
"_____no_output_____"
]
],
[
[
"# Check how train dataset looks like.",
"_____no_output_____"
]
],
[
[
"dataset.tail()",
"_____no_output_____"
],
[
"X = dataset.iloc[:,[1,2,3,4,5,6,7,8,10,11]]\ny = dataset.risk_flag",
"_____no_output_____"
],
[
"X.tail()",
"_____no_output_____"
],
[
"y.tail()",
"_____no_output_____"
]
],
[
[
"# Clean the data.",
"_____no_output_____"
]
],
[
[
"# Encoding string variables\nX['married'] = lab.fit_transform(X['married'])\nX['house_ownership'] = lab.fit_transform(X['house_ownership'])\nX['car_ownership'] = lab.fit_transform(X['car_ownership'])\nX['profession'] = lab.fit_transform(X['profession'])\nX['city'] = lab.fit_transform(X['city'])\nX.tail()",
"/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \n/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:3: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n This is separate from the ipykernel package so we can avoid doing imports until\n/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:4: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n after removing the cwd from sys.path.\n/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:5: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \"\"\"\n/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:6: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \n"
],
[
"X = pd.get_dummies(X, columns=['married', 'house_ownership', 'car_ownership', 'profession', 'city'], drop_first=True)\nX.tail()",
"_____no_output_____"
],
[
"X = scaler.fit_transform(X)\nprint(X)",
"[[-1.28314452 -1.57960273 -1.18023232 ... -0.06219388 -0.04271712\n -0.05120484]\n [ 0.89545724 -0.58334335 -0.01406671 ... -0.06219388 -0.04271712\n -0.05120484]\n [-0.3492686 0.94034746 -1.01363724 ... -0.06219388 -0.04271712\n -0.05120484]\n ...\n [-0.16491255 -0.2317224 -0.51385197 ... -0.06219388 -0.04271712\n -0.05120484]\n [ 0.5246182 -0.29032589 -1.68001759 ... -0.06219388 -0.04271712\n -0.05120484]\n [ 1.41510816 1.17476143 1.15209891 ... -0.06219388 -0.04271712\n -0.05120484]]\n"
]
],
[
[
"# Train the Model\n",
"_____no_output_____"
]
],
[
[
"# log_reg.fit(X, y)",
"_____no_output_____"
],
[
"xgbc.fit(X, y)",
"[15:08:11] WARNING: ../src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.\n"
]
],
[
[
"# Import Testing Dataset",
"_____no_output_____"
]
],
[
[
"#Obtaining the test data\ndataset_test = pd.read_csv(\"Test Data.csv\")\ndataset_test.tail()",
"_____no_output_____"
],
[
"X_test = dataset_test.iloc[:,[1,2,3,4,5,6,7,8,10,11]]\nX_test.tail()",
"_____no_output_____"
]
],
[
[
"# Clean the Data.",
"_____no_output_____"
]
],
[
[
"# Encoding string variables\nX_test['married'] = lab.fit_transform(X_test['married'])\nX_test['house_ownership'] = lab.fit_transform(X_test['house_ownership'])\nX_test['car_ownership'] = lab.fit_transform(X_test['car_ownership'])\nX_test['profession'] = lab.fit_transform(X_test['profession'])\nX_test['city'] = lab.fit_transform(X_test['city'])\nX_test.tail()",
"/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \n/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:3: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n This is separate from the ipykernel package so we can avoid doing imports until\n/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:4: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n after removing the cwd from sys.path.\n/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:5: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \"\"\"\n/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:6: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \n"
],
[
"X_test = pd.get_dummies(X_test, columns=['married', 'house_ownership', 'car_ownership', 'profession', 'city'], drop_first=True)\nX_test.tail()",
"_____no_output_____"
],
[
"X_test = scaler.fit_transform(X_test)\nprint(X_test)",
"[[ 0.8249986 0.5222151 1.47325342 ... -0.0628018 -0.05006262\n -0.0467261 ]\n [-1.33148683 -1.46265637 -0.84954617 ... -0.0628018 -0.05006262\n -0.0467261 ]\n [ 1.35145994 -0.00319206 0.31185362 ... -0.0628018 -0.05006262\n -0.0467261 ]\n ...\n [ 1.06561022 -1.52103494 -0.84954617 ... -0.0628018 -0.05006262\n -0.0467261 ]\n [ 1.55141132 0.05518652 0.47776788 ... -0.0628018 -0.05006262\n -0.0467261 ]\n [ 1.47328257 -0.47022064 -0.18588915 ... -0.0628018 -0.05006262\n -0.0467261 ]]\n"
]
],
[
[
"# Test your Model",
"_____no_output_____"
]
],
[
[
"# y_test = log_reg.predict(X_test)\n# print(y_test)",
"_____no_output_____"
],
[
"y_test_xgbc = xgbc.predict(X_test)",
"_____no_output_____"
],
[
"y_pred = xgbc.predict(X)",
"_____no_output_____"
],
[
"# y_pred_lr = log_reg.predict(X)",
"_____no_output_____"
]
],
[
[
"# Generating the Output File",
"_____no_output_____"
]
],
[
[
"output = pd.read_csv(\"Test Data.csv\")\noutput['risk_flag'] = y_test_xgbc\noutput.tail()",
"_____no_output_____"
],
[
"output = output.iloc[:,[-1]]\noutput.tail()",
"_____no_output_____"
],
[
"output.to_csv(\"Test Data with Predictons3.csv\")",
"_____no_output_____"
]
],
[
[
"# Evaluating the Model",
"_____no_output_____"
]
],
[
[
"# log_reg.score(X, y)",
"_____no_output_____"
],
[
"xgbc.score(X, y)",
"_____no_output_____"
],
[
"from sklearn.metrics import roc_auc_score\nauc = roc_auc_score(y, y_pred)\nprint('ROC AUC: %f' % auc)",
"ROC AUC: 0.530831\n"
],
[
"# auc = roc_auc_score(y, y_pred_lr)\n# print('ROC AUC: %f' % auc)",
"_____no_output_____"
],
[
"print(classification_report(y, y_pred))",
" precision recall f1-score support\n\n 0 0.88 1.00 0.94 221004\n 1 0.74 0.06 0.12 30996\n\n accuracy 0.88 252000\n macro avg 0.81 0.53 0.53 252000\nweighted avg 0.87 0.88 0.84 252000\n\n"
],
[
"# print(classification_report(y, y_pred_lr))",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aa91baccc6462dbeba937cd772607579de34734
| 639 |
ipynb
|
Jupyter Notebook
|
tests/ipynb/rst2ipynb/math.ipynb
|
ocayrol/sphinxcontrib-jupyter
|
6bdaefa56d4dd2bec2c54e391afd93261fab840a
|
[
"BSD-3-Clause"
] | null | null | null |
tests/ipynb/rst2ipynb/math.ipynb
|
ocayrol/sphinxcontrib-jupyter
|
6bdaefa56d4dd2bec2c54e391afd93261fab840a
|
[
"BSD-3-Clause"
] | null | null | null |
tests/ipynb/rst2ipynb/math.ipynb
|
ocayrol/sphinxcontrib-jupyter
|
6bdaefa56d4dd2bec2c54e391afd93261fab840a
|
[
"BSD-3-Clause"
] | null | null | null | 21.3 | 91 | 0.428795 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4aa923c561a1ba1343b959f8c6c5f7b693b65758
| 2,785 |
ipynb
|
Jupyter Notebook
|
FindApheroidNotebook.ipynb
|
gronteix/Cell-Tracking-2D
|
f772bbef750836fac03f4263094d3968d0dad7a9
|
[
"MIT"
] | null | null | null |
FindApheroidNotebook.ipynb
|
gronteix/Cell-Tracking-2D
|
f772bbef750836fac03f4263094d3968d0dad7a9
|
[
"MIT"
] | null | null | null |
FindApheroidNotebook.ipynb
|
gronteix/Cell-Tracking-2D
|
f772bbef750836fac03f4263094d3968d0dad7a9
|
[
"MIT"
] | null | null | null | 25.787037 | 250 | 0.597846 |
[
[
[
"import os\nimport sys\nimport tqdm\nimport numpy as np\nimport pandas\n\nfrom tqdm import tqdm_notebook as tqdm\nfrom pims_nd2 import ND2_Reader\nfrom scipy.ndimage import gaussian_filter\n\nimport matplotlib.pyplot as plt\n\nimport cv2\nfrom numpy import unravel_index",
"_____no_output_____"
]
],
[
[
"## Cell tracking and identification\n\nWe analyze the images starting from the raw images. They are arganized in the following order:\n\n - experiment\n - well no.\n - channel no.\n \nWe call them from the trackingparr function.",
"_____no_output_____"
]
],
[
[
"from nd2reader import ND2Reader",
"_____no_output_____"
]
],
[
[
"## Spheroid segmentation\n\nInitial step is to retrieve spheroid coords so that we can compare them to the cell displacements and classify them. The first set of functions are workhouse functions to identify the well center and then crop away the left-over data points.\n\nThis function saves all the files at the destination indicated in the SAVEPATH.",
"_____no_output_____"
]
],
[
[
"import DetermineCellState\n\nDATAPATH = r'\\\\atlas.pasteur.fr\\Multicell\\Shreyansh\\20191017\\exp_matrigel_conc_Tcell_B16\\50pc\\TIFF\\DataFrames'\nPATH = r'\\\\atlas.pasteur.fr\\Multicell\\Shreyansh\\20191017\\exp_matrigel_conc_Tcell_B16\\50pc\\TIFF'\nSAVEPATH = r'C:\\Users\\gronteix\\Documents\\Research\\SpheroidPositionAnalysis\\20191017\\B1650pcMatrigel' \n\nwellDiameter = 440\nmarginDistance = 160\naspectRatio = 3\nCHANNEL = '2'\n\nDetermineCellState._loopThroughExperiments(PATH, DATAPATH, SAVEPATH, CHANNEL, wellDiameter, marginDistance, aspectRatio)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aa9484d9e59c546db0daf1d9e614617adb15dba
| 552,210 |
ipynb
|
Jupyter Notebook
|
code_neurips/main_infocnf_cond_cifar_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_beta_1_run1.ipynb
|
minhtannguyen/ffjord
|
f3418249eaa4647f4339aea8d814cf2ce33be141
|
[
"MIT"
] | null | null | null |
code_neurips/main_infocnf_cond_cifar_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_beta_1_run1.ipynb
|
minhtannguyen/ffjord
|
f3418249eaa4647f4339aea8d814cf2ce33be141
|
[
"MIT"
] | null | null | null |
code_neurips/main_infocnf_cond_cifar_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_beta_1_run1.ipynb
|
minhtannguyen/ffjord
|
f3418249eaa4647f4339aea8d814cf2ce33be141
|
[
"MIT"
] | null | null | null | 81.494982 | 1,451 | 0.331218 |
[
[
[
"import os\nos.environ['CUDA_VISIBLE_DEVICES']='4,5,6,7'",
"_____no_output_____"
],
[
"%run -p ../train_cnf_disentangle_rl_semisup.py --data cifar10 --dims 64,64,64 --strides 1,1,1,1 --num_blocks 2 --layer_type concat --multiscale True --rademacher True --batch_size 900 --test_batch_size 500 --save ../experiments_published/infocnf_cond_cifar10_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_nsup4k_beta_1_run1 --seed 1 --lr 0.001 --conditional True --controlled_tol False --train_mode semisup --log_freq 10 --weight_y 0.5 --condition_ratio 0.5 --dropout_rate 0.5 --scale_fac 1.0 --scale_std 6.0 --labeled_batch_size 450 --num_train_sup 4000 --beta 1.0\n#",
"/tancode/repos/tan-ffjord/train_cnf_disentangle_rl_semisup.py\nimport argparse\nimport os\nimport time\nimport numpy as np\n\nimport torch\nimport torch.optim as optim\nimport torchvision.datasets as dset\nimport torchvision.transforms as tforms\nfrom torchvision.utils import save_image\n\nimport torch.utils.data as data\nfrom torch.utils.data import Dataset\n\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.dpi'] = 300\n\nfrom PIL import Image\nimport os.path\nimport errno\nimport codecs\n\nimport lib.layers as layers\nimport lib.utils as utils\nimport lib.multiscale_parallel as multiscale_parallel\nimport lib.modules as modules\nimport lib.thops as thops\n\nfrom train_misc import standard_normal_logprob\nfrom train_misc import set_cnf_options, count_nfe, count_parameters, count_total_time, count_nfe_gate\nfrom train_misc import add_spectral_norm, spectral_norm_power_iteration\nfrom train_misc import create_regularization_fns, get_regularization, append_regularization_to_log\n\nfrom tensorboardX import SummaryWriter\n\nimport glob\n\nfrom utils import data as datasemisup\n\n# go fast boi!!\ntorch.backends.cudnn.benchmark = True\nSOLVERS = [\"dopri5\", \"bdf\", \"rk4\", \"midpoint\", 'adams', 'explicit_adams']\nGATES = [\"cnn1\", \"cnn2\", \"rnn\"]\n\nparser = argparse.ArgumentParser(\"Continuous Normalizing Flow\")\nparser.add_argument(\"--data\", choices=[\"mnist\", \"colormnist\", \"svhn\", \"cifar10\", 'lsun_church'], type=str, default=\"mnist\")\nparser.add_argument(\"--dims\", type=str, default=\"8,32,32,8\")\nparser.add_argument(\"--strides\", type=str, default=\"2,2,1,-2,-2\")\nparser.add_argument(\"--num_blocks\", type=int, default=1, help='Number of stacked CNFs.')\n\nparser.add_argument(\"--conv\", type=eval, default=True, choices=[True, False])\nparser.add_argument(\n \"--layer_type\", type=str, default=\"ignore\",\n choices=[\"ignore\", \"concat\", \"concat_v2\", \"squash\", \"concatsquash\", \"concatcoord\", \"hyper\", \"blend\"]\n)\nparser.add_argument(\"--divergence_fn\", type=str, default=\"approximate\", choices=[\"brute_force\", \"approximate\"])\nparser.add_argument(\n \"--nonlinearity\", type=str, default=\"softplus\", choices=[\"tanh\", \"relu\", \"softplus\", \"elu\", \"swish\"]\n)\n\nparser.add_argument(\"--seed\", type=int, default=0)\n\nparser.add_argument('--solver', type=str, default='dopri5', choices=SOLVERS)\nparser.add_argument('--atol', type=float, default=1e-5)\nparser.add_argument('--rtol', type=float, default=1e-5)\nparser.add_argument(\"--step_size\", type=float, default=None, help=\"Optional fixed step size.\")\n\nparser.add_argument('--gate', type=str, default='cnn1', choices=GATES)\nparser.add_argument('--scale', type=float, default=1.0)\nparser.add_argument('--scale_fac', type=float, default=1.0)\nparser.add_argument('--scale_std', type=float, default=1.0)\nparser.add_argument('--eta', default=0.1, type=float,\n help='tuning parameter that allows us to trade-off the competing goals of' \n 'minimizing the prediction loss and maximizing the gate rewards ')\nparser.add_argument('--rl-weight', default=0.01, type=float,\n help='rl weight')\n\nparser.add_argument('--gamma', default=0.99, type=float,\n help='discount factor, default: (0.99)')\n\nparser.add_argument('--test_solver', type=str, default=None, choices=SOLVERS + [None])\nparser.add_argument('--test_atol', type=float, default=None)\nparser.add_argument('--test_rtol', type=float, default=None)\n\nparser.add_argument(\"--imagesize\", type=int, default=None)\nparser.add_argument(\"--alpha\", type=float, default=1e-6)\nparser.add_argument('--time_length', type=float, default=1.0)\nparser.add_argument('--train_T', type=eval, default=True)\n\nparser.add_argument(\"--num_epochs\", type=int, default=500)\nparser.add_argument(\"--batch_size\", type=int, default=200)\nparser.add_argument(\n \"--batch_size_schedule\", type=str, default=\"\", help=\"Increases the batchsize at every given epoch, dash separated.\"\n)\nparser.add_argument(\"--test_batch_size\", type=int, default=200)\nparser.add_argument(\"--lr\", type=float, default=1e-3)\nparser.add_argument(\"--warmup_iters\", type=float, default=1000)\nparser.add_argument(\"--weight_decay\", type=float, default=0.0)\nparser.add_argument(\"--spectral_norm_niter\", type=int, default=10)\nparser.add_argument(\"--weight_y\", type=float, default=0.5)\nparser.add_argument(\"--annealing_std\", type=eval, default=False, choices=[True, False])\nparser.add_argument(\"--y_class\", type=int, default=10)\nparser.add_argument(\"--y_color\", type=int, default=10)\n\nparser.add_argument(\"--add_noise\", type=eval, default=True, choices=[True, False])\nparser.add_argument(\"--batch_norm\", type=eval, default=False, choices=[True, False])\nparser.add_argument('--residual', type=eval, default=False, choices=[True, False])\nparser.add_argument('--autoencode', type=eval, default=False, choices=[True, False])\nparser.add_argument('--rademacher', type=eval, default=True, choices=[True, False])\nparser.add_argument('--spectral_norm', type=eval, default=False, choices=[True, False])\nparser.add_argument('--multiscale', type=eval, default=False, choices=[True, False])\nparser.add_argument('--parallel', type=eval, default=False, choices=[True, False])\nparser.add_argument('--conditional', type=eval, default=False, choices=[True, False])\nparser.add_argument('--controlled_tol', type=eval, default=False, choices=[True, False])\nparser.add_argument(\"--train_mode\", choices=[\"semisup\", \"sup\", \"unsup\"], type=str, default=\"semisup\")\nparser.add_argument(\"--condition_ratio\", type=float, default=0.5)\nparser.add_argument(\"--dropout_rate\", type=float, default=0.0)\n\n\n# Regularizations\nparser.add_argument('--l1int', type=float, default=None, help=\"int_t ||f||_1\")\nparser.add_argument('--l2int', type=float, default=None, help=\"int_t ||f||_2\")\nparser.add_argument('--dl2int', type=float, default=None, help=\"int_t ||f^T df/dt||_2\")\nparser.add_argument('--JFrobint', type=float, default=None, help=\"int_t ||df/dx||_F\")\nparser.add_argument('--JdiagFrobint', type=float, default=None, help=\"int_t ||df_i/dx_i||_F\")\nparser.add_argument('--JoffdiagFrobint', type=float, default=None, help=\"int_t ||df/dx - df_i/dx_i||_F\")\n\nparser.add_argument(\"--time_penalty\", type=float, default=0, help=\"Regularization on the end_time.\")\nparser.add_argument(\n \"--max_grad_norm\", type=float, default=1e10,\n help=\"Max norm of graidents (default is just stupidly high to avoid any clipping)\"\n)\n\nparser.add_argument(\"--begin_epoch\", type=int, default=1)\nparser.add_argument(\"--resume\", type=str, default=None)\nparser.add_argument(\"--save\", type=str, default=\"experiments/cnf\")\nparser.add_argument(\"--load_dir\", type=str, default=None)\nparser.add_argument(\"--resume_load\", type=int, default=1)\nparser.add_argument(\"--val_freq\", type=int, default=1)\nparser.add_argument(\"--log_freq\", type=int, default=1)\n\n# for semi-supervised learning\nparser.add_argument(\"--labeled_batch_size\", type=int, default=None)\nparser.add_argument(\"--num_train_sup\", type=int, default=4000)\nparser.add_argument(\"--datadir\", type=str, default=\"../data-local/images/cifar/cifar10/by-image\", help=\"dataset directory\")\nparser.add_argument(\"--labels\", type=str, default=\"../data-local/labels/cifar10/4000_balanced_labels/00.txt\", help=\"label directory\")\nparser.add_argument(\"--train_subdir\", type=str, default=\"train+val\")\nparser.add_argument(\"--eval_subdir\", type=str, default=\"test\")\nparser.add_argument(\"--workers\", type=int, default=4)\n\nparser.add_argument('--beta', default=0.01, type=float,\n help='disentanglement weight')\n\nargs = parser.parse_args()\n\nimport lib.odenvp_conditional_rl as odenvp\n \n# set seed\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\n\n# logger\nutils.makedirs(args.save)\nlogger = utils.get_logger(logpath=os.path.join(args.save, 'logs'), filepath=os.path.abspath(__file__)) # write to log file\nwriter = SummaryWriter(os.path.join(args.save, 'tensorboard')) # write to tensorboard\n\nif args.layer_type == \"blend\":\n logger.info(\"!! Setting time_length from None to 1.0 due to use of Blend layers.\")\n args.time_length = 1.0\n\nlogger.info(args)\n\nclass ColorMNIST(data.Dataset):\n \"\"\"\n ColorMNIST\n \"\"\"\n urls = [\n 'http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz',\n 'http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz',\n 'http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz',\n 'http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz',\n ]\n raw_folder = 'raw'\n processed_folder = 'processed'\n training_file = 'training.pt'\n test_file = 'test.pt'\n\n def __init__(self, root, train=True, transform=None, target_transform=None, download=False):\n self.root = os.path.expanduser(root)\n self.transform = transform\n self.target_transform = target_transform\n self.train = train # training set or test set\n\n if download:\n self.download()\n\n if not self._check_exists():\n raise RuntimeError('Dataset not found.' +\n ' You can use download=True to download it')\n\n if self.train:\n self.train_data, self.train_labels = torch.load(\n os.path.join(self.root, self.processed_folder, self.training_file))\n \n self.train_data = np.tile(self.train_data[:, :, :, np.newaxis], 3)\n else:\n self.test_data, self.test_labels = torch.load(\n os.path.join(self.root, self.processed_folder, self.test_file))\n \n self.test_data = np.tile(self.test_data[:, :, :, np.newaxis], 3)\n \n self.pallette = [[31, 119, 180],\n [255, 127, 14],\n [44, 160, 44],\n [214, 39, 40],\n [148, 103, 189],\n [140, 86, 75],\n [227, 119, 194],\n [127, 127, 127],\n [188, 189, 34],\n [23, 190, 207]]\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (image, target) where target is index of the target class.\n \"\"\"\n if self.train:\n img, target = self.train_data[index].copy(), self.train_labels[index]\n else:\n img, target = self.test_data[index].copy(), self.test_labels[index]\n \n # doing this so that it is consistent with all other datasets\n # to return a PIL Image\n y_color_digit = np.random.randint(0, args.y_color)\n c_digit = self.pallette[y_color_digit]\n \n img[:, :, 0] = img[:, :, 0] / 255 * c_digit[0]\n img[:, :, 1] = img[:, :, 1] / 255 * c_digit[1]\n img[:, :, 2] = img[:, :, 2] / 255 * c_digit[2]\n \n img = Image.fromarray(img)\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, [target,torch.from_numpy(np.array(y_color_digit))]\n\n def __len__(self):\n if self.train:\n return len(self.train_data)\n else:\n return len(self.test_data)\n\n def _check_exists(self):\n return os.path.exists(os.path.join(self.root, self.processed_folder, self.training_file)) and \\\n os.path.exists(os.path.join(self.root, self.processed_folder, self.test_file))\n\n def download(self):\n \"\"\"Download the MNIST data if it doesn't exist in processed_folder already.\"\"\"\n from six.moves import urllib\n import gzip\n\n if self._check_exists():\n return\n\n # download files\n try:\n os.makedirs(os.path.join(self.root, self.raw_folder))\n os.makedirs(os.path.join(self.root, self.processed_folder))\n except OSError as e:\n if e.errno == errno.EEXIST:\n pass\n else:\n raise\n\n for url in self.urls:\n print('Downloading ' + url)\n data = urllib.request.urlopen(url)\n filename = url.rpartition('/')[2]\n file_path = os.path.join(self.root, self.raw_folder, filename)\n with open(file_path, 'wb') as f:\n f.write(data.read())\n with open(file_path.replace('.gz', ''), 'wb') as out_f, \\\n gzip.GzipFile(file_path) as zip_f:\n out_f.write(zip_f.read())\n os.unlink(file_path)\n\n # process and save as torch files\n print('Processing...')\n\n training_set = (\n read_image_file(os.path.join(self.root, self.raw_folder, 'train-images-idx3-ubyte')),\n read_label_file(os.path.join(self.root, self.raw_folder, 'train-labels-idx1-ubyte'))\n )\n test_set = (\n read_image_file(os.path.join(self.root, self.raw_folder, 't10k-images-idx3-ubyte')),\n read_label_file(os.path.join(self.root, self.raw_folder, 't10k-labels-idx1-ubyte'))\n )\n with open(os.path.join(self.root, self.processed_folder, self.training_file), 'wb') as f:\n torch.save(training_set, f)\n with open(os.path.join(self.root, self.processed_folder, self.test_file), 'wb') as f:\n torch.save(test_set, f)\n\n print('Done!')\n\n def __repr__(self):\n fmt_str = 'Dataset ' + self.__class__.__name__ + '\\n'\n fmt_str += ' Number of datapoints: {}\\n'.format(self.__len__())\n tmp = 'train' if self.train is True else 'test'\n fmt_str += ' Split: {}\\n'.format(tmp)\n fmt_str += ' Root Location: {}\\n'.format(self.root)\n tmp = ' Transforms (if any): '\n fmt_str += '{0}{1}\\n'.format(tmp, self.transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\n tmp = ' Target Transforms (if any): '\n fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\n return fmt_str\n\ndef add_noise(x):\n \"\"\"\n [0, 1] -> [0, 255] -> add noise -> [0, 1]\n \"\"\"\n if args.add_noise:\n noise = x.new().resize_as_(x).uniform_()\n x = x * 255 + noise\n x = x / 256\n return x\n\n\ndef update_lr(optimizer, itr):\n iter_frac = min(float(itr + 1) / max(args.warmup_iters, 1), 1.0)\n lr = args.lr * iter_frac\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = lr\n\n \ndef update_scale_std(model, epoch):\n epoch_frac = 1.0 - float(epoch - 1) / max(args.num_epochs + 1, 1)\n scale_std = args.scale_std * epoch_frac\n model.set_scale_std(scale_std)\n\n\ndef get_train_loader(train_set, epoch, unlabeled_idxs=None, labeled_idxs=None):\n if args.batch_size_schedule != \"\":\n epochs = [0] + list(map(int, args.batch_size_schedule.split(\"-\")))\n n_passed = sum(np.array(epochs) <= epoch)\n current_batch_size = int(args.batch_size * n_passed)\n current_labeled_bs = int(args.labeled_batch_size * n_passed)\n else:\n current_batch_size = args.batch_size\n current_labeled_bs = args.labeled_batch_size\n \n if args.labeled_batch_size is None:\n train_loader = torch.utils.data.DataLoader(\n dataset=train_set, batch_size=current_batch_size, shuffle=True, drop_last=True, pin_memory=True\n )\n else:\n batch_sampler = datasemisup.TwoStreamBatchSampler(unlabeled_idxs, labeled_idxs, current_batch_size, current_labeled_bs)\n train_loader = torch.utils.data.DataLoader(train_set,\n batch_sampler=batch_sampler,\n num_workers=args.workers,\n pin_memory=True)\n logger.info(\"===> Using batch size {}. Total {} iterations/epoch.\".format(current_batch_size, len(train_loader)))\n return train_loader\n\n\ndef get_dataset(args):\n trans = lambda im_size: tforms.Compose([tforms.Resize(im_size), tforms.ToTensor(), add_noise])\n\n if args.data == \"mnist\":\n im_dim = 1\n im_size = 28 if args.imagesize is None else args.imagesize\n train_set = dset.MNIST(root=\"../data\", train=True, transform=trans(im_size), download=True)\n test_set = dset.MNIST(root=\"../data\", train=False, transform=trans(im_size), download=True)\n elif args.data == \"colormnist\":\n im_dim = 3\n im_size = 28 if args.imagesize is None else args.imagesize\n train_set = ColorMNIST(root=\"../data\", train=True, transform=trans(im_size), download=True)\n test_set = ColorMNIST(root=\"../data\", train=False, transform=trans(im_size), download=True)\n elif args.data == \"svhn\":\n im_dim = 3\n im_size = 32 if args.imagesize is None else args.imagesize\n train_set = dset.SVHN(root=\"../data\", split=\"train\", transform=trans(im_size), download=True)\n test_set = dset.SVHN(root=\"../data\", split=\"test\", transform=trans(im_size), download=True) \n elif args.data == \"cifar10\":\n if args.labeled_batch_size is None:\n im_dim = 3\n im_size = 32 if args.imagesize is None else args.imagesize\n train_set = dset.CIFAR10(\n root=\"../data\", train=True, transform=tforms.Compose([\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ]), download=True\n )\n test_set = dset.CIFAR10(root=\"../data\", train=False, transform=trans(im_size), download=True)\n else:\n print('Load semi-sup datasets for CIFAR10')\n im_dim = 3\n im_size = 32 if args.imagesize is None else args.imagesize\n channel_stats = dict(mean=[0.4914, 0.4822, 0.4465], std=[0.2470, 0.2435, 0.2616])\n# train_transformation = tforms.Compose([\n# tforms.Resize(im_size),\n# datasemisup.RandomTranslateWithReflect(4),\n# tforms.RandomHorizontalFlip(),\n# tforms.ToTensor(),\n# tforms.Normalize(**channel_stats),\n# add_noise,\n# ])\n train_transformation = tforms.Compose([\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ])\n eval_transformation = tforms.Compose([\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise\n ])\n traindir = os.path.join(args.datadir, args.train_subdir)\n evaldir = os.path.join(args.datadir, args.eval_subdir)\n \n train_set = dset.ImageFolder(traindir, train_transformation)\n \n with open(args.labels) as f:\n labels = dict(line.split(' ') for line in f.read().splitlines())\n labeled_idxs, unlabeled_idxs = datasemisup.relabel_dataset(train_set, labels)\n \n test_set = dset.ImageFolder(evaldir, eval_transformation)\n \n elif args.data == 'celeba':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.CelebA(\n train=True, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.CelebA(\n train=False, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n elif args.data == 'lsun_church':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.LSUN(\n '../data', ['church_outdoor_train'], transform=tforms.Compose([\n tforms.Resize(96),\n tforms.RandomCrop(64),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.LSUN(\n '../data', ['church_outdoor_val'], transform=tforms.Compose([\n tforms.Resize(96),\n tforms.RandomCrop(64),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n ) \n elif args.data == 'imagenet_64':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.ImageFolder(\n train=True, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.ImageFolder(\n train=False, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n \n data_shape = (im_dim, im_size, im_size)\n if not args.conv:\n data_shape = (im_dim * im_size * im_size,)\n \n if args.labeled_batch_size is None:\n test_loader = torch.utils.data.DataLoader(\n dataset=test_set, batch_size=args.test_batch_size, shuffle=False, drop_last=True\n )\n unlabeled_idxs = None\n labeled_idxs = None\n else:\n test_loader = torch.utils.data.DataLoader(\n test_set,\n batch_size=args.test_batch_size,\n shuffle=False,\n num_workers=2 * args.workers, # Needs images twice as fast\n pin_memory=True,\n drop_last=True)\n \n return train_set, test_loader, data_shape, unlabeled_idxs, labeled_idxs\n\n\ndef compute_bits_per_dim(x, model):\n zero = torch.zeros(x.shape[0], 1).to(x)\n\n # Don't use data parallelize if batch size is small.\n # if x.shape[0] < 200:\n # model = model.module\n \n z, delta_logp, atol, rtol, logp_actions, nfe = model(x, zero) # run model forward\n\n logpz = standard_normal_logprob(z).view(z.shape[0], -1).sum(1, keepdim=True) # logp(z)\n logpx = logpz - delta_logp\n\n logpx_per_dim = torch.sum(logpx) / x.nelement() # averaged over batches\n bits_per_dim = -(logpx_per_dim - np.log(256)) / np.log(2)\n\n return bits_per_dim, atol, rtol, logp_actions, nfe\n\ndef compute_bits_per_dim_conditional(x, y, model):\n zero = torch.zeros(x.shape[0], 1).to(x)\n y_onehot = thops.onehot(y, num_classes=model.module.y_class).to(x)\n \n z, delta_logp, atol, rtol, logp_actions, nfe = model(x, zero) # run model forward\n \n dim_sup = int(args.condition_ratio * np.prod(z.size()[1:]))\n \n # prior\n mean, logs = model.module._prior(y_onehot)\n \n # compute the conditional nll\n logpz_sup = modules.GaussianDiag.logp(mean, logs, z[:, 0:dim_sup]).view(-1,1) # logp(z)_sup\n logpz_unsup = standard_normal_logprob(z[:, dim_sup:]).view(z.shape[0], -1).sum(1, keepdim=True)\n logpz = logpz_sup + logpz_unsup\n logpx = logpz - delta_logp\n\n logpx_per_dim = torch.sum(logpx) / x.nelement() # averaged over batches\n bits_per_dim = -(logpx_per_dim - np.log(256)) / np.log(2)\n \n ###################################################################################################\n # compute the marginal nll\n logpz_sup_marginal = []\n \n for indx in range(model.module.y_class):\n y_i = torch.full_like(y, indx).to(y)\n y_onehot = thops.onehot(y_i, num_classes=model.module.y_class).to(x)\n # prior\n mean, logs = model.module._prior(y_onehot)\n logpz_sup_marginal.append(modules.GaussianDiag.logp(mean, logs, z[:, 0:dim_sup]).view(-1,1) - torch.log(torch.tensor(model.module.y_class).to(z))) # logp(z)_sup\n \n logpz_sup_marginal = torch.cat(logpz_sup_marginal,dim=1)\n logpz_sup_marginal = torch.logsumexp(logpz_sup_marginal, 1, keepdim=True)\n \n logpz_marginal = logpz_sup_marginal + logpz_unsup\n \n logpx_marginal = logpz_marginal - delta_logp\n\n logpx_per_dim_marginal = torch.sum(logpx_marginal) / x.nelement() # averaged over batches\n bits_per_dim_marginal = -(logpx_per_dim_marginal - np.log(256)) / np.log(2)\n \n ###################################################################################################\n \n # dropout\n if args.dropout_rate > 0:\n zsup = model.module.dropout(z[:, 0:dim_sup])\n else:\n zsup = z[:, 0:dim_sup]\n \n # compute xentropy loss\n y_logits = model.module.project_class(zsup)\n loss_xent = model.module.loss_class(y_logits, y.to(x.get_device()))\n y_predicted = np.argmax(y_logits.cpu().detach().numpy(), axis=1)\n\n return bits_per_dim, loss_xent, y_predicted, atol, rtol, logp_actions, nfe, bits_per_dim_marginal\n\ndef compute_bits_per_dim_semisup(x, y, model):\n minibatch_unsup_size = args.batch_size - args.labeled_batch_size\n \n zero = torch.zeros(x.shape[0], 1).to(x)\n \n z, delta_logp, atol, rtol, logp_actions, nfe = model(x, zero) # run model forward\n \n z_unl = z[:minibatch_unsup_size]\n z_lab = z[minibatch_unsup_size:]\n y_unl = y[:minibatch_unsup_size]\n y_lab = y[minibatch_unsup_size:]\n \n y_lab_onehot = thops.onehot(y_lab, num_classes=model.module.y_class).to(x)\n \n dim_sup = int(args.condition_ratio * np.prod(z.size()[1:]))\n \n # prior\n mean_lab, logs_lab = model.module._prior(y_lab_onehot)\n \n # compute the conditional nll\n logpz_lab_sup = modules.GaussianDiag.logp(mean_lab, logs_lab, z_lab[:, 0:dim_sup]).view(-1,1) # logp(z)_sup\n beta_logpz_lab_sup = logpz_lab_sup * (1.0 - args.beta * torch.exp(logpz_lab_sup) / torch.tensor(model.module.y_class).to(z))\n \n ##########################################################################################\n # compute the marginal nll\n logpz_unl_sup = []\n \n for indx in range(model.module.y_class):\n y_unl_i = torch.full_like(y_unl, indx).to(y_unl)\n y_unl_onehot = thops.onehot(y_unl_i, num_classes=model.module.y_class).to(x)\n # prior\n mean_unl, logs_unl = model.module._prior(y_unl_onehot)\n logpz_unl_sup.append(modules.GaussianDiag.logp(mean_unl, logs_unl, z_unl[:, 0:dim_sup]).view(-1,1) - torch.log(torch.tensor(model.module.y_class).to(z))) # logp(z)_sup\n \n logpz_unl_sup = torch.cat(logpz_unl_sup,dim=1)\n logpz_unl_sup = torch.logsumexp(logpz_unl_sup, 1, keepdim=True)\n beta_logpz_unl_sup = logpz_unl_sup * (1.0 - args.beta * torch.exp(logpz_unl_sup))\n \n ##########################################################################################\n \n logpz_sup = torch.cat([beta_logpz_unl_sup, beta_logpz_lab_sup], dim=0)\n \n logpz_unsup = standard_normal_logprob(z[:, dim_sup:]).view(z.shape[0], -1).sum(1, keepdim=True)\n \n logpz = logpz_sup + logpz_unsup\n logpx = logpz - delta_logp\n\n logpx_per_dim = torch.sum(logpx) / x.nelement() # averaged over batches\n bits_per_dim = -(logpx_per_dim - np.log(256)) / np.log(2)\n \n # dropout\n if args.dropout_rate > 0:\n z_lab_sup = model.module.dropout(z_lab[:, 0:dim_sup])\n else:\n z_lab_sup = z_lab[:, 0:dim_sup]\n \n # compute xentropy loss\n y_lab_logits = model.module.project_class(z_lab_sup)\n loss_xent = model.module.loss_class(y_lab_logits, y_lab.to(x.get_device()))\n y_predicted = np.argmax(y_lab_logits.cpu().detach().numpy(), axis=1)\n\n return bits_per_dim, loss_xent, y_predicted, atol, rtol, logp_actions, nfe\n\n\ndef compute_marginal_bits_per_dim(x, y, model):\n zero = torch.zeros(x.shape[0], 1).to(x)\n \n z, delta_logp, atol, rtol, logp_actions, nfe = model(x, zero) # run model forward\n \n dim_sup = int(args.condition_ratio * np.prod(z.size()[1:]))\n \n logpz_sup = []\n \n for indx in range(model.module.y_class):\n y_i = torch.full_like(y, indx).to(y)\n y_onehot = thops.onehot(y_i, num_classes=model.module.y_class).to(x)\n # prior\n mean, logs = model.module._prior(y_onehot)\n logpz_sup.append(modules.GaussianDiag.logp(mean, logs, z[:, 0:dim_sup]).view(-1,1) - torch.log(torch.tensor(model.module.y_class).to(z))) # logp(z)_sup\n \n logpz_sup = torch.cat(logpz_sup,dim=1)\n logpz_sup = torch.logsumexp(logpz_sup, 1, keepdim=True)\n \n logpz_unsup = standard_normal_logprob(z[:, dim_sup:]).view(z.shape[0], -1).sum(1, keepdim=True)\n logpz = logpz_sup + logpz_unsup\n \n logpx = logpz - delta_logp\n\n logpx_per_dim = torch.sum(logpx) / x.nelement() # averaged over batches\n bits_per_dim = -(logpx_per_dim - np.log(256)) / np.log(2)\n\n return bits_per_dim\n\ndef create_model(args, data_shape, regularization_fns):\n hidden_dims = tuple(map(int, args.dims.split(\",\")))\n strides = tuple(map(int, args.strides.split(\",\")))\n\n if args.multiscale:\n model = odenvp.ODENVP(\n (args.batch_size, *data_shape),\n n_blocks=args.num_blocks,\n intermediate_dims=hidden_dims,\n nonlinearity=args.nonlinearity,\n alpha=args.alpha,\n cnf_kwargs={\"T\": args.time_length, \"train_T\": args.train_T, \"regularization_fns\": regularization_fns, \"solver\": args.solver, \"atol\": args.atol, \"rtol\": args.rtol, \"scale\": args.scale, \"scale_fac\": args.scale_fac, \"scale_std\": args.scale_std, \"gate\": args.gate},\n condition_ratio=args.condition_ratio,\n dropout_rate=args.dropout_rate,\n y_class = args.y_class)\n elif args.parallel:\n model = multiscale_parallel.MultiscaleParallelCNF(\n (args.batch_size, *data_shape),\n n_blocks=args.num_blocks,\n intermediate_dims=hidden_dims,\n alpha=args.alpha,\n time_length=args.time_length,\n )\n else:\n if args.autoencode:\n\n def build_cnf():\n autoencoder_diffeq = layers.AutoencoderDiffEqNet(\n hidden_dims=hidden_dims,\n input_shape=data_shape,\n strides=strides,\n conv=args.conv,\n layer_type=args.layer_type,\n nonlinearity=args.nonlinearity,\n )\n odefunc = layers.AutoencoderODEfunc(\n autoencoder_diffeq=autoencoder_diffeq,\n divergence_fn=args.divergence_fn,\n residual=args.residual,\n rademacher=args.rademacher,\n )\n cnf = layers.CNF(\n odefunc=odefunc,\n T=args.time_length,\n regularization_fns=regularization_fns,\n solver=args.solver,\n )\n return cnf\n else:\n\n def build_cnf():\n diffeq = layers.ODEnet(\n hidden_dims=hidden_dims,\n input_shape=data_shape,\n strides=strides,\n conv=args.conv,\n layer_type=args.layer_type,\n nonlinearity=args.nonlinearity,\n )\n odefunc = layers.ODEfunc(\n diffeq=diffeq,\n divergence_fn=args.divergence_fn,\n residual=args.residual,\n rademacher=args.rademacher,\n )\n cnf = layers.CNF(\n odefunc=odefunc,\n T=args.time_length,\n train_T=args.train_T,\n regularization_fns=regularization_fns,\n solver=args.solver,\n )\n return cnf\n\n chain = [layers.LogitTransform(alpha=args.alpha)] if args.alpha > 0 else [layers.ZeroMeanTransform()]\n chain = chain + [build_cnf() for _ in range(args.num_blocks)]\n if args.batch_norm:\n chain.append(layers.MovingBatchNorm2d(data_shape[0]))\n model = layers.SequentialFlow(chain)\n return model\n\n\nif __name__ == \"__main__\":\n\n # get deivce\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n cvt = lambda x: x.type(torch.float32).to(device, non_blocking=True)\n\n # load dataset\n train_set, test_loader, data_shape, unlabeled_idxs, labeled_idxs = get_dataset(args)\n\n # build model\n regularization_fns, regularization_coeffs = create_regularization_fns(args)\n model = create_model(args, data_shape, regularization_fns)\n\n if args.spectral_norm: add_spectral_norm(model, logger)\n set_cnf_options(args, model)\n\n logger.info(model)\n logger.info(\"Number of trainable parameters: {}\".format(count_parameters(model)))\n \n writer.add_text('info', \"Number of trainable parameters: {}\".format(count_parameters(model)))\n\n # optimizer\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n \n # set initial iter\n itr = 1\n \n # set the meters\n time_epoch_meter = utils.RunningAverageMeter(0.97)\n time_meter = utils.RunningAverageMeter(0.97)\n loss_meter = utils.RunningAverageMeter(0.97) # track total loss\n nll_meter = utils.RunningAverageMeter(0.97) # track negative log-likelihood\n xent_meter = utils.RunningAverageMeter(0.97) # track xentropy score\n error_meter = utils.RunningAverageMeter(0.97) # track error score\n steps_meter = utils.RunningAverageMeter(0.97)\n grad_meter = utils.RunningAverageMeter(0.97)\n tt_meter = utils.RunningAverageMeter(0.97)\n # nll_marginal_meter = utils.RunningAverageMeter(0.97) # track negative marginal log-likelihood\n \n if args.load_dir is not None:\n filelist = glob.glob(os.path.join(args.load_dir,\"*epoch_*_checkpt.pth\"))\n all_indx = []\n for infile in sorted(filelist):\n all_indx.append(int(infile.split('_')[-2]))\n \n indxmax = max(all_indx)\n indxstart = max(1, args.resume_load)\n \n for i in range(indxstart,indxmax+1):\n model = create_model(args, data_shape, regularization_fns)\n infile = os.path.join(args.load_dir,\"epoch_%i_checkpt.pth\"%i)\n print(infile)\n checkpt = torch.load(infile, map_location=lambda storage, loc: storage)\n model.load_state_dict(checkpt[\"state_dict\"])\n \n if torch.cuda.is_available():\n model = torch.nn.DataParallel(model).cuda()\n \n model.eval()\n \n with torch.no_grad():\n logger.info(\"validating...\")\n losses = []\n for (x, y) in test_loader:\n if args.data == \"colormnist\":\n y = y[0]\n \n if not args.conv:\n x = x.view(x.shape[0], -1)\n x = cvt(x)\n nll = compute_marginal_bits_per_dim(x, y, model)\n losses.append(nll.cpu().numpy())\n \n loss = np.mean(losses)\n writer.add_scalars('nll_marginal', {'validation': loss}, i)\n \n raise SystemExit(0)\n \n # restore parameters\n if args.resume is not None:\n checkpt = torch.load(args.resume, map_location=lambda storage, loc: storage)\n model.load_state_dict(checkpt[\"state_dict\"])\n if \"optim_state_dict\" in checkpt.keys():\n optimizer.load_state_dict(checkpt[\"optim_state_dict\"])\n # Manually move optimizer state to device.\n for state in optimizer.state.values():\n for k, v in state.items():\n if torch.is_tensor(v):\n state[k] = cvt(v)\n args.begin_epoch = checkpt['epoch'] + 1\n itr = checkpt['iter'] + 1\n time_epoch_meter.set(checkpt['epoch_time_avg'])\n time_meter.set(checkpt['time_train'])\n loss_meter.set(checkpt['loss_train'])\n nll_meter.set(checkpt['bits_per_dim_train'])\n xent_meter.set(checkpt['xent_train'])\n error_meter.set(checkpt['error_train'])\n steps_meter.set(checkpt['nfe_train'])\n grad_meter.set(checkpt['grad_train'])\n tt_meter.set(checkpt['total_time_train'])\n # nll_marginal_meter.set(checkpt['bits_per_dim_marginal_train'])\n\n if torch.cuda.is_available():\n model = torch.nn.DataParallel(model).cuda()\n\n # For visualization.\n if args.conditional:\n dim_unsup = int((1.0 - args.condition_ratio) * np.prod(data_shape))\n fixed_y = torch.from_numpy(np.arange(model.module.y_class)).repeat(model.module.y_class).type(torch.long).to(device, non_blocking=True)\n fixed_y_onehot = thops.onehot(fixed_y, num_classes=model.module.y_class)\n with torch.no_grad():\n mean, logs = model.module._prior(fixed_y_onehot)\n fixed_z_sup = modules.GaussianDiag.sample(mean, logs)\n fixed_z_unsup = cvt(torch.randn(model.module.y_class**2, dim_unsup))\n fixed_z = torch.cat((fixed_z_sup, fixed_z_unsup),1)\n else:\n fixed_z = cvt(torch.randn(100, *data_shape))\n \n\n if args.spectral_norm and not args.resume: spectral_norm_power_iteration(model, 500)\n\n best_loss_nll = float(\"inf\")\n best_error_score = float(\"inf\")\n best_loss_nll_marginal = float(\"inf\")\n \n for epoch in range(args.begin_epoch, args.num_epochs + 1):\n start_epoch = time.time()\n model.train()\n if args.annealing_std:\n update_scale_std(model.module, epoch)\n \n train_loader = get_train_loader(train_set, epoch, unlabeled_idxs=unlabeled_idxs, labeled_idxs=labeled_idxs)\n \n for _, (x, y) in enumerate(train_loader):\n if args.data == \"colormnist\":\n y = y[0]\n \n minibatch_unsup_size = args.batch_size - args.labeled_batch_size\n y_lab = y[minibatch_unsup_size:]\n \n start = time.time()\n update_lr(optimizer, itr)\n optimizer.zero_grad()\n\n if not args.conv:\n x = x.view(x.shape[0], -1)\n\n # cast data and move to device\n x = cvt(x)\n \n # set up unlabeled input and labeled input with the corresponding labels\n # NOTE: NEED TO DOUBLE-CHECK IF WE NEED TO HAVE TH.AUTOGRAD.VARIABLE HERE\n \n # compute loss\n if args.conditional:\n loss_nll, loss_xent, y_predicted, atol, rtol, logp_actions, nfe = compute_bits_per_dim_semisup(x, y, model)\n \n if args.train_mode == \"semisup\":\n loss = loss_nll + args.weight_y * loss_xent # need to understand the weight of xentropy\n elif args.train_mode == \"sup\":\n loss = loss_xent\n elif args.train_mode == \"unsup\":\n loss = loss_nll\n else:\n raise ValueError('Choose supported train_mode: semisup, sup, unsup')\n error_score = 1. - np.mean(y_predicted.astype(int) == y_lab.numpy()) \n \n else:\n loss, atol, rtol, logp_actions, nfe = compute_bits_per_dim(x, model)\n loss_nll, loss_xent, error_score = loss, 0., 0.\n \n if regularization_coeffs:\n reg_states = get_regularization(model, regularization_coeffs)\n reg_loss = sum(\n reg_state * coeff for reg_state, coeff in zip(reg_states, regularization_coeffs) if coeff != 0\n )\n loss = loss + reg_loss\n total_time = count_total_time(model)\n loss = loss + total_time * args.time_penalty\n\n # re-weight the gate rewards\n normalized_eta = args.eta / len(logp_actions)\n \n # collect cumulative future rewards\n R = - loss\n cum_rewards = []\n for r in nfe[::-1]:\n R = -normalized_eta * r.view(-1,1) + args.gamma * R\n cum_rewards.insert(0,R)\n \n # apply REINFORCE\n rl_loss = 0\n for lpa, r in zip(logp_actions, cum_rewards):\n rl_loss = rl_loss - lpa.view(-1,1) * args.rl_weight * r\n \n loss = loss + rl_loss.mean()\n \n loss.backward()\n \n grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)\n\n optimizer.step()\n\n if args.spectral_norm: spectral_norm_power_iteration(model, args.spectral_norm_niter)\n \n # STOP HERE. Need to check p(x|y) vs. p(x)\n \n time_meter.update(time.time() - start)\n loss_meter.update(loss.item())\n nll_meter.update(loss_nll.item())\n if args.conditional:\n xent_meter.update(loss_xent.item())\n else:\n xent_meter.update(loss_xent)\n error_meter.update(error_score)\n steps_meter.update(count_nfe_gate(model))\n grad_meter.update(grad_norm)\n tt_meter.update(total_time)\n # nll_marginal_meter.update(loss_nll_marginal.item())\n \n for idx in range(len(model.module.transforms)):\n for layer in model.module.transforms[idx].chain:\n if hasattr(layer, 'atol'):\n layer.odefunc.after_odeint()\n \n # write to tensorboard\n writer.add_scalars('time', {'train_iter': time_meter.val}, itr)\n writer.add_scalars('loss', {'train_iter': loss_meter.val}, itr)\n writer.add_scalars('bits_per_dim', {'train_iter': nll_meter.val}, itr)\n writer.add_scalars('xent', {'train_iter': xent_meter.val}, itr)\n writer.add_scalars('error', {'train_iter': error_meter.val}, itr)\n writer.add_scalars('nfe', {'train_iter': steps_meter.val}, itr)\n writer.add_scalars('grad', {'train_iter': grad_meter.val}, itr)\n writer.add_scalars('total_time', {'train_iter': tt_meter.val}, itr)\n # writer.add_scalars('bits_per_dim_marginal', {'train_iter': nll_marginal_meter.val}, itr)\n\n if itr % args.log_freq == 0:\n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_%i'%tol_indx, {'train': atol[tol_indx].mean()}, itr)\n writer.add_scalars('rtol_%i'%tol_indx, {'train': rtol[tol_indx].mean()}, itr)\n \n log_message = (\n \"Iter {:04d} | Time {:.4f}({:.4f}) | Bit/dim {:.4f}({:.4f}) | Xent {:.4f}({:.4f}) | Loss {:.4f}({:.4f}) | Error {:.4f}({:.4f}) \"\n \"Steps {:.0f}({:.2f}) | Grad Norm {:.4f}({:.4f}) | Total Time {:.2f}({:.2f})\".format(\n itr, time_meter.val, time_meter.avg, nll_meter.val, nll_meter.avg, xent_meter.val, xent_meter.avg, loss_meter.val, loss_meter.avg, error_meter.val, error_meter.avg, steps_meter.val, steps_meter.avg, grad_meter.val, grad_meter.avg, tt_meter.val, tt_meter.avg\n )\n )\n if regularization_coeffs:\n log_message = append_regularization_to_log(log_message, regularization_fns, reg_states)\n logger.info(log_message)\n writer.add_text('info', log_message, itr)\n\n itr += 1\n \n # compute test loss\n model.eval()\n if epoch % args.val_freq == 0:\n with torch.no_grad():\n # write to tensorboard\n writer.add_scalars('time', {'train_epoch': time_meter.avg}, epoch)\n writer.add_scalars('loss', {'train_epoch': loss_meter.avg}, epoch)\n writer.add_scalars('bits_per_dim', {'train_epoch': nll_meter.avg}, epoch)\n writer.add_scalars('xent', {'train_epoch': xent_meter.avg}, epoch)\n writer.add_scalars('error', {'train_epoch': error_meter.avg}, epoch)\n writer.add_scalars('nfe', {'train_epoch': steps_meter.avg}, epoch)\n writer.add_scalars('grad', {'train_epoch': grad_meter.avg}, epoch)\n writer.add_scalars('total_time', {'train_epoch': tt_meter.avg}, epoch)\n # writer.add_scalars('bits_per_dim_marginal', {'train_epoch': nll_marginal_meter.avg}, epoch)\n \n start = time.time()\n logger.info(\"validating...\")\n writer.add_text('info', \"validating...\", epoch)\n losses_nll = []; losses_xent = []; losses = []; losses_nll_marginal = []\n total_correct = 0\n \n for (x, y) in test_loader:\n if args.data == \"colormnist\":\n y = y[0]\n \n print(y)\n if not args.conv:\n x = x.view(x.shape[0], -1)\n x = cvt(x)\n if args.conditional:\n loss_nll, loss_xent, y_predicted, atol, rtol, logp_actions, nfe, loss_nll_marginal = compute_bits_per_dim_conditional(x, y, model)\n if args.train_mode == \"semisup\":\n loss = loss_nll + args.weight_y * loss_xent\n elif args.train_mode == \"sup\":\n loss = loss_xent\n elif args.train_mode == \"unsup\":\n loss = loss_nll\n else:\n raise ValueError('Choose supported train_mode: semisup, sup, unsup')\n total_correct += np.sum(y_predicted.astype(int) == y.numpy())\n else:\n loss, atol, rtol, logp_actions, nfe = compute_bits_per_dim(x, model)\n loss_nll, loss_xent, loss_nll_marginal = loss, 0., 0.\n losses_nll.append(loss_nll.cpu().numpy())\n losses.append(loss.cpu().numpy())\n losses_nll_marginal.append(loss_nll_marginal.cpu().numpy())\n if args.conditional: \n losses_xent.append(loss_xent.cpu().numpy())\n else:\n losses_xent.append(loss_xent)\n \n if args.data == \"colormnist\":\n # print test images\n xall = []\n ximg = x[0:40].cpu().numpy().transpose((0,2,3,1))\n for i in range(ximg.shape[0]):\n xall.append(ximg[i])\n\n xall = np.hstack(xall)\n\n plt.imshow(xall)\n plt.axis('off')\n plt.show()\n \n loss_nll = np.mean(losses_nll); loss_xent = np.mean(losses_xent); loss = np.mean(losses)\n loss_nll_marginal = np.mean(losses_nll_marginal)\n error_score = 1. - total_correct / len(test_loader.dataset)\n time_epoch_meter.update(time.time() - start_epoch)\n \n # write to tensorboard\n test_time_spent = time.time() - start\n writer.add_scalars('time', {'validation': test_time_spent}, epoch)\n writer.add_scalars('epoch_time', {'validation': time_epoch_meter.val}, epoch)\n writer.add_scalars('bits_per_dim', {'validation': loss_nll}, epoch)\n writer.add_scalars('xent', {'validation': loss_xent}, epoch)\n writer.add_scalars('loss', {'validation': loss}, epoch)\n writer.add_scalars('error', {'validation': error_score}, epoch)\n writer.add_scalars('bits_per_dim_marginal', {'validation': loss_nll_marginal}, epoch)\n \n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_%i'%tol_indx, {'validation': atol[tol_indx].mean()}, epoch)\n writer.add_scalars('rtol_%i'%tol_indx, {'validation': rtol[tol_indx].mean()}, epoch)\n \n log_message = \"Epoch {:04d} | Time {:.4f}, Epoch Time {:.4f}({:.4f}), Bit/dim {:.4f}(best: {:.4f}), Bit/dim Marginal {:.4f}(best: {:.4f}), Xent {:.4f}, Loss {:.4f}, Error {:.4f}(best: {:.4f})\".format(epoch, time.time() - start, time_epoch_meter.val, time_epoch_meter.avg, loss_nll, best_loss_nll, loss_nll_marginal, best_loss_nll_marginal, loss_xent, loss, error_score, best_error_score)\n logger.info(log_message)\n writer.add_text('info', log_message, epoch)\n \n for name, param in model.named_parameters():\n writer.add_histogram(name, param.clone().cpu().data.numpy(), epoch)\n \n \n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"bits_per_dim_marginal\": loss_nll_marginal,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"epoch_%i_checkpt.pth\"%epoch))\n \n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"bits_per_dim_marginal\": loss_nll_marginal,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"current_checkpt.pth\"))\n \n if loss_nll < best_loss_nll:\n best_loss_nll = loss_nll\n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"bits_per_dim_marginal\": loss_nll_marginal,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"best_nll_checkpt.pth\"))\n \n if loss_nll_marginal < best_loss_nll_marginal:\n best_loss_nll_marginal = loss_nll_marginal\n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"bits_per_dim_marginal\": loss_nll_marginal,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"best_nll_marginal_checkpt.pth\"))\n \n if args.conditional:\n if error_score < best_error_score:\n best_error_score = error_score\n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"bits_per_dim_marginal\": loss_nll_marginal,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"best_error_checkpt.pth\"))\n \n\n # visualize samples and density\n with torch.no_grad():\n fig_filename = os.path.join(args.save, \"figs\", \"{:04d}.jpg\".format(epoch))\n utils.makedirs(os.path.dirname(fig_filename))\n generated_samples, atol, rtol, logp_actions, nfe = model(fixed_z, reverse=True)\n generated_samples = generated_samples.view(-1, *data_shape)\n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_gen_%i'%tol_indx, {'validation': atol[tol_indx].mean()}, epoch)\n writer.add_scalars('rtol_gen_%i'%tol_indx, {'validation': rtol[tol_indx].mean()}, epoch)\n save_image(generated_samples, fig_filename, nrow=10)\n if args.data == \"mnist\":\n writer.add_images('generated_images', generated_samples.repeat(1,3,1,1), epoch)\n else:\n writer.add_images('generated_images', generated_samples.repeat(1,1,1,1), epoch)\nNamespace(JFrobint=None, JdiagFrobint=None, JoffdiagFrobint=None, add_noise=True, alpha=1e-06, annealing_std=False, atol=1e-05, autoencode=False, batch_norm=False, batch_size=900, batch_size_schedule='', begin_epoch=1, beta=1.0, condition_ratio=0.5, conditional=True, controlled_tol=False, conv=True, data='cifar10', datadir='../data-local/images/cifar/cifar10/by-image', dims='64,64,64', divergence_fn='approximate', dl2int=None, dropout_rate=0.5, eta=0.1, eval_subdir='test', gamma=0.99, gate='cnn1', imagesize=None, l1int=None, l2int=None, labeled_batch_size=450, labels='../data-local/labels/cifar10/4000_balanced_labels/00.txt', layer_type='concat', load_dir=None, log_freq=10, lr=0.001, max_grad_norm=10000000000.0, multiscale=True, nonlinearity='softplus', num_blocks=2, num_epochs=500, num_train_sup=4000, parallel=False, rademacher=True, residual=False, resume=None, resume_load=1, rl_weight=0.01, rtol=1e-05, save='../experiments_published/infocnf_cond_cifar10_bs900_sratio_0_5_drop_0_5_rl_stdscale_6_nsup4k_beta_1_run1', scale=1.0, scale_fac=1.0, scale_std=6.0, seed=1, solver='dopri5', spectral_norm=False, spectral_norm_niter=10, step_size=None, strides='1,1,1,1', test_atol=None, test_batch_size=500, test_rtol=None, test_solver=None, time_length=1.0, time_penalty=0, train_T=True, train_mode='semisup', train_subdir='train+val', val_freq=1, warmup_iters=1000, weight_decay=0.0, weight_y=0.5, workers=4, y_class=10, y_color=10)\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
4aa94d25b80a1d9886d92f77c1824371a3129fd4
| 233,287 |
ipynb
|
Jupyter Notebook
|
InternetData.ipynb
|
BrianLucas26/The-best-hood
|
c8deb8e541a5b59954aa6a9a9e0b35ea8c3a2446
|
[
"MIT"
] | null | null | null |
InternetData.ipynb
|
BrianLucas26/The-best-hood
|
c8deb8e541a5b59954aa6a9a9e0b35ea8c3a2446
|
[
"MIT"
] | null | null | null |
InternetData.ipynb
|
BrianLucas26/The-best-hood
|
c8deb8e541a5b59954aa6a9a9e0b35ea8c3a2446
|
[
"MIT"
] | null | null | null | 278.718041 | 128,864 | 0.905284 |
[
[
[
"### Data of Internet Service Providers in Each Neighborhood of Pittsburgh\n\nThe dataset that I chose to interpret contains the information on what service providers are in pittsburgh, what neighborhoods they are in, and how many are in each neighborhood. Of course, the data does not give us all that right away, which is where our data interpretation skills come in. Within this notebook, I was able to get rid of data that I would not be using for our final result, sort the data by providers per neighborhood, and then calculate and sort by providers per acre of each neighborhood to find the best overall coverage. ",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport geopandas",
"_____no_output_____"
],
[
"ispdata = pd.read_csv(\"pittsburghispsbyblock.csv\", \n index_col=\"Neighborhood\") # use the column named _id as the row index\nhooddata = pd.read_csv(\"RAC223Neighborhoods_.csv\")",
"_____no_output_____"
]
],
[
[
"The first two codeblocks are simple imports of the python packages I am using and the actual dataset that I am getting my data from. In this first block below, I first sort the dataset by each neighborhoood alphabetically. Then, I use the drop method to remove all of the unnessecary data columns from my set.",
"_____no_output_____"
]
],
[
[
"ispdata = ispdata.sort_values(by=[\"Neighborhood\"])\nthislist = [\"GEOID\", \"LogRecNo\", \"Provider_Id\", \"FRN\", \"ProviderName\", \"DBAName\", \"HocoNum\", \"StateAbbr\", \"BlockCode\", \"TechCode\", \"Consumer\", \"MaxAdDown\", \"MaxAdUp\", \"Business\", \"MaxCIRDown\", \"MaxCIRUp\", \"HocoFinal\"]\nispdata = ispdata.drop(axis=1,labels=thislist)\nispdata.groupby(\"Neighborhood\").count()",
"_____no_output_____"
]
],
[
[
"For our project, we decided we only wanted to look at the neighborhoods that have Verizon internet. We decided upon this because we all use and trust verizon internet and, to us, it is the best service provider due to converage and 5G capabilities. In the code block below, I used code that we practiced in our weekly excercises to isolate all of the rows with \"Verizon Communications Inc.\" and make a new dataset with only the Verizon neighborhoods.",
"_____no_output_____"
]
],
[
[
"query_mask = ispdata['HoldingCompanyName'] == 'Verizon Communications Inc.'\n\nverizon = ispdata[query_mask]\nverizon",
"_____no_output_____"
]
],
[
[
"Here I simply take the verizon dataset and sort it to count how many verizon networks are in each neighborhood",
"_____no_output_____"
]
],
[
[
"verizon = verizon.groupby(\"Neighborhood\").count()\nverizon",
"_____no_output_____"
]
],
[
[
"Next, I use the other dataset with the neighborhood data and sort it by each neighborhood's acreage",
"_____no_output_____"
]
],
[
[
"hooddata = hooddata[['hood', 'acres']]\nhooddata = hooddata.sort_values(by=['hood'])\nhooddata",
"_____no_output_____"
]
],
[
[
"Next, this code block begins to merge the two datasets of ISPs per Neighborhood and Neighborhood acreage into one dataset that computes the average ISP per acre for every neighborhood in the set. I used a for loop to calculate the ISP per Acre for every row in the dataset, with each row being each individual neighborhood. This gives us the final dataset with each neighborhoods acreage, ISP per Neighborhood, and ISP per Acre.",
"_____no_output_____"
]
],
[
[
"merged = pd.merge(hooddata, verizon, left_on=\"hood\", right_on=\"Neighborhood\")\nmerged.at[60, \"acres\"] = 775.68\n\nnewarray = []\nfor x in range(90):\n newarray.append(merged.iloc[x, 2]/merged.iloc[x, 1])\n\nmerged[\"ISPs-Per-Acre\"] = newarray\nmerged",
"_____no_output_____"
]
],
[
[
"Here, this dataset is made to sort the data specifically for graphing. It is sorted by ISP per Acre from least to greatest and graphed on a line graph.",
"_____no_output_____"
]
],
[
[
"graphable = merged.drop(columns = [\"HoldingCompanyName\", \"acres\"])\ngraphable = graphable.sort_values(by=[\"ISPs-Per-Acre\"])\ngraphable.plot(x=\"hood\", y=\"ISPs-Per-Acre\", kind=\"bar\", figsize=(15,15))",
"_____no_output_____"
]
],
[
[
"Finally, I used geopandas to make a map that would show the ISP per Acre for each neighborhood. This lets you see the density of each neighborhood's ISP data based on how big the actual neighborhood is. It is very obvious in both of these graphs that Marshall-Shadeland is the best neighborhood for Verizon internet per Acre.",
"_____no_output_____"
]
],
[
[
"neighborhoods = geopandas.read_file(\"Neighborhood/Neighborhoods_.shp\") # read in the shapefile\nsign_map = neighborhoods.merge(graphable, how='left', left_on='hood', right_on='hood')\nsign_map.plot(column='ISPs-Per-Acre', # set the data to be used for coloring\n cmap='Blues', # choose a color palette\n edgecolor=\"white\", # outline the districts in white\n legend=True, # show the legend\n legend_kwds={'label': \"ISPs-Per-Acre\"}, # label the legend\n figsize=(15, 10), # set the size\n # missing_kwds={\"color\": \"lightgrey\"} # set disctricts with no data to gray\n )\n",
"_____no_output_____"
]
],
[
[
"This block simply converts the data I interpreted into a form that can be combined with the other two datasets from the project.",
"_____no_output_____"
]
],
[
[
"combiner=[]\nfor value in graphable[\"ISPs-Per-Acre\"]:\n combiner.append((value/graphable.iloc[89,1])*100)\n\ngraphable[\"Scaled\"] = combiner\nISPDrop = graphable.drop(columns=['ISPs-Per-Acre'])\nISPDrop = graphableDrop.sort_values(by=[\"hood\"])\nprint(graphableDrop)",
" hood Scaled\n0 Allegheny Center 9.756045\n1 Allegheny West 28.933378\n2 Allentown 72.005138\n3 Arlington 26.081671\n4 Arlington Heights 4.315382\n.. ... ...\n85 Upper Lawrenceville 35.614459\n86 West End 30.638297\n87 West Oakland 28.492075\n88 Westwood 17.554704\n89 Windgap 12.319806\n\n[90 rows x 2 columns]\n"
]
],
[
[
"The final answer for my dataset is that Marshall-Shadeland has the most ISPs per Acre out of all the neighborhoods I was dealing with. This is shown in the calculations and the two provided graphs.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aa965fa7f926a16b158cbdc259e143df76be414
| 16,397 |
ipynb
|
Jupyter Notebook
|
notebooks/.ipynb_checkpoints/MultiAssetExchangeOptions-checkpoint.ipynb
|
pdghawk/optionpricer
|
0086054817b8c1d6dc78faee8e12fd0df99bcae7
|
[
"Apache-2.0"
] | null | null | null |
notebooks/.ipynb_checkpoints/MultiAssetExchangeOptions-checkpoint.ipynb
|
pdghawk/optionpricer
|
0086054817b8c1d6dc78faee8e12fd0df99bcae7
|
[
"Apache-2.0"
] | 2 |
2020-03-24T17:13:54.000Z
|
2020-03-31T03:46:06.000Z
|
notebooks/.ipynb_checkpoints/MultiAssetExchangeOptions-checkpoint.ipynb
|
pdghawk/optionpricer
|
0086054817b8c1d6dc78faee8e12fd0df99bcae7
|
[
"Apache-2.0"
] | null | null | null | 66.926531 | 2,165 | 0.66128 |
[
[
[
"# Multi-asset option pricing - Monte Carlo - exchange option",
"_____no_output_____"
]
],
[
[
"import sys\nsys.path.append('..')\n\n\nfrom optionpricer import payoff\nfrom optionpricer import option\nfrom optionpricer import bspde\nfrom optionpricer import analytics\nfrom optionpricer import parameter as prmtr\nfrom optionpricer import path\nfrom optionpricer import generator\nfrom optionpricer import montecarlo\n\nimport numpy as np\nfrom scipy import linalg\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns",
"_____no_output_____"
],
[
"# option and market properties \nexpiry = 1.0/12.0 # time until expiry (annualized)\nr0 = 0.094 # interest rate (as decimal, not percentage) \n\n# properties of the underlyings\nsig=np.array([0.05,0.09]) # volatility (annualized) for underlyings [vol stock 1, vol stock 2]\nrho = 0.8 # correlation between the two underlyings\ncorrelation_matrix = np.array([[1.0,rho],[rho,1.0]])\n\n# the spot values we will want to price the option at for the two underlyings\nspot0 = np.linspace(30.0,70.0,30)\nspot1 = np.linspace(40.0,60.0,20)\n# create a meshgrid to easily run over all combinations of spots, and for ease of plotting later \nSPOT0,SPOT1 = np.meshgrid(spot0,spot1)\n\n# # use r0, and the volatilities (elements of sig) to make a SimpleParam objects containing these values\nr_param = prmtr.SimpleParam(r0)\nsig0_p = prmtr.SimpleParam(sig[0])\nsig1_p = prmtr.SimpleParam(sig[1])",
"_____no_output_____"
],
[
"# we can use the correlation matrix of the underlyings to construct the covariance matrix\n\ncovars = correlation_matrix*np.outer(sig,sig)\n\n# We can then Cholesky decompose the covariance matrix\nL = linalg.cholesky(covars,lower=True)\n# we obtain a lower traingular matrix which can be used to generate movements of the underlying \n# which obey the covariance (/correlation) we defined above\nprint(L)\nprint(np.dot(L,L.T))\n\n# create a simpleArrayParam (this object stores an array which is constant in time) usung L\ncovariance_param = prmtr.SimpleArrayParam(covars)\ncholesky_param = prmtr.SimpleArrayParam(L)",
"[[0.05 0. ]\n [0.072 0.054]]\n[[0.0025 0.0036]\n [0.0036 0.0081]]\n"
],
[
"# define the Spread option - with strike of 0 to make it an exchange option\nexchange_po = payoff.SpreadPayOff(0.0)\n# also valid for payoff of exchnage option: exchange_po=payoff.ExchangePayOff()\nexchange_option = option.VanillaOption(exchange_po,expiry)",
"_____no_output_____"
],
[
"# define the random generator for problem - here normally districuted log returns\ngen_norm = generator.Normal()\n# decorate the generator, making it an antithetic generator for variance reduction\ngen_norm_antith = generator.Antithetic(gen_norm)",
"_____no_output_____"
],
[
"# Define a multiasset montecarlo pricer\nmc_pricer = montecarlo.MAMonteCarlo(exchange_option,gen_norm_antith)\n\n# initialize arrays for prices \nmc_prices = np.zeros_like(SPOT0)\n# we also initialize an array of option prices using the analytic magrabe price of exchange option\nmagrabe_prices = np.zeros_like(SPOT0)\n\n# loop over spots, and calculate the price of the option\nfor ind0 in range(SPOT0.shape[0]):\n for ind1 in range(SPOT0.shape[1]):\n s = np.array([SPOT0[ind0,ind1],SPOT1[ind0,ind1]])\n mc_prices[ind0,ind1] = mc_pricer.solve_price(s,r_param,covariance_param,cholesky_param,eps_tol=0.0001)\n magrabe_prices[ind0,ind1] = analytics.margrabe_option_price(s,expiry,covars)\n",
"_____no_output_____"
],
[
"# set up plotting parameters for nice to view plots\nsns.set()\nmpl.rcParams['lines.linewidth'] = 2.0\nmpl.rcParams['font.weight'] = 'bold'\nmpl.rcParams['axes.labelweight'] = 'bold'\nmpl.rcParams['axes.titlesize'] = 12\nmpl.rcParams['axes.titleweight'] = 'bold'\nmpl.rcParams['font.size'] = 12\nmpl.rcParams['legend.frameon'] = False\nmpl.rcParams['figure.figsize'] = [15,10]",
"_____no_output_____"
],
[
"# we will plot the monte carlo, magrabe price, and the differen between the two (the error)\n\nf, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True)\n\n# calculate values of min and max expected values \n# use to set colormap max/min values to ensure they're the same for both plots of price\nvmin_=min(np.amin(mc_prices),np.amin(magrabe_prices))\nvmax_=max(np.amax(mc_prices),np.amax(magrabe_prices))\n\n# subplot of Monte Carlo\nim1 = ax1.pcolormesh(spot0,spot1,mc_prices,vmin=vmin_,vmax=vmax_)\nplt.colorbar(im1,ax=ax1)\n\n# subplot of Magrabe price\nim2 = ax2.pcolormesh(spot0,spot1,magrabe_prices,vmin=vmin_,vmax=vmax_)\nplt.colorbar(im2,ax=ax2)\n\n# subplot of error\nim3 = ax3.pcolormesh(spot0,spot1,np.abs(magrabe_prices-mc_prices))\nplt.colorbar(im3,ax=ax3)\nax3.set_xlabel('spot 0')\n\n# set titles and y lables of subplots\ntitles = ['Monte Carlo','Magrabe Price','|Margrabe-MC|']\nfor i,ax in enumerate([ax1,ax2,ax3]):\n ax.set_ylabel('spot 1')\n ax.set_title(titles[i])\n\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aa96b8b9ab958c7f0abb7bfd4b23103af46e397
| 17,457 |
ipynb
|
Jupyter Notebook
|
code/04-integrating_functional_data.ipynb
|
samwalkow/SDC-BIDS-fMRI
|
a4b3af0f9c7f1235f411a9954f6a753a63a22d29
|
[
"CC-BY-4.0"
] | null | null | null |
code/04-integrating_functional_data.ipynb
|
samwalkow/SDC-BIDS-fMRI
|
a4b3af0f9c7f1235f411a9954f6a753a63a22d29
|
[
"CC-BY-4.0"
] | null | null | null |
code/04-integrating_functional_data.ipynb
|
samwalkow/SDC-BIDS-fMRI
|
a4b3af0f9c7f1235f411a9954f6a753a63a22d29
|
[
"CC-BY-4.0"
] | null | null | null | 31.062278 | 530 | 0.617804 |
[
[
[
"# Integrating Functional Data\n\nSo far most of our work has been examining anatomical images - the reason being is that it provides a nice visual way of exploring the effects of data manipulation and visualization is easy. In practice, you will most likely not analyze anatomical data using <code>nilearn</code> since there are other tools that are better suited for that kind of analysis (freesurfer, connectome-workbench, mindboggle, etc...). \n\nIn this notebook we'll finally start working with functional MR data - the modality of interest in this workshop. First we'll cover some basics about how the data is organized (similar to T1s but slightly more complex), and then how we can integrate our anatomical and functional data together using tools provided by <code>nilearn</code>",
"_____no_output_____"
],
[
"Functional data consists of full 3D brain volumes that are *sampled* at multiple time points. Therefore you have a sequence of 3D brain volumes, stepping through sequences is stepping through time and therefore time is our 4th dimension! Here's a visualization to make this concept more clear:",
"_____no_output_____"
],
[
"<img src=\"./static/images/4D_array.png\" alt=\"Drawing\" align=\"middle\" width=\"500px\"/>",
"_____no_output_____"
],
[
"Each index along the 4th dimensions (called TR for \"Repetition Time\", or Sample) is a full 3D scan of the brain. Pulling out volumes from 4-dimensional images is similar to that of 3-dimensional images except you're now dealing with:\n\n\n<code> img.slicer[x,y,z,time] </code>!\n\nLet's try a couple of examples to familiarize ourselves with dealing with 4D images. But first, let's pull some functional data using PyBIDS!",
"_____no_output_____"
]
],
[
[
"fmriprep_dir = '../data/ds000030/derivatives/fmriprep/'\nlayout=BIDSLayout(fmriprep_dir, validate=False)\nT1w_files = layout.get(subject='10788', datatype='anat', suffix='preproc')\nbrainmask_files = layout.get(subject='10788', datatype='anat', suffix='brainmask')\nfunc_files = layout.get(subject='10788', datatype='func', suffix='preproc')\nfunc_mask_files = layout.get(subject='10788', datatype='func', suffix='brainmask')",
"_____no_output_____"
]
],
[
[
"We'll be using functional files in MNI space rather than T1w space. Recall, that MNI space data is data that was been warped into standard space. These are the files you would typically use for a group-level functional imaging analysis!",
"_____no_output_____"
],
[
"First, take a look at the shape of the functional image:",
"_____no_output_____"
],
[
"Notice that the Functional MR scan contains *4 dimensions*. This is in the form of $(x,y,z,t)$, where $t$ is time. \nWe can use slicer as usual where instead of using 3 dimensions we use 4. \n\nFor example:\n\n<code> func.slicer[x,y,z] </code> \n\nvs.\n\n<code> func.slicer[x,y,z,t] </code>",
"_____no_output_____"
],
[
"### Exercise\n\nTry pulling out the 5th TR and visualizing it using <code>plot.plot_epi</code>. <code>plot_epi</code> is exactly the same as <code>plot_anat</code> except it displays using colors that make more sense for functional images...",
"_____no_output_____"
]
],
[
[
"#Pull the 5th TR\nfunc_vol5 = func_mni_img.slicer[??,??,??,??]\nplot.plot_epi(??)",
"_____no_output_____"
]
],
[
[
"## What fMRI actually represents",
"_____no_output_____"
],
[
"We've represented fMRI as a snapshot of MR signal over multiple timepoints. This is a useful way of understanding the organization of fMRI, however it isn't typically how we think about the data when we analyze fMRI data. fMRI is typically thought of as **time-series** data. We can think of each voxel (x,y,z coordinate) as having a time-series of length T. The length T represents the number of volumes/timepoints in the data. Let's pick an example voxel and examine its time-series using <code>func_mni_img.slicer</code>:",
"_____no_output_____"
]
],
[
[
"#Pick one voxel at coordinate (60,45,88)\n",
"_____no_output_____"
]
],
[
[
"As you can see here, we pulled one voxel that contains 152 timepoints. For plotting purposes as 4-dimensional array is difficult to deal with so we'll flatten it to 1 dimension (time) for convenience:",
"_____no_output_____"
],
[
"Here we've pulled out a voxel at a specific coordinate at every single time-point. This voxel has a single value for each timepoint and therefore is a time-series. We can visualize this time-series signal by using a standard python plotting library. We won't go into too much detail about python plotting, the intuition about what the data looks like is what is most important:",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"## Resampling\nRecall from our introductory exploration of neuroimaging data:\n\n- T1 images are typically composed of voxels that are 1x1x1 in dimension\n- Functional images are typically composed of voxels that are 4x4x4 in dimension\n\nIf we'd like to overlay our functional on top of our T1 (for visualization purposes, or analyses), then we need to match the size of the voxels! \n\nThink of this like trying to overlay a 10x10 JPEG and a 20x20 JPEG on top of each other. To get perfect overlay we need to resize (or more accurately *resample*) our JPEGs to match!\n\n**Note**: \nResampling is a method of interpolating in between data-points. When we stretch an image we need to figure out what goes in the spaces that are created via stretching - resampling does just that. In fact, resizing any type of image is actually just resampling to new dimensions. ",
"_____no_output_____"
],
[
"Let's resampling some MRI data using nilearn. \n\n**Goal**: Match the dimensions of the structural image to that of the functional image",
"_____no_output_____"
]
],
[
[
"#Files we'll be using (Notice that we're using _space-MNI..._ which means they are normalized brains)\n",
"_____no_output_____"
]
],
[
[
"Let's take a look at the sizes of both our functional and structural files:",
"_____no_output_____"
],
[
"Resampling in nilearn is as easy as telling it which image you want to sample and what the target image is.\nStructure of function:\n\nimg.resample_to_img(source_img,target_img,interpolation) \n- source_img = the image you want to sample\n- target_img = the image you wish to *resample to* \n- interpolation = the method of interpolation\n\nA note on **interpolation**\n\nnilearn supports 3 types of interpolation, the one you'll use depends on the type of data you're resampling!\n1. **continuous** - Interpolate but maintain some edge features. Ideal for structural images where edges are well-defined. Uses $3^\\text{rd}$-order spline interpolation.\n2. **linear (default)** - Interpolate uses a combination of neighbouring voxels - will blur. Uses trilinear interpolation.\n3. **nearest** - matches value of closest voxel (majority vote from neighbours). This is ideal for masks which are binary since it will preserve the 0's and 1's and will not produce in-between values (ex: 0.342). Also ideal for numeric labels where values are 0,1,2,3... (parcellations). Uses nearest-neighbours interpolation with majority vote.\n",
"_____no_output_____"
]
],
[
[
"#Try playing around with methods of interpolation\n#options: 'linear','continuous','nearest'\n",
"_____no_output_____"
],
[
"import matplotlib.animation\nfrom IPython.display import HTML",
"_____no_output_____"
],
[
"%%capture\n%matplotlib inline\n#Resample the T1 to the size of the functional image!\nresamp_t1 = img.resample_to_img(source_img=T1_mni_img, target_img=func_mni_img, interpolation='continuous')\nfig, ax = plt.subplots()\n\ndef animate(image):\n plot.plot_anat(image, figure=fig, cut_coords=(0,0,0))\n ax.set_facecolor('black')\n \nani = matplotlib.animation.FuncAnimation(fig, animate, frames=[resamp_t1, T1_mni_img]) \n#change the frames to look at the functional mask over the resampled T1\n# ani = matplotlib.animation.FuncAnimation(fig, animate, frames=[resamp_t1, func]) ",
"_____no_output_____"
],
[
"# Display animation\nHTML(ani.to_jshtml())",
"_____no_output_____"
]
],
[
[
"## **Exercise**\n\nUsing **Native** T1 and **T1w** resting state functional do the following:\n1. Resample the native T1 image to resting state size\n2. Replace the brain in the T1 image with the first frame of the resting state brain",
"_____no_output_____"
]
],
[
[
"#Files we'll need\n\n\n####STRUCTURAL FILES\n\n#T1 image\nex_t1 = img.load_img(T1w_files[0].path)\n\n#mask file\nex_t1_bm = img.load_img(brainmask_files[0].path)\n\n\n####FUNCTIONAL FILES\n\n#This is the pre-processed resting state data that hasn't been standardized\nex_func = img.load_img(func_files[1].path)\n\n#This is the associated mask for the resting state image.\nex_func_bm = img.load_img(func_mask_files[1].path)",
"_____no_output_____"
]
],
[
[
"The first step we need to do is to make sure the dimensions for our T1 image and resting state image match each other:",
"_____no_output_____"
]
],
[
[
"#Resample the T1 to the size of the functional image!\nresamp_t1 = img.resample_to_img(source_img=??, target_img=??, interpolation='continuous')\nplot.plot_anat(??)\nprint(resamp_t1.shape)",
"_____no_output_____"
]
],
[
[
"Next we want to make sure that the brain mask for the T1 is also the same dimensions as the functional image. This is exactly the same as above, except we use the brain mask as the source.\n\nWhat kind of interpolation should we use for masks? ",
"_____no_output_____"
]
],
[
[
"resamp_bm = img.??(??)\n\n#Plot the image\n??\n\nprint(resamp_bm.shape)",
"_____no_output_____"
]
],
[
[
"Once we've resampled both our T1 and our brain mask. We now want to remove the brain from the T1 image so that we can replace it with the funtional image instead. Remember to do this we need to:\n\n1. Invert the T1 mask\n2. Apply the inverted mask to the brain",
"_____no_output_____"
]
],
[
[
"inverted_bm_t1 = img.math_img(??,a=resamp_bm)\nplot.plot_anat(inverted_bm_t1)",
"_____no_output_____"
]
],
[
[
"Now apply the mask:",
"_____no_output_____"
]
],
[
[
"resamp_t1_nobrain = img.??(??)\nplot.plot_anat(resamp_t1_nobrain)",
"_____no_output_____"
]
],
[
[
"We now have a skull missing the structural T1 brain. The final steps is to stick in the brain from the functional image into the now brainless head. First we need to remove the surrounding signal from the functional image.\n\nSince a functional image is 4-Dimensional, we'll need to pull the first volume to work with. This is because the structural image is 3-dimensional and operations will fail if we try to mix 3D and 4D data.",
"_____no_output_____"
]
],
[
[
"#Let's visualize the first volume of the functional image:\nfirst_vol = ex_func.slicer[??,??,??,??]\nplot.plot_epi(first_vol)",
"_____no_output_____"
]
],
[
[
"As shown in the figure above, the image has some \"signal\" outside of the brain. In order to place this within the now brainless head we made earlier, we need to mask out the functional MR data as well!",
"_____no_output_____"
]
],
[
[
"#Mask first_vol using ex_func_bm\nmasked_func = img.math_img('??', a=??, b=??)\nplot.plot_epi(masked_func)",
"_____no_output_____"
]
],
[
[
"The final step is to stick this data into the head of the T1 data. Since the hole in the T1 data is represented as $0$'s. We can add the two images together to place the functional data into the void:",
"_____no_output_____"
]
],
[
[
"#Now overlay the functional image on top of the anatomical\ncombined_img = img.math_img(??)\nplot.plot_anat(combined_img)",
"_____no_output_____"
]
],
[
[
"***",
"_____no_output_____"
],
[
"In this section we explored functional MR imaging. Specifically we covered:\n \n1. How the data in a fMRI scan is organized - with the additional dimension of timepoints\n2. How we can integrate functional MR images to our structural image using resampling\n3. How we can just as easily manipulate functional images using <code>nilearn</code>\n\nNow that we've covered all the basics, it's time to start working on data processing using the tools that we've picked up. ",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
4aa96dda5664affd8e8ee244b8dcefe81ff5fbaf
| 29,016 |
ipynb
|
Jupyter Notebook
|
Chapter05/Code/5_2.Using App Config in Notebooks.ipynb
|
ssprsiva/cloned_databricks
|
b9cda4f1160f0bd4dba66de6c6c40939fc52f75c
|
[
"MIT"
] | 11 |
2021-04-19T05:09:33.000Z
|
2022-01-17T08:46:16.000Z
|
Chapter05/Code/5_2.Using App Config in Notebooks.ipynb
|
ssprsiva/cloned_databricks
|
b9cda4f1160f0bd4dba66de6c6c40939fc52f75c
|
[
"MIT"
] | null | null | null |
Chapter05/Code/5_2.Using App Config in Notebooks.ipynb
|
ssprsiva/cloned_databricks
|
b9cda4f1160f0bd4dba66de6c6c40939fc52f75c
|
[
"MIT"
] | 21 |
2019-12-25T17:48:02.000Z
|
2022-03-30T01:42:03.000Z
| 29,016 | 29,016 | 0.7307 |
[
[
[
"%pip install azure-appconfiguration",
"_____no_output_____"
],
[
"from azure.appconfiguration import AzureAppConfigurationClient, ConfigurationSetting",
"_____no_output_____"
],
[
"try:\r\n connection_string = \"Endpoint=https://devdemoappconfigurationres.azconfig.io;Id=V/Ri-l0-s0:zzzzzzzzzz\"\r\n app_config_client = AzureAppConfigurationClient.from_connection_string(connection_string)\r\n retrieved_config_setting = app_config_client.get_configuration_setting(key='StorageKey')\r\n storageKey= retrieved_config_setting.value\r\nexcept Exception as ex:\r\n print('Exception:')\r\n print(ex)",
"_____no_output_____"
],
[
"#Storage account key is stored in Azure Key-Vault as a sceret. The secret name is blobstoragesecret and KeyVaultScope is the name of the scope we have created. We can also store the storage account name as a new secret if we don't want users to know the name of the storage account.\r\n\r\nstorageAccount=\"cookbookblobstorage1\"\r\n# storageKey = dbutils.secrets.get(scope=\"KeyVaultScope\",key=\"blobstoragesecret\")\r\nmountpoint = \"/mnt/AppConfigBlob\"\r\nstorageEndpoint = \"wasbs://rawdata@{}.blob.core.windows.net\".format(storageAccount)\r\nstorageConnSting = \"fs.azure.account.key.{}.blob.core.windows.net\".format(storageAccount)\r\n\r\ntry:\r\n dbutils.fs.mount(\r\n source = storageEndpoint,\r\n mount_point = mountpoint,\r\n extra_configs = {storageConnSting:storageKey})\r\nexcept:\r\n print(\"Already mounted....\"+mountpoint)\r\n",
"_____no_output_____"
],
[
"%fs ls /mnt/AppConfigBlob",
"_____no_output_____"
],
[
"display(dbutils.fs.ls(\"/mnt/AppConfigBlob/Customer/parquetFiles\"))",
"_____no_output_____"
],
[
"#Lets read data from csv file which is copied to Blob Storage\ndf_cust= spark.read.format(\"parquet\").option(\"header\",True).load(\"dbfs:/mnt/AppConfigBlob/Customer/parquetFiles/*.parquet\")",
"_____no_output_____"
],
[
"display(df_cust.limit(10))",
"_____no_output_____"
],
[
"df_cust.count()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aa974247c1f2c7a92fdd5a71a5a2df7a6cd4a43
| 844,754 |
ipynb
|
Jupyter Notebook
|
ML/Lectures/07-regression-classification.ipynb
|
TheFebrin/Machine-Learning
|
3e58b89315960e7d4896e44075a8105fcb78f0c0
|
[
"MIT"
] | null | null | null |
ML/Lectures/07-regression-classification.ipynb
|
TheFebrin/Machine-Learning
|
3e58b89315960e7d4896e44075a8105fcb78f0c0
|
[
"MIT"
] | null | null | null |
ML/Lectures/07-regression-classification.ipynb
|
TheFebrin/Machine-Learning
|
3e58b89315960e7d4896e44075a8105fcb78f0c0
|
[
"MIT"
] | null | null | null | 3,187.750943 | 216,907 | 0.955657 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4aa9775d11ff9b22edcf78fb7894124b9757fb6f
| 622,769 |
ipynb
|
Jupyter Notebook
|
notebooks/01_spindles_detection.ipynb
|
HKH515/yasa
|
4b5973bfcf92788f080e3ca05bc2aa1402df8865
|
[
"BSD-3-Clause"
] | null | null | null |
notebooks/01_spindles_detection.ipynb
|
HKH515/yasa
|
4b5973bfcf92788f080e3ca05bc2aa1402df8865
|
[
"BSD-3-Clause"
] | null | null | null |
notebooks/01_spindles_detection.ipynb
|
HKH515/yasa
|
4b5973bfcf92788f080e3ca05bc2aa1402df8865
|
[
"BSD-3-Clause"
] | null | null | null | 676.187839 | 91,732 | 0.944605 |
[
[
[
"# Spindles detection\n\nThis notebook demonstrates how to use YASA to perform **single-channel sleep spindles detection**. It also shows a step-by-step description of the detection algorithm.\n\nPlease make sure to install the latest version of YASA first by typing the following line in your terminal or command prompt:\n\n`pip install --upgrade yasa`",
"_____no_output_____"
]
],
[
[
"import yasa\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(font_scale=1.2)",
"_____no_output_____"
]
],
[
[
"## Single-channel spindles detection\nAs an example, we load 15 seconds of N2 sleep on a single\nchannel central EEG data. The sampling rate is 200 Hz.",
"_____no_output_____"
]
],
[
[
"# Load data\ndata = np.loadtxt('data_N2_spindles_15sec_200Hz.txt')\n\n# Define sampling frequency and time vector\nsf = 200.\ntimes = np.arange(data.size) / sf\n\n# Plot the signal\nfig, ax = plt.subplots(1, 1, figsize=(14, 4))\nplt.plot(times, data, lw=1.5, color='k')\nplt.xlabel('Time (seconds)')\nplt.ylabel('Amplitude (uV)')\nplt.xlim([times.min(), times.max()])\nplt.title('N2 sleep EEG data (2 spindles)')\nsns.despine()",
"_____no_output_____"
]
],
[
[
"We can clearly see that there are two clean spindles on this 15-seconds epoch. The first one starting at around 3.5 seconds and the second one starting around 13 seconds.\n\nLet's try to detect these two spindles using the [yasa.spindles_detect](https://raphaelvallat.com/yasa/build/html/generated/yasa.spindles_detect.html) function. Here' we're using a minimal example, but there are many other optional arguments that you can pass to this function.",
"_____no_output_____"
]
],
[
[
"# Apply the detection using yasa.spindles_detect\nsp = yasa.spindles_detect(data, sf)\n\n# Display the results using .summary()\nsp.summary()",
"_____no_output_____"
]
],
[
[
"Hooray! The algorithm successfully identified the two spindles! \n\nThe output of the spindles detection is a [SpindlesResults](https://raphaelvallat.com/yasa/build/html/generated/yasa.SpindlesResults.html#yasa.SpindlesResults) class, which comes with some pre-compiled functions (also called methods). For instance, the [summary](https://raphaelvallat.com/yasa/build/html/generated/yasa.SpindlesResults.html#yasa.SpindlesResults.summary) method returns a [pandas DataFrame](http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe) with all the detected spindles and their properties.",
"_____no_output_____"
],
[
"### Plot an overlay of our detected spindles\n\nFirst we need to create a boolean array of the same size of data indicating for each sample if this sample is part of a spindles or not. This is done using the [get_mask](https://raphaelvallat.com/yasa/build/html/generated/yasa.SpindlesResults.html#yasa.SpindlesResults.get_mask) method:",
"_____no_output_____"
]
],
[
[
"# Let's get a bool vector indicating for each sample\nmask = sp.get_mask()\nmask",
"_____no_output_____"
],
[
"# Now let's plot\nspindles_highlight = data * mask\nspindles_highlight[spindles_highlight == 0] = np.nan\n\nplt.figure(figsize=(14, 4))\nplt.plot(times, data, 'k')\nplt.plot(times, spindles_highlight, 'indianred')\nplt.xlabel('Time (seconds)')\nplt.ylabel('Amplitude (uV)')\nplt.xlim([0, times[-1]])\nplt.title('N2 sleep EEG data (2 spindles detected)')\nsns.despine()\n# plt.savefig('detection.png', dpi=300, bbox_inches='tight')",
"_____no_output_____"
]
],
[
[
"### Logging\n\nYASA uses the [logging](https://docs.python.org/3/library/logging.html) module to selectively print relevant messages. The default level of the logger is set to \"WARNING\", which means that a message will only be displayed if a warning occurs. However, you can easily set this parameter to \"INFO\" to get some relevant infos about the detection pipeline and the data.\n\nThis can be useful to debug the detection and/or if you feel that the detection is not working well on your data.",
"_____no_output_____"
]
],
[
[
"# The default verbose is None which corresponds to verbose='warning'\nsp = yasa.spindles_detect(data, sf, thresh={'rms': None}, verbose='info')\nsp.summary()",
"29-Jun-20 17:27:02 | INFO | Number of samples in data = 3000\n29-Jun-20 17:27:02 | INFO | Sampling frequency = 200.00 Hz\n29-Jun-20 17:27:02 | INFO | Data duration = 15.00 seconds\n29-Jun-20 17:27:02 | INFO | Trimmed standard deviation of CHAN000 = 15.5869 uV\n29-Jun-20 17:27:02 | INFO | Peak-to-peak amplitude of CHAN000 = 289.6042 uV\n29-Jun-20 17:27:02 | INFO | N supra-theshold relative power = 313\n29-Jun-20 17:27:02 | INFO | N supra-theshold moving corr = 345\n"
]
],
[
[
"### Safety check\n\nTo make sure that our spindle detection does not detect false positives, let's load a new dataset, this time without any sleep spindles. The data represents 30 seconds of N3 sleep sampled at 100 Hz and acquired on a young, healthy, individual.",
"_____no_output_____"
]
],
[
[
"data_no_sp = np.loadtxt('data_N3_no-spindles_30sec_100Hz.txt')\nsf_no_sp = 100\ntimes_no_sp = np.arange(data_no_sp.size) / sf_no_sp\n\nplt.figure(figsize=(14, 4))\nplt.plot(times_no_sp, data_no_sp, 'k')\nplt.xlim(0, times_no_sp.max())\nplt.xlabel('Time (seconds)')\nplt.ylabel('Voltage')\nplt.xlim([times_no_sp.min(), times_no_sp.max()])\nplt.title('N3 sleep EEG data (0 spindle)')\nsns.despine()",
"_____no_output_____"
],
[
"sp = yasa.spindles_detect(data_no_sp, sf_no_sp)\nsp",
"29-Jun-20 17:27:03 | WARNING | No spindle were found in channel CHAN000.\n29-Jun-20 17:27:03 | WARNING | No spindles were found in data. Returning None.\n"
]
],
[
[
"As hoped for, no spindles were detected in this window.",
"_____no_output_____"
],
[
"### Execution time\n\nThe total execution time on a regular laptop is 10-20 ms per 15 seconds of data sampled at 200 Hz. Scaled to a full night recording, the computation time should not exceed 5-10 seconds per channel on any modern computers. Furthermore, it is possible to disable one or more threshold and thus speed up the computation. Note that most of the computation cost is dominated by the bandpass filter(s).",
"_____no_output_____"
]
],
[
[
"%timeit -r 3 -n 100 yasa.spindles_detect(data, sf)",
"11.4 ms ± 856 µs per loop (mean ± std. dev. of 3 runs, 100 loops each)\n"
],
[
"%timeit -r 3 -n 100 yasa.spindles_detect(data, sf, thresh={'rms': 3, 'corr': None, 'rel_pow': None})",
"10.4 ms ± 713 µs per loop (mean ± std. dev. of 3 runs, 100 loops each)\n"
],
[
"# Line profiling\n# %load_ext line_profiler\n# %lprun -f yasa.spindles_detect yasa.spindles_detect(data, sf)",
"_____no_output_____"
]
],
[
[
"****************\n\n## The YASA spindles algorithm: step-by-step\n\nThe YASA spindles algorithm is largely inspired by the A7 algorithm described in [Lacourse et al. 2018](https://doi.org/10.1016/j.jneumeth.2018.08.014):\n\n> Lacourse, K., Delfrate, J., Beaudry, J., Peppard, P., Warby, S.C., 2018. A sleep spindle detection algorithm that emulates human expert spindle scoring. *J. Neurosci. Methods*. https://doi.org/10.1016/j.jneumeth.2018.08.014\n\nThe main idea of the algorithm is to compute different thresholds from the broadband-filtered signal (1 to 30Hz, $\\text{EEG}_{bf}$) and the sigma-filtered signal (11 to 16 Hz, $\\text{EEG}_{\\sigma}$).\n\n**There are some notable exceptions between YASA and the A7 algorithm:**\n1. YASA uses 3 different thresholds (relative $\\sigma$ power, [root mean square](https://en.wikipedia.org/wiki/Root_mean_square) and correlation). The A7 algorithm uses 4 thresholds (absolute and relative $\\sigma$ power, covariance and correlation). Note that it is possible in YASA to disable one or more threshold by putting ``None`` instead.\n2. The windowed detection signals are resampled to the original time vector of the data using cubic interpolation, thus resulting in a pointwise detection signal (= one value at every sample). The time resolution of YASA is therefore higher than the A7 algorithm. This allows for more precision to detect the beginning, end and durations of the spindles (typically, A7 = 100 ms and YASA = 10 ms).\n3. The relative power in the sigma band is computed using a Short-Term Fourier Transform. The relative sigma power is not z-scored.\n4. The median frequency and absolute power of each spindle is computed using an Hilbert transform.\n5. YASA computes some additional spindles properties, such as the symmetry index and number of oscillations. These metrics are inspired from [Purcell et al. 2017](https://www.nature.com/articles/ncomms15930).\n7. Potential sleep spindles are discarded if their duration is below 0.5 seconds and above 2 seconds. These values are respectively 0.3 and 2.5 seconds in the A7 algorithm.\n8. YASA incorporates an automatic rejection of pseudo or fake events based on an [Isolation Forest](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html) algorithm.",
"_____no_output_____"
],
[
"### Preprocessing\n\nThe raw signal is bandpass filtered to the broadband frequency range defined in the (optional) parameter `freq_broad`. The default is to use a FIR filter from 1 to 30 Hz. The filter is done using the MNE built-in [filter_data](https://martinos.org/mne/stable/generated/mne.filter.filter_data.html) function. The resulting, filtered, signal is $\\text{EEG}_{bf}$.",
"_____no_output_____"
]
],
[
[
"from mne.filter import resample, filter_data\n\n# Broadband (1 - 30 Hz) bandpass filter\nfreq_broad = (1, 30)\ndata_broad = filter_data(data, sf, freq_broad[0], freq_broad[1], method='fir',verbose=0)",
"_____no_output_____"
]
],
[
[
"### Threshold 1: Relative power in the sigma band\n\nThe first detection signal is the power in the sigma frequency range (11-16 Hz) relative to the total power in the broadband frequency (1-30 Hz). This is calculated using a [Short-Term Fourier Transform](https://en.wikipedia.org/wiki/Short-time_Fourier_transform) (STFT) on consecutive epochs of 2 seconds and with an overlap of 200 ms. The first threshold is exceeded whenever a sample has a relative power in the sigma frequency range $\\geq 0.2$. In other words, it means that 20% of the signal's total power must be contained within the sigma band. The goal of this threshold is to make sure that the increase in sigma power is actually specific to the sigma frequency range and not just due to a global increase in power (e.g. caused by artefacts).\n\nImportantly, you may want to lower this threshold if you aim to detect spindles in N3 sleep (slow-wave sleep), a sleep stage in which most of the relative spectral power is contained in the delta band (0.5 to 4 Hz). \n\n#### More about the STFT\n\nBecause our STFT has a window of 2 seconds, it means that our frequency resolution is $1 / 2 = 0.5$ Hz. In other words, our frequency vector is *[1, 1.5, 2, ..., 29, 29.5, 30]* Hz. The power in the sigma frequency range is simply the sum, at each time point, of the power values at $f_{\\sigma}=$*[11, 11.5, 12, 12.5, 13, 13.5, 14, 14.5, 15, 15.5, 16]* Hz.",
"_____no_output_____"
]
],
[
[
"# Compute the pointwise relative power using STFT and cubic interpolation\nf, t, Sxx = yasa.main.stft_power(data_broad, sf, window=2, step=.2, band=freq_broad, norm=True, interp=True)\n\n# Extract the relative power in the sigma band\nidx_sigma = np.logical_and(f >= 11, f <= 16)\nrel_pow = Sxx[idx_sigma].sum(0)\n\n# Plot\nfig, (ax1, ax2) = plt.subplots(2, 1, figsize=(14, 8), sharex=True)\nplt.subplots_adjust(hspace=.25)\nim = ax1.pcolormesh(t, f, Sxx, cmap='Spectral_r', vmax=0.2)\nax1.set_title('Spectrogram')\nax1.set_ylabel('Frequency (Hz)')\nax2.plot(t, rel_pow)\nax2.set_ylabel('Relative power (% $uV^2$)')\nax2.set_xlim(t[0], t[-1])\nax2.set_xlabel('Time (sec)')\nax2.axhline(0.20, ls=':', lw=2, color='indianred', label='Threshold #1')\nplt.legend()\n_ = ax2.set_title('Relative power in the sigma band')",
"<ipython-input-13-40e87383a020>:11: MatplotlibDeprecationWarning: shading='flat' when X and Y have the same dimensions as C is deprecated since 3.3. Either specify the corners of the quadrilaterals with X and Y, or pass shading='auto', 'nearest' or 'gouraud', or set rcParams['pcolor.shading']. This will become an error two minor releases later.\n im = ax1.pcolormesh(t, f, Sxx, cmap='Spectral_r', vmax=0.2)\n"
]
],
[
[
"### Threshold 2: Moving correlation\n\nFor the two remaining thresholds, we are going to need the sigma-filtered signal ($\\text{EEG}_{\\sigma}$). Here again, we use the MNE built-in [FIR filter](https://martinos.org/mne/stable/generated/mne.filter.filter_data.html). Note that we use a FIR filter and not a IIR filter because *\"FIR filters are easier to control, are always stable, have a well-defined passband, and can be corrected to zero-phase without additional computations\"* ([Widmann et al. 2015](https://doi.org/10.1016/j.jneumeth.2014.08.002)).\n\nThe default sigma bandpass filtering in YASA uses a 12 to 15 Hz zero-phase FIR filtering with transition bands of 1.5 Hz at each side. The - 6dB cutoff is therefore defined at 11.25 Hz and 15.75 Hz.\n\nPlease refer to the [MNE documentation](https://martinos.org/mne/stable/auto_tutorials/plot_background_filtering.html#sphx-glr-auto-tutorials-plot-background-filtering-py) for more details on filtering.",
"_____no_output_____"
]
],
[
[
"data_sigma = filter_data(data, sf, 12, 15, l_trans_bandwidth=1.5, \n h_trans_bandwidth=1.5, method='fir', verbose=0)\n\n# Plot the filtered signal\nplt.figure(figsize=(14, 4))\nplt.plot(times, data_sigma, 'k')\nplt.xlabel('Time (seconds)')\nplt.ylabel('Amplitude (uV)')\nplt.title('$EEG_{\\sigma}$ (11-16 Hz)')\n_ = plt.xlim(0, times[-1])",
"_____no_output_____"
]
],
[
[
"Our second detection signal is calculated by taking, with a moving sliding window of 300 ms and a step of 100 ms, the [Pearson correlation coefficient](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient) between and $\\text{EEG}_{bf}$ and $\\text{EEG}_{\\sigma}$. According to [Lacourse et al. 2018](http://dx.doi.org/10.1016/j.jneumeth.2018.08.014):\n\n> The current spindle detector design is unique because it uses a correlation filter between the EEG signal filtered in the sigma band and the raw EEG signal itself. The proposed design is therefore biased to detect spindles that are visible on the raw EEG signal by requiring a high correlation between raw EEG signal and the filtered sigma burst (the pattern that represents a spindle).\n\nOnce again, the values are interpolated using cubic interpolation to obtain one value per each time point. The second threshold is exceeded whenever a sample has a correlation value $r \\geq .65$.",
"_____no_output_____"
]
],
[
[
"t, mcorr = yasa.main.moving_transform(data_sigma, data_broad, sf, window=.3, step=.1, method='corr', interp=True)\n\nplt.figure(figsize=(14, 4))\nplt.plot(times, mcorr)\nplt.xlabel('Time (seconds)')\nplt.ylabel('Pearson correlation')\nplt.axhline(0.65, ls=':', lw=2, color='indianred', label='Threshold #2')\nplt.legend()\nplt.title('Moving correlation between $EEG_{bf}$ and $EEG_{\\sigma}$')\n_ = plt.xlim(0, times[-1])",
"_____no_output_____"
]
],
[
[
"### Threshold 3: Moving RMS\n\nThe third and last threshold is defined by computing a moving [root mean square](https://en.wikipedia.org/wiki/Root_mean_square) (RMS) of $\\text{EEG}_{\\sigma}$, with a window size of 300 ms and a step of 100 ms. The purpose of this threshold is simply to detect increase of energy in the $\\text{EEG}_{\\sigma}$ signal. As before, the values are interpolated using cubic interpolation to obtain one value per each time point. The third threshold is exceeded whenever a sample has a $\\text{RMS} \\geq \\text{RMS}_{\\text{thresh}}$, the latter being defined as:\n\n$\\text{RMS}_{\\text{thresh}} = \\text{RMS}_{\\text{mean}} + 1.5 \\times \\text{RMS}_{\\text{std}}$\n\nNote that the 10% lowest and 10% highest values are removed from the RMS signal before computing the standard deviation ($\\text{RMS}_{\\text{std}}$). This reduces the bias caused by potential artifacts and/or extreme values.",
"_____no_output_____"
]
],
[
[
"t, mrms = yasa.main.moving_transform(data_sigma, data, sf, window=.3, step=.1, method='rms', interp=True)\n\n# Define threshold\ntrimmed_std = yasa.main.trimbothstd(mrms, cut=0.025)\nthresh_rms = mrms.mean() + 1.5 * trimmed_std\n\nplt.figure(figsize=(14, 4))\nplt.plot(times, mrms)\nplt.xlabel('Time (seconds)')\nplt.ylabel('Root mean square')\nplt.axhline(thresh_rms, ls=':', lw=2, color='indianred', label='Threshold #3')\nplt.legend()\nplt.title('Moving RMS of $EEG_{\\sigma}$')\n_ = plt.xlim(0, times[-1])",
"_____no_output_____"
]
],
[
[
"### Decision function\nEvery sample of the data that validate all 3 thresholds is considered as a potential sleep spindle. However, the detection using the three thresholds tends to underestimate the real duration of the spindle. To overcome this, we compute a soft threshold by smoothing the decision vector with a 100 ms window. We then find indices in the decision vector that are strictly greater than 2. In other words, we find\nthe *true* beginning and *true* end of the events by finding the indices at which two out of the three treshold were crossed.",
"_____no_output_____"
]
],
[
[
"# Combine all three threholds\nidx_rel_pow = (rel_pow >= 0.2).astype(int)\nidx_mcorr = (mcorr >= 0.65).astype(int)\nidx_mrms = (mrms >= 10).astype(int)\nidx_sum = (idx_rel_pow + idx_mcorr + idx_mrms).astype(int)\n\n# Soft threshold\nw = int(0.1 * sf)\nidx_sum = np.convolve(idx_sum, np.ones(w) / w, mode='same')\n\nplt.figure(figsize=(14, 4))\nplt.plot(times, idx_sum, '.-', markersize=5)\nplt.fill_between(times, 2, idx_sum, where=idx_sum > 2, color='indianred', alpha=.8)\nplt.xlabel('Time (seconds)')\nplt.ylabel('Number of passed thresholds')\nplt.title('Decision function')\n_ = plt.xlim(0, times[-1])",
"_____no_output_____"
]
],
[
[
"### Morphological criteria\n\nNow that we have our potential spindles candidates, we apply two additional steps to optimize the detection:\n1. Spindles that are too close to each other (less than 500 ms) are merged together\n2. Spindles that are either too short ($<0.5$ sec) or too long ($>2$ sec) are removed.",
"_____no_output_____"
]
],
[
[
"where_sp = np.where(idx_sum > 2)[0]\n\n# Merge events that are too close together\nwhere_sp = yasa.main._merge_close(where_sp, 500, sf)\n\n# Extract start, end, and duration of each spindle\nsp = np.split(where_sp, np.where(np.diff(where_sp) != 1)[0] + 1)\nidx_start_end = np.array([[k[0], k[-1]] for k in sp]) / sf\nsp_start, sp_end = idx_start_end.T\nsp_dur = sp_end - sp_start\n\n# Find events with good duration\ngood_dur = np.logical_and(sp_dur > 0.5, sp_dur < 2)\n\nprint(sp_dur, good_dur)",
"[0.69 0.145 0.795] [ True False True]\n"
]
],
[
[
"### Spindles properties\nFrom then, we can be pretty confident that our detected spindles are actually *true* sleep spindles.\n\nThe last step of the algorithm is to extract, for each individual spindle, several properties:\n- Start and end time in seconds\n- Duration (seconds)\n- Amplitude ($\\mu V$)\n- Root mean square ($\\mu V$)\n- Median absolute power ($\\log_{10} \\mu V^2$)\n- Median relative power (from 0 to 1, % $\\mu V^2$)\n- Median frequency (Hz, extracted with an Hilbert transform)\n- Number of oscillations\n- Index of the most prominent peak (in seconds)\n- Symmetry (indicates where is the most prominent peak on a 0 to 1 vector where 0 is the beginning of the spindles and 1 the end. Ideally it should be around 0.5)\n\nIn the example below, we plot the two detected spindles and compute the peak-to-peak amplitude of the spindles.\nTo see how the other properties are computed, please refer to the [source code](https://github.com/raphaelvallat/yasa/blob/master/yasa/main.py) of the `spindles_detect` function.",
"_____no_output_____"
]
],
[
[
"from scipy.signal import detrend\n\nsp_amp = np.zeros(len(sp))\n\nplt.figure(figsize=(8, 4))\n\nfor i in np.arange(len(sp))[good_dur]:\n # Important: detrend the spindle signal to avoid wrong peak-to-peak amplitude\n sp_det = detrend(data[sp[i]], type='linear')\n \n # Now extract the peak to peak amplitude\n sp_amp[i] = np.ptp(sp_det) # Peak-to-peak amplitude\n\n # And plot the spindles\n plt.plot(np.arange(sp_det.size) / sf, sp_det,\n lw=2, label='Spindle #' + str(i+1))\n\nplt.legend()\nplt.xlabel('Time (sec)')\nplt.ylabel('Amplitude ($uV$)')\n\nprint('Peak-to-peak amplitude:\\t', sp_amp)",
"Peak-to-peak amplitude:\t [ 85.2111293 0. 106.32701275]\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aa978e83030aeeb8f073656afb3dc890333e48b
| 2,609 |
ipynb
|
Jupyter Notebook
|
00_core.ipynb
|
arunabha4k/test_app
|
f1d5d952f60dae63976dc568ce70ccd3218da8e0
|
[
"Apache-2.0"
] | null | null | null |
00_core.ipynb
|
arunabha4k/test_app
|
f1d5d952f60dae63976dc568ce70ccd3218da8e0
|
[
"Apache-2.0"
] | null | null | null |
00_core.ipynb
|
arunabha4k/test_app
|
f1d5d952f60dae63976dc568ce70ccd3218da8e0
|
[
"Apache-2.0"
] | null | null | null | 17.993103 | 164 | 0.466846 |
[
[
[
"# default_exp core",
"_____no_output_____"
]
],
[
[
"# Core\n\n> API details.",
"_____no_output_____"
]
],
[
[
"#hide\nfrom nbdev.showdoc import *",
"_____no_output_____"
],
[
"#export\ndef say_hello(to):\n \"\"\"Say hello to somebody!\"\"\"\n return f'Hello {to}!'",
"_____no_output_____"
],
[
"print(say_hello('me'))\nassert(say_hello('me')=='Hello me!')",
"Hello me!\n"
],
[
"show_doc(say_hello)",
"_____no_output_____"
],
[
"#export\ndef add(a, b):\n \"\"\"adding two numbers\"\"\"\n return a+b",
"_____no_output_____"
],
[
"assert(add(2,3)==5)",
"_____no_output_____"
],
[
"from nbdev.export import notebook2script\nnotebook2script()",
"Converted 00_core.ipynb.\nConverted index.ipynb.\n"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aa979050572fdd71e71741b7b59d3830b527744
| 451,622 |
ipynb
|
Jupyter Notebook
|
document-clustering/backup/cluster_analysis.ipynb
|
DisenWang/data-analysis-tutorials
|
cd747be4aedbbcc1eec7718a04497e844acc8a7a
|
[
"MIT"
] | 1 |
2021-01-14T14:32:20.000Z
|
2021-01-14T14:32:20.000Z
|
document-clustering/backup/cluster_analysis.ipynb
|
DisenWang/data-analysis-tutorials
|
cd747be4aedbbcc1eec7718a04497e844acc8a7a
|
[
"MIT"
] | 2 |
2020-09-12T10:45:18.000Z
|
2020-09-12T10:45:18.000Z
|
document-clustering/backup/cluster_analysis.ipynb
|
DisenWang/data-analysis-tutorials
|
cd747be4aedbbcc1eec7718a04497e844acc8a7a
|
[
"MIT"
] | 2 |
2020-04-21T15:09:00.000Z
|
2020-12-01T07:27:10.000Z
| 203.800542 | 168,391 | 0.818186 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4aa97b622144adb86b2af6757cc67dcad6df0382
| 5,033 |
ipynb
|
Jupyter Notebook
|
FeatureCollection/column_statistics.ipynb
|
kylebarron/earthengine-py-notebooks
|
4e9e3bae244fb66284f77c264f19aa297fb0fea1
|
[
"MIT"
] | null | null | null |
FeatureCollection/column_statistics.ipynb
|
kylebarron/earthengine-py-notebooks
|
4e9e3bae244fb66284f77c264f19aa297fb0fea1
|
[
"MIT"
] | null | null | null |
FeatureCollection/column_statistics.ipynb
|
kylebarron/earthengine-py-notebooks
|
4e9e3bae244fb66284f77c264f19aa297fb0fea1
|
[
"MIT"
] | null | null | null | 26.489474 | 234 | 0.593086 |
[
[
[
"# Pydeck Earth Engine Introduction\n\nThis is an introduction to using [Pydeck](https://pydeck.gl) and [Deck.gl](https://deck.gl) with [Google Earth Engine](https://earthengine.google.com/) in Jupyter Notebooks.",
"_____no_output_____"
],
[
"If you wish to run this locally, you'll need to install some dependencies. Installing into a new Conda environment is recommended. To create and enter the environment, run:\n```\nconda create -n pydeck-ee -c conda-forge python jupyter notebook pydeck earthengine-api requests -y\nsource activate pydeck-ee\njupyter nbextension install --sys-prefix --symlink --overwrite --py pydeck\njupyter nbextension enable --sys-prefix --py pydeck\n```\nthen open Jupyter Notebook with `jupyter notebook`.",
"_____no_output_____"
],
[
"Now in a Python Jupyter Notebook, let's first import required packages:",
"_____no_output_____"
]
],
[
[
"from pydeck_earthengine_layers import EarthEngineLayer\nimport pydeck as pdk\nimport requests\nimport ee",
"_____no_output_____"
]
],
[
[
"## Authentication\n\nUsing Earth Engine requires authentication. If you don't have a Google account approved for use with Earth Engine, you'll need to request access. For more information and to sign up, go to https://signup.earthengine.google.com/.",
"_____no_output_____"
],
[
"If you haven't used Earth Engine in Python before, you'll need to run the following authentication command. If you've previously authenticated in Python or the command line, you can skip the next line.\n\nNote that this creates a prompt which waits for user input. If you don't see a prompt, you may need to authenticate on the command line with `earthengine authenticate` and then return here, skipping the Python authentication.",
"_____no_output_____"
]
],
[
[
"try:\n ee.Initialize()\nexcept Exception as e:\n ee.Authenticate()\n ee.Initialize()",
"_____no_output_____"
]
],
[
[
"## Create Map\n\nNext it's time to create a map. Here we create an `ee.Image` object",
"_____no_output_____"
]
],
[
[
"# Initialize objects\nee_layers = []\nview_state = pdk.ViewState(latitude=37.7749295, longitude=-122.4194155, zoom=10, bearing=0, pitch=45)",
"_____no_output_____"
],
[
"# %%\n# Add Earth Engine dataset\nfromFT = ee.FeatureCollection(\"users/wqs/Pipestem/Pipestem_HUC10\")\ngeom = fromFT.geometry()\nee_layers.append(EarthEngineLayer(ee_object=ee.Image().paint(geom,0,2), vis_params={}))\n\nprint(fromFT.aggregate_stats('AreaSqKm'))\n\ntotal_area = fromFT.reduceColumns(**{\n 'reducer': ee.Reducer.sum(),\n 'selectors': ['AreaSqKm']\n # weightSelectors: ['weight']\n}).getInfo()\n\nprint(\"Total area: \", total_area)\n\n\n",
"_____no_output_____"
]
],
[
[
"Then just pass these layers to a `pydeck.Deck` instance, and call `.show()` to create a map:",
"_____no_output_____"
]
],
[
[
"r = pdk.Deck(layers=ee_layers, initial_view_state=view_state)\nr.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aa97d8e2175dad0283c313f9b2f9b114ccc50dd
| 15,570 |
ipynb
|
Jupyter Notebook
|
Practice/adapter_roberta/tutorial/06_Text_Generation_gpt2_chinese.ipynb
|
accordproject/labs-cicero-classify
|
3a52ebaf45252515c417bf94a05e33fc1c2628b8
|
[
"Apache-2.0"
] | 2 |
2021-07-07T01:06:18.000Z
|
2021-11-12T18:54:21.000Z
|
Practice/adapter_roberta/tutorial/06_Text_Generation_gpt2_chinese.ipynb
|
accordproject/labs_cicero_classify
|
3a52ebaf45252515c417bf94a05e33fc1c2628b8
|
[
"Apache-2.0"
] | 3 |
2021-06-25T12:40:23.000Z
|
2022-02-14T13:42:30.000Z
|
Practice/adapter_roberta/tutorial/06_Text_Generation_gpt2_chinese.ipynb
|
accordproject/labs_cicero_classify
|
3a52ebaf45252515c417bf94a05e33fc1c2628b8
|
[
"Apache-2.0"
] | null | null | null | 28.516484 | 292 | 0.542582 |
[
[
[
"First we need to download the dataset. In this case we use a datasets containing poems. By doing so we train the model to create its own poems.",
"_____no_output_____"
]
],
[
[
"from datasets import load_dataset\n\ndataset = load_dataset(\"poem_sentiment\")\nprint(dataset)",
"Using custom data configuration default\nReusing dataset poem_sentiment (/home/eason/.cache/huggingface/datasets/poem_sentiment/default/1.0.0/4e44428256d42cdde0be6b3db1baa587195e91847adabf976e4f9454f6a82099)\n"
]
],
[
[
"Before training we need to preprocess the dataset. We tokenize the entries in the dataset and remove all columns we don't need to train the adapter.",
"_____no_output_____"
]
],
[
[
"from transformers import BertTokenizer, GPT2LMHeadModel, TextGenerationPipeline\n\ntokenizer = BertTokenizer.from_pretrained(\"uer/gpt2-chinese-cluecorpussmall\")",
"_____no_output_____"
],
[
"from transformers import GPT2Tokenizer\n\ndef encode_batch(batch):\n \"\"\"Encodes a batch of input data using the model tokenizer.\"\"\"\n encoding = tokenizer(batch[\"verse_text\"])\n # For language modeling the labels need to be the input_ids\n #encoding[\"labels\"] = encoding[\"input_ids\"]\n return encoding\n\n#tokenizer = GPT2Tokenizer.from_pretrained(\"gpt2\")\n#tokenizer.pad_token = tokenizer.eos_token\n\n# The GPT-2 tokenizer does not have a padding token. In order to process the data \n# in batches we set one here \ncolumn_names = dataset[\"train\"].column_names\ndataset = dataset.map(encode_batch, remove_columns=column_names, batched=True)\n\n",
"_____no_output_____"
]
],
[
[
"Next we concatenate the documents in the dataset and create chunks with a length of `block_size`. This is beneficial for language modeling.",
"_____no_output_____"
]
],
[
[
"block_size = 50\n# Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.\ndef group_texts(examples):\n # Concatenate all texts.\n concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}\n total_length = len(concatenated_examples[list(examples.keys())[0]])\n # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can\n # customize this part to your needs.\n total_length = (total_length // block_size) * block_size\n # Split by chunks of max_len.\n result = {\n k: [t[i : i + block_size] for i in range(0, total_length, block_size)]\n for k, t in concatenated_examples.items()\n }\n result[\"labels\"] = result[\"input_ids\"].copy()\n return result\n\ndataset = dataset.map(group_texts,batched=True,)\n\ndataset.set_format(type=\"torch\", columns=[\"input_ids\", \"attention_mask\", \"labels\"])",
"_____no_output_____"
]
],
[
[
"Next we create the model and add our new adapter.Let's just call it `poem` since it is trained to create new poems. Then we activate it and prepare it for training.",
"_____no_output_____"
]
],
[
[
"from transformers import AutoModelForCausalLM\n\nmodel = AutoModelForCausalLM.from_pretrained(\"uer/gpt2-chinese-cluecorpussmall\")",
"_____no_output_____"
],
[
"\n# add new adapter\nmodel.add_adapter(\"poem\")\n# activate adapter for training\nmodel.train_adapter(\"poem\")",
"_____no_output_____"
]
],
[
[
"The last thing we need to do before we can start training is create the trainer. As trainingsargumnénts we choose a learningrate of 1e-4. Feel free to play around with the paraeters and see how they affect the result.",
"_____no_output_____"
]
],
[
[
"from transformers import Trainer, TrainingArguments\ntraining_args = TrainingArguments(\n output_dir=\"./examples\", \n do_train=True,\n remove_unused_columns=False,\n learning_rate=5e-4,\n num_train_epochs=3,\n)\n\n\ntrainer = Trainer(\n model=model,\n args=training_args,\n tokenizer=tokenizer,\n train_dataset=dataset[\"train\"],\n eval_dataset=dataset[\"validation\"], \n )",
"_____no_output_____"
],
[
"trainer.train()",
"/home/eason/data/anaconda3/envs/adapter/lib/python3.7/site-packages/torch/nn/parallel/_functions.py:65: UserWarning: Was asked to gather along dimension 0, but all input tensors were scalars; will instead unsqueeze and return a vector.\n warnings.warn('Was asked to gather along dimension 0, but all '\n"
]
],
[
[
"Now that we have a trained udapter we save it for future usage.",
"_____no_output_____"
]
],
[
[
"PREFIX = \"what a \"",
"_____no_output_____"
],
[
"encoding = tokenizer(PREFIX, return_tensors=\"pt\")\nencoding = encoding.to(model.device)\noutput_sequence = model.generate(\n input_ids=encoding[\"input_ids\"][:,:-1],\n attention_mask=encoding[\"attention_mask\"][:,:-1],\n do_sample=True,\n num_return_sequences=5,\n max_length = 50,\n)",
"Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.\n"
]
],
[
[
"Lastly we want to see what the model actually created. Too de this we need to decode the tokens from ids back to words and remove the end of sentence tokens. You can easily use this code with an other dataset. Don't forget to share your adapters at [AdapterHub](https://adapterhub.ml/).",
"_____no_output_____"
]
],
[
[
" for generated_sequence_idx, generated_sequence in enumerate(output_sequence):\n print(\"=== GENERATED SEQUENCE {} ===\".format(generated_sequence_idx + 1))\n generated_sequence = generated_sequence.tolist()\n\n # Decode text\n text = tokenizer.decode(generated_sequence, clean_up_tokenization_spaces=True)\n # Remove EndOfSentence Tokens\n text = text[: text.find(tokenizer.pad_token)]\n\n print(text)",
"=== GENERATED SEQUENCE 1 ===\n[CLS] what a little wonder does [SEP] [CLS] within that worst [SEP] [CLS] that is a truth. [SEP] [CLS] truth was in trup. and he bed a spread : [SEP] [CLS] and fa\n=== GENERATED SEQUENCE 2 ===\n[CLS] what a great mother, [SEP] [CLS] and i have your broos or not that! this, whose stranged, [SEP] [CLS] and that even bleed to [SEP] [CLS] in their time to do the poo\n=== GENERATED SEQUENCE 3 ===\n[CLS] what a snow father below : in folin , like noone , he likeed means on which a snow ; [SEP] [CLS] their eyes of your growt , and likely grown \n=== GENERATED SEQUENCE 4 ===\n[CLS] what a situations to me, [SEP] [CLS] with me, [SEP] [CLS] what a worrys is, and they't [SEP] [CLS] that there'' their name and i mugul! when, the eagle th\n=== GENERATED SEQUENCE 5 ===\n[CLS] what a sack when quink [SEP] [CLS] the mercies seed [UNK] while in the moon, [SEP] [CLS] and my father i will looking be a seats and the dar, [SEP] [CLS] a sea'\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aa982e22cf1f00d3fa1da5379a742b2455b21e3
| 9,214 |
ipynb
|
Jupyter Notebook
|
experiments_mxnet/SynFlow/synflow-syntheticdata.ipynb
|
zhangtj1996/ParaACE
|
a0a6658c9520a1c71f26be98af8d5c63a8886689
|
[
"Apache-2.0"
] | 2 |
2022-03-08T02:07:59.000Z
|
2022-03-28T18:10:56.000Z
|
experiments_mxnet/SynFlow/synflow-syntheticdata.ipynb
|
zhangtj1996/ParaACE
|
a0a6658c9520a1c71f26be98af8d5c63a8886689
|
[
"Apache-2.0"
] | null | null | null |
experiments_mxnet/SynFlow/synflow-syntheticdata.ipynb
|
zhangtj1996/ParaACE
|
a0a6658c9520a1c71f26be98af8d5c63a8886689
|
[
"Apache-2.0"
] | null | null | null | 36.856 | 122 | 0.54504 |
[
[
[
"import numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nfrom Utils import load\nfrom Utils import generator\nfrom Utils import metrics\nfrom train import *\nfrom prune import *\nfrom Layers import layers",
"_____no_output_____"
],
[
"from torch.nn import functional as F\nimport torch.nn as nn\ndef fc(input_shape, nonlinearity=nn.ReLU()):\n size = np.prod(input_shape)\n\n # Linear feature extractor\n modules = [nn.Flatten()]\n modules.append(layers.Linear(size, 5000))\n modules.append(nonlinearity)\n modules.append(layers.Linear(5000, 900))\n modules.append(nonlinearity)\n modules.append(layers.Linear(900, 400))\n modules.append(nonlinearity)\n modules.append(layers.Linear(400, 100))\n modules.append(nonlinearity) \n modules.append(layers.Linear(100, 30))\n modules.append(nonlinearity)\n modules.append(layers.Linear(30, 1))\n\n model = nn.Sequential(*modules)\n\n return model",
"_____no_output_____"
],
[
"\nfrom data import *\nfrom models import *\nfrom utils import *\nfrom sklearn.model_selection import KFold\nimport os, shutil, pickle\nctx = mx.gpu(0) if mx.context.num_gpus() > 0 else mx.cpu(0)\n\nloss_before_prune=[]\nloss_after_prune=[]\nloss_prune_posttrain=[]\nNUM_PARA=[]\nfor datasetindex in range(10):#[0,1,4,5,6,7,8,9]:\n dataset=str(datasetindex)+'.csv'\n X, y= get_data(dataset)\n\n np.random.seed(0) \n kf = KFold(n_splits=5,random_state=0,shuffle=True)\n kf.get_n_splits(X)\n seed=0#[0,1,2,3,4]\n chosenarmsList=[]\n for train_index, test_index in kf.split(X):\n X_tr, X_te = X[train_index], X[test_index]\n y_tr, y_te = y[train_index], y[test_index]\n X_test=nd.array(X_te).as_in_context(ctx) # Fix test data for all seeds\n y_test=nd.array(y_te).as_in_context(ctx)\n factor=np.max(y_te)-np.min(y_te) #normalize RMSE\n print(factor)\n #X_tr, X_te, y_tr, y_te = get_data(0.2,0)\n #selected_interaction = detectNID(X_tr,y_tr,X_te,y_te,test_size,seed)\n #index_Subsets=get_interaction_index(selected_interaction)\n \n N=X_tr.shape[0]\n p=X_tr.shape[1]\n batch_size=500\n n_epochs=300\n if N<250:\n batch_size=50\n X_train=nd.array(X_tr).as_in_context(ctx)\n y_train=nd.array(y_tr).as_in_context(ctx)\n train_dataset = ArrayDataset(X_train, y_train)\n# num_workers=4\n train_data = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)#,num_workers=num_workers)\n #X_test=nd.array(X_te).as_in_context(ctx)\n #y_test=nd.array(y_te).as_in_context(ctx)\n \n \n print('start training FC')\n FCnet=build_FC(train_data,ctx) # initialize the overparametrized network\n FCnet.load_parameters('Selected_models/FCnet_'+str(datasetindex)+'_seed_'+str(seed),ctx=ctx)\n \n import torch.nn as nn\n model=fc(10) \n loss = nn.MSELoss()\n dataset=torch.utils.data.TensorDataset(torch.Tensor(X_tr),torch.Tensor(y_tr))\n for i in range(6):\n model[int(i*2+1)].weight.data=torch.Tensor(FCnet[i].weight.data().asnumpy())\n model[int(i*2+1)].bias.data=torch.Tensor(FCnet[i].bias.data().asnumpy())\n \n \n print(\"dataset:\",datasetindex,\"seed\",seed)\n print(\"before prune:\",torch.sqrt(torch.mean((model(torch.Tensor(X_te))-torch.Tensor(y_te))**2))/factor)\n loss_before_prune.append(torch.sqrt(loss(model(torch.Tensor(X_te)),torch.Tensor(y_te)))/factor) \n print(torch.sqrt(loss(model(torch.Tensor(X_te)),torch.Tensor(y_te)))/factor)\n # Prune ##\n\n device = torch.device(\"cpu\")\n prune_loader = load.dataloader(dataset, 64, True, 4, 1)\n prune_epochs=10\n print('Pruning with {} for {} epochs.'.format('synflow', prune_epochs))\n pruner = load.pruner('synflow')(generator.masked_parameters(model, False, False, False))\n sparsity = 10**(-float(2.44715803134)) #280X #100X 10**(-float(2))\n\n prune_loop(model, loss, pruner, prune_loader, device, sparsity, \n 'exponential', 'global', prune_epochs, False, False, False, False)\n\n pruner.apply_mask()\n\n\n print(\"after prune:\",torch.sqrt(loss(model(torch.Tensor(X_te)),torch.Tensor(y_te)))/factor)\n loss_after_prune.append(torch.sqrt(loss(model(torch.Tensor(X_te)),torch.Tensor(y_te)))/factor)\n ## post_train\n\n train_loader = load.dataloader(dataset, 64, True, 4)\n test_loader = load.dataloader(dataset, 200 , False, 4)\n optimizer = torch.optim.Adam(generator.parameters(model), betas=(0.9, 0.99))\n\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer,milestones=[30,80], gamma=0.1)\n\n post_result = train_eval_loop(model, loss, optimizer, scheduler, train_loader, \n test_loader, device, 100, True) \n\n print(\"after post_train:\",torch.sqrt(loss(model(torch.Tensor(X_te)),torch.Tensor(y_te)))/factor)\n loss_prune_posttrain.append(torch.sqrt(loss(model(torch.Tensor(X_te)),torch.Tensor(y_te)))/factor)\n\n num=0\n for i in pruner.masked_parameters:\n num=num+sum(sum(i[0]))\n print(num)\n NUM_PARA.append(num)\n seed=seed+1\n \n import mxnet.gluon.nn as nn\n\n",
"_____no_output_____"
],
[
"##synflow results 280X\na=0\nfor i in range(10):\n print(sum(loss_prune_posttrain[5*i:5*i+5])/5)\n a=a+sum(loss_prune_posttrain[5*i:5*i+5])/5\nprint(\"ave:\",a/10)",
"tensor(0.0254, grad_fn=<DivBackward0>)\ntensor(0.0483, grad_fn=<DivBackward0>)\ntensor(0.0339, grad_fn=<DivBackward0>)\ntensor(0.0349, grad_fn=<DivBackward0>)\ntensor(0.0394, grad_fn=<DivBackward0>)\ntensor(0.0314, grad_fn=<DivBackward0>)\ntensor(0.0151, grad_fn=<DivBackward0>)\ntensor(0.0179, grad_fn=<DivBackward0>)\ntensor(0.0263, grad_fn=<DivBackward0>)\ntensor(0.0218, grad_fn=<DivBackward0>)\nave: tensor(0.0294, grad_fn=<DivBackward0>)\n"
],
[
"##synflow results 100X\na=0\nfor i in range(10):\n print(sum(loss_prune_posttrain[5*i:5*i+5])/5)\n a=a+sum(loss_prune_posttrain[5*i:5*i+5])/5\nprint(\"ave:\",a/10)",
"tensor(0.0260, grad_fn=<DivBackward0>)\ntensor(0.0503, grad_fn=<DivBackward0>)\ntensor(0.0372, grad_fn=<DivBackward0>)\ntensor(0.0394, grad_fn=<DivBackward0>)\ntensor(0.0383, grad_fn=<DivBackward0>)\ntensor(0.0344, grad_fn=<DivBackward0>)\ntensor(0.0150, grad_fn=<DivBackward0>)\ntensor(0.0185, grad_fn=<DivBackward0>)\ntensor(0.0275, grad_fn=<DivBackward0>)\ntensor(0.0218, grad_fn=<DivBackward0>)\nave: tensor(0.0308, grad_fn=<DivBackward0>)\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code"
]
] |
4aa98e7eba3b3a2fffbca480ec03bd613c3533d5
| 4,214 |
ipynb
|
Jupyter Notebook
|
quora/kernels/quora-1-nb-sklearn.ipynb
|
alexandru-dinu/kaggle
|
9db0de112ef6d630541bb77f769f71797fb5a4cd
|
[
"MIT"
] | null | null | null |
quora/kernels/quora-1-nb-sklearn.ipynb
|
alexandru-dinu/kaggle
|
9db0de112ef6d630541bb77f769f71797fb5a4cd
|
[
"MIT"
] | 1 |
2019-04-23T12:25:39.000Z
|
2019-04-25T20:26:21.000Z
|
quora/kernels/quora-1-nb-sklearn.ipynb
|
alexandru-dinu/kaggle
|
9db0de112ef6d630541bb77f769f71797fb5a4cd
|
[
"MIT"
] | null | null | null | 24.934911 | 97 | 0.586379 |
[
[
[
"import numpy as np\nimport pandas as pd\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\n\nfrom functools import reduce\nimport random\nimport re\nfrom tqdm import tqdm_notebook as tqdm",
"_____no_output_____"
],
[
"DATA_DIR = \"../input\"\nTRAIN_CSV = f\"{DATA_DIR}/train.csv\"\nTEST_CSV = f\"{DATA_DIR}/test.csv\"\n\ntrain_df = pd.read_csv(TRAIN_CSV)\ntest_df = pd.read_csv(TEST_CSV)\n\nprint(f\"Train shape: {train_df.shape}; cols: {list(train_df.columns)}\")\nprint(f\"Test shape: {test_df.shape}; cols: {list(test_df.columns)}\")",
"_____no_output_____"
],
[
"# randomly show a train example\nlist(train_df.iloc[random.randint(0, len(train_df))])",
"_____no_output_____"
]
],
[
[
"### Data analysis",
"_____no_output_____"
]
],
[
[
"sincere = train_df.loc[train_df['target'] == 0]\ninsincere = train_df.loc[train_df['target'] == 1]\n\nprint(insincere.iloc[random.randint(0, len(insincere))]['question_text'])\n\nprint(f\"Sincere: {len(sincere)} ({round(100.0 * len(sincere)/len(train_df), 3)}%)\")\nprint(f\"Insincere: {len(insincere)} ({round(100.0 * len(insincere)/len(train_df), 3)}%)\")",
"_____no_output_____"
]
],
[
[
"### Naive Bayes\n",
"_____no_output_____"
]
],
[
[
"count_vect = CountVectorizer()\ntrain_counts = count_vect.fit_transform(train_df.question_text)\nprint(train_counts.shape)\n\nmodel = MultinomialNB(alpha=1)\nmodel.fit(train_counts, train_df.target)",
"_____no_output_____"
],
[
"test_counts = count_vect.transform((\"this car is a nice car\",))\npred = model.predict(test_counts)\nprint(\"Insincere\" if pred.data[0] == 1 else \"Sincere\")",
"_____no_output_____"
],
[
"test_counts = count_vect.transform(test_df.question_text)\npreds = model.predict(test_counts).astype(int)",
"_____no_output_____"
],
[
"submission = pd.DataFrame.from_dict({\n 'qid': test_df['qid'],\n 'prediction': preds\n})\n\nsubmission.to_csv('submission.csv', index=False)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4aa9abadaa6cea08eadcbdf66394b74869749426
| 4,354 |
ipynb
|
Jupyter Notebook
|
cs224w/one1.ipynb
|
kidrabit/Data-Visualization-Lab-RND
|
baa19ee4e9f3422a052794e50791495632290b36
|
[
"Apache-2.0"
] | 1 |
2022-01-18T01:53:34.000Z
|
2022-01-18T01:53:34.000Z
|
cs224w/one1.ipynb
|
kidrabit/Data-Visualization-Lab-RND
|
baa19ee4e9f3422a052794e50791495632290b36
|
[
"Apache-2.0"
] | null | null | null |
cs224w/one1.ipynb
|
kidrabit/Data-Visualization-Lab-RND
|
baa19ee4e9f3422a052794e50791495632290b36
|
[
"Apache-2.0"
] | null | null | null | 45.354167 | 1,698 | 0.593018 |
[
[
[
"class LSTM(nn.Module):\n def __init__(self, input_size, output_size = 1, hidden_size = 10, hidden_num = 2):\n super(LSTM, self).__init__()\n self.input_size = input_size\n self.output_size = output_size\n self.hidden_size = hidden_size\n self.hidden_num = hidden_num\n\n self.hidden = self.init_hidden()\n\n self.relu = nn.ReLU()\n self.lstm1 = nn.LSTM(self.input_size, self.hidden_size)\n self.lstm2 = nn.LSTM(self.hidden_size, self.hidden_size)\n self.linear = nn.Conv1d(self.hidden_size,1,1)\n\n def init_hidden(self):\n return (torch.zeros(1, self.hidden_size, 1),\n torch.zeros(1, self.hidden_size, 1))\n\n\n def forward(self, x):\n x, self.hidden = self.lstm1(x, self.hidden)\n x = self.relu(x)\n for i in range(self.hidden_num):\n x, self.hidden = self.lstm2(x, self.hidden)\n x = self.relu(x)\n\n pred = self.linear(x.transpose(2,1))\n\n return pred",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
4aa9af62130bf0e28aa7055a577abeb5e0a1e865
| 217,725 |
ipynb
|
Jupyter Notebook
|
ecu_fingerprint_classification.ipynb
|
vermakun/UMD-SS21-ECE-5831-ECU-Fingerprinting
|
0ab99af123d48f56a7c78891a649c6da1cb485a4
|
[
"BSD-3-Clause"
] | null | null | null |
ecu_fingerprint_classification.ipynb
|
vermakun/UMD-SS21-ECE-5831-ECU-Fingerprinting
|
0ab99af123d48f56a7c78891a649c6da1cb485a4
|
[
"BSD-3-Clause"
] | null | null | null |
ecu_fingerprint_classification.ipynb
|
vermakun/UMD-SS21-ECE-5831-ECU-Fingerprinting
|
0ab99af123d48f56a7c78891a649c6da1cb485a4
|
[
"BSD-3-Clause"
] | null | null | null | 140.016077 | 31,798 | 0.802985 |
[
[
[
"# In-Vehicle Security using Pattern Recognition Techniques\n---\n*ECE 5831 - 08/17/2021 - Kunaal Verma*",
"_____no_output_____"
],
[
"The goal of this project is to train a machine learning model to recognize unique signatures of each ECU in order to identify when intrusive messages are being fed to the network.\n\nThe dataset for this project consists of several time-series recordings of clock pulses produced by several ECUs on an in-vehicle CAN High network.\n\nThe test network has 8 trusted ECUs, with 30 records of 600 samples of the clock signal for each ECU.\n",
"_____no_output_____"
],
[
"# I. Initialization",
"_____no_output_____"
]
],
[
[
"### I. Initialization ###\nprint('--- Intialize ---')\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport re\nimport seaborn as sn\nimport sklearn.metrics as sm\n\nfrom google.colab import drive\ndrive.mount('/content/drive')",
"--- Intialize ---\nMounted at /content/drive\n"
]
],
[
[
"# II. File Pre-conditioning\n",
"_____no_output_____"
]
],
[
[
"### II. File Pre-conditioning ###\nprint('\\n--- Pre-condition Files ---\\n')\n\n# Dataset path\ndatapath = 'drive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset'\n# datapath = './Dataset'\n\nprint('Path to Dataset:')\nprint(datapath)\n\n# List of files in directory, append to list recursively\nfile_list = []\nfor path, folders, files in os.walk(datapath):\n for file in files:\n file_list.append(os.path.join(path, file))\n\n# Sort file list by record number, but use a copy that contains leading zeros\nfile_list0 = []\nfor filename in file_list:\n m = re.search('_[0-9]\\.', filename)\n if m:\n found = m.group(0)\n filename = re.sub('_[0-9]\\.', found[0] + '0' + found[1:-1] + '.', filename)\n file_list0.append(filename)\n\nfile_list1 = dict(zip(file_list0,file_list))\nfile_list2 = dict(sorted(file_list1.items(), key = lambda x:x[0]))\n\n# Produce sorted file lists\nfile_list = list(file_list2.values()) # Original list, properly sorted\nfile_list0 = list(file_list2.keys()) # Modified list with leading zeros, sorted\n\n# Remove CAN5 items (CAN1 and CAN5 were made purposely similar, this is not realistic in real-world CAN networks)\nfile_list = [i for i in file_list if re.search(\"CAN5_2m_Thick_uns1\", i) == None]\nfile_list0 = [i for i in file_list0 if re.search(\"CAN5_2m_Thick_uns1\", i) == None]\n\nprint('\\nAbsolute Paths to Records (Subset):')\n# for filename in file_list[0:10]:\nfor filename in file_list:\n print(filename)",
"\n--- Pre-condition Files ---\n\nPath to Dataset:\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset\n\nAbsolute Paths to Records (Subset):\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_1.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_2.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_3.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_4.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_5.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_6.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_7.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_8.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_9.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_10.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_11.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_12.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_13.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_14.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_15.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_16.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_17.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_18.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_19.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_20.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_21.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_22.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_23.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_24.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_25.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_26.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_27.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_28.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_29.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_30.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_2.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_3.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_4.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_5.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_6.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_7.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_8.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_9.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_10.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_11.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_12.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_13.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_14.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_15.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_16.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_17.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_18.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_19.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_20.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_21.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_22.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_23.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_24.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_25.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_26.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_27.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_28.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_29.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_30.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_1.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_2.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_3.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_4.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_5.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_6.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_7.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_8.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_9.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_10.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_11.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_12.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_13.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_14.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_15.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_16.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_17.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_18.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_19.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_20.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_21.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_22.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_23.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_24.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_25.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_26.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_27.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_28.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_29.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_30.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_1.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_2.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_3.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_4.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_5.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_6.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_7.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_8.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_9.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_10.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_11.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_12.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_13.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_14.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_15.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_16.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_17.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_18.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_19.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_20.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_21.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_22.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_23.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_24.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_25.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_26.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_27.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_28.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_29.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_30.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_1.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_2.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_3.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_4.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_5.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_6.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_7.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_8.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_9.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_10.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_11.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_12.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_13.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_14.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_15.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_16.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_17.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_18.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_19.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_20.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_21.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_22.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_23.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_24.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_25.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_26.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_27.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_28.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_29.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN91_2m_Silver_uns1/CAN10_TypeD2_auns1_30.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_1.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_2.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_3.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_4.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_5.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_6.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_7.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_8.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_9.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_10.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_11.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_12.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_13.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_14.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_15.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_16.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_17.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_18.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_19.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_20.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_21.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_22.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_23.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_24.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_25.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_26.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_27.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_28.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_29.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN92_6m_Silver_uns1/CAN10_TypeD6_auns1_30.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_1.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_2.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_3.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_4.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_5.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_6.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_7.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_8.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_9.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_10.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_11.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_12.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_13.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_14.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_15.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_16.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_17.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_18.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_19.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_20.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_21.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_22.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_23.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_24.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_25.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_26.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_27.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_28.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_29.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN93_10m_Silver_uns1/CAND_10_auns1_30.csv\n"
]
],
[
[
"# III. Feature Extraction\n\n",
"_____no_output_____"
]
],
[
[
"### III. Feature Extraction ###\nprint('\\n--- Extract Features ---\\n')\n\n!cp '/content/drive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/github/ecu_fingerprint_lib.py' .\nfrom ecu_fingerprint_lib import Record\n\npkl_path = './ecu_fingerprint.pkl'\n\nif os.path.exists(pkl_path):\n\n df = pd.read_pickle(pkl_path)\n \nelse:\n\n # Dict instantiation\n d = {}\n\n # Iteratively build data dictionary\n for i in np.arange(len(file_list0)):\n\n filepath = file_list[i]\n filepath0 = file_list0[i]\n\n print(filepath)\n\n # Extract folder name of current record\n folder = os.path.basename(os.path.dirname(filepath0))\n filename = os.path.basename(filepath0)\n\n # Extract record identifiers\n id, pl, pm, did = folder.split('_')\n filename = re.split(r'_|\\.',filename)\n\n # Open File\n with open(filepath) as file_name:\n array = np.loadtxt(file_name, delimiter=\",\")\n \n # Extract Features\n r = Record(array)\n \n # Add Features and File Attributes to Dict\n if i == 0:\n # File Metadata\n d['Filepath'] = []\n d['CAN_Id'] = []\n d['CAN_PhyLen'] = []\n d['CAN_PhyMat'] = []\n d['CAN_RecId'] = []\n # Feature Data\n for feature_name in r.headers:\n d[feature_name] = []\n\n # Build data table\n for k in np.arange(r.total_rec):\n for j in np.arange(len(r.headers)):\n d[r.headers[j]].append(r.features[j][k])\n d['Filepath'].append(filepath)\n d['CAN_Id'].append(id)\n d['CAN_PhyLen'].append(pl)\n d['CAN_PhyMat'].append(pm)\n d['CAN_RecId'].append(filename[-2])\n\n df = pd.DataFrame.from_dict(d)\n df.to_pickle(pkl_path)\n\nprint('\\nDataFrame Object:\\n')\nprint(df.info())",
"\n--- Extract Features ---\n\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_1.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_2.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_3.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_4.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_5.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_6.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_7.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_8.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_9.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_10.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_11.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_12.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_13.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_14.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_15.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_16.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_17.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_18.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_19.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_20.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_21.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_22.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_23.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_24.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_25.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_26.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_27.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_28.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_29.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN1_2m_Thin_uns1/CAN1Aauns1_30.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_2.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_3.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_4.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_5.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_6.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_7.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_8.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_9.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_10.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_11.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_12.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_13.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_14.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_15.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_16.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_17.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_18.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_19.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_20.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_21.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_22.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_23.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_24.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_25.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_26.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_27.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_28.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_29.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN2_6m_Thin_uns1/CAN2A_ECU10_auns1_30.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_1.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_2.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_3.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_4.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_5.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_6.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_7.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_8.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_9.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_10.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_11.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_12.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_13.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_14.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_15.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_16.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_17.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_18.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_19.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_20.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_21.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_22.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_23.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_24.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_25.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_26.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_27.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_28.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_29.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN3_10m_Thin_uns1/CAN5uns1_30.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_1.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_2.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_3.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_4.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_5.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_6.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_7.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_8.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_9.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_10.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_11.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_12.csv\ndrive/MyDrive/School/UMich Dearborn/SS21/ECE 5831/Project/Dataset/CAN6_6m_Thick_uns1/CAN8A_ECU8_auns1_13.csv\n"
]
],
[
[
"# IV. Prepare Training and Test Datasets",
"_____no_output_____"
]
],
[
[
"### IV. Prepare Traininf and Test Datasets ###\nprint('\\n--- Training and Test Datasets ---\\n')\n\n# Attribute and Label Datasets\n\n## Full, Dom, Rec\nX = df.iloc[:,5:] # Full feature set 0.0%\n\ny = df.iloc[:,1]\n\n# Change Labels from Categorical to Numerical values\n\nfrom sklearn import preprocessing\nle = preprocessing.LabelEncoder()\nY = le.fit_transform(y)\n\n# Train-Test Split (70/30)\n\nfrom sklearn.model_selection import train_test_split\n# X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=4) # Apples to Apples Debugging\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3)\n\n# Feature Scaling\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nscaler.fit(X_train)\n\nX_train = scaler.transform(X_train)\nX_test = scaler.transform(X_test)\n\nprint('Training Input:\\n')\nprint(' %s: %s' %(X_train.dtype, X_train.shape))\nprint('\\nTraining Output:\\n')\nprint(' %s: %s' %(Y_train.dtype, Y_train.shape))\nprint('\\nTest Input:\\n')\nprint(' %s: %s' %(X_test.dtype, X_test.shape))\nprint('\\nTest Output:\\n')\nprint(' %s: %s' %(Y_test.dtype, Y_test.shape))",
"\n--- Training and Test Datasets ---\n\nTraining Input:\n\n float64: (576, 35)\n\nTraining Output:\n\n int64: (576,)\n\nTest Input:\n\n float64: (248, 35)\n\nTest Output:\n\n int64: (248,)\n"
]
],
[
[
"# V. Train Neural Network",
"_____no_output_____"
]
],
[
[
"### V. Train Neural Network ###\nprint('\\n--- Neural Network Training ---\\n')\n\nfrom sklearn.neural_network import MLPClassifier\nmlp = MLPClassifier(hidden_layer_sizes=([3*len(df),]), max_iter=2000)\nmlp.fit(X_train, Y_train.ravel())\nY_pred = mlp.predict(X_test)\nprint('Hidden Layer Nodes: ',len(mlp.coefs_[1]))\nprint('Neural Network Solver: ',mlp.solver)",
"\n--- Neural Network Training ---\n\nHidden Layer Nodes: 2472\nNeural Network Solver: adam\n"
]
],
[
[
"# VI. Produce Confusion Matrix",
"_____no_output_____"
]
],
[
[
"### VI. Produce Confusion Matrix ###\nprint('\\n--- Confusion Matrix ---\\n')\n\ncm = sm.confusion_matrix(Y_test, Y_pred)\ntr = cm.size # Total Records\nnp.sum(cm, axis=0) # Column Sum (Horizontal Result)\nnp.sum(cm, axis=1) # Row Sum (Vertical Result)\nnp.trace(cm) # Diagonal Sum (Total Result)\n\nlabels = [re.sub('CAN', 'Class', i) for i in y.unique()]\ndf_cm = pd.DataFrame(cm, labels, labels)\nsn.set(font_scale=1.4) # for label size\nsn.heatmap(df_cm, annot=True, annot_kws={\"size\": 12}) # font size\nplt.xlabel(\"Prediction\", fontsize = 12)\nplt.ylabel(\"Actual\", fontsize = 12)\n\nplt.show()\n\nprint('')\nprint(cm)",
"\n--- Confusion Matrix ---\n\n"
],
[
"labels = [re.sub('CAN', 'Class', i) for i in y.unique()]\n\ndf_cm = pd.DataFrame(cm, labels, labels)\nsn.set(font_scale=1.4) # for label size\nsn.heatmap(df_cm, annot=True, annot_kws={\"size\": 12}) # font size\nplt.xlabel(\"Prediction\", fontsize = 12)\nplt.ylabel(\"Actual\", fontsize = 12)",
"_____no_output_____"
]
],
[
[
"# VII. Evaluate Peformance Metrics",
"_____no_output_____"
]
],
[
[
"### VII. Evaluate Performance Metrics ###\nprint('\\n--- Performance Metrics ---\\n')\n\ndef perf_metrics(cm, report=False):\n\n cm_acc = []\n cm_pre = []\n cm_rec = []\n cm_f1s = []\n cm_err = []\n\n if report:\n print('[ ECU_Id | Accuracy | Precision | Recall | F1 Score | Error ]')\n print('=========|==========|===========|========|==========|========')\n\n for i in np.arange(len(cm)):\n cm_working = cm.copy()\n idx = np.concatenate((np.arange(0,i),np.arange(-len(cm)+i+1,0)))\n\n tp = cm_working[i,i]\n fn = cm_working[i,idx]; fn = np.sum(fn)\n fp = cm_working[idx,i]; fp = np.sum(fp)\n\n cm_working[i,i] = 0\n cm_working[i,idx] = 0\n cm_working[idx,i] = 0\n\n tn = np.sum(cm_working)\n\n acc = (tp + tn)/(tp + tn + fp + fn)\n err = 1-acc\n pre = tp/(tp + fp)\n rec = tp/(tp + fn)\n f1s = 2*(pre*rec)/(pre+rec)\n\n cm_acc.append(acc)\n cm_pre.append(pre)\n cm_rec.append(rec)\n cm_f1s.append(f1s)\n cm_err.append(err)\n\n if report:\n print('[%7s | %8.3f | %9.3f | %6.3f | %8.3f | %5.3f ]' \\\n % (y.unique()[i], acc, pre, rec, f1s, err))\n\n return cm_acc, cm_pre, cm_rec, cm_f1s, cm_err\n\nacc, pre, rec, f1s, err = perf_metrics(cm, True)\n\n# Plot results\n\nbw = 0.15 # Box plot bar width\n\np1 = np.arange(len(acc)) # Category x-axis positions\np2 = [x + bw for x in p1]\np3 = [x + bw for x in p2]\np4 = [x + bw for x in p3]\np5 = [x + bw for x in p4]\n\nprint('') \nplt.bar(p1, acc, width=bw)\nplt.bar(p2, pre, width=bw)\nplt.bar(p3, rec, width=bw)\nplt.bar(p4, f1s, width=bw)\nplt.bar(p5, err, width=bw)\n \nplt.xticks([p + bw for p in range(len(acc))], y.unique(), fontsize = 10)\nplt.legend(['Accuracy','Precision','Recall','F1 Score','Error'], fontsize = 10, bbox_to_anchor = (1, 0.67))",
"\n--- Performance Metrics ---\n\n[ ECU_Id | Accuracy | Precision | Recall | F1 Score | Error ]\n=========|==========|===========|========|==========|========\n[ CAN1 | 0.958 | 0.731 | 0.792 | 0.760 | 0.042 ]\n[ CAN2 | 0.993 | 0.950 | 1.000 | 0.974 | 0.007 ]\n[ CAN3 | 1.000 | 1.000 | 1.000 | 1.000 | 0.000 ]\n[ CAN5 | 0.958 | 0.878 | 0.837 | 0.857 | 0.042 ]\n[ CAN6 | 1.000 | 1.000 | 1.000 | 1.000 | 0.000 ]\n[ CAN91 | 0.979 | 0.889 | 0.941 | 0.914 | 0.021 ]\n[ CAN92 | 0.986 | 1.000 | 0.889 | 0.941 | 0.014 ]\n[ CAN93 | 1.000 | 1.000 | 1.000 | 1.000 | 0.000 ]\n\n"
]
],
[
[
"# Appendix I. Neural Network Hyperparameter Testing",
"_____no_output_____"
]
],
[
[
"### IV. Prepare Training and Test Datasets ###\nprint('\\n--- Training and Test Datasets ---\\n')\n\n# Attribute and Label Datasets\n\n## Full, Spectral, Contrl, Dom, Rec Acc %\n# X = df.iloc[:,5:] # Full feature set 98.76%\n# X = df.iloc[:,[12,13,14,15,16,17,18,19,20,21,22,23,24,32,33,34,35,36,37,38,39]] # Spectral Only 97.26%\n# X = df.iloc[:,[5,6,7,8,9,10,11,25,26,27,28,29,30,31]] # Control Only 97.17%\n# X = df.iloc[:, 5:24] # Dominant Only 98.14%\n# X = df.iloc[:,25:39] # Recessive Only 96.73%\n\n## Spectral Features (sorted by Accuracy)\n# X = df.iloc[:,[22,37]] # SNR 95.23%\n# X = df.iloc[:,[23,38]] # Mean Freq 94.96%\n# X = df.iloc[:,[12,13,14,15,16,17,18,19,20,21,32,33,34,35,36]] # Spectral Density 92.93%\n# X = df.iloc[:,[24,39]] # Median Freq 91.34%\n\n## Spectral Features (added by rank)\n# X = df.iloc[:,[22,37]] # SNR 95.23% [ ]\n# X = df.iloc[:,[22,23,37,38]] # + Mean Freq 97.35% [+] <<<\n# X = df.iloc[:,[12,13,14,15,16,17,18,19,20,21,22,23,32,33,34,35,36,37,38]] # + Spectral Density 97.26% [-]\n# X = df.iloc[:,[12,13,14,15,16,17,18,19,20,21,22,23,32,33,34,35,36,37,38]] # + Median Freq 97.26% [-]\n\n## Control Features (sorted by Accuracy)\n# X = df.iloc[:,[ 8,28]] # Steady State Value 95.23%\n# X = df.iloc[:,[ 9,29]] # Steady State Error 95.05%\n# X = df.iloc[:,[ 6,26]] # Percent Overshoot 91.52%\n# X = df.iloc[:,[ 7,27]] # Settling Time 91.52%\n# X = df.iloc[:,[10,30]] # Rise Time 83.48%\n# X = df.iloc[:,[11,31]] # Delay Time 81.89%\n# X = df.iloc[:,[ 5,25]] # Peak Time 80.12%\n\n## Control Features (added by rank)\n# X = df.iloc[:,[8,28]] # SSV 95.23% [ ]\n# X = df.iloc[:,[8,9,28,29]] # + SSE 97.70% [+]\n# X = df.iloc[:,[6,8,9,26,28,29]] # + %OS 98.32% [+] <<<\n# X = df.iloc[:,[6,7,8,9,26,27,28,29]] # + Ts 98.32% [=]\n# X = df.iloc[:,[6,7,8,9,10,26,27,28,29,30]] # + Tr 97.26 [-]\n# X = df.iloc[:,[6,7,8,9,10,11,26,27,28,29,30,31]] # + Td 97.17% [-]\n# X = df.iloc[:,[ 5,25]] # + Tp 97.17% [=]\n\n## All Features (added by rank)\n# X = df.iloc[:,[22,37]] # SNR 95.23% [ ]\n# X = df.iloc[:,[8,22,28,37]] # + SSV 97.53% [+]\n# X = df.iloc[:,[8,9,22,28,29,37]] # + SSE 97.97% [+]\n# X = df.iloc[:,[8,9,22,23,28,29,37,38]] # + Mean Freq. 98.59% [+]\n# X = df.iloc[:,[6,8,9,22,23,26,28,29,37,38]] # + %OS 98.94% [+] <<<\n# X = df.iloc[:,[6,7,8,9,22,23,26,27,28,29,37,38]] # + Ts 98.85% [-]\n# X = df.iloc[:,[6,7,8,9,22,23,24,26,27,28,29,37,38,39]] # + Med. Freq. 98.67% [-]\n# X = df.iloc[:,[6,8,9,12,13,14,15,16,17,18,19,20,21,22,23,26,28,29,32,33,34,35,36,37,38]] # + SD 98.32% [-]\n# X = df.iloc[:,[10,30]] # + Tr ...\n# X = df.iloc[:,[11,31]] # + Td ...\n# X = df.iloc[:,[ 5,25]] # + Tp ...\n\n## Final Feature Set: (Control) SSV, SSE, %OS (Spectral) SNR, Mean Freq.\nX = df.iloc[:,[6,8,9,22,23,26,28,29,37,38]] # 99.36%\n\n# Testing Results\ny = df.iloc[:,1]\n\n# Change Labels from Categorical to Numerical values\nfrom sklearn import preprocessing\nle = preprocessing.LabelEncoder()\nY = le.fit_transform(y)\n\n# Train-Test Split (70/30)\nfrom sklearn.model_selection import train_test_split\n# X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=0) # Apples to Apples Debugging\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nscaler.fit(X_train)\n\nX_train = scaler.transform(X_train)\nX_test = scaler.transform(X_test)\n\n# Print Training/Test Set Details\nprint('Training Input:\\n')\nprint(' %s: %s' %(X_train.dtype, X_train.shape))\nprint('\\nTraining Output:\\n')\nprint(' %s: %s' %(Y_train.dtype, Y_train.shape))\nprint('\\nTest Input:\\n')\nprint(' %s: %s' %(X_test.dtype, X_test.shape))\nprint('\\nTest Output:\\n')\nprint(' %s: %s' %(Y_test.dtype, Y_test.shape))\n\n### V. Train Neural Network ###\nprint('\\n--- Neural Network Training ---\\n')\n\nfrom sklearn.neural_network import MLPClassifier\n\nhls = 1000\nmit = 3000\n\nmlp = MLPClassifier(hidden_layer_sizes=([hls,]), max_iter=mit)\nmlp.fit(X_train, Y_train.ravel())\nY_pred = mlp.predict(X_test)\nprint('Hidden Layer Nodes: ',len(mlp.coefs_[1]))\nprint('Neural Network Solver: ',mlp.solver)\n\n### VI. Produce Confusion Matrix ###\nprint('\\n--- Confusion Matrix ---\\n')\n\ncm = sm.confusion_matrix(Y_test, Y_pred)\ntr = cm.size # Total Records\nnp.sum(cm, axis=0) # Column Sum (Horizontal Result)\nnp.sum(cm, axis=1) # Row Sum (Vertical Result)\nnp.trace(cm) # Diagonal Sum (Total Result)\n\n# labels = [re.sub('CAN', 'Class', i) for i in y.unique()]\nlabels = [\"Class%i\" % i for i in 1 + np.arange(len(y.unique()))]\ndf_cm = pd.DataFrame(cm, labels, labels)\nsn.set(font_scale=1.4) # for label size\nsn.heatmap(df_cm, annot=True, annot_kws={\"size\": 12}) # font size\nplt.xlabel(\"Prediction\", fontsize = 12)\nplt.ylabel(\"Actual\", fontsize = 12)\n\nplt.show()\n\nprint('')\nprint(cm)\n\n### VII. Evaluate Performance Metrics ###\nprint('\\n--- Performance Metrics ---\\n')\n\ndef perf_metrics(cm, report=False):\n\n cm_acc = []\n cm_pre = []\n cm_rec = []\n cm_f1s = []\n cm_err = []\n\n if report:\n print('[ ECU_Id | Accuracy | Precision | Recall | F1 Score | Error ]')\n print('=========|==========|===========|========|==========|========')\n\n for i in np.arange(len(cm)):\n cm_working = cm.copy()\n idx = np.concatenate((np.arange(0,i),np.arange(-len(cm)+i+1,0)))\n\n tp = cm_working[i,i]\n fn = cm_working[i,idx]; fn = np.sum(fn)\n fp = cm_working[idx,i]; fp = np.sum(fp)\n\n cm_working[i,i] = 0\n cm_working[i,idx] = 0\n cm_working[idx,i] = 0\n\n tn = np.sum(cm_working)\n\n acc = (tp + tn)/(tp + tn + fp + fn)\n err = 1-acc\n pre = tp/(tp + fp)\n rec = tp/(tp + fn)\n f1s = 2*(pre*rec)/(pre+rec)\n\n cm_acc.append(acc)\n cm_pre.append(pre)\n cm_rec.append(rec)\n cm_f1s.append(f1s)\n cm_err.append(err)\n\n if report:\n print('[%7s | %8.3f | %9.3f | %6.3f | %8.3f | %5.3f ]' \\\n % (y.unique()[i], acc, pre, rec, f1s, err))\n\n return cm_acc, cm_pre, cm_rec, cm_f1s, cm_err\n\nacc, pre, rec, f1s, err = perf_metrics(cm, True)\n\n# Plot results\n\nbw = 0.15 # Box plot bar width\n\np1 = np.arange(len(acc)) # Category x-axis positions\np2 = [x + bw for x in p1]\np3 = [x + bw for x in p2]\np4 = [x + bw for x in p3]\np5 = [x + bw for x in p4]\n\nprint('') \nplt.bar(p1, acc, width=bw)\nplt.bar(p2, pre, width=bw)\nplt.bar(p3, rec, width=bw)\nplt.bar(p4, f1s, width=bw)\nplt.bar(p5, err, width=bw)\n \nplt.xticks([p + bw for p in range(len(acc))], y.unique(), fontsize = 10)\nplt.legend(['Accuracy','Precision','Recall','F1 Score','Error'], fontsize = 10, bbox_to_anchor = (1, 0.67))\n\nacc_avg = np.average(acc)*100\npre_avg = np.average(pre)*100\nrec_avg = np.average(rec)*100\nf1s_avg = np.average(f1s)*100\nerr_avg = np.average(err)*100\n\nprint('%2.2f %2.2f %2.2f %2.2f %2.2f' % (acc_avg, pre_avg, rec_avg, f1s_avg, err_avg))",
"\n--- Training and Test Datasets ---\n\nTraining Input:\n\n float64: (576, 10)\n\nTraining Output:\n\n int64: (576,)\n\nTest Input:\n\n float64: (248, 10)\n\nTest Output:\n\n int64: (248,)\n\n--- Neural Network Training ---\n\nHidden Layer Nodes: 1000\nNeural Network Solver: adam\n\n--- Confusion Matrix ---\n\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aa9bb5d5585d5447ca5cc8c1a8eaa7c75b52131
| 572,499 |
ipynb
|
Jupyter Notebook
|
normalizingflows(colab files)/results/nyc_taxi/combi_nyc_results.ipynb
|
MathiasNT/Thesis_Density_Estimation_w_Normalizing_Flows
|
d541c226c53d74214102b5dec7bb793b1f23740b
|
[
"MIT"
] | null | null | null |
normalizingflows(colab files)/results/nyc_taxi/combi_nyc_results.ipynb
|
MathiasNT/Thesis_Density_Estimation_w_Normalizing_Flows
|
d541c226c53d74214102b5dec7bb793b1f23740b
|
[
"MIT"
] | null | null | null |
normalizingflows(colab files)/results/nyc_taxi/combi_nyc_results.ipynb
|
MathiasNT/Thesis_Density_Estimation_w_Normalizing_Flows
|
d541c226c53d74214102b5dec7bb793b1f23740b
|
[
"MIT"
] | null | null | null | 572,499 | 572,499 | 0.950803 |
[
[
[
"# Description\nThis notebook compares the results of training a Conditional Normalizing Flow model on the synthetic two moons data. The data have rotation and moon class as conditioning variables.\n\nThe comparison is between a base flow with no regularization at all and adding in Clipped Adam and Batchnormalization.\n\nLots of different hyperparamters are tested to see if we can get batch normalization to work",
"_____no_output_____"
],
[
"# Base loads",
"_____no_output_____"
]
],
[
[
"!pip install pyro-ppl==1.3.0",
"Collecting pyro-ppl==1.3.0\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/f6/97/42073ec6cc550f6bf1e3982ded454500c657ee2a3fd2dd6886984c8d4ca2/pyro_ppl-1.3.0-py3-none-any.whl (495kB)\n\u001b[K |████████████████████████████████| 501kB 2.8MB/s \n\u001b[?25hRequirement already satisfied: torch>=1.4.0 in /usr/local/lib/python3.6/dist-packages (from pyro-ppl==1.3.0) (1.5.0+cu101)\nCollecting pyro-api>=0.1.1\n Downloading https://files.pythonhosted.org/packages/fc/81/957ae78e6398460a7230b0eb9b8f1cb954c5e913e868e48d89324c68cec7/pyro_api-0.1.2-py3-none-any.whl\nRequirement already satisfied: numpy>=1.7 in /usr/local/lib/python3.6/dist-packages (from pyro-ppl==1.3.0) (1.18.5)\nRequirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from pyro-ppl==1.3.0) (3.2.1)\nRequirement already satisfied: tqdm>=4.36 in /usr/local/lib/python3.6/dist-packages (from pyro-ppl==1.3.0) (4.41.1)\nRequirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from torch>=1.4.0->pyro-ppl==1.3.0) (0.16.0)\nInstalling collected packages: pyro-api, pyro-ppl\nSuccessfully installed pyro-api-0.1.2 pyro-ppl-1.3.0\n"
],
[
"!nvidia-smi",
"Sun Jun 14 21:50:59 2020 \n+-----------------------------------------------------------------------------+\n| NVIDIA-SMI 450.36.06 Driver Version: 418.67 CUDA Version: 10.1 |\n|-------------------------------+----------------------+----------------------+\n| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|===============================+======================+======================|\n| 0 Tesla P100-PCIE... Off | 00000000:00:04.0 Off | 0 |\n| N/A 47C P0 28W / 250W | 0MiB / 16280MiB | 0% Default |\n| | | ERR! |\n+-------------------------------+----------------------+----------------------+\n \n+-----------------------------------------------------------------------------+\n| Processes: |\n| GPU GI CI PID Type Process name GPU Memory |\n| ID ID Usage |\n|=============================================================================|\n| No running processes found |\n+-----------------------------------------------------------------------------+\n"
],
[
"# \"Standard\" imports\nimport numpy as np\nfrom time import time\nimport itertools\nimport matplotlib.pyplot as plt\nimport pickle\nimport os\nimport pandas as pd\nimport folium\nimport datetime\n\n# Pytorch imports\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch import optim\nfrom torch.utils.data import DataLoader\n\n# Pyro imports\nimport pyro\nfrom pyro.distributions import ConditionalTransformedDistribution, ConditionalTransformModule, TransformModule\nimport pyro.distributions as dist\nfrom pyro.distributions.transforms import affine_coupling, affine_autoregressive, permute\n\n# Sklearn imports\nfrom sklearn import datasets\nfrom sklearn.preprocessing import StandardScaler\n\n# Notebooks imports\nfrom IPython.display import Image, display, clear_output\nfrom tqdm import tqdm\nfrom ipywidgets import interact, interactive, fixed, interact_manual\nimport ipywidgets as widgets\n\n\nimport numpy as np\nimport folium\nfrom folium import plugins\nimport matplotlib\nimport seaborn as sns",
"/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n import pandas.util.testing as tm\n"
],
[
"# Mount my drive\nfrom google.colab import drive\nimport sys\nimport os\ndrive.mount('/content/drive/')\nroot_path = 'drive/My Drive/Colab_Notebooks/normalizingflows'\ntrained_flows_folder = 'drive/My Drive/Colab_Notebooks/normalizingflows/trained_flows'\nplot_folder = f'{root_path}/plot_notebooks/generated_plots'\ndataset_folder = 'drive/My Drive/Colab_Notebooks/normalizingflows/datasets'\nsys.path.append(root_path)",
"Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n\nEnter your authorization code:\n··········\nMounted at /content/drive/\n"
]
],
[
[
"## Load Git code",
"_____no_output_____"
]
],
[
[
"%cd drive/'My Drive'/Thesis/code/DEwNF/\n!git pull\n%cd /content/",
"/content/drive/My Drive/Thesis/code/DEwNF\nAlready up to date.\n/content\n"
],
[
"git_folder_path = 'drive/My Drive/Thesis/code/DEwNF/'\nsys.path.append(git_folder_path)",
"_____no_output_____"
],
[
"from DEwNF.flows import ConditionalAffineCoupling, ConditionedAffineCoupling, ConditionalNormalizingFlowWrapper, conditional_affine_coupling, normalizing_flow_factory, conditional_normalizing_flow_factory\nfrom DEwNF.utils import plot_4_contexts_cond_flow, plot_loss, sliding_plot_loss, plot_samples, simple_data_split_conditional, simple_data_split, circle_transform\nfrom DEwNF.samplers import RotatingTwoMoonsConditionalSampler\nfrom DEwNF.regularizers import NoiseRegularizer, rule_of_thumb_noise_schedule, approx_rule_of_thumb_noise_schedule, square_root_noise_schedule, constant_regularization_schedule\n",
"_____no_output_____"
]
],
[
[
"# Func def",
"_____no_output_____"
]
],
[
[
"def minMax(x):\n return pd.Series(index=['min','max'],data=[x.min(),x.max()])\n\ndef rescale_samples(plot_flow_dist, scaler, n_samples=256):\n x_s = plot_flow_dist.sample((n_samples,))\n if x_s.is_cuda:\n x_s = x_s.cpu()\n if scaler is not None:\n x_s = scaler.inverse_transform(x_s)\n return x_s\n\ndef add_marker_w_prob(coords, obs_scaler, flow_dist, hub_map, name):\n scaled_coords = obs_scaler.transform(np.flip(np.array([coords])))\n log_prob = flow_dist.log_prob(torch.tensor(scaled_coords).float().cuda()).cpu().detach().numpy()\n folium.CircleMarker(\n location=coords,\n popup=folium.Popup(f'{name} log likelihood: {log_prob}', show=False),\n icon=folium.Icon(icon='cloud')\n ).add_to(hub_map)\n\ndef create_overlay(shape, bounds, flow_dist, hub_map, cm, flip):\n with torch.no_grad():\n nlats, nlons = shape\n \n lats_array = torch.linspace(start=bounds[1][0], end=bounds[0][0], steps=nlats)\n lons_array = torch.linspace(start=bounds[0][1], end=bounds[1][1], steps=nlons)\n x, y = torch.meshgrid(lats_array, lons_array)\n\n points = torch.stack((x.reshape(-1), y.reshape(-1)), axis=1)\n\n if flip:\n points = points.flip(1)\n\n scaled_points = torch.tensor(obs_scaler.transform(points), requires_grad=False).float()\n\n data = flow_dist.log_prob(scaled_points.cuda()).reshape(nlats,nlons).cpu().detach().numpy()\n data = np.exp(data)\n overlay = cm(data)\n\n folium.raster_layers.ImageOverlay(\n image=overlay,\n bounds=bounds,\n mercator_project=False,\n opacity=0.75\n ).add_to(hub_map)\n\n return overlay\n\n\ndef plot_samples(samples, hub_map):\n\n for point in samples:\n folium.CircleMarker(\n location=point,\n radius=2,\n color='#3186cc',\n fill=True,\n fill_color='#3186cc',\n opacityb=0.1).add_to(hub_map)\n\n return hub_map",
"_____no_output_____"
]
],
[
[
"# Load planar conditional model",
"_____no_output_____"
]
],
[
[
"unconditional_path = os.path.join(root_path, \"results/nyc_taxi/combi/test_combi_fixed_bn\")",
"_____no_output_____"
],
[
"os.listdir(unconditional_path)",
"_____no_output_____"
],
[
"loaded_dicts = {}\n\nfolders = os.listdir(unconditional_path)\nfor run_name in folders:\n run_path = folder = os.path.join(unconditional_path, run_name)\n model_names = os.listdir(run_path)\n loaded_dicts[run_name] = {}\n for model_name in model_names:\n model_path = os.path.join(run_path, model_name)\n file = os.path.join(model_path)\n with open(file, 'rb') as f:\n loaded_dict = pickle.load(f)\n loaded_dicts[run_name][model_name] = loaded_dict\n \nruns = list(loaded_dicts.keys())\n#runs = ['reg_comparisons2']\nmodels = list(loaded_dicts[runs[0]].keys())\n\nresults_dict = {}\n\nfor model in models:\n results_dict[model] = {}\n runs_arr = []\n for run in runs:\n runs_arr.append(loaded_dicts[run][model]['logs']['test'][-1])\n results_dict[model]['mean'] = np.mean(runs_arr)\n results_dict[model]['max'] = np.max(runs_arr)\n results_dict[model]['min'] = np.min(runs_arr)\n\ncombi_conditional_dicts = loaded_dicts\ncombi_conditional_results = results_dict",
"_____no_output_____"
],
[
"combi_conditional_dicts['run1']['nyc_model_combi.pickle']['settings']",
"_____no_output_____"
]
],
[
[
"# Compare results",
"_____no_output_____"
]
],
[
[
"combi_conditional_results",
"_____no_output_____"
],
[
"plt.figure(figsize=(15,10))\nplt.plot(combi_conditional_dicts['run1']['nyc_model_combi.pickle']['logs']['test'])\nplt.plot(combi_conditional_dicts['run1']['nyc_model_combi.pickle']['logs']['no_noise_losses'], '--')\nplt.plot(combi_conditional_dicts['run1']['nyc_model_combi.pickle']['logs']['train'])\nplt.ylim((0,5))",
"_____no_output_____"
]
],
[
[
"# Model visualization\n",
"_____no_output_____"
],
[
"## planar cond model",
"_____no_output_____"
]
],
[
[
"nyc_data_small_path = f\"{dataset_folder}/NYC_yellow_taxi/processed_nyc_taxi_small.csv\"",
"_____no_output_____"
],
[
"nyc_data_small = pd.read_csv(nyc_data_small_path)\nobs_cols = ['dropoff_longitude', 'dropoff_latitude']\ncontext_cols = ['pickup_longitude', 'pickup_latitude', 'pickup_dow_sin', 'pickup_dow_cos',\n 'pickup_tod_sin', 'pickup_tod_cos']",
"_____no_output_____"
],
[
"train_dataloader, test_dataloader, obs_scaler, context_scaler= simple_data_split_conditional(df=nyc_data_small,\n obs_cols=obs_cols,\n context_cols=context_cols,\n batch_size=50000,\n cuda_exp=True)",
"_____no_output_____"
],
[
"combi_conditional_dicts[run]['nyc_model_combi.pickle']['settings']",
"_____no_output_____"
],
[
"x_bounds = [-74.04, -73.75]\ny_bounds = [40.62, 40.86]\n\nx_loc = np.mean(x_bounds)\ny_loc = np.mean(y_bounds)\n\nlower_left = [y_bounds[0], x_bounds[0]]\nupper_right = [y_bounds[1], x_bounds[1]]\nbounds = [lower_left, upper_right]\ninitial_location = [y_loc, x_loc]",
"_____no_output_____"
]
],
[
[
"# Conditional model",
"_____no_output_____"
]
],
[
[
"combi_cond_flow1 = combi_conditional_dicts['run1']['nyc_model_combi.pickle']['model']\ncombi_cond_flow2 = combi_conditional_dicts['run2']['nyc_model_combi.pickle']['model']\ncombi_cond_flow3 = combi_conditional_dicts['run3']['nyc_model_combi.pickle']['model']",
"_____no_output_____"
],
[
"combi_cond_flow1.dist.transforms",
"_____no_output_____"
],
[
"pickup_tod_cos, pickup_tod_sin = circle_transform(1,23)\npickup_dow_cos, pickup_dow_sin = circle_transform(1,6)\n\ncontext = np.array([[-7.38950000e+01, 4.07400000e+01, pickup_dow_sin, pickup_dow_cos, pickup_tod_sin, pickup_tod_cos]])\nprint(context)\n\nscaled_context = torch.tensor(context_scaler.transform(context)).type(torch.FloatTensor).cuda()\n#scaled_context = torch.tensor([-0.4450, 0.1878, -1.2765, -0.8224, 1.4222, -0.8806]).float().cuda()\n\ncond_dist = combi_cond_flow1.condition(scaled_context)",
"[[-73.895 40.74 0.8660254 0.5 0.26979677\n 0.96291729]]\n"
],
[
"def plot_func(hour, dayofweek, pickup_lat, pickup_lon, flow):\n # Made for the context order:\n #['pickup_longitude', 'pickup_latitude', 'pickup_dow_sin', 'pickup_dow_cos', 'pickup_tod_sin, 'pickup_tod_cos']\n\n flow.modules.eval()\n\n pickup_tod_cos, pickup_tod_sin = circle_transform(hour,23)\n pickup_dow_cos, pickup_dow_sin = circle_transform(dayofweek,6)\n\n context = np.array([[pickup_lon, pickup_lat, pickup_dow_sin, pickup_dow_cos, pickup_tod_sin, pickup_tod_cos]])\n print(context)\n\n scaled_context = torch.tensor(context_scaler.transform(context)).type(torch.FloatTensor).cuda()\n #scaled_context = torch.tensor([-0.4450, 0.1878, -1.2765, -0.8224, 1.4222, -0.8806]).float().cuda()\n\n cond_dist = flow.condition(scaled_context)\n\n \n x_bounds = [-74.04, -73.75]\n y_bounds = [40.62, 40.86]\n\n x_loc = np.mean(x_bounds)\n y_loc = np.mean(y_bounds)\n\n lower_left = [y_bounds[0], x_bounds[0]]\n upper_right = [y_bounds[1], x_bounds[1]]\n bounds = [lower_left, upper_right]\n initial_location = [y_loc, x_loc]\n hub_map = folium.Map(width=845,height=920,location=initial_location, zoom_start=12, zoom_control=False)\n\n\n cm = sns.cubehelix_palette(reverse=True, dark=0, light=1, gamma=0.8, as_cmap=True)\n\n create_overlay(shape=(800,800), bounds=bounds, flow_dist=cond_dist, hub_map=hub_map, cm=cm, flip=True)\n\n #samples = rescale_samples(cond_dist, obs_scaler, n_samples=1000)\n #plot_samples(samples, hub_map)\n\n\n folium.CircleMarker(\n location=[pickup_lat, pickup_lon],\n radius=2,\n color='#3186cc',\n fill=True,\n fill_color='#3186cc',\n opacityb=0.1).add_to(hub_map)\n\n # add log prob at JFC\n jfc_coords = [40.645587,-73.787536]\n add_marker_w_prob(coords=jfc_coords, obs_scaler=obs_scaler, flow_dist=cond_dist, hub_map=hub_map, name='JFC')\n\n # add log prob at LaGuardia\n lg_coords = [40.774277,-73.874258]\n add_marker_w_prob(coords=lg_coords, obs_scaler=obs_scaler, flow_dist=cond_dist, hub_map=hub_map, name='LaGuardia')\n\n\n display(hub_map)\n return hub_map",
"_____no_output_____"
],
[
"input_hour = 6\ninput_dayofweek = 1\ninput_pickup_lon =-73.89500000000001\ninput_pickup_lat = 40.739999999999995\n\nhub_map = plot_func(hour=input_hour, dayofweek=input_dayofweek, pickup_lat=input_pickup_lat, pickup_lon=input_pickup_lon, flow=combi_cond_flow3)\n",
"[[-7.38950000e+01 4.07400000e+01 8.66025404e-01 5.00000000e-01\n 9.97668769e-01 -6.82424134e-02]]\n"
],
[
"input_hour = 18\ninput_dayofweek = 1\ninput_pickup_lon =-73.983313\ninput_pickup_lat = 40.733348\n\nhub_map = plot_func(hour=input_hour, dayofweek=input_dayofweek, pickup_lat=input_pickup_lat, pickup_lon=input_pickup_lon, flow=combi_cond_flow3)\n\nhub_map.save(f'{plot_folder}/nyc_combi_cond_manhattan.html')\n",
"[[-73.983313 40.733348 0.8660254 0.5 -0.97908409\n 0.20345601]]\n"
],
[
"input_hour = 18\ninput_dayofweek = 1\ninput_pickup_lon =-73.983313\ninput_pickup_lat = 40.733348\n\nhub_map = plot_func(hour=input_hour, dayofweek=input_dayofweek, pickup_lat=input_pickup_lat, pickup_lon=input_pickup_lon, flow=combi_cond_flow2)\n\n",
"[[-73.983313 40.733348 0.8660254 0.5 -0.97908409\n 0.20345601]]\n"
],
[
"input_hour = 6\ninput_dayofweek = 5\ninput_pickup_lon =-73.983313\ninput_pickup_lat = 40.733348\n\nhub_map = plot_func(hour=input_hour, dayofweek=input_dayofweek, pickup_lat=input_pickup_lat, pickup_lon=input_pickup_lon, flow=combi_cond_flow2)\n\n",
"[[-7.39833130e+01 4.07333480e+01 -8.66025404e-01 5.00000000e-01\n 9.97668769e-01 -6.82424134e-02]]\n"
],
[
"interactive_plot = interactive(plot_func,\n hour=(0,23),\n dayofweek=(0,6),\n pickup_lat=(y_bounds[0],y_bounds[1], 0.01),\n pickup_lon=(x_bounds[0],x_bounds[1], 0.01),\n flow=fixed(planar_cond_flow1)\n )\nhub_map = interactive_plot\ndisplay(hub_map)\n",
"_____no_output_____"
],
[
"input_hour = 17\ninput_dayofweek = 1\ninput_pickup_lon = -73.787536\ninput_pickup_lat = 40.645587\n\nhub_map = plot_func(hour=input_hour, dayofweek=input_dayofweek, pickup_lat=input_pickup_lat, pickup_lon=input_pickup_lon, flow=combi_cond_flow3)\nhub_map.save(f'{plot_folder}/nyc_combi_large_jfc.html')\n",
"[[-7.37875360e+01 4.06455870e+01 8.66025404e-01 5.00000000e-01\n -9.97668769e-01 -6.82424134e-02]]\n"
]
],
[
[
"# Path stuff 2",
"_____no_output_____"
]
],
[
[
"def plot_func(hour, dayofweek, pickup_lat, pickup_lon, flow):\n # Made for the context order:\n #['pickup_longitude', 'pickup_latitude', 'pickup_dow_sin', 'pickup_dow_cos', 'pickup_tod_sin, 'pickup_tod_cos']\n\n flow.modules.eval()\n\n pickup_tod_cos, pickup_tod_sin = circle_transform(hour,23)\n pickup_dow_cos, pickup_dow_sin = circle_transform(dayofweek,6)\n\n context = np.array([[pickup_lon, pickup_lat, pickup_dow_sin, pickup_dow_cos, pickup_tod_sin, pickup_tod_cos]])\n print(context)\n\n scaled_context = torch.tensor(context_scaler.transform(context)).type(torch.FloatTensor).cuda()\n #scaled_context = torch.tensor([-0.4450, 0.1878, -1.2765, -0.8224, 1.4222, -0.8806]).float().cuda()\n\n cond_dist = flow.condition(scaled_context)\n\n \n x_bounds = [-73.95, -73.75]\n y_bounds = [40.62, 40.86]\n\n x_loc = np.mean(x_bounds)\n y_loc = np.mean(y_bounds)\n\n lower_left = [y_bounds[0], x_bounds[0]]\n upper_right = [y_bounds[1], x_bounds[1]]\n bounds = [lower_left, upper_right]\n #initial_location = [40.739999999999995, -73.85]\n initial_location = [40.720999999999995, -73.855]\n hub_map = folium.Map(width=550,height=650,location=initial_location, zoom_start=12, zoom_control=False)\n\n\n cm = sns.cubehelix_palette(reverse=True, dark=0, light=1, gamma=0.8, as_cmap=True)\n\n create_overlay(shape=(800,800), bounds=bounds, flow_dist=cond_dist, hub_map=hub_map, cm=cm, flip=True)\n\n #samples = rescale_samples(cond_dist, obs_scaler, n_samples=1000)\n #plot_samples(samples, hub_map)\n\n\n folium.CircleMarker(\n location=[pickup_lat, pickup_lon],\n radius=2,\n color='#3186cc',\n fill=True,\n fill_color='#3186cc',\n opacityb=0.1).add_to(hub_map)\n\n # add log prob at JFC\n jfc_coords = [40.645587,-73.787536]\n add_marker_w_prob(coords=jfc_coords, obs_scaler=obs_scaler, flow_dist=cond_dist, hub_map=hub_map, name='JFC')\n\n # add log prob at LaGuardia\n lg_coords = [40.774277,-73.874258]\n add_marker_w_prob(coords=lg_coords, obs_scaler=obs_scaler, flow_dist=cond_dist, hub_map=hub_map, name='LaGuardia')\n\n train_station1 = [40.6586078,-73.8052761]\n folium.CircleMarker(\n location=train_station1,\n radius=2,\n color='#3186cc',\n fill=True,\n fill_color='#3186cc',\n opacityb=0.1).add_to(hub_map)\n\n train_station2 = [40.6612707,-73.8294946]\n folium.CircleMarker(\n location=train_station2,\n radius=2,\n color='#3186cc',\n fill=True,\n fill_color='#3186cc',\n opacityb=0.1).add_to(hub_map)\n\n\n display(hub_map)\n return hub_map",
"_____no_output_____"
],
[
"input_hour = 18\ninput_dayofweek = 1\ninput_pickup_lon =-73.983313\ninput_pickup_lat = 40.733348\n\nhub_map = plot_func(hour=input_hour, dayofweek=input_dayofweek, pickup_lat=input_pickup_lat, pickup_lon=input_pickup_lon, flow=combi_cond_flow3)\n\nhub_map.save(f'{plot_folder}/nyc_combi_manhattan_path.html')\n",
"[[-73.983313 40.733348 0.8660254 0.5 -0.97908409\n 0.20345601]]\n"
],
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4aa9cc81bc030715d730e90ad6f3a0eb681053c4
| 56,733 |
ipynb
|
Jupyter Notebook
|
notebooks/03_MPDATA_error_analysis.ipynb
|
atmos-cloud-sim-uj/MoAC
|
4d342391020ceb4b6cb392259da30d70c52a0ee1
|
[
"CC-BY-4.0"
] | 3 |
2020-02-23T19:55:51.000Z
|
2020-08-17T18:56:34.000Z
|
notebooks/03_MPDATA_error_analysis.ipynb
|
atmos-cloud-sim-uj/MoAC
|
4d342391020ceb4b6cb392259da30d70c52a0ee1
|
[
"CC-BY-4.0"
] | null | null | null |
notebooks/03_MPDATA_error_analysis.ipynb
|
atmos-cloud-sim-uj/MoAC
|
4d342391020ceb4b6cb392259da30d70c52a0ee1
|
[
"CC-BY-4.0"
] | 1 |
2021-04-04T12:20:51.000Z
|
2021-04-04T12:20:51.000Z
| 226.027888 | 35,316 | 0.914054 |
[
[
[
"import numpy as np\nfrom matplotlib import pyplot",
"_____no_output_____"
],
[
"def flux(psi_l, psi_r, C):\n return .5 * (C + abs(C)) * psi_l + \\\n .5 * (C - abs(C)) * psi_r",
"_____no_output_____"
],
[
"def upwind(psi, i, C):\n return psi[i] - flux(psi[i ], psi[i+one], C[i]) + \\\n flux(psi[i-one], psi[i ], C[i-one])",
"_____no_output_____"
],
[
"def C_corr(C, nx, psi):\n j = slice(0, nx-1)\n return (abs(C[j]) - C[j]**2) * (psi[j+one] - psi[j]) / (psi[j+one] + psi[j] + 1e-10)",
"_____no_output_____"
],
[
"class shift:\n def __radd__(self, i): \n return slice(i.start+1, i.stop+1)\n def __rsub__(self, i): \n return slice(i.start-1, i.stop-1)\none = shift()",
"_____no_output_____"
],
[
"def psi_0(x):\n a = 25\n return np.where(np.abs(x)<np.pi/2*a, np.cos(x/a)**2, 0)",
"_____no_output_____"
],
[
"def plot(x, psi_0, psi_T_a, psi_T_n, n_corr_it):\n pyplot.step(x, psi_0, label='initial', where='mid')\n pyplot.step(x, psi_T_a, label='analytical', where='mid')\n pyplot.step(x, psi_T_n, label='numerical', where='mid')\n pyplot.grid()\n pyplot.legend()\n pyplot.title(f'MPDATA {n_corr_it} corrective iterations')\n pyplot.show()",
"_____no_output_____"
],
[
"def solve(nx=75, nt=50, n_corr_it=2, make_plot=False):\n T = 50\n x_min, x_max = -50, 250\n C = .1",
"_____no_output_____"
],
[
" dt = T / nt\n x, dx = np.linspace(x_min, x_max, nx, endpoint=False, retstep=True)\n v = C / dt * dx\n assert C <= 1\n i = slice(1, nx-2)\n C_phys = np.full(nx-1, C)\n psi = psi_0(x)\n \n for _ in range(nt):\n psi[i] = upwind(psi, i, C_phys)\n C_iter = C_phys\n for it in range(n_corr_it):\n C_iter = C_corr(C_iter, nx, psi)\n psi[i] = upwind(psi, i, C_iter)\n \n psi_true = psi_0(x-v*nt*dt)\n err = np.sqrt(sum(pow(psi-psi_true, 2)) / nt / nx)\n if make_plot:\n plot(x, psi_0(x), psi_T_a=psi_true, psi_T_n=psi, n_corr_it=n_corr_it)\n return dx, dt, err",
"_____no_output_____"
],
[
"solve(nx=150, nt=500, n_corr_it=0, make_plot=True)",
"_____no_output_____"
],
[
"for n_it in [0,1,2]:\n data = {'x':[], 'y':[]}\n for nx in range(600,1000,50):\n dx, dt, err = solve(nx=nx, nt=300, n_corr_it=n_it)\n data['x'].append(np.log2(dx))\n data['y'].append(np.log2(err))\n pyplot.scatter(data['x'], data['y'], label=f\"{n_it} corrective iters\")\n pyplot.plot(data['x'], data['y'])\n \ndef line(k, offset, label=False):\n pyplot.plot(\n data['x'], \n k*np.array(data['x']) + offset, \n label=f'$err \\sim dx^{k}$' if label else '', \n linestyle=':',\n color='black'\n )\nline(k=2, offset=-10.1, label=True)\nline(k=3, offset=-9.1, label=True)\n\nline(k=2, offset=-14)\nline(k=3, offset=-13)\n \npyplot.legend()\npyplot.gca().set_xlabel('$log_2(dx)$')\npyplot.gca().set_ylabel('$log_2(err)$')\npyplot.grid()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aa9d18783436a4de13ac2b10e3bd1ef6823922d
| 4,588 |
ipynb
|
Jupyter Notebook
|
exercises/boston_housing_classification_log_reg.ipynb
|
sturc/ds_bd
|
122ddb290c27d6a7e4d58c3b7fa55aa66085ef34
|
[
"Apache-2.0"
] | 1 |
2020-05-07T21:12:31.000Z
|
2020-05-07T21:12:31.000Z
|
exercises/boston_housing_classification_log_reg.ipynb
|
sturc/ds_bd
|
122ddb290c27d6a7e4d58c3b7fa55aa66085ef34
|
[
"Apache-2.0"
] | 1 |
2020-12-05T07:39:39.000Z
|
2020-12-05T07:39:39.000Z
|
exercises/boston_housing_classification_log_reg.ipynb
|
sturc/ds_bd
|
122ddb290c27d6a7e4d58c3b7fa55aa66085ef34
|
[
"Apache-2.0"
] | 1 |
2021-05-17T18:35:24.000Z
|
2021-05-17T18:35:24.000Z
| 22.94 | 132 | 0.552092 |
[
[
[
"# Boston Housing Classification Logistic Regression",
"_____no_output_____"
]
],
[
[
"import sys\nsys.path.append(\"..\")\nfrom pyspark.sql.types import BooleanType\nfrom pyspark.ml.feature import StringIndexer, VectorAssembler\nfrom pyspark.ml.classification import LogisticRegression\nfrom pyspark.sql.session import SparkSession\nfrom pyspark.sql.functions import expr\nfrom pyspark.ml.evaluation import BinaryClassificationEvaluator\nfrom helpers.path_translation import translate_to_file_string\nfrom helpers.data_prep_and_print import print_df",
"_____no_output_____"
],
[
"inputFile = translate_to_file_string(\"../data/Boston_Housing_Data.csv\")",
"_____no_output_____"
]
],
[
[
"Spark session creation ",
"_____no_output_____"
]
],
[
[
"spark = (SparkSession\n .builder \n .master(\"local\") \n .appName(\"BostonHousingClass\")\n .getOrCreate())",
"_____no_output_____"
]
],
[
[
"DataFrame creation using an ifered Schema ",
"_____no_output_____"
]
],
[
[
"df = spark.read.option(\"header\", \"true\") \\\n .option(\"inferSchema\", \"true\") \\\n .option(\"delimiter\", \";\") \\\n .csv(inputFile) \\\n .withColumn(\"CATBOOL\", expr(\"CAT\").cast(BooleanType()))\nprint(df.printSchema())",
"_____no_output_____"
]
],
[
[
"Prepare training and test data.",
"_____no_output_____"
]
],
[
[
"featureCols = df.columns.copy()\nfeatureCols.remove(\"MEDV\")\nfeatureCols.remove(\"CAT\")\nfeatureCols.remove(\"CATBOOL\") \nprint(featureCols)\n\nassembler = VectorAssembler(outputCol=\"features\", inputCols=featureCols)",
"_____no_output_____"
],
[
"labledPointDataSet = assembler.transform(df)\nsplits = labledPointDataSet.randomSplit([0.9, 0.1 ], 12345)\ntraining = splits[0]\ntest = splits[1]",
"_____no_output_____"
]
],
[
[
"Logistic regression",
"_____no_output_____"
]
],
[
[
"#TODO Optimize the paramters \nlr = LogisticRegression(labelCol=\"CAT\",featuresCol=\"features\", maxIter=100, \\\n regParam=0.5)",
"_____no_output_____"
]
],
[
[
"Train the model ",
"_____no_output_____"
]
],
[
[
"lrModel = lr.fit(training)",
"_____no_output_____"
]
],
[
[
"Test the model",
"_____no_output_____"
]
],
[
[
"predictions = lrModel.transform(test)\nprint_df(predictions,10)",
"_____no_output_____"
],
[
"evaluator = BinaryClassificationEvaluator(labelCol=\"CAT\",rawPredictionCol=\"rawPrediction\", metricName=\"areaUnderROC\")\naccuracy = evaluator.evaluate(predictions)\nprint(\"Test Error\",(1.0 - accuracy))",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4aa9d993b10e51cfa12836b5952be985ed0fdfe5
| 185,975 |
ipynb
|
Jupyter Notebook
|
Chapter03-web-crawlers.ipynb
|
QTYResources/python-scraping
|
d7afe25a012fb5d079ee42372c7fce94b9494b9f
|
[
"MIT"
] | 1 |
2019-07-11T16:25:15.000Z
|
2019-07-11T16:25:15.000Z
|
Chapter03-web-crawlers.ipynb
|
QTYResources/python-scraping
|
d7afe25a012fb5d079ee42372c7fce94b9494b9f
|
[
"MIT"
] | 8 |
2020-01-28T22:54:14.000Z
|
2022-02-10T00:17:47.000Z
|
Chapter03-web-crawlers.ipynb
|
QTYResources/python-scraping
|
d7afe25a012fb5d079ee42372c7fce94b9494b9f
|
[
"MIT"
] | 2 |
2019-03-21T15:11:20.000Z
|
2019-03-23T08:38:36.000Z
| 101.848302 | 4,888 | 0.683484 |
[
[
[
"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup \n\nhtml = urlopen('http://en.wikipedia.org/wiki/Kevin_Bacon')\nbs = BeautifulSoup(html, 'html.parser')\nfor link in bs.find_all('a'):\n if 'href' in link.attrs:\n print(link.attrs['href'])",
"/wiki/Wikipedia:Protection_policy#semi\n#mw-head\n#p-search\n/wiki/Kevin_Bacon_(disambiguation)\n/wiki/File:Kevin_Bacon_SDCC_2014.jpg\n/wiki/San_Diego_Comic-Con\n/wiki/Philadelphia\n/wiki/Pennsylvania\n/wiki/Kyra_Sedgwick\n/wiki/Sosie_Bacon\n/wiki/Edmund_Bacon_(architect)\n/wiki/Michael_Bacon_(musician)\nhttp://baconbros.com/\n#cite_note-1\n#cite_note-actor-2\n/wiki/Footloose_(1984_film)\n/wiki/JFK_(film)\n/wiki/A_Few_Good_Men\n/wiki/Apollo_13_(film)\n/wiki/Mystic_River_(film)\n/wiki/Sleepers\n/wiki/The_Woodsman_(2004_film)\n/wiki/Fox_Broadcasting_Company\n/wiki/The_Following\n/wiki/HBO\n/wiki/Taking_Chance\n/wiki/Golden_Globe_Award\n/wiki/Screen_Actors_Guild_Award\n/wiki/Primetime_Emmy_Award\n/wiki/The_Guardian\n/wiki/Academy_Award\n#cite_note-3\n/wiki/Hollywood_Walk_of_Fame\n#cite_note-4\n/wiki/Social_networks\n/wiki/Six_Degrees_of_Kevin_Bacon\n/wiki/SixDegrees.org\n#cite_note-walk-5\n#Early_life_and_education\n#Acting_career\n#Early_work\n#1980s\n#1990s\n#2000s\n#2010s\n#Advertising_work\n#Personal_life\n#Six_Degrees_of_Kevin_Bacon\n#Music\n#Awards_and_nominations\n#Filmography\n#See_also\n#References\n#External_links\n/wiki/Philadelphia\n#cite_note-actor-2\n#cite_note-actor-2\n/wiki/Edmund_Bacon_(architect)\n#cite_note-bacon-6\n/wiki/Pennsylvania_Governor%27s_School_for_the_Arts\n/wiki/Bucknell_University\n#cite_note-7\n/wiki/Glory_Van_Scott\n#cite_note-walk-5\n#cite_note-bacon-6\n/wiki/Circle_in_the_Square\n/wiki/Nancy_Mills\n/wiki/Cosmopolitan_(magazine)\n#cite_note-cosmo91-8\n/wiki/Fraternities_and_sororities\n/wiki/Animal_House\n#cite_note-bacon-6\n/wiki/Search_for_Tomorrow\n/wiki/Guiding_Light\n/wiki/Friday_the_13th_(1980_film)\n#cite_note-9\n/wiki/Phoenix_Theater\n/wiki/Flux\n/wiki/Second_Stage_Theatre\n#cite_note-bio-10\n/wiki/Obie_Award\n/wiki/Forty_Deuce\n#cite_note-kevin-11\n/wiki/Slab_Boys\n/wiki/Sean_Penn\n/wiki/Val_Kilmer\n/wiki/Barry_Levinson\n/wiki/Diner_(film)\n/wiki/Steve_Guttenberg\n/wiki/Daniel_Stern_(actor)\n/wiki/Mickey_Rourke\n/wiki/Tim_Daly\n/wiki/Ellen_Barkin\n#cite_note-12\n/wiki/Footloose_(1984_film)\n#cite_note-bio-10\n/wiki/James_Dean\n/wiki/Rebel_Without_a_Cause\n/wiki/Mickey_Rooney\n/wiki/Judy_Garland\n#cite_note-time84-13\n#cite_note-bacon-6\n#cite_note-14\n#cite_note-15\n/wiki/People_(American_magazine)\n/wiki/Typecasting_(acting)\n/wiki/John_Hughes_(filmmaker)\n/wiki/She%27s_Having_a_Baby\n#cite_note-bio-10\n/wiki/The_Big_Picture_(1989_film)\n#cite_note-16\n/wiki/Tremors_(film)\n#cite_note-17\n/wiki/Joel_Schumacher\n/wiki/Flatliners\n#cite_note-bio-10\n/wiki/Elizabeth_Perkins\n/wiki/He_Said,_She_Said\n#cite_note-bio-10\n/wiki/The_New_York_Times\n#cite_note-nyt94-18\n/wiki/Oliver_Stone\n/wiki/JFK_(film)\n#cite_note-19\n/wiki/A_Few_Good_Men_(film)\n#cite_note-20\n/wiki/Michael_Greif\n#cite_note-bio-10\n/wiki/Golden_Globe_Award\n/wiki/The_River_Wild\n#cite_note-bio-10\n/wiki/Meryl_Streep\n/wiki/Murder_in_the_First_(film)\n#cite_note-bio-10\n/wiki/Blockbuster_(entertainment)\n/wiki/Apollo_13_(film)\n#cite_note-21\n/wiki/Sleepers_(film)\n#cite_note-22\n/wiki/Picture_Perfect_(1997_film)\n#cite_note-bio-10\n/wiki/Losing_Chase\n#cite_note-austin-23\n/wiki/Digging_to_China\n#cite_note-bio-10\n/wiki/Payola\n/wiki/Telling_Lies_in_America_(film)\n#cite_note-bio-10\n/wiki/Wild_Things_(film)\n/wiki/Stir_of_Echoes\n/wiki/David_Koepp\n#cite_note-24\n/wiki/File:KevinBaconTakingChanceFeb09.jpg\n/wiki/File:KevinBaconTakingChanceFeb09.jpg\n/wiki/Taking_Chance\n/wiki/Paul_Verhoeven\n/wiki/Hollow_Man\n#cite_note-25\n/wiki/Colin_Firth\n/wiki/Rachel_Blanchard\n/wiki/M%C3%A9nage_%C3%A0_trois\n/wiki/Where_the_Truth_Lies\n#cite_note-26\n/wiki/Atom_Egoyan\n/wiki/MPAA\n/wiki/MPAA_film_rating_system\n#cite_note-27\n/wiki/Pedophile\n/wiki/The_Woodsman_(2004_film)\n#cite_note-28\n/wiki/HBO_Films\n/wiki/Taking_Chance\n/wiki/Michael_Strobl\n/wiki/Desert_Storm\n#cite_note-29\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Male_Actor_in_a_Miniseries_or_Television_Movie\n/wiki/Matthew_Vaughn\n/wiki/X-Men:_First_Class\n#cite_note-30\n/wiki/Sebastian_Shaw_(comics)\n#cite_note-31\n/wiki/Dustin_Lance_Black\n/wiki/8_(play)\n/wiki/Perry_v._Brown\n/wiki/Proposition_8\n/wiki/Charles_J._Cooper\n#cite_note-8_the_play-32\n/wiki/Wilshire_Ebell_Theatre\n/wiki/American_Foundation_for_Equal_Rights\n#cite_note-8_play_video-33\n#cite_note-34\n/wiki/The_Following\n#cite_note-35\n/wiki/Saturn_Award_for_Best_Actor_on_Television\n#cite_note-36\n/wiki/Huffington_Post\n/wiki/Wikipedia:Citation_needed\n/wiki/Tremors_(film)\n/wiki/Wikipedia:Citation_needed\n/wiki/Tremors_5:_Bloodline\n/wiki/EE_(telecommunications_company)\n/wiki/United_Kingdom\n#cite_note-37\n#cite_note-38\n/wiki/Egg_as_food\n#cite_note-39\n/wiki/Kyra_Sedgwick\n/wiki/PBS\n/wiki/Lanford_Wilson\n/wiki/Lemon_Sky\n#cite_note-cosmo91-8\n/wiki/Pyrates\n/wiki/Murder_in_the_First_(film)\n/wiki/The_Woodsman_(2004_film)\n/wiki/Loverboy_(2005_film)\n/wiki/Sosie_Bacon\n/wiki/Upper_West_Side\n/wiki/Manhattan\n#cite_note-40\n/wiki/Tracy_Pollan\n#cite_note-41\n#cite_note-42\n#cite_note-43\n/wiki/The_Times\n#cite_note-44\n#cite_note-45\n/wiki/Will.i.am\n/wiki/It%27s_a_New_Day_(Will.i.am_song)\n/wiki/Barack_Obama\n/wiki/Ponzi_scheme\n/wiki/Bernard_Madoff\n#cite_note-financialpost-46\n#cite_note-47\n/wiki/Finding_Your_Roots\n/wiki/Henry_Louis_Gates\n#cite_note-48\n#cite_note-49\n#cite_note-50\n/wiki/Six_Degrees_of_Kevin_Bacon\n/wiki/Trivia\n/wiki/Big_screen\n/wiki/Six_degrees_of_separation\n/wiki/Internet_meme\n/wiki/SixDegrees.org\n#cite_note-51\n/wiki/Bacon_number\n/wiki/Internet_Movie_Database\n#cite_note-52\n/wiki/Paul_Erd%C5%91s\n/wiki/Erd%C5%91s_number\n/wiki/Paul_Erd%C5%91s\n/wiki/Bacon_number\n/wiki/Erd%C5%91s_number\n/wiki/Erd%C5%91s%E2%80%93Bacon_number\n#cite_note-53\n/wiki/The_Bacon_Brothers\n/wiki/Michael_Bacon_(musician)\n/wiki/Music_album\n#cite_note-54\n/wiki/File:Question_book-new.svg\n/wiki/Wikipedia:Citing_sources\n/wiki/Wikipedia:Verifiability\n//en.wikipedia.org/w/index.php?title=Kevin_Bacon&action=edit\n/wiki/Help:Introduction_to_referencing_with_Wiki_Markup/1\n/wiki/Wikipedia:Verifiability#Burden_of_evidence\n/wiki/Help:Maintenance_template_removal\n/wiki/Golden_Globe_Awards\n/wiki/Golden_Globe_Award_for_Best_Supporting_Actor_%E2%80%93_Motion_Picture\n/wiki/The_River_Wild\n/wiki/Broadcast_Film_Critics_Association_Awards\n/wiki/Broadcast_Film_Critics_Association_Award_for_Best_Actor\n/wiki/Murder_in_the_First_(film)\n/wiki/Screen_Actors_Guild_Awards\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Cast_in_a_Motion_Picture\n/wiki/Apollo_13_(film)\n/wiki/Screen_Actors_Guild_Awards\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Male_Actor_in_a_Supporting_Role\n/wiki/Murder_in_the_First_(film)\n/wiki/MTV_Movie_Awards\n/wiki/MTV_Movie_Award_for_Best_Villain\n/wiki/Hollow_Man\n/wiki/Boston_Society_of_Film_Critics_Awards\n/wiki/Boston_Society_of_Film_Critics_Award_for_Best_Cast\n/wiki/Mystic_River_(film)\n/wiki/Screen_Actors_Guild_Awards\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Cast_in_a_Motion_Picture\n/wiki/Mystic_River_(film)\n/wiki/Satellite_Awards\n/wiki/Satellite_Award_for_Best_Actor_%E2%80%93_Motion_Picture_Drama\n/wiki/The_Woodsman_(2004_film)\n/wiki/Teen_Choice_Awards\n/wiki/Teen_Choice_Awards\n/wiki/Beauty_Shop\n/wiki/Primetime_Emmy_Awards\n/wiki/Primetime_Emmy_Award_for_Outstanding_Lead_Actor_in_a_Miniseries_or_a_Movie\n/wiki/Taking_Chance\n/wiki/Satellite_Awards\n/wiki/Satellite_Award_for_Best_Actor_%E2%80%93_Miniseries_or_Television_Film\n/wiki/Taking_Chance\n/wiki/Screen_Actors_Guild_Awards\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Cast_in_a_Motion_Picture\n/wiki/Frost/Nixon_(film)\n/wiki/Golden_Globe_Awards\n/wiki/Golden_Globe_Award_for_Best_Actor_%E2%80%93_Miniseries_or_Television_Film\n/wiki/Taking_Chance\n/wiki/Screen_Actors_Guild_Awards\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Male_Actor_in_a_Miniseries_or_Television_Movie\n/wiki/Taking_Chance\n/wiki/Teen_Choice_Awards\n/wiki/Teen_Choice_Awards\n/wiki/X-Men:_First_Class\n/wiki/Saturn_Awards\n/wiki/Saturn_Award_for_Best_Actor_on_Television\n/wiki/The_Following\n/wiki/People%27s_Choice_Awards\n/wiki/People%27s_Choice_Awards\n/wiki/The_Following\n/wiki/Saturn_Awards\n/wiki/Saturn_Award_for_Best_Actor_on_Television\n/wiki/The_Following\n/wiki/Golden_Globe_Awards\n/wiki/Golden_Globe_Award_for_Best_Actor_%E2%80%93_Television_Series_Musical_or_Comedy\n/wiki/I_Love_Dick_(TV_series)\n#cite_note-55\n#cite_note-56\n#cite_note-57\n#cite_note-58\n/wiki/Kevin_Bacon_filmography\n/wiki/List_of_actors_with_Hollywood_Walk_of_Fame_motion_picture_stars\n#cite_ref-1\nhttps://web.archive.org/web/20090113222205/http://www.newenglandancestors.org/research/services/articles_gbr78.asp\nhttp://www.newenglandancestors.org/research/services/articles_gbr78.asp\n#cite_ref-actor_2-0\n#cite_ref-actor_2-1\n#cite_ref-actor_2-2\nhttp://www.biography.com/people/kevin-bacon-9542173\n#cite_ref-3\nhttps://www.theguardian.com/film/filmblog/2009/feb/19/best-actors-never-nominated-for-oscars\n#cite_ref-4\nhttp://www.walkoffame.com/kevin-bacon\n#cite_ref-walk_5-0\n#cite_ref-walk_5-1\nhttps://web.archive.org/web/20141016202657/http://www.thebiographychannel.co.uk/biographies/kevin-bacon.html\nhttp://www.thebiographychannel.co.uk/biographies/kevin-bacon.html\n#cite_ref-bacon_6-0\n#cite_ref-bacon_6-1\n#cite_ref-bacon_6-2\n#cite_ref-bacon_6-3\nhttp://www.biography.com/news/kevin-bacon-biography-facts\n#cite_ref-7\nhttps://movies.yahoo.com/person/kevin-bacon/biography.html\n#cite_ref-cosmo91_8-0\n#cite_ref-cosmo91_8-1\n#cite_ref-9\nhttp://www.nydailynews.com/entertainment/happy-halloween-superstars-start-horror-flick-gallery-1.98345\n#cite_ref-bio_10-0\n#cite_ref-bio_10-1\n#cite_ref-bio_10-2\n#cite_ref-bio_10-3\n#cite_ref-bio_10-4\n#cite_ref-bio_10-5\n#cite_ref-bio_10-6\n#cite_ref-bio_10-7\n#cite_ref-bio_10-8\n#cite_ref-bio_10-9\n#cite_ref-bio_10-10\nhttps://www.pbs.org/wnet/finding-your-roots/profiles/kevin-bacon%C2%A0/\n#cite_ref-kevin_11-0\nhttp://www.tvguide.com/celebrities/kevin-bacon/bio/160550\n#cite_ref-12\nhttp://news.moviefone.com/2012/03/02/diner-30th-anniversary/\n#cite_ref-time84_13-0\nhttp://www.time.com/time/magazine/article/0,9171,950019,00.html\n#cite_ref-14\nhttp://www.huffingtonpost.com/2014/08/25/kevin-bacon-footloose_n_5710413.html\n#cite_ref-15\nhttps://web.archive.org/web/20090109152125/http://www.thebiographychannel.co.uk/biography_story/522%3A492/1/Kevin_Bacon.htm\nhttp://www.thebiographychannel.co.uk/biography_story/522:492/1/Kevin_Bacon.htm\n#cite_ref-16\nhttps://www.nytimes.com/1994/09/25/movies/a-second-wind-is-blowing-for-kevin-bacon.html\n#cite_ref-17\nhttps://www.nytimes.com/movie/review?res=9C0CE2DE1631F93AA25752C0A966958260\n#cite_ref-nyt94_18-0\nhttps://query.nytimes.com/gst/fullpage.html?res=9C07E6D91F3BF936A1575AC0A962958260&sec=&spon=&pagewanted=all\n#cite_ref-19\nhttp://www.jfk-online.com/jfkbacon.html\n#cite_ref-20\nhttp://www.tcm.com/this-month/article/143158%7C0/A-Few-Good-Men.html\n#cite_ref-21\nhttp://collider.com/kevin-bacon-commercials-footloose/\n#cite_ref-22\nhttp://www.rogerebert.com/reviews/sleepers-1996\n#cite_ref-austin_23-0\nhttp://www.austinchronicle.com/calendar/film/1997-02-07/283342/\n/wiki/The_Austin_Chronicle\n#cite_ref-24\nhttp://www.criminalelement.com/blogs/2013/09/under-the-raderhorror-movies-you-may-have-missed-stir-of-echoes\n#cite_ref-25\nhttp://www.rogerebert.com/reviews/hollow-man-2000\n#cite_ref-26\nhttp://movies.about.com/od/wherethetruthlies/a/truthkb101305.htm\n#cite_ref-27\nhttp://jam.canoe.ca/Movies/2005/09/14/1216527.html\n#cite_ref-28\nhttp://www.latimes.com/entertainment/la-et-kevin-bacon-photo6-photo.html\n#cite_ref-29\nhttp://www.nydailynews.com/entertainment/tv-movies/kevin-bacon-chance-body-fallen-marine-home-article-1.392226\n#cite_ref-30\nhttps://web.archive.org/web/20100722010545/http://heatvision.hollywoodreporter.com/2010/07/winters-bone-star-cast-as-mystique-in-xmen-first-class.html\nhttp://heatvision.hollywoodreporter.com/2010/07/winters-bone-star-cast-as-mystique-in-xmen-first-class.html\n#cite_ref-31\nhttps://web.archive.org/web/20100720060214/http://www.forcesofgeek.com/2010/07/kevin-bacon-playing-sebastian-shaw-in-x.html\nhttp://www.forcesofgeek.com/2010/07/kevin-bacon-playing-sebastian-shaw-in-x.html\n#cite_ref-8_the_play_32-0\nhttp://www.accesshollywood.com/jesse-tyler-ferguson/glee-stars-touched-by-brad-pitt-and-george-clooneys-support-of-8_article_61543\n/wiki/Access_Hollywood\n#cite_ref-8_play_video_33-0\nhttps://www.youtube.com/watch?v=qlUG8F9uVgM\n#cite_ref-34\nhttp://www.pinknews.co.uk/2012/03/01/youtube-to-broadcast-proposition-8-play-live/\n#cite_ref-35\nhttp://www.fox.com/the-following/\n#cite_ref-36\nhttps://news.yahoo.com/blogs/trending-now/kevin-bacon-gives-millennials-a-history-lesson-about-the--80s-162525915.html\n#cite_ref-37\nhttp://www.campaignlive.co.uk/news/1294856/\n#cite_ref-38\nhttp://parade.condenast.com/269380/ashleighschmitz/kevin-bacon-reprises-his-most-iconic-film-roles-in-british-commercial/\n#cite_ref-39\nhttp://money.cnn.com/2015/03/13/media/kevin-bacon-eggs/index.html?iid=HP_LN\n#cite_ref-40\nhttp://www.nydailynews.com/entertainment/tv-movies/kevin-bacon-loyalty-nyc-philly-origins-peace-bustling-city-article-1.147197\n#cite_ref-41\nhttp://www.people.com/people/archive/article/0,,20093025,00.html\n#cite_ref-42\nhttp://www.au.org/media/church-and-state/archives/2008/05/two-thumbs-up.html\n#cite_ref-43\nhttps://www.washingtonpost.com/wp-dyn/content/article/2008/03/25/AR2008032503852.html\n#cite_ref-44\n#cite_ref-45\nhttp://www.foxnews.com/story/0,2933,343589,00.html\n#cite_ref-financialpost_46-0\nhttps://web.archive.org/web/20140314085857/http://economiccrisis.us/2009/06/may-god-spare-mercy-victim-tells-madoff/\nhttp://economiccrisis.us/2009/06/may-god-spare-mercy-victim-tells-madoff/\n#cite_ref-47\n#cite_ref-48\nhttp://www.huffingtonpost.com/megan-smolenyak-smolenyak/6-degrees-of-separation-k_b_900707.html\n#cite_ref-49\nhttps://web.archive.org/web/20130405182304/http://www.drawtheline.org/watch-stuff/\nhttp://www.drawtheline.org/watch-stuff\n#cite_ref-50\nhttp://www.drawtheline.org/sign-now/\n#cite_ref-51\nhttp://www.sixdegrees.org/\n#cite_ref-52\nhttp://www.webmonkey.com/2012/09/easter-egg-google-connects-the-dots-for-bacon-number-search/\n#cite_ref-53\nhttp://www.telegraph.co.uk/science/science-news/4768389/And-the-winner-tonight-is.html\n#cite_ref-54\nhttp://baconbros.com/\n#cite_ref-55\n/wiki/Reuters\nhttps://www.cbsnews.com/pictures/golden-globes-2018-highlights/50/\n/wiki/CBS_News\n#cite_ref-56\nhttps://www.theverge.com/2018/1/7/16861812/golden-globes-2018-aziz-ansari-master-of-none-best-actor-tv\n/wiki/The_Verge\n#cite_ref-57\nhttps://www.hollywoodreporter.com/news/aziz-ansari-wins-best-performance-by-an-actor-a-tv-series-comedy-musical-golden-globes-2018-1072154\n/wiki/The_Hollywood_Reporter\n#cite_ref-58\nhttp://www.indiewire.com/2018/01/aziz-ansari-wins-golden-globe-best-actor-tv-comedy-1201914235/\n/wiki/Indie_Wire\nhttps://commons.wikimedia.org/wiki/Category:Kevin_Bacon\nhttp://www.imdb.com/name/nm0000102/\n/wiki/IMDb\nhttps://www.ibdb.com/Person/View/90569\n/wiki/Internet_Broadway_Database\nhttps://www.wikidata.org/wiki/Q3454165#P1220\nhttp://www.lortel.org/Archives/CreditableEntity/5597\n/wiki/Lortel_Archives\nhttps://www.allmovie.com/artist/p3164\n/wiki/AllMovie\nhttp://oracleofbacon.org\n/wiki/Template:Critics%27_Choice_Movie_Award_for_Best_Actor\n/wiki/Template_talk:Critics%27_Choice_Movie_Award_for_Best_Actor\n//en.wikipedia.org/w/index.php?title=Template:Critics%27_Choice_Movie_Award_for_Best_Actor&action=edit\n/wiki/Critics%27_Choice_Movie_Award_for_Best_Actor\n/wiki/Geoffrey_Rush\n/wiki/Jack_Nicholson\n/wiki/Ian_McKellen\n/wiki/Russell_Crowe\n/wiki/Russell_Crowe\n/wiki/Russell_Crowe\n/wiki/Daniel_Day-Lewis\n/wiki/Jack_Nicholson\n/wiki/Sean_Penn\n/wiki/Jamie_Foxx\n/wiki/Philip_Seymour_Hoffman\n/wiki/Forest_Whitaker\n/wiki/Daniel_Day-Lewis\n/wiki/Sean_Penn\n/wiki/Jeff_Bridges\n/wiki/Colin_Firth\n/wiki/George_Clooney\n/wiki/Daniel_Day-Lewis\n/wiki/Matthew_McConaughey\n/wiki/Michael_Keaton\n/wiki/Leonardo_DiCaprio\n/wiki/Casey_Affleck\n/wiki/Gary_Oldman\n/wiki/Template:GoldenGlobeBestActorTVMiniseriesFilm\n/wiki/Template_talk:GoldenGlobeBestActorTVMiniseriesFilm\n//en.wikipedia.org/w/index.php?title=Template:GoldenGlobeBestActorTVMiniseriesFilm&action=edit\n/wiki/Golden_Globe_Award_for_Best_Actor_%E2%80%93_Miniseries_or_Television_Film\n/wiki/Mickey_Rooney\n/wiki/Anthony_Andrews\n/wiki/Richard_Chamberlain\n/wiki/Ted_Danson\n/wiki/Dustin_Hoffman\n/wiki/James_Woods\n/wiki/Randy_Quaid\n/wiki/Michael_Caine\n/wiki/Stacy_Keach\n/wiki/Robert_Duvall\n/wiki/James_Garner\n/wiki/Beau_Bridges\n/wiki/Robert_Duvall\n/wiki/James_Garner\n/wiki/Ra%C3%BAl_Juli%C3%A1\n/wiki/Gary_Sinise\n/wiki/Alan_Rickman\n/wiki/Ving_Rhames\n/wiki/Stanley_Tucci\n/wiki/Jack_Lemmon\n/wiki/Brian_Dennehy\n/wiki/James_Franco\n/wiki/Albert_Finney\n/wiki/Al_Pacino\n/wiki/Geoffrey_Rush\n/wiki/Jonathan_Rhys_Meyers\n/wiki/Bill_Nighy\n/wiki/Jim_Broadbent\n/wiki/Paul_Giamatti\n/wiki/Al_Pacino\n/wiki/Idris_Elba\n/wiki/Kevin_Costner\n/wiki/Michael_Douglas\n/wiki/Billy_Bob_Thornton\n/wiki/Oscar_Isaac\n/wiki/Tom_Hiddleston\n/wiki/Ewan_McGregor\n/wiki/Template:Saturn_Award_for_Best_Actor_on_Television\n/wiki/Template_talk:Saturn_Award_for_Best_Actor_on_Television\n//en.wikipedia.org/w/index.php?title=Template:Saturn_Award_for_Best_Actor_on_Television&action=edit\n/wiki/Saturn_Award_for_Best_Actor_on_Television\n/wiki/Kyle_Chandler\n/wiki/Steven_Weber_(actor)\n/wiki/Richard_Dean_Anderson\n/wiki/David_Boreanaz\n/wiki/Robert_Patrick\n/wiki/Ben_Browder\n/wiki/David_Boreanaz\n/wiki/David_Boreanaz\n/wiki/Ben_Browder\n/wiki/Matthew_Fox\n/wiki/Michael_C._Hall\n/wiki/Matthew_Fox\n/wiki/Edward_James_Olmos\n/wiki/Josh_Holloway\n/wiki/Stephen_Moyer\n/wiki/Bryan_Cranston\n/wiki/Bryan_Cranston\n/wiki/Mads_Mikkelsen\n/wiki/Hugh_Dancy\n/wiki/Andrew_Lincoln\n/wiki/Bruce_Campbell\n/wiki/Andrew_Lincoln\n/wiki/Template:ScreenActorsGuildAward_MaleTVMiniseriesMovie\n/wiki/Template_talk:ScreenActorsGuildAward_MaleTVMiniseriesMovie\n//en.wikipedia.org/w/index.php?title=Template:ScreenActorsGuildAward_MaleTVMiniseriesMovie&action=edit\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Male_Actor_in_a_Miniseries_or_Television_Movie\n/wiki/Ra%C3%BAl_Juli%C3%A1\n/wiki/Gary_Sinise\n/wiki/Alan_Rickman\n/wiki/Gary_Sinise\n/wiki/Christopher_Reeve\n/wiki/Jack_Lemmon\n/wiki/Brian_Dennehy\n/wiki/Ben_Kingsley\n/wiki/William_H._Macy\n/wiki/Al_Pacino\n/wiki/Geoffrey_Rush\n/wiki/Paul_Newman\n/wiki/Jeremy_Irons\n/wiki/Kevin_Kline\n/wiki/Paul_Giamatti\n/wiki/Al_Pacino\n/wiki/Paul_Giamatti\n/wiki/Kevin_Costner\n/wiki/Michael_Douglas\n/wiki/Mark_Ruffalo\n/wiki/Idris_Elba\n/wiki/Bryan_Cranston\n/wiki/Alexander_Skarsg%C3%A5rd\n/wiki/Template:ScreenActorsGuildAward_CastMotionPicture_1995%E2%80%932000\n/wiki/Template_talk:ScreenActorsGuildAward_CastMotionPicture_1995%E2%80%932000\n//en.wikipedia.org/w/index.php?title=Template:ScreenActorsGuildAward_CastMotionPicture_1995%E2%80%932000&action=edit\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Cast_in_a_Motion_Picture\n/wiki/Apollo_13_(film)\n/wiki/Tom_Hanks\n/wiki/Ed_Harris\n/wiki/Bill_Paxton\n/wiki/Kathleen_Quinlan\n/wiki/Gary_Sinise\n/wiki/The_Birdcage\n/wiki/Hank_Azaria\n/wiki/Christine_Baranski\n/wiki/Dan_Futterman\n/wiki/Gene_Hackman\n/wiki/Nathan_Lane\n/wiki/Dianne_Wiest\n/wiki/Robin_Williams\n/wiki/The_Full_Monty\n/wiki/Mark_Addy\n/wiki/Paul_Barber_(actor)\n/wiki/Robert_Carlyle\n/w/index.php?title=Deirdre_Costello_(actress)&action=edit&redlink=1\n/wiki/Steve_Huison\n/wiki/Bruce_Jones_(actor)\n/wiki/Lesley_Sharp\n/wiki/William_Snape\n/wiki/Hugo_Speer\n/wiki/Tom_Wilkinson\n/wiki/Emily_Woof\n/wiki/Shakespeare_in_Love\n/wiki/Ben_Affleck\n/wiki/Simon_Callow\n/wiki/Jim_Carter_(actor)\n/wiki/Martin_Clunes\n/wiki/Judi_Dench\n/wiki/Joseph_Fiennes\n/wiki/Colin_Firth\n/wiki/Gwyneth_Paltrow\n/wiki/Geoffrey_Rush\n/wiki/Antony_Sher\n/wiki/Imelda_Staunton\n/wiki/American_Beauty_(1999_film)\n/wiki/Annette_Bening\n/wiki/Wes_Bentley\n/wiki/Thora_Birch\n/wiki/Chris_Cooper\n/wiki/Peter_Gallagher\n/wiki/Allison_Janney\n/wiki/Kevin_Spacey\n/wiki/Mena_Suvari\n/wiki/Traffic_(2000_film)\n/wiki/Steven_Bauer\n/wiki/Benjamin_Bratt\n/wiki/James_Brolin\n/wiki/Don_Cheadle\n/wiki/Erika_Christensen\n/wiki/Clifton_Collins_Jr.\n/wiki/Benicio_del_Toro\n/wiki/Michael_Douglas\n/wiki/Miguel_Ferrer\n/wiki/Albert_Finney\n/wiki/Topher_Grace\n/wiki/Luis_Guzm%C3%A1n\n/wiki/Amy_Irving\n/wiki/Tomas_Milian\n/wiki/D._W._Moffett\n/wiki/Dennis_Quaid\n/wiki/Peter_Riegert\n/wiki/Jacob_Vargas\n/wiki/Catherine_Zeta-Jones\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Cast_in_a_Motion_Picture\n/wiki/Template:ScreenActorsGuildAward_CastMotionPicture_1995%E2%80%932000\n/wiki/Template:ScreenActorsGuildAward_CastMotionPicture_2001%E2%80%932010\n/wiki/Template:ScreenActorsGuildAward_CastMotionPicture_2011%E2%80%932020\n/wiki/Help:Authority_control\nhttps://www.worldcat.org/identities/containsVIAFID/39570812\n/wiki/Virtual_International_Authority_File\nhttps://viaf.org/viaf/39570812\n/wiki/Library_of_Congress_Control_Number\nhttp://id.loc.gov/authorities/names/n88034930\n/wiki/International_Standard_Name_Identifier\nhttp://isni.org/isni/0000000121291300\n/wiki/Integrated_Authority_File\nhttps://d-nb.info/gnd/124109659\n/wiki/Syst%C3%A8me_universitaire_de_documentation\nhttps://www.idref.fr/084292652\n/wiki/Biblioth%C3%A8que_nationale_de_France\nhttp://catalogue.bnf.fr/ark:/12148/cb139817766\nhttp://data.bnf.fr/ark:/12148/cb139817766\n/wiki/MusicBrainz\nhttps://musicbrainz.org/artist/cc0dbdfc-9b2c-4e31-8448-808412388406\n/wiki/SNAC\nhttp://socialarchive.iath.virginia.edu/ark:/99166/w6w67gw2\nhttps://en.wikipedia.org/w/index.php?title=Kevin_Bacon&oldid=821876006\n/wiki/Help:Category\n/wiki/Category:1958_births\n/wiki/Category:20th-century_American_male_actors\n/wiki/Category:21st-century_American_male_actors\n/wiki/Category:American_atheists\n/wiki/Category:American_male_film_actors\n/wiki/Category:American_male_soap_opera_actors\n/wiki/Category:American_male_television_actors\n/wiki/Category:American_male_voice_actors\n/wiki/Category:The_Bacon_Brothers_members\n/wiki/Category:Best_Miniseries_or_Television_Movie_Actor_Golden_Globe_winners\n/wiki/Category:Circle_in_the_Square_Theatre_School_alumni\n/wiki/Category:Living_people\n/wiki/Category:Male_actors_from_Philadelphia\n/wiki/Category:Obie_Award_recipients\n/wiki/Category:Outstanding_Performance_by_a_Cast_in_a_Motion_Picture_Screen_Actors_Guild_Award_winners\n/wiki/Category:Sedgwick_family\n/wiki/Category:Wikipedia_indefinitely_semi-protected_biographies_of_living_people\n/wiki/Category:Use_mdy_dates_from_October_2016\n/wiki/Category:Articles_with_hCards\n/wiki/Category:All_articles_with_unsourced_statements\n/wiki/Category:Articles_with_unsourced_statements_from_January_2016\n/wiki/Category:Articles_needing_additional_references_from_October_2017\n/wiki/Category:All_articles_needing_additional_references\n/wiki/Category:Articles_with_IBDb_links\n/wiki/Category:Wikipedia_articles_with_VIAF_identifiers\n/wiki/Category:Wikipedia_articles_with_LCCN_identifiers\n/wiki/Category:Wikipedia_articles_with_ISNI_identifiers\n/wiki/Category:Wikipedia_articles_with_GND_identifiers\n/wiki/Category:Wikipedia_articles_with_BNF_identifiers\n/wiki/Category:Wikipedia_articles_with_MusicBrainz_identifiers\n/wiki/Category:Wikipedia_articles_with_SNAC-ID_identifiers\n/wiki/Special:MyTalk\n/wiki/Special:MyContributions\n/w/index.php?title=Special:CreateAccount&returnto=Kevin+Bacon\n/w/index.php?title=Special:UserLogin&returnto=Kevin+Bacon\n/wiki/Kevin_Bacon\n/wiki/Talk:Kevin_Bacon\n/wiki/Kevin_Bacon\n/w/index.php?title=Kevin_Bacon&action=edit\n/w/index.php?title=Kevin_Bacon&action=history\n/wiki/Main_Page\n/wiki/Main_Page\n/wiki/Portal:Contents\n/wiki/Portal:Featured_content\n/wiki/Portal:Current_events\n/wiki/Special:Random\nhttps://donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&utm_medium=sidebar&utm_campaign=C13_en.wikipedia.org&uselang=en\n//shop.wikimedia.org\n/wiki/Help:Contents\n/wiki/Wikipedia:About\n/wiki/Wikipedia:Community_portal\n/wiki/Special:RecentChanges\n//en.wikipedia.org/wiki/Wikipedia:Contact_us\n/wiki/Special:WhatLinksHere/Kevin_Bacon\n/wiki/Special:RecentChangesLinked/Kevin_Bacon\n/wiki/Wikipedia:File_Upload_Wizard\n/wiki/Special:SpecialPages\n/w/index.php?title=Kevin_Bacon&oldid=821876006\n/w/index.php?title=Kevin_Bacon&action=info\nhttps://www.wikidata.org/wiki/Special:EntityPage/Q3454165\n/w/index.php?title=Special:CiteThisPage&page=Kevin_Bacon&id=821876006\n/w/index.php?title=Special:Book&bookcmd=book_creator&referer=Kevin+Bacon\n/w/index.php?title=Special:ElectronPdf&page=Kevin+Bacon&action=show-download-screen\n/w/index.php?title=Kevin_Bacon&printable=yes\nhttps://commons.wikimedia.org/wiki/Category:Kevin_Bacon\nhttps://af.wikipedia.org/wiki/Kevin_Bacon\nhttps://ar.wikipedia.org/wiki/%D9%83%D9%8A%D9%81%D9%8A%D9%86_%D8%A8%D9%8A%D9%83%D9%86\nhttps://an.wikipedia.org/wiki/Kevin_Bacon\nhttps://ast.wikipedia.org/wiki/Kevin_Bacon\nhttps://azb.wikipedia.org/wiki/%DA%A9%D9%88%DB%8C%D9%86_%D8%A8%DB%8C%DA%A9%D9%86\nhttps://zh-min-nan.wikipedia.org/wiki/Kevin_Bacon\nhttps://bi.wikipedia.org/wiki/Kevin_Bacon\nhttps://bg.wikipedia.org/wiki/%D0%9A%D0%B5%D0%B2%D0%B8%D0%BD_%D0%91%D0%B5%D0%B9%D0%BA%D1%8A%D0%BD\nhttps://bs.wikipedia.org/wiki/Kevin_Bacon\nhttps://ca.wikipedia.org/wiki/Kevin_Bacon\nhttps://cs.wikipedia.org/wiki/Kevin_Bacon\nhttps://da.wikipedia.org/wiki/Kevin_Bacon\nhttps://de.wikipedia.org/wiki/Kevin_Bacon\nhttps://el.wikipedia.org/wiki/%CE%9A%CE%AD%CE%B2%CE%B9%CE%BD_%CE%9C%CF%80%CE%AD%CE%B9%CE%BA%CE%BF%CE%BD\nhttps://eml.wikipedia.org/wiki/Kevin_Bacon\nhttps://es.wikipedia.org/wiki/Kevin_Bacon\nhttps://eu.wikipedia.org/wiki/Kevin_Bacon\nhttps://fa.wikipedia.org/wiki/%DA%A9%D9%88%DB%8C%D9%86_%D8%A8%DB%8C%DA%A9%D9%86\nhttps://fr.wikipedia.org/wiki/Kevin_Bacon\nhttps://gl.wikipedia.org/wiki/Kevin_Bacon\nhttps://ko.wikipedia.org/wiki/%EC%BC%80%EB%B9%88_%EB%B2%A0%EC%9D%B4%EC%BB%A8\nhttps://hy.wikipedia.org/wiki/%D5%94%D6%87%D5%AB%D5%B6_%D4%B2%D5%A5%D5%B5%D6%84%D5%B8%D5%B6\nhttps://hr.wikipedia.org/wiki/Kevin_Bacon\nhttps://io.wikipedia.org/wiki/Kevin_Bacon\nhttps://id.wikipedia.org/wiki/Kevin_Bacon\nhttps://it.wikipedia.org/wiki/Kevin_Bacon\nhttps://he.wikipedia.org/wiki/%D7%A7%D7%95%D7%95%D7%99%D7%9F_%D7%91%D7%99%D7%99%D7%A7%D7%95%D7%9F\nhttps://ka.wikipedia.org/wiki/%E1%83%99%E1%83%94%E1%83%95%E1%83%98%E1%83%9C_%E1%83%91%E1%83%94%E1%83%98%E1%83%99%E1%83%9D%E1%83%9C%E1%83%98\nhttps://kk.wikipedia.org/wiki/%D0%9A%D0%B5%D0%B2%D0%B8%D0%BD_%D0%91%D1%8D%D0%B9%D0%BA%D0%BE%D0%BD\nhttps://lv.wikipedia.org/wiki/Kevins_B%C4%93kons\nhttps://hu.wikipedia.org/wiki/Kevin_Bacon\nhttps://xmf.wikipedia.org/wiki/%E1%83%99%E1%83%94%E1%83%95%E1%83%98%E1%83%9C_%E1%83%91%E1%83%94%E1%83%98%E1%83%99%E1%83%9D%E1%83%9C%E1%83%98\nhttps://mn.wikipedia.org/wiki/%D0%9A%D0%B5%D0%B2%D0%B8%D0%BD_%D0%91%D1%8D%D0%B9%D0%BA%D0%BE%D0%BD\nhttps://nl.wikipedia.org/wiki/Kevin_Bacon\nhttps://ja.wikipedia.org/wiki/%E3%82%B1%E3%83%B4%E3%82%A3%E3%83%B3%E3%83%BB%E3%83%99%E3%83%BC%E3%82%B3%E3%83%B3\nhttps://no.wikipedia.org/wiki/Kevin_Bacon\nhttps://oc.wikipedia.org/wiki/Kevin_Bacon\nhttps://pl.wikipedia.org/wiki/Kevin_Bacon\nhttps://pt.wikipedia.org/wiki/Kevin_Bacon\nhttps://ro.wikipedia.org/wiki/Kevin_Bacon\nhttps://ru.wikipedia.org/wiki/%D0%91%D0%B5%D0%B9%D0%BA%D0%BE%D0%BD,_%D0%9A%D0%B5%D0%B2%D0%B8%D0%BD\nhttps://sco.wikipedia.org/wiki/Kevin_Bacon\nhttps://simple.wikipedia.org/wiki/Kevin_Bacon\nhttps://sk.wikipedia.org/wiki/Kevin_Bacon\nhttps://ckb.wikipedia.org/wiki/%DA%A9%DB%8E%DA%A4%D9%86_%D8%A8%DB%95%DB%8C%DA%A9%D9%86\nhttps://sr.wikipedia.org/wiki/%D0%9A%D0%B5%D0%B2%D0%B8%D0%BD_%D0%91%D0%B5%D1%98%D0%BA%D0%BE%D0%BD\nhttps://sh.wikipedia.org/wiki/Kevin_Bacon\nhttps://fi.wikipedia.org/wiki/Kevin_Bacon\nhttps://sv.wikipedia.org/wiki/Kevin_Bacon\nhttps://th.wikipedia.org/wiki/%E0%B9%80%E0%B8%84%E0%B8%A7%E0%B8%B4%E0%B8%99_%E0%B9%80%E0%B8%9A%E0%B8%84%E0%B8%AD%E0%B8%99\nhttps://tr.wikipedia.org/wiki/Kevin_Bacon\nhttps://uk.wikipedia.org/wiki/%D0%9A%D0%B5%D0%B2%D1%96%D0%BD_%D0%91%D0%B5%D0%B9%D0%BA%D0%BE%D0%BD\nhttps://vi.wikipedia.org/wiki/Kevin_Bacon\nhttps://zh.wikipedia.org/wiki/%E5%87%AF%E6%96%87%C2%B7%E8%B4%9D%E8%82%AF\nhttps://www.wikidata.org/wiki/Special:EntityPage/Q3454165#sitelinks-wikipedia\n//en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\n//creativecommons.org/licenses/by-sa/3.0/\n//wikimediafoundation.org/wiki/Terms_of_Use\n//wikimediafoundation.org/wiki/Privacy_policy\n//www.wikimediafoundation.org/\nhttps://wikimediafoundation.org/wiki/Privacy_policy\n/wiki/Wikipedia:About\n/wiki/Wikipedia:General_disclaimer\n//en.wikipedia.org/wiki/Wikipedia:Contact_us\nhttps://www.mediawiki.org/wiki/Special:MyLanguage/How_to_contribute\nhttps://wikimediafoundation.org/wiki/Cookie_statement\n//en.m.wikipedia.org/w/index.php?title=Kevin_Bacon&mobileaction=toggle_view_mobile\nhttps://wikimediafoundation.org/\n//www.mediawiki.org/\n"
]
],
[
[
"## Retrieving Articles Only",
"_____no_output_____"
]
],
[
[
"from urllib.request import urlopen \nfrom bs4 import BeautifulSoup \nimport re\n\nhtml = urlopen('http://en.wikipedia.org/wiki/Kevin_Bacon')\nbs = BeautifulSoup(html, 'html.parser')\nfor link in bs.find('div', {'id':'bodyContent'}).find_all(\n 'a', href=re.compile('^(/wiki/)((?!:).)*$')):\n if 'href' in link.attrs:\n print(link.attrs['href'])",
"/wiki/Kevin_Bacon_(disambiguation)\n/wiki/San_Diego_Comic-Con\n/wiki/Philadelphia\n/wiki/Pennsylvania\n/wiki/Kyra_Sedgwick\n/wiki/Sosie_Bacon\n/wiki/Edmund_Bacon_(architect)\n/wiki/Michael_Bacon_(musician)\n/wiki/Footloose_(1984_film)\n/wiki/JFK_(film)\n/wiki/A_Few_Good_Men\n/wiki/Apollo_13_(film)\n/wiki/Mystic_River_(film)\n/wiki/Sleepers\n/wiki/The_Woodsman_(2004_film)\n/wiki/Fox_Broadcasting_Company\n/wiki/The_Following\n/wiki/HBO\n/wiki/Taking_Chance\n/wiki/Golden_Globe_Award\n/wiki/Screen_Actors_Guild_Award\n/wiki/Primetime_Emmy_Award\n/wiki/The_Guardian\n/wiki/Academy_Award\n/wiki/Hollywood_Walk_of_Fame\n/wiki/Social_networks\n/wiki/Six_Degrees_of_Kevin_Bacon\n/wiki/SixDegrees.org\n/wiki/Philadelphia\n/wiki/Edmund_Bacon_(architect)\n/wiki/Pennsylvania_Governor%27s_School_for_the_Arts\n/wiki/Bucknell_University\n/wiki/Glory_Van_Scott\n/wiki/Circle_in_the_Square\n/wiki/Nancy_Mills\n/wiki/Cosmopolitan_(magazine)\n/wiki/Fraternities_and_sororities\n/wiki/Animal_House\n/wiki/Search_for_Tomorrow\n/wiki/Guiding_Light\n/wiki/Friday_the_13th_(1980_film)\n/wiki/Phoenix_Theater\n/wiki/Flux\n/wiki/Second_Stage_Theatre\n/wiki/Obie_Award\n/wiki/Forty_Deuce\n/wiki/Slab_Boys\n/wiki/Sean_Penn\n/wiki/Val_Kilmer\n/wiki/Barry_Levinson\n/wiki/Diner_(film)\n/wiki/Steve_Guttenberg\n/wiki/Daniel_Stern_(actor)\n/wiki/Mickey_Rourke\n/wiki/Tim_Daly\n/wiki/Ellen_Barkin\n/wiki/Footloose_(1984_film)\n/wiki/James_Dean\n/wiki/Rebel_Without_a_Cause\n/wiki/Mickey_Rooney\n/wiki/Judy_Garland\n/wiki/People_(American_magazine)\n/wiki/Typecasting_(acting)\n/wiki/John_Hughes_(filmmaker)\n/wiki/She%27s_Having_a_Baby\n/wiki/The_Big_Picture_(1989_film)\n/wiki/Tremors_(film)\n/wiki/Joel_Schumacher\n/wiki/Flatliners\n/wiki/Elizabeth_Perkins\n/wiki/He_Said,_She_Said\n/wiki/The_New_York_Times\n/wiki/Oliver_Stone\n/wiki/JFK_(film)\n/wiki/A_Few_Good_Men_(film)\n/wiki/Michael_Greif\n/wiki/Golden_Globe_Award\n/wiki/The_River_Wild\n/wiki/Meryl_Streep\n/wiki/Murder_in_the_First_(film)\n/wiki/Blockbuster_(entertainment)\n/wiki/Apollo_13_(film)\n/wiki/Sleepers_(film)\n/wiki/Picture_Perfect_(1997_film)\n/wiki/Losing_Chase\n/wiki/Digging_to_China\n/wiki/Payola\n/wiki/Telling_Lies_in_America_(film)\n/wiki/Wild_Things_(film)\n/wiki/Stir_of_Echoes\n/wiki/David_Koepp\n/wiki/Taking_Chance\n/wiki/Paul_Verhoeven\n/wiki/Hollow_Man\n/wiki/Colin_Firth\n/wiki/Rachel_Blanchard\n/wiki/M%C3%A9nage_%C3%A0_trois\n/wiki/Where_the_Truth_Lies\n/wiki/Atom_Egoyan\n/wiki/MPAA\n/wiki/MPAA_film_rating_system\n/wiki/Pedophile\n/wiki/The_Woodsman_(2004_film)\n/wiki/HBO_Films\n/wiki/Taking_Chance\n/wiki/Michael_Strobl\n/wiki/Desert_Storm\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Male_Actor_in_a_Miniseries_or_Television_Movie\n/wiki/Matthew_Vaughn\n/wiki/Sebastian_Shaw_(comics)\n/wiki/Dustin_Lance_Black\n/wiki/8_(play)\n/wiki/Perry_v._Brown\n/wiki/Proposition_8\n/wiki/Charles_J._Cooper\n/wiki/Wilshire_Ebell_Theatre\n/wiki/American_Foundation_for_Equal_Rights\n/wiki/The_Following\n/wiki/Saturn_Award_for_Best_Actor_on_Television\n/wiki/Huffington_Post\n/wiki/Tremors_(film)\n/wiki/EE_(telecommunications_company)\n/wiki/United_Kingdom\n/wiki/Egg_as_food\n/wiki/Kyra_Sedgwick\n/wiki/PBS\n/wiki/Lanford_Wilson\n/wiki/Lemon_Sky\n/wiki/Pyrates\n/wiki/Murder_in_the_First_(film)\n/wiki/The_Woodsman_(2004_film)\n/wiki/Loverboy_(2005_film)\n/wiki/Sosie_Bacon\n/wiki/Upper_West_Side\n/wiki/Manhattan\n/wiki/Tracy_Pollan\n/wiki/The_Times\n/wiki/Will.i.am\n/wiki/It%27s_a_New_Day_(Will.i.am_song)\n/wiki/Barack_Obama\n/wiki/Ponzi_scheme\n/wiki/Bernard_Madoff\n/wiki/Finding_Your_Roots\n/wiki/Henry_Louis_Gates\n/wiki/Six_Degrees_of_Kevin_Bacon\n/wiki/Trivia\n/wiki/Big_screen\n/wiki/Six_degrees_of_separation\n/wiki/Internet_meme\n/wiki/SixDegrees.org\n/wiki/Bacon_number\n/wiki/Internet_Movie_Database\n/wiki/Paul_Erd%C5%91s\n/wiki/Erd%C5%91s_number\n/wiki/Paul_Erd%C5%91s\n/wiki/Bacon_number\n/wiki/Erd%C5%91s_number\n/wiki/Erd%C5%91s%E2%80%93Bacon_number\n/wiki/The_Bacon_Brothers\n/wiki/Michael_Bacon_(musician)\n/wiki/Music_album\n/wiki/Golden_Globe_Awards\n/wiki/Golden_Globe_Award_for_Best_Supporting_Actor_%E2%80%93_Motion_Picture\n/wiki/The_River_Wild\n/wiki/Broadcast_Film_Critics_Association_Awards\n/wiki/Broadcast_Film_Critics_Association_Award_for_Best_Actor\n/wiki/Murder_in_the_First_(film)\n/wiki/Screen_Actors_Guild_Awards\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Cast_in_a_Motion_Picture\n/wiki/Apollo_13_(film)\n/wiki/Screen_Actors_Guild_Awards\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Male_Actor_in_a_Supporting_Role\n/wiki/Murder_in_the_First_(film)\n/wiki/MTV_Movie_Awards\n/wiki/MTV_Movie_Award_for_Best_Villain\n/wiki/Hollow_Man\n/wiki/Boston_Society_of_Film_Critics_Awards\n/wiki/Boston_Society_of_Film_Critics_Award_for_Best_Cast\n/wiki/Mystic_River_(film)\n/wiki/Screen_Actors_Guild_Awards\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Cast_in_a_Motion_Picture\n/wiki/Mystic_River_(film)\n/wiki/Satellite_Awards\n/wiki/Satellite_Award_for_Best_Actor_%E2%80%93_Motion_Picture_Drama\n/wiki/The_Woodsman_(2004_film)\n/wiki/Teen_Choice_Awards\n/wiki/Teen_Choice_Awards\n/wiki/Beauty_Shop\n/wiki/Primetime_Emmy_Awards\n/wiki/Primetime_Emmy_Award_for_Outstanding_Lead_Actor_in_a_Miniseries_or_a_Movie\n/wiki/Taking_Chance\n/wiki/Satellite_Awards\n/wiki/Satellite_Award_for_Best_Actor_%E2%80%93_Miniseries_or_Television_Film\n/wiki/Taking_Chance\n/wiki/Screen_Actors_Guild_Awards\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Cast_in_a_Motion_Picture\n/wiki/Frost/Nixon_(film)\n/wiki/Golden_Globe_Awards\n/wiki/Golden_Globe_Award_for_Best_Actor_%E2%80%93_Miniseries_or_Television_Film\n/wiki/Taking_Chance\n/wiki/Screen_Actors_Guild_Awards\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Male_Actor_in_a_Miniseries_or_Television_Movie\n/wiki/Taking_Chance\n/wiki/Teen_Choice_Awards\n/wiki/Teen_Choice_Awards\n/wiki/Saturn_Awards\n/wiki/Saturn_Award_for_Best_Actor_on_Television\n/wiki/The_Following\n/wiki/People%27s_Choice_Awards\n/wiki/People%27s_Choice_Awards\n/wiki/The_Following\n/wiki/Saturn_Awards\n/wiki/Saturn_Award_for_Best_Actor_on_Television\n/wiki/The_Following\n/wiki/Golden_Globe_Awards\n/wiki/Golden_Globe_Award_for_Best_Actor_%E2%80%93_Television_Series_Musical_or_Comedy\n/wiki/I_Love_Dick_(TV_series)\n/wiki/Kevin_Bacon_filmography\n/wiki/List_of_actors_with_Hollywood_Walk_of_Fame_motion_picture_stars\n/wiki/The_Austin_Chronicle\n/wiki/Access_Hollywood\n/wiki/Reuters\n/wiki/CBS_News\n/wiki/The_Verge\n/wiki/The_Hollywood_Reporter\n/wiki/Indie_Wire\n/wiki/IMDb\n/wiki/Internet_Broadway_Database\n/wiki/Lortel_Archives\n/wiki/AllMovie\n/wiki/Critics%27_Choice_Movie_Award_for_Best_Actor\n/wiki/Geoffrey_Rush\n/wiki/Jack_Nicholson\n/wiki/Ian_McKellen\n/wiki/Russell_Crowe\n/wiki/Russell_Crowe\n/wiki/Russell_Crowe\n/wiki/Daniel_Day-Lewis\n/wiki/Jack_Nicholson\n/wiki/Sean_Penn\n/wiki/Jamie_Foxx\n/wiki/Philip_Seymour_Hoffman\n/wiki/Forest_Whitaker\n/wiki/Daniel_Day-Lewis\n/wiki/Sean_Penn\n/wiki/Jeff_Bridges\n/wiki/Colin_Firth\n/wiki/George_Clooney\n/wiki/Daniel_Day-Lewis\n/wiki/Matthew_McConaughey\n/wiki/Michael_Keaton\n/wiki/Leonardo_DiCaprio\n/wiki/Casey_Affleck\n/wiki/Gary_Oldman\n/wiki/Golden_Globe_Award_for_Best_Actor_%E2%80%93_Miniseries_or_Television_Film\n/wiki/Mickey_Rooney\n/wiki/Anthony_Andrews\n/wiki/Richard_Chamberlain\n/wiki/Ted_Danson\n/wiki/Dustin_Hoffman\n/wiki/James_Woods\n/wiki/Randy_Quaid\n/wiki/Michael_Caine\n/wiki/Stacy_Keach\n/wiki/Robert_Duvall\n/wiki/James_Garner\n/wiki/Beau_Bridges\n/wiki/Robert_Duvall\n/wiki/James_Garner\n/wiki/Ra%C3%BAl_Juli%C3%A1\n/wiki/Gary_Sinise\n/wiki/Alan_Rickman\n/wiki/Ving_Rhames\n/wiki/Stanley_Tucci\n/wiki/Jack_Lemmon\n/wiki/Brian_Dennehy\n/wiki/James_Franco\n/wiki/Albert_Finney\n/wiki/Al_Pacino\n/wiki/Geoffrey_Rush\n/wiki/Jonathan_Rhys_Meyers\n/wiki/Bill_Nighy\n/wiki/Jim_Broadbent\n/wiki/Paul_Giamatti\n/wiki/Al_Pacino\n/wiki/Idris_Elba\n/wiki/Kevin_Costner\n/wiki/Michael_Douglas\n/wiki/Billy_Bob_Thornton\n/wiki/Oscar_Isaac\n/wiki/Tom_Hiddleston\n/wiki/Ewan_McGregor\n/wiki/Saturn_Award_for_Best_Actor_on_Television\n/wiki/Kyle_Chandler\n/wiki/Steven_Weber_(actor)\n/wiki/Richard_Dean_Anderson\n/wiki/David_Boreanaz\n/wiki/Robert_Patrick\n/wiki/Ben_Browder\n/wiki/David_Boreanaz\n/wiki/David_Boreanaz\n/wiki/Ben_Browder\n/wiki/Matthew_Fox\n/wiki/Michael_C._Hall\n/wiki/Matthew_Fox\n/wiki/Edward_James_Olmos\n/wiki/Josh_Holloway\n/wiki/Stephen_Moyer\n/wiki/Bryan_Cranston\n/wiki/Bryan_Cranston\n/wiki/Mads_Mikkelsen\n/wiki/Hugh_Dancy\n/wiki/Andrew_Lincoln\n/wiki/Bruce_Campbell\n/wiki/Andrew_Lincoln\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Male_Actor_in_a_Miniseries_or_Television_Movie\n/wiki/Ra%C3%BAl_Juli%C3%A1\n/wiki/Gary_Sinise\n/wiki/Alan_Rickman\n/wiki/Gary_Sinise\n/wiki/Christopher_Reeve\n/wiki/Jack_Lemmon\n/wiki/Brian_Dennehy\n/wiki/Ben_Kingsley\n/wiki/William_H._Macy\n/wiki/Al_Pacino\n/wiki/Geoffrey_Rush\n/wiki/Paul_Newman\n/wiki/Jeremy_Irons\n/wiki/Kevin_Kline\n/wiki/Paul_Giamatti\n/wiki/Al_Pacino\n/wiki/Paul_Giamatti\n/wiki/Kevin_Costner\n/wiki/Michael_Douglas\n/wiki/Mark_Ruffalo\n/wiki/Idris_Elba\n/wiki/Bryan_Cranston\n/wiki/Alexander_Skarsg%C3%A5rd\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Cast_in_a_Motion_Picture\n/wiki/Apollo_13_(film)\n/wiki/Tom_Hanks\n/wiki/Ed_Harris\n/wiki/Bill_Paxton\n/wiki/Kathleen_Quinlan\n/wiki/Gary_Sinise\n/wiki/The_Birdcage\n/wiki/Hank_Azaria\n/wiki/Christine_Baranski\n/wiki/Dan_Futterman\n/wiki/Gene_Hackman\n/wiki/Nathan_Lane\n/wiki/Dianne_Wiest\n/wiki/Robin_Williams\n/wiki/The_Full_Monty\n/wiki/Mark_Addy\n/wiki/Paul_Barber_(actor)\n/wiki/Robert_Carlyle\n/wiki/Steve_Huison\n/wiki/Bruce_Jones_(actor)\n/wiki/Lesley_Sharp\n/wiki/William_Snape\n/wiki/Hugo_Speer\n/wiki/Tom_Wilkinson\n/wiki/Emily_Woof\n/wiki/Shakespeare_in_Love\n/wiki/Ben_Affleck\n/wiki/Simon_Callow\n/wiki/Jim_Carter_(actor)\n/wiki/Martin_Clunes\n/wiki/Judi_Dench\n/wiki/Joseph_Fiennes\n/wiki/Colin_Firth\n/wiki/Gwyneth_Paltrow\n/wiki/Geoffrey_Rush\n/wiki/Antony_Sher\n/wiki/Imelda_Staunton\n/wiki/American_Beauty_(1999_film)\n/wiki/Annette_Bening\n/wiki/Wes_Bentley\n/wiki/Thora_Birch\n/wiki/Chris_Cooper\n/wiki/Peter_Gallagher\n/wiki/Allison_Janney\n/wiki/Kevin_Spacey\n/wiki/Mena_Suvari\n/wiki/Traffic_(2000_film)\n/wiki/Steven_Bauer\n/wiki/Benjamin_Bratt\n/wiki/James_Brolin\n/wiki/Don_Cheadle\n/wiki/Erika_Christensen\n/wiki/Clifton_Collins_Jr.\n/wiki/Benicio_del_Toro\n/wiki/Michael_Douglas\n/wiki/Miguel_Ferrer\n/wiki/Albert_Finney\n/wiki/Topher_Grace\n/wiki/Luis_Guzm%C3%A1n\n/wiki/Amy_Irving\n/wiki/Tomas_Milian\n/wiki/D._W._Moffett\n/wiki/Dennis_Quaid\n/wiki/Peter_Riegert\n/wiki/Jacob_Vargas\n/wiki/Catherine_Zeta-Jones\n/wiki/Screen_Actors_Guild_Award_for_Outstanding_Performance_by_a_Cast_in_a_Motion_Picture\n/wiki/Virtual_International_Authority_File\n/wiki/Library_of_Congress_Control_Number\n/wiki/International_Standard_Name_Identifier\n/wiki/Integrated_Authority_File\n/wiki/Syst%C3%A8me_universitaire_de_documentation\n/wiki/Biblioth%C3%A8que_nationale_de_France\n/wiki/MusicBrainz\n/wiki/SNAC\n"
]
],
[
[
"## Random Walk",
"_____no_output_____"
]
],
[
[
"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport datetime\nimport random\nimport re\n\nrandom.seed(datetime.datetime.now())\ndef getLinks(articleUrl):\n html = urlopen('http://en.wikipedia.org{}'.format(articleUrl))\n bs = BeautifulSoup(html, 'html.parser')\n return bs.find('div', {'id':'bodyContent'}).find_all('a', href=re.compile('^(/wiki/)((?!:).)*$'))\n\nlinks = getLinks('/wiki/Kevin_Bacon')\nwhile len(links) > 0:\n newArticle = links[random.randint(0, len(links)-1)].attrs['href']\n print(newArticle)\n links = getLinks(newArticle)",
"/wiki/MusicBrainz\n/wiki/ICANN\n/wiki/U.S._House_of_Representatives\n/wiki/United_States_Copyright_Office\n/wiki/U.S._representative_bibliography_(congressional_memoirs)\n/wiki/United_States_Senate\n/wiki/Richard_A._Baker_(historian)\n/wiki/Robert_Byrd\n/wiki/Washington_College_of_Law\n"
]
],
[
[
"## Recursively crawling an entire site",
"_____no_output_____"
]
],
[
[
"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\n\npages = set()\ndef getLinks(pageUrl):\n global pages\n html = urlopen('http://en.wikipedia.org{}'.format(pageUrl))\n bs = BeautifulSoup(html, 'html.parser')\n for link in bs.find_all('a', href=re.compile('^(/wiki/)')):\n if 'href' in link.attrs:\n if link.attrs['href'] not in pages:\n #We have encountered a new page\n newPage = link.attrs['href']\n print(newPage)\n pages.add(newPage)\n getLinks(newPage)\ngetLinks('')",
"/wiki/Wikipedia\n/wiki/Wikipedia:Protection_policy#semi\n/wiki/Wikipedia:Requests_for_page_protection\n/wiki/Wikipedia:Requests_for_permissions\n"
]
],
[
[
"## Collecting Data Across an Entire Site",
"_____no_output_____"
]
],
[
[
"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\n\npages = set()\ndef getLinks(pageUrl):\n global pages\n html = urlopen('http://en.wikipedia.org{}'.format(pageUrl))\n bs = BeautifulSoup(html, 'html.parser')\n try:\n print(bs.h1.get_text())\n print(bs.find(id ='mw-content-text').find_all('p')[0])\n print(bs.find(id='ca-edit').find('span').find('a').attrs['href'])\n except AttributeError:\n print('This page is missing something! Continuing.')\n \n for link in bs.find_all('a', href=re.compile('^(/wiki/)')):\n if 'href' in link.attrs:\n if link.attrs['href'] not in pages:\n #We have encountered a new page\n newPage = link.attrs['href']\n print('-'*20)\n print(newPage)\n pages.add(newPage)\n getLinks(newPage)\ngetLinks('') ",
"Main Page\n<p>The <b><a href=\"/wiki/Finnish_Civil_War\" title=\"Finnish Civil War\">Finnish Civil War</a></b> (27 January – 15 May 1918) marked the transition from the <a href=\"/wiki/Grand_Duchy_of_Finland\" title=\"Grand Duchy of Finland\">Grand Duchy of Finland</a>, part of the <a href=\"/wiki/Russian_Empire\" title=\"Russian Empire\">Russian Empire</a>, to an independent state. Arising during <a href=\"/wiki/World_War_I\" title=\"World War I\">World War I</a>, it was fought between the Reds, led by the <a href=\"/wiki/Social_Democratic_Party_of_Finland\" title=\"Social Democratic Party of Finland\">Social Democratic Party</a>, and the Whites, led by the conservative <a href=\"/wiki/Senate_of_Finland\" title=\"Senate of Finland\">Senate</a>. In February 1918, the Reds carried out an unsuccessful offensive, supplied with weapons by <a class=\"mw-redirect\" href=\"/wiki/Soviet_Russia\" title=\"Soviet Russia\">Soviet Russia</a>. A counteroffensive by the Whites began in March, reinforced by the <a href=\"/wiki/German_Empire\" title=\"German Empire\">German Empire</a>'s military detachments in April. The decisive engagements were the battles of <a href=\"/wiki/Battle_of_Tampere\" title=\"Battle of Tampere\">Tampere</a> and <a href=\"/wiki/Battle_of_Vyborg\" title=\"Battle of Vyborg\">Vyborg</a>, won by the Whites, and the battles of <a href=\"/wiki/Battle_of_Helsinki\" title=\"Battle of Helsinki\">Helsinki</a> and <a href=\"/wiki/Battle_of_Lahti\" title=\"Battle of Lahti\">Lahti</a>, won by German troops, leading to overall victory for the Whites and the German forces. The 39,000 casualties included <a class=\"mw-redirect\" href=\"/wiki/Political_terror\" title=\"Political terror\">political terror</a> deaths. Although the Senate and Parliament were initially pressured into accepting the <a href=\"/wiki/Prince_Frederick_Charles_of_Hesse\" title=\"Prince Frederick Charles of Hesse\">brother-in-law</a> of German Emperor <a class=\"mw-redirect\" href=\"/wiki/William_II,_German_Emperor\" title=\"William II, German Emperor\">William II</a> as the <a href=\"/wiki/Kingdom_of_Finland_(1918)\" title=\"Kingdom of Finland (1918)\">King of Finland</a>, the country emerged within a few months as an independent, democratic republic. The war would divide the nation for decades. (<a href=\"/wiki/Finnish_Civil_War\" title=\"Finnish Civil War\"><b>Full article...</b></a>)</p>\nThis page is missing something! No worries, we will continue!\n--------------------\n/wiki/Wikipedia\nWikipedia\n<p><b>Wikipedia</b> (<span class=\"nowrap\"><span class=\"IPA nopopups noexcerpt\"><a href=\"/wiki/Help:IPA/English\" title=\"Help:IPA/English\">/<span style=\"border-bottom:1px dotted\"><span title=\"/ˌ/: secondary stress follows\">ˌ</span><span title=\"'w' in 'wind'\">w</span><span title=\"/ɪ/: 'i' in 'kit'\">ɪ</span><span title=\"'k' in 'kind'\">k</span><span title=\"/ɪ/: 'i' in 'kit'\">ɪ</span><span title=\"/ˈ/: primary stress follows\">ˈ</span><span title=\"'p' in 'pie'\">p</span><span title=\"/iː/: 'ee' in 'fleece'\">iː</span><span title=\"'d' in 'dye'\">d</span><span title=\"/i/: 'y' in 'happy'\">i</span><span title=\"/ə/: 'a' in 'about'\">ə</span></span>/</a></span><small class=\"nowrap\"> (<span class=\"unicode haudio\"><span class=\"fn\"><span style=\"white-space:nowrap\"><a href=\"/wiki/File:GT_Wikipedia_BE.ogg\" title=\"About this sound\"><img alt=\"About this sound\" data-file-height=\"20\" data-file-width=\"20\" height=\"11\" src=\"//upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Loudspeaker.svg/11px-Loudspeaker.svg.png\" srcset=\"//upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Loudspeaker.svg/17px-Loudspeaker.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Loudspeaker.svg/22px-Loudspeaker.svg.png 2x\" width=\"11\"/></a> </span><a class=\"internal\" href=\"//upload.wikimedia.org/wikipedia/commons/0/01/GT_Wikipedia_BE.ogg\" title=\"GT Wikipedia BE.ogg\">listen</a></span></span>)</small></span> <a href=\"/wiki/Help:Pronunciation_respelling_key\" title=\"Help:Pronunciation respelling key\"><i title=\"English pronunciation respelling\"><span style=\"font-size:90%\">WIK</span>-i-<span style=\"font-size:90%\">PEE</span>-dee-ə</i></a> or <span class=\"nowrap\"><span class=\"IPA nopopups noexcerpt\"><a href=\"/wiki/Help:IPA/English\" title=\"Help:IPA/English\">/<span style=\"border-bottom:1px dotted\"><span title=\"/ˌ/: secondary stress follows\">ˌ</span><span title=\"'w' in 'wind'\">w</span><span title=\"/ɪ/: 'i' in 'kit'\">ɪ</span><span title=\"'k' in 'kind'\">k</span><span title=\"/i/: 'y' in 'happy'\">i</span><span title=\"/ˈ/: primary stress follows\">ˈ</span><span title=\"'p' in 'pie'\">p</span><span title=\"/iː/: 'ee' in 'fleece'\">iː</span><span title=\"'d' in 'dye'\">d</span><span title=\"/i/: 'y' in 'happy'\">i</span><span title=\"/ə/: 'a' in 'about'\">ə</span></span>/</a></span><small class=\"nowrap\"> (<span class=\"unicode haudio\"><span class=\"fn\"><span style=\"white-space:nowrap\"><a href=\"/wiki/File:GT_Wikipedia_AE.ogg\" title=\"About this sound\"><img alt=\"About this sound\" data-file-height=\"20\" data-file-width=\"20\" height=\"11\" src=\"//upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Loudspeaker.svg/11px-Loudspeaker.svg.png\" srcset=\"//upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Loudspeaker.svg/17px-Loudspeaker.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Loudspeaker.svg/22px-Loudspeaker.svg.png 2x\" width=\"11\"/></a> </span><a class=\"internal\" href=\"//upload.wikimedia.org/wikipedia/commons/4/4c/GT_Wikipedia_AE.ogg\" title=\"GT Wikipedia AE.ogg\">listen</a></span></span>)</small></span> <a href=\"/wiki/Help:Pronunciation_respelling_key\" title=\"Help:Pronunciation respelling key\"><i title=\"English pronunciation respelling\"><span style=\"font-size:90%\">WIK</span>-ee-<span style=\"font-size:90%\">PEE</span>-dee-ə</i></a>) is a free <a href=\"/wiki/Online_encyclopedia\" title=\"Online encyclopedia\">online encyclopedia</a> with the mission of allowing anyone to edit articles.<sup class=\"reference\" id=\"cite_ref-6\"><a href=\"#cite_note-6\">[3]</a></sup><sup class=\"noprint Inline-Template\" style=\"white-space:nowrap;\">[<i><a href=\"/wiki/Wikipedia:Verifiability\" title=\"Wikipedia:Verifiability\"><span title=\"The material near this tag failed verification of its source citation(s). (January 2018)\">not in citation given</span></a></i>]</sup> Wikipedia is the largest and most popular general <a href=\"/wiki/Reference_work\" title=\"Reference work\">reference work</a> on the Internet,<sup class=\"reference\" id=\"cite_ref-Tancer_7-0\"><a href=\"#cite_note-Tancer-7\">[4]</a></sup><sup class=\"reference\" id=\"cite_ref-Woodson_8-0\"><a href=\"#cite_note-Woodson-8\">[5]</a></sup><sup class=\"reference\" id=\"cite_ref-9\"><a href=\"#cite_note-9\">[6]</a></sup> and is ranked the fifth-most popular website.<sup class=\"reference\" id=\"cite_ref-Alexa_siteinfo_10-0\"><a href=\"#cite_note-Alexa_siteinfo-10\">[7]</a></sup> Wikipedia is owned by the nonprofit <a href=\"/wiki/Wikimedia_Foundation\" title=\"Wikimedia Foundation\">Wikimedia Foundation</a>.<sup class=\"reference\" id=\"cite_ref-11\"><a href=\"#cite_note-11\">[8]</a></sup><sup class=\"reference\" id=\"cite_ref-12\"><a href=\"#cite_note-12\">[9]</a></sup><sup class=\"reference\" id=\"cite_ref-13\"><a href=\"#cite_note-13\">[10]</a></sup></p>\nThis page is missing something! No worries, we will continue!\n--------------------\n/wiki/Wikipedia:Protection_policy#semi\nWikipedia:Protection policy\n<p>Wikipedia is built around the principle that <a href=\"/wiki/Wiki\" title=\"Wiki\">anyone can edit it</a>, and it therefore aims to have as many of its pages as possible open for public editing so that anyone can add material and correct errors. However, in some particular circumstances, because of a specifically identified likelihood of damage resulting if editing is left open, some individual pages may need to be subject to technical restrictions (often only temporary but sometimes indefinitely) on who is permitted to modify them. The placing of such restrictions on pages is called <b>protection</b>.</p>\nThis page is missing something! No worries, we will continue!\n--------------------\n/wiki/Wikipedia:Requests_for_page_protection\nWikipedia:Requests for page protection\n<p>This page is for requesting that a page, file or template be <b>fully protected</b>, <b>create protected</b> (<a href=\"/wiki/Wikipedia:Protection_policy#Creation_protection\" title=\"Wikipedia:Protection policy\">salted</a>), <b>extended confirmed protected</b>, <b>semi-protected</b>, added to <b>pending changes</b>, <b>move-protected</b>, <b>template protected</b> (template-specific), <b>upload protected</b> (file-specific), or <b>unprotected</b>. Please read up on the <a href=\"/wiki/Wikipedia:Protection_policy\" title=\"Wikipedia:Protection policy\">protection policy</a>. Full protection is used to stop edit warring between multiple users or to prevent vandalism to <a href=\"/wiki/Wikipedia:High-risk_templates\" title=\"Wikipedia:High-risk templates\">high-risk templates</a>; semi-protection and pending changes are usually used only to prevent IP and new user vandalism (see the <a href=\"/wiki/Wikipedia:Rough_guide_to_semi-protection\" title=\"Wikipedia:Rough guide to semi-protection\">rough guide to semi-protection</a>); and move protection is used to stop <a href=\"/wiki/Wikipedia:Moving_a_page\" title=\"Wikipedia:Moving a page\">pagemove</a> revert wars. Extended confirmed protection is used where semi-protection has proved insufficient (see the <a href=\"/wiki/Wikipedia:Rough_guide_to_extended_confirmed_protection\" title=\"Wikipedia:Rough guide to extended confirmed protection\">rough guide to extended confirmed protection</a>)</p>\n/w/index.php?title=Wikipedia:Requests_for_page_protection&action=edit\n--------------------\n/wiki/Wikipedia:Requests_for_permissions\n"
]
],
[
[
"## Crawling across the Internet",
"_____no_output_____"
]
],
[
[
"from urllib.request import urlopen\nfrom urllib.parse import urlparse\nfrom bs4 import BeautifulSoup\nimport re\nimport datetime\nimport random\n\npages = set()\nrandom.seed(datetime.datetime.now())\n\n#Retrieves a list of all Internal links found on a page\ndef getInternalLinks(bs, includeUrl):\n includeUrl = '{}://{}'.format(urlparse(includeUrl).scheme, urlparse(includeUrl).netloc)\n internalLinks = []\n #Finds all links that begin with a \"/\"\n for link in bs.find_all('a', href=re.compile('^(/|.*'+includeUrl+')')):\n if link.attrs['href'] is not None:\n if link.attrs['href'] not in internalLinks:\n if(link.attrs['href'].startswith('/')):\n internalLinks.append(includeUrl+link.attrs['href'])\n else:\n internalLinks.append(link.attrs['href'])\n return internalLinks\n \n#Retrieves a list of all external links found on a page\ndef getExternalLinks(bs, excludeUrl):\n externalLinks = []\n #Finds all links that start with \"http\" that do\n #not contain the current URL\n for link in bs.find_all('a', href=re.compile('^(http|www)((?!'+excludeUrl+').)*$')):\n if link.attrs['href'] is not None:\n if link.attrs['href'] not in externalLinks:\n externalLinks.append(link.attrs['href'])\n return externalLinks\n\ndef getRandomExternalLink(startingPage):\n html = urlopen(startingPage)\n bs = BeautifulSoup(html, 'html.parser')\n externalLinks = getExternalLinks(bs, urlparse(startingPage).netloc)\n if len(externalLinks) == 0:\n print('No external links, looking around the site for one')\n domain = '{}://{}'.format(urlparse(startingPage).scheme, urlparse(startingPage).netloc)\n internalLinks = getInternalLinks(bs, domain)\n return getRandomExternalLink(internalLinks[random.randint(0,\n len(internalLinks)-1)])\n else:\n return externalLinks[random.randint(0, len(externalLinks)-1)]\n \ndef followExternalOnly(startingSite):\n externalLink = getRandomExternalLink(startingSite)\n print('Random external link is: {}'.format(externalLink))\n followExternalOnly(externalLink)\n \nfollowExternalOnly('http://oreilly.com')",
"Random external link is: http://twitter.com/oreillymedia\n"
]
],
[
[
"## Collect all External Links from a Site",
"_____no_output_____"
]
],
[
[
"# Collects a list of all external URLs found on the site\nallExtLinks = set()\nallIntLinks = set()\n\n\ndef getAllExternalLinks(siteUrl):\n html = urlopen(siteUrl)\n domain = '{}://{}'.format(urlparse(siteUrl).scheme,\n urlparse(siteUrl).netloc)\n bs = BeautifulSoup(html, 'html.parser')\n internalLinks = getInternalLinks(bs, domain)\n externalLinks = getExternalLinks(bs, domain)\n\n for link in externalLinks:\n if link not in allExtLinks:\n allExtLinks.add(link)\n print(link)\n for link in internalLinks:\n if link not in allIntLinks:\n allIntLinks.add(link)\n getAllExternalLinks(link)\n\n\nallIntLinks.add('http://oreilly.com')\ngetAllExternalLinks('http://oreilly.com')",
"https://www.oreilly.com\nhttp://www.oreilly.com/ideas\nhttps://www.safaribooksonline.com/?utm_medium=content&utm_source=oreilly.com&utm_campaign=lgen&utm_content=20170601+nav\nhttp://www.oreilly.com/conferences/\nhttp://shop.oreilly.com/\nhttp://members.oreilly.com\nhttps://www.oreilly.com/topics\nhttps://www.safaribooksonline.com/?utm_medium=content&utm_source=oreilly.com&utm_campaign=lgen&utm_content=20170505+homepage+get+started+now\nhttps://www.safaribooksonline.com/accounts/login/?utm_medium=content&utm_source=oreilly.com&utm_campaign=lgen&utm_content=20170203+homepage+sign+in\nhttps://www.safaribooksonline.com/live-training/?utm_medium=content&utm_source=oreilly.com&utm_campaign=lgen&utm_content=20170201+homepage+take+a+live+online+course\nhttps://www.safaribooksonline.com/learning-paths/?utm_medium=content&utm_source=oreilly.com&utm_campaign=lgen&utm_content=20170201+homepage+follow+a+path\nhttps://www.safaribooksonline.com/?utm_medium=content&utm_source=oreilly.com&utm_campaign=lgen&utm_content=20170505+homepage+unlimited+access\nhttp://www.oreilly.com/live-training/?view=grid\nhttps://www.safaribooksonline.com/your-experience/?utm_medium=content&utm_source=oreilly.com&utm_campaign=lgen&utm_content=20170201+homepage+safari+platform\nhttps://cdn.oreillystatic.com/pdf/oreilly_high_performance_organizations_whitepaper.pdf\nhttps://www.oreilly.com/ideas/8-data-trends-on-our-radar-for-2017?utm_medium=referral&utm_source=oreilly.com&utm_campaign=lgen&utm_content=link+2017+trends\nhttps://www.oreilly.com/ideas?utm_medium=referral&utm_source=oreilly.com&utm_campaign=lgen&utm_content=link+read+latest+articles\nhttp://www.oreilly.com/about/\nhttp://www.oreilly.com/work-with-us.html\nhttp://www.oreilly.com/careers/\nhttp://shop.oreilly.com/category/customer-service.do\nhttp://www.oreilly.com/about/contact.html\nhttp://twitter.com/oreillymedia\nhttp://fb.co/OReilly\nhttps://www.linkedin.com/company/oreilly-media\nhttps://www.youtube.com/user/OreillyMedia\nhttp://www.oreilly.com/emails/newsletters/\nhttp://www.oreilly.com/terms/\nhttp://www.oreilly.com/privacy.html\nhttp://www.oreilly.com/about/editorial_independence.html\nhttps://www.safaribooksonline.com/home/?utm_medium=content&utm_source=oreilly.com&utm_campaign=lgen&utm_content=20170601+nav\nhttp://www.oreilly.com/emails/newsletters/?display=preview#ai\nhttps://www.oreilly.com/privacy.html\nhttp://www.oreilly.com/ai/building-bots-with-natural-language-processing.csp?utm_source=oreilly&utm_medium=newsite&utm_campaign=ai-topic-cta\nhttps://www.flickr.com/photos/ebmorse/7536436622/in/dateposted/\nhttp://oreilly.com/about/\nhttp://oreilly.com/work-with-us.html\nhttp://oreilly.com/careers/\nhttps://plus.google.com/+oreillymedia\nhttp://oreilly.com/terms/\nhttp://oreilly.com/privacy.html\nhttps://www.safaribooksonline.com/home/?utm_source=newsite&utm_medium=content&utm_campaign=lgen&utm_content=business-topic-cta\nhttps://www.flickr.com/photos/pagedooley/4253159181/\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aa9dcee5424ccc44c10ed36fd30b9e6c621184e
| 44,981 |
ipynb
|
Jupyter Notebook
|
SMOTE Vectorized vs Original Zenodo.ipynb
|
MattEding/SMOTE-Benchmark
|
1c4834887c0cdf159b27077b89ab18832c01a54b
|
[
"Unlicense"
] | null | null | null |
SMOTE Vectorized vs Original Zenodo.ipynb
|
MattEding/SMOTE-Benchmark
|
1c4834887c0cdf159b27077b89ab18832c01a54b
|
[
"Unlicense"
] | null | null | null |
SMOTE Vectorized vs Original Zenodo.ipynb
|
MattEding/SMOTE-Benchmark
|
1c4834887c0cdf159b27077b89ab18832c01a54b
|
[
"Unlicense"
] | null | null | null | 135.48494 | 35,888 | 0.851293 |
[
[
[
"# Comparison of SMOTE implementations\nReplacing \"for loops\" in favor of numpy vectorizations.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"vector = pd.read_pickle('vector.pkl')\noriginal = pd.read_pickle('original.pkl')\n\nvec_time = vector['Time']\nvec_stat = vector.drop(columns=['Time'])\n\norig_time = original['Time']\norig_stat = original.drop(columns=['Time'])",
"_____no_output_____"
],
[
"# X_new and y_new are the same values between implementations\n(vec_stat == orig_stat).all().all()",
"_____no_output_____"
],
[
"# timeit with 100 trials\ntimes = pd.concat([vec_time, orig_time], axis=1) / 100\ntimes.columns = ['Vectorized', 'Original']\ntimes",
"_____no_output_____"
],
[
"times.plot.bar(figsize=(16, 10))\nplt.title('SMOTE Zenodo Average Times')\nplt.xlabel('Dataset')\nplt.ylabel('Time (sec)');",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
4aa9ddeccebd4a1d5b686b749ac3ec19adf15635
| 256,699 |
ipynb
|
Jupyter Notebook
|
pca_subcont.ipynb
|
GinoBacallao/hgdp_tgp
|
b674a79ad60da4c78b0b55a77e4cc4f138e9057e
|
[
"MIT"
] | 1 |
2021-02-26T17:45:20.000Z
|
2021-02-26T17:45:20.000Z
|
pca_subcont.ipynb
|
GinoBacallao/hgdp_tgp
|
b674a79ad60da4c78b0b55a77e4cc4f138e9057e
|
[
"MIT"
] | null | null | null |
pca_subcont.ipynb
|
GinoBacallao/hgdp_tgp
|
b674a79ad60da4c78b0b55a77e4cc4f138e9057e
|
[
"MIT"
] | null | null | null | 51.216879 | 2,517 | 0.541268 |
[
[
[
"import hail as hl",
"_____no_output_____"
]
],
[
[
"# *set up dataset* ",
"_____no_output_____"
]
],
[
[
"# read in the dataset Zan produced \n# metadata from Alicia + sample QC metadata from Julia + densified mt from Konrad\n# no samples or variants removed yet \nmt = hl.read_matrix_table('gs://african-seq-data/hgdp_tgp/hgdp_tgp_dense_meta_preQC.mt') # 211358784 snps & 4151 samples",
"Initializing Hail with default parameters...\nRunning on Apache Spark version 3.1.1\nSparkUI available at http://mty-m.c.neurogap-analysis.internal:39245\nWelcome to\n __ __ <>__\n / /_/ /__ __/ /\n / __ / _ `/ / /\n /_/ /_/\\_,_/_/_/ version 0.2.65-367cf1874d85\nLOGGING: writing to /home/hail/hail-20210726-2222-0.2.65-367cf1874d85.log\n"
],
[
"# read in variant QC metadata\nvar_meta = hl.read_table('gs://gcp-public-data--gnomad/release/3.1.1/ht/genomes/gnomad.genomes.v3.1.1.sites.ht')\n\n# annotate variant QC metadata onto mt \nmt = mt.annotate_rows(**var_meta[mt.locus, mt.alleles]) ",
"_____no_output_____"
],
[
"# read in the new dataset (including samples that were removed unknowngly) \nmt_post = hl.read_matrix_table('gs://african-seq-data/hgdp_tgp/new_hgdp_tgp_postQC.mt') # (155648020, 4099)",
"_____no_output_____"
]
],
[
[
"# *gnomAD filter QC*",
"_____no_output_____"
]
],
[
[
"# editing the format of the filter names and putting them together in a set so that we won't have an issue later when filtering the matrixTable using difference()\n# create a set of the gnomAD qc filters (column names under \"sample filters\") - looks like: {'sex_aneuploidy', 'insert_size', ...} but not in a certain order (randomly ordered)\nall_sample_filters = set(mt['sample_filters']) ",
"_____no_output_____"
],
[
"import re # for renaming purposes\n\n# bad_sample_filters are filters that removed whole populations despite them passing all other gnomAD filters (mostly AFR and OCE popns)\n# remove \"fail_\" from the filter names and pick those out (9 filters) - if the filter name starts with 'fail_' then replace it with ''\nbad_sample_filters = {re.sub('fail_', '', x) for x in all_sample_filters if x.startswith('fail_')} ",
"_____no_output_____"
],
[
"# this filters to only samples that passed all gnomad QC or only failed filters in bad_sample_filters\n# 'qc_metrics_filters' is under 'sample_filters' and includes a set of all qc filters a particular sample failed \n# if a sample passed all gnomAD qc filters then the column entry for that sample under 'qc_metrics_filters' is an empty set\n# so this line goes through the 'qc_metrics_filters'column and sees if there are any samples that passed all the other qc filters except for the ones in the \"bad_sample_filters\" set (difference()) \n# if a sample has an empty set for the 'qc_metrics_filters' column or if it only failed the filters that are found in the bad_sample_filters set, then a value of zero is returned and we would keep that sample \n# if a sample failed any filters that are not in the \"bad_sample_filters\" set, remove it\n# same as gs://african-seq-data/hgdp_tgp/hgdp_tgp_dense_meta_filt.mt - 211358784 snps & 4120 samples \nmt_filt = mt.filter_cols(mt['sample_filters']['qc_metrics_filters'].difference(bad_sample_filters).length() == 0) ",
"_____no_output_____"
],
[
"# How many samples were removed by the initial QC?\n\nprint('Num of samples before initial QC = ' + str(mt.count()[1])) # 4151\nprint('Num of samples after initial QC = ' + str(mt_filt.count()[1])) # 4120\nprint('Samples removed = ' + str(mt.count()[1] - mt_filt.count()[1])) # 31",
"Num of samples before initial QC = 4151\nNum of samples after initial QC = 4120\nSamples removed = 31\n"
]
],
[
[
"# *remove duplicate sample*",
"_____no_output_____"
]
],
[
[
"# duplicate sample - NA06985\nmt_filt = mt_filt.distinct_by_col()\nprint('Num of samples after removal of duplicate sample = ' + str(mt_filt.count()[1])) # 4119",
"Num of samples after removal of duplicate sample = 4119\n"
]
],
[
[
"# *keep only PASS variants*",
"_____no_output_____"
]
],
[
[
"# subset to only PASS variants (those which passed variant QC) ~6min to run \nmt_filt = mt_filt.filter_rows(hl.len(mt_filt.filters) !=0, keep=False)\nprint('Num of only PASS variants = ' + str(mt_filt.count()[0])) # 155648020",
"Num of only PASS variants = 155648020\n"
]
],
[
[
"# *variant filter and ld pruning* ",
"_____no_output_____"
]
],
[
[
"# run common variant statistics (quality control metrics) - more info https://hail.is/docs/0.2/methods/genetics.html#hail.methods.variant_qc \nmt_var = hl.variant_qc(mt_filt) ",
"_____no_output_____"
],
[
"# trying to get down to ~100-300k SNPs - might need to change values later accordingly \n# AF: allele freq and call_rate: fraction of calls neither missing nor filtered\n# mt.variant_qc.AF[0] is referring to the first element of the list under that column field \nmt_var_filt = mt_var.filter_rows((mt_var.variant_qc.AF[0] > 0.05) & (mt_var.variant_qc.AF[0] < 0.95) & (mt_var.variant_qc.call_rate > 0.999))",
"_____no_output_____"
],
[
"# ~20min to run \nmt_var_filt.count() # started with 155648020 snps and ended up with 6787034 snps ",
"_____no_output_____"
],
[
"# LD pruning (~113 min to run) \npruned = hl.ld_prune(mt_var_filt.GT, r2=0.1, bp_window_size=500000) ",
"2021-07-26 22:52:54 Hail: INFO: ld_prune: running local pruning stage with max queue size of 62138 variants\n2021-07-26 23:16:39 Hail: INFO: wrote table with 274800 rows in 5000 partitions to /tmp/SzTfV8GDfzsG9mBobMHawS\n Total size: 9.59 MiB\n * Rows: 9.59 MiB\n * Globals: 11.00 B\n * Smallest partition: 0 rows (21.00 B)\n * Largest partition: 359 rows (11.46 KiB)\n2021-07-27 00:41:45 Hail: INFO: Wrote all 136 blocks of 274800 x 4119 matrix with block size 4096.\n2021-07-27 00:46:32 Hail: INFO: wrote table with 43257 rows in 135 partitions to /tmp/3kwmZug0i0cztPhCBfhJwk\n Total size: 4.38 MiB\n * Rows: 749.66 KiB\n * Globals: 3.65 MiB\n * Smallest partition: 0 rows (21.00 B)\n * Largest partition: 1263 rows (22.23 KiB)\n"
],
[
"# subset data even further \nmt_var_pru_filt = mt_var_filt.filter_rows(hl.is_defined(pruned[mt_var_filt.row_key])) ",
"_____no_output_____"
],
[
"# write out the output as a temp file - make sure to save the file on this step b/c the pruning step takes a while to run\n# saving took ~23 min \nmt_var_pru_filt.write('gs://african-seq-data/hgdp_tgp/filtered_n_pruned_output_updated.mt', overwrite=False)",
"2021-07-27 01:18:32 Hail: INFO: wrote matrix table with 248634 rows and 4119 columns in 5000 partitions to gs://african-seq-data/hgdp_tgp/filtered_n_pruned_output_updated.mt\n Total size: 15.53 GiB\n * Rows/entries: 15.53 GiB\n * Columns: 1.70 MiB\n * Globals: 11.00 B\n * Smallest partition: 0 rows (20.00 B)\n * Largest partition: 357 rows (23.90 MiB)\n"
],
[
"# after saving the pruned file to the cloud, reading it back in for the next steps \nmt_var_pru_filt = hl.read_matrix_table('gs://african-seq-data/hgdp_tgp/filtered_n_pruned_output_updated.mt') ",
"Initializing Hail with default parameters...\nRunning on Apache Spark version 3.1.1\nSparkUI available at http://mty-m.c.neurogap-analysis.internal:40349\nWelcome to\n __ __ <>__\n / /_/ /__ __/ /\n / __ / _ `/ / /\n /_/ /_/\\_,_/_/_/ version 0.2.74-0c3a74d12093\nLOGGING: writing to /home/hail/hail-20210729-1724-0.2.74-0c3a74d12093.log\n"
],
[
"# how many snps are left after filtering and prunning? \nmt_var_pru_filt.count() # 248,634 snps \n# between ~100-300k so we proceed without any value adjustments ",
"_____no_output_____"
]
],
[
[
"# *run pc_relate* ",
"_____no_output_____"
]
],
[
[
"# compute relatedness estimates between individuals using a variant of the PC-Relate method (https://hail.is/docs/0.2/methods/relatedness.html#hail.methods.pc_relate)\n# only compute the kinship statistic using:\n# a minimum minor allele frequency filter of 0.05, \n# excluding sample-pairs with kinship less than 0.05, and \n# 20 principal components to control for population structure \n# a hail table is produced (~4min to run) \nrelatedness_ht = hl.pc_relate(mt_var_pru_filt.GT, min_individual_maf=0.05, min_kinship=0.05, statistics='kin', k=20).key_by()",
"2021-07-29 20:05:08 Hail: INFO: hwe_normalized_pca: running PCA using 248634 variants.\n2021-07-29 20:05:18 Hail: INFO: pca: running PCA with 20 components...\n2021-07-29 20:09:25 Hail: INFO: Wrote all 122 blocks of 248634 x 4119 matrix with block size 4096.\n"
],
[
"# write out result - for Julia (~2hr 19min to run)\n# includes i – first sample, j – second sample, and kin – kinship estimate\nrelatedness_ht.write('gs://african-seq-data/hgdp_tgp/relatedness.ht')",
"2021-07-29 17:30:34 Hail: INFO: wrote matrix with 21 rows and 248634 columns as 61 blocks of size 4096 to /tmp/pcrelate-write-read-OzfLBhWkelepw7GaY2fPwS.bm\n2021-07-29 17:30:39 Hail: INFO: wrote matrix with 248634 rows and 4119 columns as 122 blocks of size 4096 to /tmp/pcrelate-write-read-MH5U1wCqjkPwn4btHf78GX.bm\n2021-07-29 18:39:57 Hail: INFO: wrote matrix with 4119 rows and 4119 columns as 4 blocks of size 4096 to /tmp/pcrelate-write-read-17rZmsqlzGxTPJV4RYvzm6.bm\n2021-07-29 19:49:07 Hail: INFO: wrote matrix with 4119 rows and 4119 columns as 4 blocks of size 4096 to /tmp/pcrelate-write-read-KN9lD8cZysgwjNlZF99mMJ.bm\n2021-07-29 19:49:09 Hail: INFO: wrote matrix with 4119 rows and 4119 columns as 4 blocks of size 4096 to /tmp/pcrelate-write-read-jwgmibzfuGIFM1XojhxyfY.bm\n2021-07-29 19:49:09 Hail: INFO: Ordering unsorted dataset with network shuffle\n2021-07-29 19:49:14 Hail: INFO: wrote table with 1389 rows in 4 partitions to gs://african-seq-data/hgdp_tgp/relatedness.ht\n Total size: 23.01 KiB\n * Rows: 23.00 KiB\n * Globals: 11.00 B\n * Smallest partition: 0 rows (21.00 B)\n * Largest partition: 849 rows (14.04 KiB)\n"
],
[
"# read back in\nrelatedness_ht = hl.read_table('gs://african-seq-data/hgdp_tgp/relatedness.ht')",
"_____no_output_____"
],
[
"# identify related individuals in pairs to remove - returns a list of sample IDs (~2hr & 22 min to run) - previous one took ~13min\nrelated_samples_to_remove = hl.maximal_independent_set(relatedness_ht.i, relatedness_ht.j, False)",
"2021-07-29 20:03:45 Hail: INFO: wrote table with 1389 rows in 4 partitions to /tmp/Hj7jfbWKn4ZHoXUOs6merW\n Total size: 13.54 KiB\n * Rows: 13.53 KiB\n * Globals: 11.00 B\n * Smallest partition: 0 rows (21.00 B)\n * Largest partition: 849 rows (8.15 KiB)\n"
],
[
"# unkey table for exporting purposes - for Julia \nunkeyed_tbl = related_samples_to_remove.expand_types()\n\n# export sample IDs of related individuals \nunkeyed_tbl.node.s.export('gs://african-seq-data/hgdp_tgp/related_sample_ids.txt', header=False)\n\n# import back to see if format is correct \n#tbl = hl.import_table('gs://african-seq-data/hgdp_tgp/related_sample_ids.txt', impute=True, no_header=True)\n#tbl.show()",
"2021-07-27 04:20:36 Hail: INFO: Ordering unsorted dataset with network shuffle\n2021-07-27 04:20:37 Hail: INFO: merging 4 files totalling 5.8K...\n2021-07-27 04:20:37 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/related_sample_ids.txt\n merge time: 167.695ms\n"
],
[
"# using sample IDs (col_key of the matrixTable), pick out the samples that are not found in 'related_samples_to_remove' (had 'False' values for the comparison) \n# subset the mt to those only \nmt_unrel = mt_var_pru_filt.filter_cols(hl.is_defined(related_samples_to_remove[mt_var_pru_filt.col_key]), keep=False) ",
"2021-07-27 04:30:06 Hail: WARN: cols(): Resulting column table is sorted by 'col_key'.\n To preserve matrix table column order, first unkey columns with 'key_cols_by()'\n"
],
[
"# do the same as above but this time for the samples with 'True' values (found in 'related_samples_to_remove') \nmt_rel = mt_var_pru_filt.filter_cols(hl.is_defined(related_samples_to_remove[mt_var_pru_filt.col_key]), keep=True) ",
"_____no_output_____"
],
[
"# write out mts of unrelated and related samples on to the cloud \n\n# unrelated mt\nmt_unrel.write('gs://african-seq-data/hgdp_tgp/unrel_updated.mt', overwrite=False) \n\n# related mt \nmt_rel.write('gs://african-seq-data/hgdp_tgp/rel_updated.mt', overwrite=False) ",
"2021-07-27 04:30:35 Hail: INFO: Coerced sorted dataset\n2021-07-27 04:30:35 Hail: INFO: Ordering unsorted dataset with network shuffle\n2021-07-27 04:31:36 Hail: INFO: wrote matrix table with 248634 rows and 3399 columns in 5000 partitions to gs://african-seq-data/hgdp_tgp/unrel_updated.mt\n Total size: 13.14 GiB\n * Rows/entries: 13.14 GiB\n * Columns: 1.41 MiB\n * Globals: 11.00 B\n * Smallest partition: 0 rows (20.00 B)\n * Largest partition: 357 rows (20.17 MiB)\n2021-07-27 04:31:38 Hail: INFO: Coerced sorted dataset\n2021-07-27 04:31:40 Hail: INFO: Ordering unsorted dataset with network shuffle\n2021-07-27 04:32:25 Hail: INFO: wrote matrix table with 248634 rows and 720 columns in 5000 partitions to gs://african-seq-data/hgdp_tgp/rel_updated.mt\n Total size: 4.11 GiB\n * Rows/entries: 4.11 GiB\n * Columns: 301.36 KiB\n * Globals: 11.00 B\n * Smallest partition: 0 rows (20.00 B)\n * Largest partition: 357 rows (6.21 MiB)\n"
],
[
"# read saved mts back in \n\n# unrelated mt\nmt_unrel = hl.read_matrix_table('gs://african-seq-data/hgdp_tgp/unrel_updated.mt') \n\n# related mt \nmt_rel = hl.read_matrix_table('gs://african-seq-data/hgdp_tgp/rel_updated.mt') ",
"_____no_output_____"
]
],
[
[
"# PCA",
"_____no_output_____"
],
[
"# *run pca* ",
"_____no_output_____"
]
],
[
[
"def run_pca(mt: hl.MatrixTable, reg_name:str, out_prefix: str, overwrite: bool = False):\n \"\"\"\n Runs PCA on a dataset\n :param mt: dataset to run PCA on\n :param reg_name: region name for saving output purposes\n :param out_prefix: path for where to save the outputs\n :return:\n \"\"\"\n\n pca_evals, pca_scores, pca_loadings = hl.hwe_normalized_pca(mt.GT, k=20, compute_loadings=True)\n pca_mt = mt.annotate_rows(pca_af=hl.agg.mean(mt.GT.n_alt_alleles()) / 2)\n pca_loadings = pca_loadings.annotate(pca_af=pca_mt.rows()[pca_loadings.key].pca_af)\n pca_scores = pca_scores.transmute(**{f'PC{i}': pca_scores.scores[i - 1] for i in range(1, 21)})\n \n pca_scores.export(out_prefix + reg_name + '_scores.txt.bgz') # save individual-level genetic region PCs\n pca_loadings.write(out_prefix + reg_name + '_loadings.ht', overwrite) # save PCA loadings",
"_____no_output_____"
]
],
[
[
"# *project related individuals*",
"_____no_output_____"
]
],
[
[
"#if running on GCP, need to add \"--packages gnomad\" when starting a cluster in order for the import to work \nfrom gnomad.sample_qc.ancestry import *\n\ndef project_individuals(pca_loadings, project_mt, reg_name:str, out_prefix: str, overwrite: bool = False):\n \"\"\"\n Project samples into predefined PCA space\n :param pca_loadings: existing PCA space - unrelated samples \n :param project_mt: matrixTable of data to project - related samples \n :param reg_name: region name for saving output purposes\n :param project_prefix: path for where to save PCA projection outputs\n :return:\n \"\"\"\n ht_projections = pc_project(project_mt, pca_loadings) \n ht_projections = ht_projections.transmute(**{f'PC{i}': ht_projections.scores[i - 1] for i in range(1, 21)}) \n ht_projections.export(out_prefix + reg_name + '_projected_scores.txt.bgz') # save output \n #return ht_projections # return to user ",
"_____no_output_____"
]
],
[
[
"# *global pca*",
"_____no_output_____"
]
],
[
[
"# run 'run_pca' function for global pca \nrun_pca(mt_unrel, 'global', 'gs://african-seq-data/hgdp_tgp/pca_preoutlier/', False)",
"2021-07-27 16:05:30 Hail: INFO: hwe_normalized_pca: running PCA using 248634 variants.\n2021-07-27 16:05:41 Hail: INFO: pca: running PCA with 20 components...\n2021-07-27 16:07:59 Hail: INFO: Coerced sorted dataset\n2021-07-27 16:08:00 Hail: INFO: Ordering unsorted dataset with network shuffle\n2021-07-27 16:08:03 Hail: INFO: merging 16 files totalling 272.0K...\n2021-07-27 16:08:03 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_preoutlier/global_scores.txt.bgz\n merge time: 279.465ms\n2021-07-27 16:08:42 Hail: INFO: wrote table with 248634 rows in 4916 partitions to gs://african-seq-data/hgdp_tgp/pca_preoutlier/global_loadings.ht\n Total size: 45.23 MiB\n * Rows: 45.23 MiB\n * Globals: 11.00 B\n * Smallest partition: 1 rows (261.00 B)\n * Largest partition: 357 rows (65.26 KiB)\n"
],
[
"# run 'project_relateds' function for global pca \nloadings = hl.read_table('gs://african-seq-data/hgdp_tgp/pca_preoutlier/global_loadings.ht') # read in the PCA loadings that were obtained from 'run_pca' function \nproject_individuals(loadings, mt_rel, 'global', 'gs://african-seq-data/hgdp_tgp/pca_preoutlier/', False) ",
"2021-07-27 16:10:42 Hail: WARN: cols(): Resulting column table is sorted by 'col_key'.\n To preserve matrix table column order, first unkey columns with 'key_cols_by()'\n2021-07-27 16:11:02 Hail: INFO: Coerced sorted dataset\n2021-07-27 16:11:04 Hail: INFO: merging 16 files totalling 60.7K...\n2021-07-27 16:11:04 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_preoutlier/global_projected_scores.txt.bgz\n merge time: 211.694ms\n"
]
],
[
[
"# *subcontinental pca* ",
"_____no_output_____"
]
],
[
[
"# obtain a list of the genetic regions in the dataset - used the unrelated dataset since it had more samples \nregions = mt_unrel['hgdp_tgp_meta']['Genetic']['region'].collect()\nregions = list(dict.fromkeys(regions)) # 7 regions - ['EUR', 'AFR', 'AMR', 'EAS', 'CSA', 'OCE', 'MID']",
"_____no_output_____"
],
[
"# set argument values \nsubcont_pca_prefix = 'gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_' # path for outputs \noverwrite = False ",
"_____no_output_____"
],
[
"# run 'run_pca' function for each region - nb freezes after printing the log for AMR \n# don't restart it - just let it run and you can follow the progress through the SparkUI\n# even after all the outputs are produced and the run is complete, the code chunk will seem as if it's still running (* in the left square bracket)\n# can check if the run is complete by either checking the output files in the Google cloud bucket or using the SparkUI \n# after checking the desired outputs are generated and the run is done, exit the current nb, open a new session, and proceed to the next step\n# ~27min to run \nfor i in regions:\n subcont_unrel = mt_unrel.filter_cols(mt_unrel['hgdp_tgp_meta']['Genetic']['region'] == i) # filter the unrelateds per region\n run_pca(subcont_unrel, i, subcont_pca_prefix, overwrite)",
"2021-07-27 16:30:27 Hail: INFO: hwe_normalized_pca: running PCA using 245567 variants.\n2021-07-27 16:30:44 Hail: INFO: pca: running PCA with 20 components...\n2021-07-27 16:34:59 Hail: INFO: Coerced sorted dataset\n2021-07-27 16:35:00 Hail: INFO: Ordering unsorted dataset with network shuffle\n2021-07-27 16:35:01 Hail: INFO: merging 16 files totalling 55.6K...\n2021-07-27 16:35:01 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_EUR_scores.txt.bgz\n merge time: 202.187ms\n2021-07-27 16:35:40 Hail: INFO: wrote table with 245567 rows in 4916 partitions to gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_EUR_loadings.ht\n Total size: 44.42 MiB\n * Rows: 44.42 MiB\n * Globals: 11.00 B\n * Smallest partition: 1 rows (261.00 B)\n * Largest partition: 354 rows (64.04 KiB)\n2021-07-27 16:35:48 Hail: INFO: hwe_normalized_pca: running PCA using 247516 variants.\n2021-07-27 16:35:56 Hail: INFO: pca: running PCA with 20 components...\n2021-07-27 16:38:42 Hail: INFO: Coerced sorted dataset\n2021-07-27 16:38:43 Hail: INFO: Ordering unsorted dataset with network shuffle\n2021-07-27 16:38:45 Hail: INFO: merging 16 files totalling 63.4K...\n2021-07-27 16:38:45 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_AFR_scores.txt.bgz\n merge time: 212.289ms\n2021-07-27 16:39:23 Hail: INFO: wrote table with 247516 rows in 4916 partitions to gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_AFR_loadings.ht\n Total size: 44.71 MiB\n * Rows: 44.71 MiB\n * Globals: 11.00 B\n * Smallest partition: 1 rows (261.00 B)\n * Largest partition: 355 rows (64.15 KiB)\n2021-07-27 16:39:31 Hail: INFO: hwe_normalized_pca: running PCA using 248528 variants.\n2021-07-27 16:39:39 Hail: INFO: pca: running PCA with 20 components...\n2021-07-27 16:44:25 Hail: INFO: Coerced sorted dataset\n2021-07-27 16:44:25 Hail: INFO: Ordering unsorted dataset with network shuffle\n2021-07-27 16:44:26 Hail: INFO: merging 16 files totalling 34.1K...\n2021-07-27 16:44:27 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_AMR_scores.txt.bgz\n merge time: 187.341ms\n2021-07-27 16:45:02 Hail: INFO: wrote table with 248528 rows in 4916 partitions to gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_AMR_loadings.ht\n Total size: 44.95 MiB\n * Rows: 44.95 MiB\n * Globals: 11.00 B\n * Smallest partition: 1 rows (261.00 B)\n * Largest partition: 357 rows (64.56 KiB)\n2021-07-27 16:45:10 Hail: INFO: hwe_normalized_pca: running PCA using 238681 variants.\n2021-07-27 16:45:23 Hail: INFO: pca: running PCA with 20 components...\n2021-07-27 16:47:40 Hail: INFO: Coerced sorted dataset\n2021-07-27 16:47:41 Hail: INFO: Ordering unsorted dataset with network shuffle\n"
],
[
"# run 'project_relateds' function for each region (~2min to run)\nfor i in regions:\n loadings = hl.read_table(subcont_pca_prefix + i + '_loadings.ht') # for each region, read in the PCA loadings that were obtained from 'run_pca' function \n subcont_rel = mt_rel.filter_cols(mt_rel['hgdp_tgp_meta']['Genetic']['region'] == i) # filter the relateds per region \n project_individuals(loadings, subcont_rel, i, subcont_pca_prefix, overwrite) ",
"2021-07-27 17:14:52 Hail: INFO: Coerced sorted dataset\n2021-07-27 17:14:52 Hail: INFO: merging 16 files totalling 10.3K...\n2021-07-27 17:14:52 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_EUR_projected_scores.txt.bgz\n merge time: 246.192ms\n2021-07-27 17:15:07 Hail: INFO: Coerced sorted dataset\n2021-07-27 17:15:08 Hail: INFO: merging 16 files totalling 20.7K...\n2021-07-27 17:15:08 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_AFR_projected_scores.txt.bgz\n merge time: 242.575ms\n2021-07-27 17:15:24 Hail: INFO: Coerced sorted dataset\n2021-07-27 17:15:25 Hail: INFO: merging 16 files totalling 14.2K...\n2021-07-27 17:15:25 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_AMR_projected_scores.txt.bgz\n merge time: 243.723ms\n2021-07-27 17:15:39 Hail: INFO: Coerced sorted dataset\n2021-07-27 17:15:40 Hail: INFO: merging 16 files totalling 9.1K...\n2021-07-27 17:15:40 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_EAS_projected_scores.txt.bgz\n merge time: 186.221ms\n2021-07-27 17:16:02 Hail: INFO: Coerced sorted dataset\n2021-07-27 17:16:02 Hail: INFO: merging 16 files totalling 10.6K...\n2021-07-27 17:16:03 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_CSA_projected_scores.txt.bgz\n merge time: 284.668ms\n2021-07-27 17:16:15 Hail: INFO: Coerced sorted dataset\n2021-07-27 17:16:15 Hail: INFO: merging 2 files totalling 394...\n2021-07-27 17:16:16 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_OCE_projected_scores.txt.bgz\n merge time: 178.652ms\n2021-07-27 17:16:28 Hail: INFO: Coerced sorted dataset\n2021-07-27 17:16:28 Hail: INFO: merging 16 files totalling 3.0K...\n2021-07-27 17:16:29 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_preoutlier/subcont_pca/subcont_pca_MID_projected_scores.txt.bgz\n merge time: 215.513ms\n"
]
],
[
[
"# *outlier removal* \n#### After plotting the PCs, 22 outliers that need to be removed were identified (the table below will be completed for the final report)\n\n\n| s | Genetic region | Population | Note |\n| --- | --- | --- | -- |\n| NA20314 | AFR | ASW | Clusters with AMR in global PCA | \n| NA20299 | - | - | - |\n| NA20274 | - | - | - |\n| HG01880 | - | - | - |\n| HG01881 | - | - | - |\n| HG01628 | - | - | - |\n| HG01629 | - | - | - |\n| HG01630 | - | - | - |\n| HG01694 | - | - | - |\n| HG01696 | - | - | - |\n| HGDP00013 | - | - | - |\n| HGDP00150 | - | - | - |\n| HGDP00029 | - | - | - |\n| HGDP01298 | - | - | - |\n| HGDP00130 | CSA | Makrani | Closer to AFR than most CSA |\n| HGDP01303 | - | - | - |\n| HGDP01300 | - | - | - |\n| HGDP00621 | MID | Bedouin | Closer to AFR than most MID |\n| HGDP01270 | MID | Mozabite | Closer to AFR than most MID |\n| HGDP01271 | MID | Mozabite | Closer to AFR than most MID |\n| HGDP00057 | - | - | - | \n| LP6005443-DNA_B02 | - | - | - |\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n",
"_____no_output_____"
]
],
[
[
"# read back in the unrelated and related mts to remove outliers and run pca \nmt_unrel_unfiltered = hl.read_matrix_table('gs://african-seq-data/hgdp_tgp/unrel_updated.mt') # unrelated mt\nmt_rel_unfiltered = hl.read_matrix_table('gs://african-seq-data/hgdp_tgp/rel_updated.mt') # related mt ",
"Initializing Hail with default parameters...\nRunning on Apache Spark version 3.1.1\nSparkUI available at http://mty-m.c.neurogap-analysis.internal:35449\nWelcome to\n __ __ <>__\n / /_/ /__ __/ /\n / __ / _ `/ / /\n /_/ /_/\\_,_/_/_/ version 0.2.74-0c3a74d12093\nLOGGING: writing to /home/hail/hail-20210803-1848-0.2.74-0c3a74d12093.log\n"
],
[
"# read the outliers file into a list\nwith hl.utils.hadoop_open('gs://african-seq-data/hgdp_tgp/pca_outliers_v2.txt') as file: \n outliers = [line.rstrip('\\n') for line in file]\n \n# capture and broadcast the list as an expression\noutliers_list = hl.literal(outliers)",
"_____no_output_____"
],
[
"# remove 22 outliers \nmt_unrel = mt_unrel_unfiltered.filter_cols(~outliers_list.contains(mt_unrel_unfiltered['s']))\nmt_rel = mt_rel_unfiltered.filter_cols(~outliers_list.contains(mt_rel_unfiltered['s']))",
"_____no_output_____"
],
[
"# sanity check \nprint('Unrelated: Before filtering ' + str(mt_unrel_unfiltered.count()[1]) + ' | After filtering ' + str(mt_unrel.count()[1]))\nprint('Related: Before filtering: ' + str(mt_rel_unfiltered.count()[1]) + ' | After filtering ' + str(mt_rel.count()[1]))\n\nnum_outliers = (mt_unrel_unfiltered.count()[1] - mt_unrel.count()[1]) + (mt_rel_unfiltered.count()[1] - mt_rel.count()[1])\nprint('Total samples removed = ' + str(num_outliers))",
"Unrelated: Before filtering 3399 | After filtering 3380\nRelated: Before filtering: 720 | After filtering 717\nTotal samples removed = 22\n"
]
],
[
[
"# rerun PCA\n### - The following steps are similar to the ones prior to removing the outliers except now we are using the updated unrelated & related dataset and a new GCS bucket path to save the outputs ",
"_____no_output_____"
],
[
"# *global pca*",
"_____no_output_____"
]
],
[
[
"# run 'run_pca' function for global pca - make sure the code block for the function (located above) is run prior to running this \nrun_pca(mt_unrel, 'global', 'gs://african-seq-data/hgdp_tgp/pca_postoutlier/', False)",
"2021-08-03 17:45:09 Hail: INFO: hwe_normalized_pca: running PCA using 248634 variants.\n2021-08-03 17:45:22 Hail: INFO: pca: running PCA with 20 components...\n2021-08-03 17:47:33 Hail: INFO: Coerced sorted dataset\n2021-08-03 17:47:34 Hail: INFO: Ordering unsorted dataset with network shuffle\n2021-08-03 17:47:37 Hail: INFO: merging 16 files totalling 270.3K...\n2021-08-03 17:47:37 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_postoutlier/global_scores.txt.bgz\n merge time: 621.536ms\n2021-08-03 17:48:11 Hail: INFO: wrote table with 248634 rows in 4916 partitions to gs://african-seq-data/hgdp_tgp/pca_postoutlier/global_loadings.ht\n Total size: 45.21 MiB\n * Rows: 45.21 MiB\n * Globals: 11.00 B\n * Smallest partition: 1 rows (261.00 B)\n * Largest partition: 357 rows (65.13 KiB)\n"
],
[
"# run 'project_relateds' function for global pca - make sure the code block for the function (located above) is run prior to running this \nloadings = hl.read_table('gs://african-seq-data/hgdp_tgp/pca_postoutlier/global_loadings.ht') # read in the PCA loadings that were obtained from 'run_pca' function \nproject_individuals(loadings, mt_rel, 'global', 'gs://african-seq-data/hgdp_tgp/pca_postoutlier/', False) ",
"2021-08-03 17:50:20 Hail: WARN: cols(): Resulting column table is sorted by 'col_key'.\n To preserve matrix table column order, first unkey columns with 'key_cols_by()'\n2021-08-03 17:51:23 Hail: INFO: Coerced sorted dataset\n2021-08-03 17:51:25 Hail: INFO: merging 16 files totalling 60.3K...\n2021-08-03 17:51:25 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_postoutlier/global_projected_scores.txt.bgz\n merge time: 205.077ms\n"
]
],
[
[
"# *subcontinental pca* ",
"_____no_output_____"
]
],
[
[
"# obtain a list of the genetic regions in the dataset - used the unrelated dataset since it had more samples \nregions = mt_unrel['hgdp_tgp_meta']['Genetic']['region'].collect()\nregions = list(dict.fromkeys(regions)) # 7 regions - ['EUR', 'AFR', 'AMR', 'EAS', 'CSA', 'OCE', 'MID']",
"_____no_output_____"
],
[
"# set argument values \nsubcont_pca_prefix = 'gs://african-seq-data/hgdp_tgp/pca_postoutlier/subcont_pca/subcont_pca_' # path for outputs \noverwrite = False ",
"_____no_output_____"
],
[
"# run 'run_pca' function (located above) for each region \n# notebook became slow and got stuck - don't restart it, just let it run and you can follow the progress through the SparkUI\n# after checking the desired outputs are generated (GCS bucket) and the run is done (SparkUI), exit the current nb, open a new session, and proceed to the next step\n# took roughly 25-27 min \nfor i in regions:\n subcont_unrel = mt_unrel.filter_cols(mt_unrel['hgdp_tgp_meta']['Genetic']['region'] == i) # filter the unrelateds per region\n run_pca(subcont_unrel, i, subcont_pca_prefix, overwrite)",
"_____no_output_____"
],
[
"# run 'project_relateds' function (located above) for each region - took ~3min \nfor i in regions:\n loadings = hl.read_table(subcont_pca_prefix + i + '_loadings.ht') # for each region, read in the PCA loadings that were obtained from 'run_pca' function \n subcont_rel = mt_rel.filter_cols(mt_rel['hgdp_tgp_meta']['Genetic']['region'] == i) # filter the relateds per region \n project_individuals(loadings, subcont_rel, i, subcont_pca_prefix, overwrite) ",
"2021-08-03 18:49:41 Hail: WARN: cols(): Resulting column table is sorted by 'col_key'.\n To preserve matrix table column order, first unkey columns with 'key_cols_by()'\n2021-08-03 18:50:38 Hail: INFO: Coerced sorted dataset\n2021-08-03 18:50:39 Hail: INFO: merging 16 files totalling 10.2K...\n2021-08-03 18:50:40 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_postoutlier/subcont_pca/subcont_pca_EUR_projected_scores.txt.bgz\n merge time: 439.201ms\n2021-08-03 18:51:13 Hail: INFO: Coerced sorted dataset\n2021-08-03 18:51:14 Hail: INFO: merging 16 files totalling 20.8K...\n2021-08-03 18:51:14 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_postoutlier/subcont_pca/subcont_pca_AFR_projected_scores.txt.bgz\n merge time: 205.399ms\n2021-08-03 18:51:45 Hail: INFO: Coerced sorted dataset\n2021-08-03 18:51:46 Hail: INFO: merging 16 files totalling 14.2K...\n2021-08-03 18:51:46 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_postoutlier/subcont_pca/subcont_pca_AMR_projected_scores.txt.bgz\n merge time: 209.273ms\n2021-08-03 18:52:15 Hail: INFO: Coerced sorted dataset\n2021-08-03 18:52:16 Hail: INFO: merging 16 files totalling 9.1K...\n2021-08-03 18:52:16 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_postoutlier/subcont_pca/subcont_pca_EAS_projected_scores.txt.bgz\n merge time: 182.984ms\n2021-08-03 18:52:44 Hail: INFO: Coerced sorted dataset\n2021-08-03 18:52:45 Hail: INFO: merging 16 files totalling 10.8K...\n2021-08-03 18:52:45 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_postoutlier/subcont_pca/subcont_pca_CSA_projected_scores.txt.bgz\n merge time: 208.388ms\n2021-08-03 18:53:12 Hail: INFO: Coerced sorted dataset\n2021-08-03 18:53:12 Hail: INFO: merging 2 files totalling 394...\n2021-08-03 18:53:12 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_postoutlier/subcont_pca/subcont_pca_OCE_projected_scores.txt.bgz\n merge time: 170.903ms\n2021-08-03 18:53:39 Hail: INFO: Coerced sorted dataset\n2021-08-03 18:53:40 Hail: INFO: merging 16 files totalling 3.0K...\n2021-08-03 18:53:40 Hail: INFO: while writing:\n gs://african-seq-data/hgdp_tgp/pca_postoutlier/subcont_pca/subcont_pca_MID_projected_scores.txt.bgz\n merge time: 207.426ms\n"
]
],
[
[
"# FST\n### For FST, we are using the data we had prior to running pc_relate (*filtered_n_pruned_output_updated.mt*)",
"_____no_output_____"
]
],
[
[
"# read filtered and pruned mt (prior to pc_relate) back in for FST analysis \nmt_var_pru_filt = hl.read_matrix_table('gs://african-seq-data/hgdp_tgp/filtered_n_pruned_output_updated.mt') \n\n# num of samples before outlier removal \nprint('Before filtering: ' + str(mt_var_pru_filt.count()[1])) ",
"Before filtering: 4119\n"
],
[
"# read the outliers file into a list\nwith hl.utils.hadoop_open('gs://african-seq-data/hgdp_tgp/pca_outliers_v2.txt') as file: \n outliers = [line.rstrip('\\n') for line in file]\n \n# capture and broadcast the list as an expression\noutliers_list = hl.literal(outliers)",
"_____no_output_____"
],
[
"# remove 22 outliers \nmt_var_pru_filt = mt_var_pru_filt.filter_cols(~outliers_list.contains(mt_var_pru_filt['s']))",
"_____no_output_____"
],
[
"# sanity check \nprint('After filtering: ' + str(mt_var_pru_filt.count()[1]))",
"After filtering: 4097\n"
]
],
[
[
"## *pair-wise comparison*",
"_____no_output_____"
],
[
"Formula to calculate number of pair-wise comparisons = (k * (k-1))/2\n\nSo in our case, since we have 78 populations, we would expect = (78 * (78-1))/2 = 6006/2 = 3003 pair-wise comparisons",
"_____no_output_____"
]
],
[
[
"pop = mt_var_pru_filt['hgdp_tgp_meta']['Population'].collect()\npop = list(dict.fromkeys(pop)) \nlen(pop) # 78 populations in total ",
"_____no_output_____"
],
[
"# example \nex = ['a','b','c']\n# pair-wise comparison \nex_pair_com = [[x,y] for i, x in enumerate(ex) for j,y in enumerate(ex) if i<j]\nex_pair_com",
"_____no_output_____"
],
[
"# pair-wise comparison - creating list of lists \n# enumerate gives index values for each population in the 'pop' list (ex. 0 CEU, 1 YRI, 2 LWK ...) and then by \n# comparing those index values, we create a pair-wise comparison between the populations \n# i < j so that it only does a single comparison among two different populations \n# ex. for a comparison between populations CEU and YRI, it only keeps CEU-YRI and discards YRI-CEU, CEU-CEU and YRI-YRI\npair_com = [[x,y] for i, x in enumerate(pop) for j,y in enumerate(pop) if i<j]",
"_____no_output_____"
],
[
"# first 5 elements in the list \npair_com[0:5]",
"_____no_output_____"
],
[
"# sanity check \nlen(pair_com)",
"_____no_output_____"
]
],
[
[
"## *subset mt into popns according to the pair-wise comparisons and run common variant statistics*",
"_____no_output_____"
]
],
[
[
"pair_com[0]",
"_____no_output_____"
],
[
"## example - pair_com[0] = ['CEU', 'YRI'] and pair_com[0][0] = 'CEU'\nCEU_mt = mt_var_pru_filt.filter_cols(mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pair_com[0][0])\nYRI_mt = mt_var_pru_filt.filter_cols(mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pair_com[0][1])\nCEU_YRI_mt = mt_var_pru_filt.filter_cols((mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pair_com[0][0]) | (mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pair_com[0][1]))",
"_____no_output_____"
],
[
"# sanity check \nCEU_mt.count()[1] + YRI_mt.count()[1] == CEU_YRI_mt.count()[1] # 175 + 170 = 345",
"_____no_output_____"
],
[
"# run common variant statistics for each population and their combined mt \nCEU_var = hl.variant_qc(CEU_mt) # individual \nYRI_var = hl.variant_qc(YRI_mt) # individual\nCEU_YRI_var = hl.variant_qc(CEU_YRI_mt) # total ",
"_____no_output_____"
]
],
[
[
"### *Set up mt table for FST calculation - the next code is run for each population and their combos*",
"_____no_output_____"
],
[
"##### *population 1*",
"_____no_output_____"
]
],
[
[
"# drop certain fields first to make mt smaller \n\n# drop all entry fields\n# everything except for 's' (key) from the column fields\n# everything from the row fields except for the keys -'locus' and 'alleles' and row field 'variant_qc' \nCEU_interm = CEU_var.drop(*list(CEU_var.entry), *list(CEU_var.col)[1:], *list(CEU_var.row)[2:-1])\n\n# only select the row field keys (locus and allele) and row fields 'AF' & 'AN' which are under 'variant_qc'\nCEU_interm2 = CEU_interm.select_rows(CEU_interm['variant_qc']['AF'], CEU_interm['variant_qc']['AN']) \n\n# quick look at the condensed mt \nCEU_interm2.describe()",
"----------------------------------------\nGlobal fields:\n None\n----------------------------------------\nColumn fields:\n 's': str\n----------------------------------------\nRow fields:\n 'locus': locus<GRCh38>\n 'alleles': array<str>\n 'AF': array<float64>\n 'AN': int32\n----------------------------------------\nEntry fields:\n None\n----------------------------------------\nColumn key: ['s']\nRow key: ['locus', 'alleles']\n----------------------------------------\n"
],
[
"CEU_interm2.rows().show(5)",
"_____no_output_____"
],
[
"# only include the second entry of the array from the row field 'AF' \nCEU_interm3 = CEU_interm2.transmute_rows(AF = CEU_interm2.AF[1])\n\n# previous code\n# key the rows only by 'locus' so that the 'allele' row field can be split into two row fields (one for each allele)\n# also, only include the second entry of the array from 'AF' row field \n#CEU_interm3 = CEU_interm2.key_rows_by('locus')\n#CEU_interm3 = CEU_interm3.transmute_rows(AF = CEU_interm3.AF[1], A1 = CEU_interm3.alleles[0], A2 = CEU_interm3.alleles[1])\n\n# add a row field with population name to keep track of which mt it came from \nCEU_final = CEU_interm3.annotate_rows(pop = pair_com[0][0])\nCEU_final.rows().show(5)",
"_____no_output_____"
]
],
[
[
"##### *population 2*",
"_____no_output_____"
]
],
[
[
"# drop fields \n\n# drop all entry fields\n# everything except for 's' (key) from the column fields\n# everything from the row fields except for the keys -'locus' and 'alleles' and row field 'variant_qc' \nCEU_YRI_interm = CEU_YRI_var.drop(*list(CEU_YRI_var.entry), *list(CEU_YRI_var.col)[1:], *list(CEU_YRI_var.row)[2:-1])\n\n# only select the row field keys (locus and allele) and row fields 'AF' & 'AN' which are under 'variant_qc'\nCEU_YRI_interm2 = CEU_YRI_interm.select_rows(CEU_YRI_interm['variant_qc']['AF'], CEU_YRI_interm['variant_qc']['AN']) \n\n# quick look at the condensed mt \nCEU_YRI_interm2.describe()",
"----------------------------------------\nGlobal fields:\n None\n----------------------------------------\nColumn fields:\n 's': str\n----------------------------------------\nRow fields:\n 'locus': locus<GRCh38>\n 'alleles': array<str>\n 'AF': array<float64>\n 'AN': int32\n----------------------------------------\nEntry fields:\n None\n----------------------------------------\nColumn key: ['s']\nRow key: ['locus', 'alleles']\n----------------------------------------\n"
],
[
"CEU_YRI_interm2.rows().show(5)",
"_____no_output_____"
],
[
"# only include the second entry of the array from the row field 'AF' \nCEU_YRI_interm3 = CEU_YRI_interm2.transmute_rows(AF = CEU_YRI_interm2.AF[1])\n\n# previous code \n# key the rows only by 'locus' so that the 'allele' row field can be split into two row fields (one for each allele)\n# also, only include the second entry of the array from 'AF' row field \n#CEU_YRI_interm3 = CEU_YRI_interm2.key_rows_by('locus')\n#CEU_YRI_interm3 = CEU_YRI_interm3.transmute_rows(AF = CEU_YRI_interm3.AF[1], A1 = CEU_YRI_interm3.alleles[0], A2 = CEU_YRI_interm3.alleles[1])\n\n# add a row field with population name to keep track of which mt it came from \nCEU_YRI_final = CEU_YRI_interm3.annotate_rows(pop = f'{pair_com[0][0]}-{pair_com[0][1]}')\nCEU_YRI_final.rows().show(5)",
"_____no_output_____"
]
],
[
[
"### *FST formula pre-setup* - trial run",
"_____no_output_____"
],
[
"#### *Variables needed for FST calculation* ",
"_____no_output_____"
]
],
[
[
"# converting lists into numpy arrarys cause it is easier to work with and more readable\n\n# assign populations to formula variables \npop1 = CEU_final\npop2 = CEU_YRI_final\n\n# number of alleles \nn1 = np.array(pop1.AN.collect())\nn2 = np.array(pop2.AN.collect())\n\n# allele frequencies \nFREQpop1 = np.array(pop1.AF.collect()) \nFREQpop2 = np.array(pop2.AF.collect()) ",
"_____no_output_____"
]
],
[
[
"#### *Weighted average allele frequency*",
"_____no_output_____"
]
],
[
[
"FREQ = ((n1*FREQpop1) + (n2*FREQpop2)) / (n1+n2)\n\n# sanity checks\nprint(((n1[0]*FREQpop1[0]) + (n2[0]*FREQpop2[0])) / (n1[0]+n2[0]) == FREQ[0])\nprint(len(FREQ) == len(FREQpop1)) # length of output should be equal to the length of arrays we started with",
"True\nTrue\n"
]
],
[
[
"#### *Filter to only freqs between 0 and 1*",
"_____no_output_____"
]
],
[
[
"INCLUDE=(FREQ>0) & (FREQ<1) # only include ave freq between 0 and 1 - started with FREQ = 248634\nprint(np.count_nonzero(INCLUDE)) # 246984 ave freq values were between 0 and 1 - returned True to the conditions above; 248634 - 246984 = 1650 were False \n\n# subset allele frequencies \nFREQpop1=FREQpop1[INCLUDE]\nFREQpop2=FREQpop2[INCLUDE]\nFREQ=FREQ[INCLUDE]\n\n# sanity check \nprint(len(FREQpop1) == np.count_nonzero(INCLUDE)) # TRUE\n\n# subset the number of alleles \nn1 = n1[INCLUDE]\nn2 = n2[INCLUDE]\n\n# sanity check \nprint(len(n1) == np.count_nonzero(INCLUDE)) # TRUE",
"246984\nTrue\nTrue\n"
]
],
[
[
"#### *FST Estimate - W&C ESTIMATOR*",
"_____no_output_____"
]
],
[
[
"## average sample size that incorporates variance\nnc =((1/(s-1)) * (n1+n2)) - ((np.square(n1) + np.square(n2))/(n1+n2))\n\nmsa= (1/(s-1))*((n1*(np.square(FREQpop1-FREQ)))+(n2*(np.square(FREQpop2-FREQ))))\n\nmsw = (1/((n1-1)+(n2-1))) * ((n1*(FREQpop1*(1-FREQpop1))) + (n2*(FREQpop2*(1-FREQpop2))))\n\nnumer = msa-msw\n\ndenom = msa + ((nc-1)*msw)\n\nFST_val = numer/denom\n\n# sanity check using the first element \nnc_0 =((1/(s-1)) * (n1[0]+n2[0])) - ((np.square(n1[0]) + np.square(n2[0]))/(n1[0]+n2[0]))\n\nmsa_0= (1/(s-1))*((n1[0]*(np.square(FREQpop1[0]-FREQ[0])))+(n2[0]*(np.square(FREQpop2[0]-FREQ[0]))))\n\nmsw_0 = (1/((n1[0]-1)+(n2[0]-1))) * ((n1[0]*(FREQpop1[0]*(1-FREQpop1[0]))) + (n2[0]*(FREQpop2[0]*(1-FREQpop2[0]))))\n\nnumer_0 = msa_0-msw_0\n\ndenom_0 = msa_0 + ((nc_0-1)*msw_0)\n\nFST_0 = numer_0/denom_0\n\nprint(FST_0 == FST_val[0]) # TRUE",
"True\n"
],
[
"FST_val",
"_____no_output_____"
]
],
[
[
"## *Which FST value is for which locus-allele?* - actual run",
"_____no_output_____"
]
],
[
[
"# resetting variables for the actual FST run \n\n# assign populations to formula variables \npop1 = CEU_final\npop2 = CEU_YRI_final\n\n# number of alleles \nn1 = np.array(pop1.AN.collect())\nn2 = np.array(pop2.AN.collect())\n\n# allele frequencies \nFREQpop1 = np.array(pop1.AF.collect()) \nFREQpop2 = np.array(pop2.AF.collect()) \n\n# locus + alleles = keys - needed for reference purposes - these values are uniform across all populations \nlocus = np.array(hl.str(pop1.locus).collect())\nalleles = np.array(hl.str(pop1.alleles).collect())\nkey = np.array([i + ' ' + j for i, j in zip(locus, alleles)])",
"_____no_output_____"
],
[
"s=2 # s is the number of populations - since we are calculating pair-wise FSTs, this is always 2 \nkey_FST = {}\nfor i in range(len(key)):\n FREQ = ((n1[i]*FREQpop1[i]) + (n2[i]*FREQpop2[i])) / (n1[i]+n2[i])\n \n if (FREQ>0) & (FREQ<1): # only include ave freq between 0 and 1\n \n ## average sample size that incorporates variance\n nc = ((1/(s-1)) * (n1[i]+n2[i])) - ((np.square(n1[i]) + np.square(n2[i]))/(n1[i]+n2[i]))\n\n msa= (1/(s-1))*((n1[i]*(np.square(FREQpop1[i]-FREQ)))+(n2[i]*(np.square(FREQpop2[i]-FREQ))))\n\n msw = (1/((n1[i]-1)+(n2[i]-1))) * ((n1[i]*(FREQpop1[i]*(1-FREQpop1[i]))) + (n2[i]*(FREQpop2[i]*(1-FREQpop2[i]))))\n\n numer = msa-msw\n\n denom = msa + ((nc-1)*msw)\n\n FST = numer/denom\n \n key_FST[key[i]] = FST",
"_____no_output_____"
],
[
"key_FST",
"_____no_output_____"
],
[
"# sanity checks \nprint(all(np.array(list(key_FST.values())) == FST_val)) # True \nprint(len(key_FST) == len(FST_val)) # True",
"True\nTrue\n"
]
],
[
[
"## *other pair*",
"_____no_output_____"
],
[
"### population 3",
"_____no_output_____"
]
],
[
[
"# population - YRI\n# same steps we did to CEU\n\nYRI_interm = YRI_var.drop(*list(YRI_var.entry), *list(YRI_var.col)[1:], *list(YRI_var.row)[2:-1])\n\n# only select the row field keys (locus and allele) and row fields 'AF' & 'AN' which are under 'variant_qc'\nYRI_interm2 = YRI_interm.select_rows(YRI_interm['variant_qc']['AF'], YRI_interm['variant_qc']['AN']) \n\n# only include the second entry of the array from the row field 'AF' \nYRI_interm3 = YRI_interm2.transmute_rows(AF = YRI_interm2.AF[1])\n\n# add a row field with population name to keep track of which mt it came from \nYRI_final = YRI_interm3.annotate_rows(pop = pair_com[0][1])\nYRI_final.rows().show(5)",
"_____no_output_____"
]
],
[
[
"### *FST*",
"_____no_output_____"
]
],
[
[
"# resetting variables for the actual FST run \n\n# assign populations to formula variables \npop1 = YRI_final\npop2 = CEU_YRI_final\n\n# number of alleles \nn1 = np.array(pop1.AN.collect())\nn2 = np.array(pop2.AN.collect())\n\n# allele frequencies \nFREQpop1 = np.array(pop1.AF.collect()) \nFREQpop2 = np.array(pop2.AF.collect()) \n\n# locus + alleles = keys - needed for reference purposes - these values are uniform across all populations \nlocus = np.array(hl.str(pop1.locus).collect())\nalleles = np.array(hl.str(pop1.alleles).collect())\nkey = np.array([i + ' ' + j for i, j in zip(locus, alleles)])",
"_____no_output_____"
],
[
"s=2 # s is the number of populations - since we are calculating pair-wise FSTs, this is always 2 \nkey_FST_YRI = {}\nfor i in range(len(key)):\n FREQ = ((n1[i]*FREQpop1[i]) + (n2[i]*FREQpop2[i])) / (n1[i]+n2[i])\n \n if (FREQ>0) & (FREQ<1): # only include ave freq between 0 and 1\n \n ## average sample size that incorporates variance\n nc = ((1/(s-1)) * (n1[i]+n2[i])) - ((np.square(n1[i]) + np.square(n2[i]))/(n1[i]+n2[i]))\n\n msa= (1/(s-1))*((n1[i]*(np.square(FREQpop1[i]-FREQ)))+(n2[i]*(np.square(FREQpop2[i]-FREQ))))\n\n msw = (1/((n1[i]-1)+(n2[i]-1))) * ((n1[i]*(FREQpop1[i]*(1-FREQpop1[i]))) + (n2[i]*(FREQpop2[i]*(1-FREQpop2[i]))))\n\n numer = msa-msw\n\n denom = msa + ((nc-1)*msw)\n\n FST = numer/denom\n \n key_FST_YRI[key[i]] = FST",
"_____no_output_____"
],
[
"CEU\nYRI\n\nkey_FST_YRI",
"_____no_output_____"
]
],
[
[
"## *three popn pairs*",
"_____no_output_____"
]
],
[
[
"## example using three sample pairs ['CEU', 'YRI'], ['CEU', 'LWK'], ['CEU', 'ESN'] and setting up the function \nexample_pairs = pair_com[0:3]\n\nex_dict = {} # empty dictionary to hold final outputs \nfor pairs in example_pairs:\n l = [] # empty list to hold the subsetted datasets \n l.append(mt_var_pru_filt.filter_cols(mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pairs[0])) # first population \n l.append(mt_var_pru_filt.filter_cols(mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pairs[1])) # second population \n l.append(mt_var_pru_filt.filter_cols((mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pairs[0]) | (mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pairs[1]))) # first + second = total population\n \n # sanity check - the sample count of the first and second subset mts should be equal to the total subset mt \n if l[0].count()[1] + l[1].count()[1] == l[2].count()[1]: \n v = [] # empty list to hold output mts from running common variant statistics \n # run common variant statistics for each population and their combined mt\n v.append(hl.variant_qc(l[0])) # first population \n v.append(hl.variant_qc(l[1])) # second population \n v.append(hl.variant_qc(l[2])) # both/total population\n \n # add to dictionary \n ex_dict[\"-\".join(pairs)] = v",
"_____no_output_____"
],
[
"# three mt subsets per comparison pair - set up as a dictionary \nex_dict",
"_____no_output_____"
],
[
"# population - YRI\n# same steps we did to CEU\n\n\nYRI_var == ex_dict['CEU-YRI'][0]\n\nYRI_interm = ex_dict['CEU-YRI'][0].drop(*list(ex_dict['CEU-YRI'][0].entry)\n\n\nYRI_interm = ex_dict['CEU-YRI'][0].drop(*list(ex_dict['CEU-YRI'][0].entry), *list(ex_dict['CEU-YRI'][0].col)[1:], *list(ex_dict['CEU-YRI'][0].row)[2:-1])\n\n# only select the row field keys (locus and allele) and row fields 'AF' & 'AN' which are under 'variant_qc'\nYRI_interm2 = YRI_interm.select_rows(YRI_interm['variant_qc']['AF'], YRI_interm['variant_qc']['AN']) \n\n# only include the second entry of the array from the row field 'AF' \nYRI_interm3 = YRI_interm2.transmute_rows(AF = YRI_interm2.AF[1])\n\n# add a row field with population name to keep track of which mt it came from \nYRI_final = YRI_interm3.annotate_rows(pop = pairs[0])\nYRI_final.rows().show(5)",
"_____no_output_____"
],
[
"# same as CEU_var['variant_qc'].show(5)\nex_dict['CEU-YRI'][0]['variant_qc'].show(5)",
"_____no_output_____"
],
[
"len(ex_dict['CEU-YRI'])",
"_____no_output_____"
],
[
"a = ['CEU-YRI','CEU-LWK', 'CEU-ESN']\nb = [0,1,2]\ndc = {}\nfor i in a:\n li = []\n for j in b:\n li.append(str(j) + i)\n dc[i] = li \n ",
"_____no_output_____"
],
[
"for i in range(len(v)-1):\n print(i)",
"0\n1\n"
],
[
"from collections import defaultdict\n\ndd = defaultdict(list)\n\nfor d in (key_FST, key_FST_YRI):\n print(d)\n #for key, value in d.items():\n #dd[key].append(value)",
"IOPub data rate exceeded.\nThe notebook server will temporarily stop sending output\nto the client in order to avoid crashing it.\nTo change this limit, set the config variable\n`--NotebookApp.iopub_data_rate_limit`.\n\nCurrent values:\nNotebookApp.iopub_data_rate_limit=1000000.0 (bytes/sec)\nNotebookApp.rate_limit_window=3.0 (secs)\n\n"
],
[
"range(len(ex_dict[pair]))",
"_____no_output_____"
],
[
"final_dic = {}\nfor pair in ex_dict.keys(): # for each population pair \n u = [] # list to hold updated mts \n for i in range(len(ex_dict[pair])): # for each population (each mt)\n # pop1\n # drop certain fields and only keep the ones we need \n interm = ex_dict[pair][i].drop(*list(ex_dict[pair][i].entry), *list(ex_dict[pair][i].col)[1:], *list(ex_dict[pair][i].row)[2:-1])\n interm2 = interm.select_rows(interm['variant_qc']['AF'], interm['variant_qc']['AN']) \n interm3 = interm2.transmute_rows(AF = interm2.AF[1])\n #final = interm3.annotate_rows(pop = pair) # keep track of which mt it came from\n u.append(interm3) # add updated mt to list \n \n # variables for FST run \n\n # assign populations to formula variables \n pop1 = u[0]\n pop2 = u[1]\n total = u[2]\n \n # number of alleles \n n1 = np.array(pop1.AN.collect())\n n2 = np.array(pop2.AN.collect())\n total_n = np.array(total.AN.collect())\n\n # allele frequencies \n FREQpop1 = np.array(pop1.AF.collect()) \n FREQpop2 = np.array(pop2.AF.collect())\n total_FREQ = np.array(total.AF.collect()) \n \n # locus + alleles = keys - needed for reference purposes during FST calculations - these values are uniform across all populations \n locus = np.array(hl.str(pop1.locus).collect())\n alleles = np.array(hl.str(pop1.alleles).collect())\n key = np.array([i + ' ' + j for i, j in zip(locus, alleles)])\n \n s=2 # s is the number of populations - since we are calculating pair-wise FSTs, this is always 2 \n \n # FST pop1 and total popn\n key_pop1_total = {}\n for i in range(len(key)):\n FREQ = ((n1[i]*FREQpop1[i]) + (total_n[i]*total_FREQ[i])) / (n1[i]+total_n[i])\n\n if (FREQ>0) & (FREQ<1): # only include ave freq between 0 and 1\n\n ## average sample size that incorporates variance\n nc = ((1/(s-1)) * (n1[i]+total_n[i])) - ((np.square(n1[i]) + np.square(total_n[i]))/(n1[i]+total_n[i]))\n\n msa= (1/(s-1))*((n1[i]*(np.square(FREQpop1[i]-FREQ)))+(total_n[i]*(np.square(total_FREQ[i]-FREQ))))\n\n msw = (1/((n1[i]-1)+(total_n[i]-1))) * ((n1[i]*(FREQpop1[i]*(1-FREQpop1[i]))) + (total_n[i]*(total_FREQ[i]*(1-total_FREQ[i]))))\n\n numer = msa-msw\n\n denom = msa + ((nc-1)*msw)\n\n FST = numer/denom\n\n key_pop1_total[key[i]] = FST\n \n # FST pop2 and total popn\n key_pop2_total = {}\n for i in range(len(key)):\n FREQ = ((n2[i]*FREQpop2[i]) + (total_n[i]*total_FREQ[i])) / (n2[i]+total_n[i])\n\n if (FREQ>0) & (FREQ<1): # only include ave freq between 0 and 1\n\n ## average sample size that incorporates variance\n nc = ((1/(s-1)) * (n2[i]+total_n[i])) - ((np.square(n2[i]) + np.square(total_n[i]))/(n2[i]+total_n[i]))\n\n msa= (1/(s-1))*((n2[i]*(np.square(FREQpop2[i]-FREQ)))+(total_n[i]*(np.square(total_FREQ[i]-FREQ))))\n\n msw = (1/((n2[i]-1)+(total_n[i]-1))) * ((n2[i]*(FREQpop2[i]*(1-FREQpop2[i]))) + (total_n[i]*(total_FREQ[i]*(1-total_FREQ[i]))))\n\n numer = msa-msw\n\n denom = msa + ((nc-1)*msw)\n\n FST = numer/denom\n\n key_pop2_total[key[i]] = FST\n \n # merge the two FST results together\n from collections import defaultdict\n\n dd = defaultdict(list)\n\n for d in (key_pop1_total, key_pop2_total):\n for key, value in d.items():\n dd[key].append(value)\n \n final_dic[pair] = dd",
"_____no_output_____"
],
[
"# convert to a table \nimport pandas as pd\n\ndf = pd.DataFrame(final_dic) \n",
"_____no_output_____"
],
[
"len(final_dic['CEU-YRI']) # 246984",
"_____no_output_____"
],
[
"## example - pair_com[0] = ['CEU', 'YRI'] and pair_com[0][0] = 'CEU'\nCEU_mt = mt_var_pru_filt.filter_cols(mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pair_com[1][0])\nLWK_mt = mt_var_pru_filt.filter_cols(mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pair_com[1][1])\nCEU_LWK_mt = mt_var_pru_filt.filter_cols((mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pair_com[1][0]) | (mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pair_com[1][1]))\n\n# run common variant statistics for each population and their combined mt \nCEU_var = hl.variant_qc(CEU_mt) # individual \nLWK_var = hl.variant_qc(LWK_mt) # individual\nCEU_LWK_var = hl.variant_qc(CEU_YRI_mt) # total ",
"_____no_output_____"
],
[
"LWK_var.count()",
"_____no_output_____"
],
[
"# population - YRI\n# same steps we did to CEU\n\nYRI_interm = YRI_var.drop(*list(YRI_var.entry), *list(YRI_var.col)[1:], *list(YRI_var.row)[2:-1])\n\n# only select the row field keys (locus and allele) and row fields 'AF' & 'AN' which are under 'variant_qc'\nYRI_interm2 = YRI_interm.select_rows(YRI_interm['variant_qc']['AF'], YRI_interm['variant_qc']['AN']) \n\n# only include the second entry of the array from the row field 'AF' \nYRI_interm3 = YRI_interm2.transmute_rows(AF = YRI_interm2.AF[1])\n\n# add a row field with population name to keep track of which mt it came from \nYRI_final = YRI_interm3.annotate_rows(pop = pair_com[0][1])\nYRI_final.rows().show(5)",
"_____no_output_____"
],
[
"for pair in ex_dict.keys(): # for each population pair \n for i in range(len(ex_dict[i])): # for each population \n \n\n\n\n interm = ex_dict[pair][i].drop(*list(ex_dict[pair][i].entry), *list(ex_dict[pair][i].col)[1:], *list(ex_dict[pair][i].row)[2:-1])\n\n # only select the row field keys (locus and allele) and row fields 'AF' & 'AN' which are under 'variant_qc'\n interm2 = interm.select_rows(interm['variant_qc']['AF'], interm['variant_qc']['AN']) \n\n # only include the second entry of the array from the row field 'AF' \n interm3 = interm2.transmute_rows(AF = interm2.AF[1])\n\n # add a row field with population name to keep track of which mt it came from \n final = interm3.annotate_rows(pop = pair)\n final.rows().show(5)\n ",
"CEU-YRI\nCEU-LWK\nCEU-ESN\n"
],
[
"%%time\n# actual function/run using all population pairs\ndict = {} # empty dictionary to hold final outputs \nfor pairs in pair_com:\n l = [] # empty list to hold the subsetted datasets \n l.append(mt_var_pru_filt.filter_cols(mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pairs[0])) # first population \n l.append(mt_var_pru_filt.filter_cols(mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pairs[1])) # second population \n l.append(mt_var_pru_filt.filter_cols((mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pairs[0]) | (mt_var_pru_filt['hgdp_tgp_meta']['Population'] == pairs[1]))) # first + second = total population\n \n # sanity check - the sample count of the first and second subset mts should be equal to the total subset mt \n if l[0].count()[1] + l[1].count()[1] == l[2].count()[1]: \n v = [] # empty list to hold output mts from running common variant statistics \n # run common variant statistics for each population and their combined mt\n v.append(hl.variant_qc(l[0])) # first population \n v.append(hl.variant_qc(l[1])) # second population \n v.append(hl.variant_qc(l[2])) # both/total population\n \n # add to dictionary \n dict[\"-\".join(pairs)] = v",
"_____no_output_____"
],
[
"len(dict)",
"_____no_output_____"
],
[
"dict",
"_____no_output_____"
],
[
"dict['CEU-YRI'][0]['variant_qc'].show(5)",
"_____no_output_____"
],
[
"dict['CEU-YRI'][1]['variant_qc'].show(5)",
"_____no_output_____"
],
[
"dict['CEU-YRI'][2]['variant_qc'].show(5)",
"_____no_output_____"
],
[
"# accessing dictionary element with index \nex_dict[list(ex_dict)[0]][0]['variant_qc'].show(5)",
"_____no_output_____"
],
[
"for l in list(ex_dict):\n print(ex_dict[l][1]['variant_qc']['AF'][1].show(5))",
"_____no_output_____"
],
[
"list(ex_dict)",
"_____no_output_____"
],
[
"CEU_af_freq = ex_dict[list(ex_dict)[0]][0]['variant_qc']['AF'][1]",
"_____no_output_____"
],
[
"play_mt = hl.utils.range_matrix_table(0, 6)",
"_____no_output_____"
],
[
"ex_dict[list(ex_dict)[0]][0].cols().show(5)",
"_____no_output_____"
],
[
"mt.select_rows(mt.r1, mt.r2,\nr3=hl.coalesce(mt.r1, mt.r2))\n\nmt.select_cols(mt.c2,\nsum=mt.c2+mt.c1)",
"_____no_output_____"
],
[
"play_mt = ex_dict[list(ex_dict)[0]][0]",
"_____no_output_____"
],
[
"row_subsetted_mt.cols().show(5)",
"_____no_output_____"
],
[
"CEU_af_freq = CEU_af_freq.annotate_cols(AN=ex_dict[list(ex_dict)[0]][0]['variant_qc']['AN'])",
"_____no_output_____"
],
[
"mtA = mtA.annotate_rows(phenos = hl.dict(hl.agg.collect((mtA.pheno, mtA.value))))\nmtB = mtB.annotate_cols(\n phenos = mtA.rows()[mtB.col_key].phenos)",
"_____no_output_____"
],
[
"# additional stuff \n\nCEU_var = hl.variant_qc(CEU_mt) \nCEU__YRI_var = hl.variant_qc(CEU_YRI_mt) \na, b, c\na -> ac\nB -> cb\na -> ab\nCEU_var.row.show()\nCEU_mt['variant_qc']['AF'][0]*CEU_mt['variant_qc']['AF'][1]\nCEU_YRI_mt['variant_qc']['AF'][0]*CEU_YRI_mt['variant_qc']['AF'][1]",
"_____no_output_____"
]
],
[
[
"# junk code below",
"_____no_output_____"
]
],
[
[
"# this code is if the alleles were split into their separate columns and if we expect a mismatch across popns \n\n# remove indels - only include single letter varients for each allele in both populations \n# this is b/c the FST formula is set up for single letter alleles \n#pop1 = CEU_final.filter_rows((CEU_final.A1.length() == 1) & (CEU_final.A2.length() == 1))\n#pop2 = CEU_YRI_final.filter_rows((CEU_YRI_final.A1.length() == 1) & (CEU_YRI_final.A2.length() == 1))\n\n\n# sanity check \n#A1 = pop1.A1.collect()\n#A1 = list(set(A1)) # OR can also do: \n### from collections import OrderedDict \n### A1 = list(OrderedDict.fromkeys(A1))\n\n#print(A1) \n#len(A1) == 4\n\n# total # of snps at the beginning - 255666 \n# unique snps before removing indels - 2712 \n# total # of snps after removing indels - 221017 (34649 snps were indels for A1, A2 or both)\n# unique snps after removing indels - 4 ['C', 'A', 'T', 'G'] - which is what we expect \n\n\n\n## *use the same reference allele - A2 is minor allele here* \n\n# get the minor alleles from both populations \n#pop1_A2 = pop1.A2.collect()\n#pop2_A2 = pop2.A2.collect()\n\n\n# find values that are unequal \n#import numpy as np\n#switch1 = (np.array(pop1_A2) != np.array(pop2_A2))\n#print(switch1.all()) # all comparisons returned 'FALSE' which means that all variants that were compared are the same \n\n# sanity check \n#print(len(pop1_A2) == len(pop2_A2) == len(switch1)) # True \n\n\n### *if there is a variant mismatch among the minor alleles of the two populations*\n# in case there was a comparison that didn't match correctly among the minor alleles of the two populations, we would adjust the allele frequency(AF) accordingly \n#new_frq = pop2.AF.collect() \n#new_frq = np.array(new_frq) # convert to numpy array for the next step\n\n# explanation (with an example) for what this does is right below it \n#new_frq[switch1] = 1-(new_frq[switch1]) \n# Example: for pop_1, A1 and A2 are 'T' and 'C' with AF of 0.25 \n# and for pop_2, A1 and A2 are 'C and 'T' with AF of 0.25\n# then since the same reference allele is not used (alleles don't correctly align) in this case, \n# we would subtract the AF of pop_2 from 1, to get the correct allele frequency \n# the AF of pop_2 with A1 and A2 oriented the same way as pop_1: 'T' and 'C', would be 1-0.25 = 0.75 (w/c is the correct AF)\n\n# if we wanted to convert array back to list \n#pop2_frq = new_frq.tolist() \n\n\n# junk code \n#pop2.rows().show(5)\n\n#p = pop2.filter_rows(str(pop2.locus) =='chr10:38960343')\np.row.show()\n\n\n# for i in locus:\n# if i =='chr1:94607079':\n# print (\"True\")\n \nsum(num == dup for num,dup in zip(locus, d))",
"_____no_output_____"
],
[
"# code to check if there are duplicates in a list and print them out \n#import collections\n#dup = [item for item, count in collections.Counter(key).items() if count > 1]\n#print('Num of duplicate loci: ' + str(len(dup))) \n#print(dup)",
"_____no_output_____"
],
[
"# which FST value is for which locus? \nkey_freq1 = {key[i]: FREQpop1[i] for i in range(len(key))}\nkey_freq2 = {key[i]: FREQpop2[i] for i in range(len(key))}\n\n\nkey_n1 = {key[i]: n1[i] for i in range(len(key))}\nkey_n2 = {key[i]: n2[i] for i in range(len(key))}\n\n# for key,value in zip (locus, FREQpop1):\n# print(dict(key, value))\n#for v1,v2 in zip(list(locus_freq1.values())[0:5], list(locus_freq2.values())[0:5]):\n #lq = ((n1*locus_freq1.values()) + (n2*locus_freq2.values())) / (n1+n2)\n #print(key,value)",
"_____no_output_____"
],
[
"#locus #220945\n#len(set(FREQpop1))\n\n\n# check if there are duplicates in locus list and print them out - 72 duplicates \n# import collections\n# d = [item for item, count in collections.Counter(locus).items() if count > 1]\n\n# list.sort(locus)\n#locus\n\n# from collections import Counter\n# [k for k,v in Counter(locus).items() if v>1]\n\n# where are each of the duplicated loci located?\nfrom collections import defaultdict\n\nD = defaultdict(list)\nfor i,item in enumerate(locus):\n D[item].append(i)\nD = {k:v for k,v in D.items() if len(v)>1}\nlocus[6202]",
"_____no_output_____"
],
[
"bad_locus = locus[INCLUDE=='FALSE']\n\n# ave freq values that were not between 0 and 1 - returned FALSE to the conditions in the above chuck of code \nprint(np.count_nonzero(INCLUDE==0))\nDONT_INCLUDE= (FREQ=='') & (FREQ>=1)\nnp.count_nonzero(DONT_INCLUDE)",
"_____no_output_____"
],
[
"# convert the output from the preimp_qc module (qced.mt) into a vcf file in Hail \nimport hail as hl \nmt = hl.read_matrix_table('gs://nepal-geno/GWASpy/Preimp_QC/Nepal_PTSD_GSA_Updated_May2021_qced.mt')\nhl.export_vcf(mt, 'gs://nepal-geno/Nepal_PTSD_GSA_Updated_May2021_qced.vcf.bgz')",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aaa065a777b9f0830136b45b0451c822c2e7d73
| 36,283 |
ipynb
|
Jupyter Notebook
|
Analytics/Financial News/Final DJIA Model.ipynb
|
jasmineseah-17/BT4222-NLP-Project
|
fa9ef5d17d46c46e9680992d83f112d167f5ec10
|
[
"MIT"
] | null | null | null |
Analytics/Financial News/Final DJIA Model.ipynb
|
jasmineseah-17/BT4222-NLP-Project
|
fa9ef5d17d46c46e9680992d83f112d167f5ec10
|
[
"MIT"
] | 7 |
2020-09-26T00:56:54.000Z
|
2021-09-08T01:53:24.000Z
|
Analytics/Financial News/Final DJIA Model.ipynb
|
jasmineseah-17/BT4222-NLP-Project
|
fa9ef5d17d46c46e9680992d83f112d167f5ec10
|
[
"MIT"
] | 2 |
2020-04-17T10:28:05.000Z
|
2020-04-27T10:55:39.000Z
| 38.313622 | 439 | 0.586115 |
[
[
[
"import pandas as pd\nfrom datetime import *\nfrom pandas_datareader.data import DataReader\nimport numpy as np\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn import metrics\nimport spacy\nimport os\nimport seaborn as sns\n\nfrom textblob import TextBlob\nimport nltk\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom nltk.classify.scikitlearn import SklearnClassifier\nimport pickle\nfrom sklearn.naive_bayes import MultinomialNB, BernoulliNB\nfrom sklearn.linear_model import LogisticRegression, SGDClassifier\nfrom sklearn.svm import SVC, LinearSVC, NuSVC\nfrom nltk.classify import ClassifierI\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom statistics import mode\nfrom nltk.tokenize import word_tokenize\nimport re\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn import metrics\nfrom scipy.sparse import coo_matrix, hstack\n\nnlp = spacy.load(\"C:/Users/ksjag/Anaconda3/Lib/site-packages/en_core_web_sm/en_core_web_sm-2.2.5\")",
"_____no_output_____"
],
[
"yahoo_url = \"https://finance.yahoo.com/quote/%5EDJI/components/\"\ndjia_table = pd.read_html(yahoo_url, header=0, index_col=0)[0]\ndjia_table = djia_table.reset_index()\n\ntickers = djia_table.Symbol",
"_____no_output_____"
],
[
"len(tickers)",
"_____no_output_____"
],
[
"start_date = \"2010-01-01\"\nend_date = \"2019-12-31\"",
"_____no_output_____"
]
],
[
[
"# Process the dataset function",
"_____no_output_____"
]
],
[
[
"def getDate(x):\n return datetime.strptime(x[0:10], \"%Y-%m-%d\")\n\n\ndef get_data_for_multiple_stocks(tickers):\n '''\n Obtain stocks information (Date, OHLC, Volume and Adjusted Close). \n Uses Pandas DataReader to make an API Call to Yahoo Finance and download the data directly.\n Computes other values - Log Return and Arithmetic Return.\n \n Input: List of Stock Tickers\n Output: A dictionary of dataframes for each stock\n '''\n stocks = dict()\n for ticker in tickers:\n s = DataReader(ticker, 'yahoo', start_date, end_date)\n s.insert(0, \"Ticker\", ticker) #insert ticker column so you can reference better later\n s['Date'] = pd.to_datetime(s.index) #useful for transformation later\n s['Adj Prev Close'] = s['Adj Close'].shift(1)\n s['Log Return'] = np.log(s['Adj Close']/s['Adj Prev Close'])\n s['Return'] = (s['Adj Close']/s['Adj Prev Close']-1)\n s = s.reset_index(drop=True)\n \n cols = list(s.columns.values) # re-arrange columns\n cols.remove(\"Date\")\n s = s[[\"Date\"] + cols]\n \n stocks[ticker] = s\n \n return stocks",
"_____no_output_____"
],
[
"def generate_features(df, ticker):\n\n ### Make into proper time series like dataframe\n df = this_df = pd.read_csv(\"../../Raw Data/Financial News/\" + ticker + \".csv\")\n df.drop(df.columns[0], axis=1, inplace=True)\n df[\"Date\"] = df[\"Date\"].apply(getDate)\n df.sort_values(by=\"Date\", inplace=True)\n df.reset_index(inplace=True, drop=True)\n df.drop(columns=[\"num_hits\"], inplace=True)\n\n # ## Named Entity Recognition to filter out non-company related stuff\n # noun_or_not = [] ## store the pos_\n # for row in range(len(df)):\n # this_headline = df.loc[row,\"main_headline\"]\n # this_doc = nlp(this_headline)\n\n # done = False\n # for token in this_doc:\n # if str(token)[0:len(company)].lower() == company.lower():\n # noun_or_not.append(token.pos_)\n # done = True\n # break\n # if done == False:\n # noun_or_not.append(\"remove\")\n # df = pd.concat([df.reset_index(drop=True), pd.DataFrame(noun_or_not, columns=[\"noun_or_not\"])], axis=1)\n # df = df[df.noun_or_not == \"PROPN\"]\n # df.drop([\"noun_or_not\"], axis=1, inplace=True)\n # df.reset_index(drop=True, inplace=True)\n\n ##### JOIN WITH PRICE HISTORY ######\n start_date = \"2010-01-01\"\n end_date = \"2019-12-31\"\n stock_prices = get_data_for_multiple_stocks([ticker])[ticker]\n\n stock_prices = stock_prices[[\"Date\", \"Adj Close\", \"Adj Prev Close\", \"Return\"]]\n df = pd.merge(df, stock_prices, how='inner', on='Date')\n\n df[\"text_label\"] = df[\"main_headline\"] + \". \" + df[\"absract\"]\n df[\"Label\"] = 1\n df.loc[df[\"Return\"] < 0, \"Label\"] = -1\n\n\n ## LEMMATIZE ###############\n w_tokenizer = nltk.tokenize.WhitespaceTokenizer()\n lemmatizer = nltk.stem.WordNetLemmatizer()\n\n def lemmatize_text(text):\n return [''.join(lemmatizer.lemmatize(w, 'v')) for w in w_tokenizer.tokenize(text)]\n def lemmatize_text_str(text):\n string = ''\n for w in w_tokenizer.tokenize(text):\n string = string + ' ' + lemmatizer.lemmatize(w, 'v')\n return string\n\n\n df_filtered = df[[\"Date\", \"word_count\", \"text_label\", \"Label\", \"Return\"]]\n df_filtered['text_lem_lst'] = df_filtered['text_label'].apply(lemmatize_text)\n df_filtered['text_lem_str'] = df_filtered['text_label'].apply(lemmatize_text_str)\n\n\n ### SENTIMENT SCORE ############\n def detect_sentiment(text): \n # use this line instead for Python 3\n blob = TextBlob(text)\n return blob.sentiment.polarity\n\n df_filtered[\"sentiment_txtblob\"] = df_filtered.text_lem_str.apply(detect_sentiment)\n\n sid = SentimentIntensityAnalyzer()\n df_filtered[\"sentiment_nltk\"] = df_filtered.text_lem_str.apply(lambda x: sid.polarity_scores(x))\n df_filtered[\"positivity_sentiment_nltk\"] = df_filtered.sentiment_nltk.apply(lambda x: x[\"pos\"])\n df_filtered[\"compound_sentiment_nltk\"] = df_filtered.sentiment_nltk.apply(lambda x: x[\"compound\"])\n df_filtered[\"negativity_sentiment_nltk\"] = df_filtered.sentiment_nltk.apply(lambda x: x[\"neg\"])\n df_filtered[\"neutral_sentiment_nltk\"] = df_filtered.sentiment_nltk.apply(lambda x: x[\"neu\"])\n df_filtered.drop(columns=[\"sentiment_nltk\"], inplace=True)\n\n return df_filtered",
"_____no_output_____"
],
[
"for ticker in tickers:\n continue ## take this out to actually run\n print(ticker)\n \n this_df = pd.read_csv(\"../../Raw Data/Financial News/\" + ticker + \".csv\")\n company = djia_table[djia_table[\"Symbol\"] == ticker][\"Company Name\"]\n \n this_features = generate_features(this_df, ticker)\n \n this_features.to_csv(\"../../Processed Data/Financial News/\" + ticker + \".csv\", index = False)",
"_____no_output_____"
]
],
[
[
"## For each company, train a model from 2010 - 2018, and generate predictions for 2019, 2020",
"_____no_output_____"
]
],
[
[
"def generate_train_test_csv(ticker):\n this_df = pd.read_csv(\"../../Processed Data/Financial News/\" + ticker + \".csv\")\n this_df.drop_duplicates(subset=\"Date\", inplace=True, keep=\"first\")\n this_df.reset_index(drop=True, inplace=True)\n \n df_train = this_df[this_df[\"Date\"] < \"2018-01-01\"]\n df_test = this_df[this_df[\"Date\"] >= \"2018-01-01\"]\n df_test.reset_index(drop=True, inplace=True)\n \n if len(df_test) == 0 or len(df_train)==0: pass\n \n cv = CountVectorizer(ngram_range=(1, 2), stop_words=\"english\", analyzer=\"word\", max_df=0.8)\n\n y_train = df_train[\"Label\"]\n y_test = df_test[\"Label\"]\n\n X_train_vect = df_train[\"text_label\"]\n X_test_vect = df_test[\"text_label\"]\n\n X_train_dtm = cv.fit_transform(X_train_vect)\n X_test_dtm = cv.transform(X_test_vect)\n\n remaining_feats = np.array(df_train[['word_count', 'sentiment_txtblob', 'positivity_sentiment_nltk',\n 'compound_sentiment_nltk', 'negativity_sentiment_nltk', 'neutral_sentiment_nltk']])\n remaining_test_feats = np.array(df_test[['word_count', 'sentiment_txtblob', 'positivity_sentiment_nltk',\n 'compound_sentiment_nltk', 'negativity_sentiment_nltk', 'neutral_sentiment_nltk']])\n\n X_train_dtm = hstack(([X_train_dtm, remaining_feats]))\n X_test_dtm = hstack(([X_test_dtm, remaining_test_feats]))\n\n BNB = BernoulliNB()\n BNB.fit(X_train_dtm, y_train)\n\n LogReg = LogisticRegression()\n LogReg.fit(X_train_dtm, y_train)\n\n SGD = SGDClassifier()\n SGD.fit(X_train_dtm, y_train)\n\n SVC_c = SVC()\n SVC_c.fit(X_train_dtm, y_train)\n\n ## TEST PREDICTIONS\n svc_pred = SVC_c.predict(X_test_dtm)\n bnb_pred = BNB.predict(X_test_dtm)\n logreg_pred = LogReg.predict(X_test_dtm)\n sgd_pred = SGD.predict(X_test_dtm)\n\n ## TRAINING PREDICTIONS\n svc_pred_train = SVC_c.predict(X_train_dtm)\n bnb_pred_train = BNB.predict(X_train_dtm)\n logreg_pred_train = LogReg.predict(X_train_dtm)\n sgd_pred_train = SGD.predict(X_train_dtm)\n\n\n ensemble_pred_test = np.add(svc_pred, bnb_pred + logreg_pred + sgd_pred)/4\n ensemble_pred_train = np.add(svc_pred_train, bnb_pred_train + logreg_pred_train + sgd_pred_train)/4\n\n this_pred_test = pd.DataFrame({ticker: list(map(lambda x: 1 if x>= 0 else -1, ensemble_pred_test))})\n this_pred_train = pd.DataFrame({ticker: list(map(lambda x: 1 if x>= 0 else -1, ensemble_pred_train))})\n\n ## merge this_pred_train with df_train and this_pred_test with df_test (dates only)\n this_pred_train.set_index(df_train[\"Date\"], inplace=True, drop=True)\n this_pred_test.set_index(df_test[\"Date\"], inplace=True, drop=True)\n\n ## Make it daily\n test_dates = pd.DataFrame(index=pd.date_range(start=\"2018-01-01\", end=\"2019-12-31\", freq=\"D\"))\n train_dates = pd.DataFrame(index=pd.date_range(start=\"2010-01-01\", end=\"2017-12-31\", freq=\"D\"))\n\n test_df = pd.merge(test_dates, this_pred_test, how='outer', left_index=True, right_index=True)\n test_df.fillna(method=\"ffill\", limit=2, inplace=True)\n test_df.fillna(0, inplace=True)\n\n train_df = pd.merge(train_dates, this_pred_train, how='outer', left_index=True, right_index=True)\n train_df.fillna(method=\"ffill\", limit=2, inplace=True)\n train_df.fillna(0, inplace=True)\n\n ## Remove Weekends\n train_df = train_df[train_df.index.dayofweek < 5]\n test_df = test_df[test_df.index.dayofweek < 5]\n \n train_df.index.rename(\"Date\", inplace=True)\n test_df.index.rename(\"Date\", inplace=True)\n\n train_df.to_csv(\"../../Predictions/Financial News/\" + ticker + \"_train.csv\")\n test_df.to_csv(\"../../Predictions/Financial News/\" + ticker + \"_test.csv\")",
"_____no_output_____"
],
[
"for ticker in tickers:\n if ticker in [\"DOW\", \"TRV\", \"DIS\"]: continue\n print(ticker)\n \n generate_train_test_csv(ticker)",
"MSFT\n"
],
[
"for ticker in tickers:\n if ticker in [\"DOW\", \"TRV\", \"DIS\"]: continue\n print(ticker)\n \n train = pd.read_csv(\"../../Predictions/Financial News/\" + ticker + \"_train.csv\")\n test = pd.read_csv(\"../../Predictions/Financial News/\" + ticker + \"_test.csv\")\n\n print(len(train[train.duplicated(subset=\"Date\") == True]))\n print(len(test[test.duplicated(subset=\"Date\") == True]))",
"MSFT\n0\n0\nWMT\n0\n0\nPG\n0\n0\nVZ\n0\n0\nV\n0\n0\nAAPL\n0\n0\nMMM\n0\n0\nMRK\n0\n0\nCSCO\n0\n0\nUNH\n0\n0\nJNJ\n0\n0\nXOM\n0\n0\nNKE\n0\n0\nIBM\n0\n0\nCAT\n0\n0\nCVX\n0\n0\nWBA\n0\n0\nPFE\n0\n0\nKO\n0\n0\nAXP\n0\n0\nINTC\n0\n0\nBA\n0\n0\nHD\n0\n0\nMCD\n0\n0\nGS\n0\n0\nUTX\n0\n0\nJPM\n0\n0\n"
],
[
"ticker = \"AAPL\"\ntrain = pd.read_csv(\"../../Predictions/Financial News/\" + ticker + \"_train.csv\")\ntest = pd.read_csv(\"../../Predictions/Financial News/\" + ticker + \"_test.csv\")\n\nlen(train[train.duplicated(subset=\"Date\") == True])\nlen(test[test.duplicated(subset=\"Date\") == True])",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4aaa0efd02eaedbe9f7e9391db70d4d8e2d2d942
| 35,370 |
ipynb
|
Jupyter Notebook
|
OOP/2.1 OOP - Part 1 - Assignment.ipynb
|
Sarthak-GitHub/SarthakNiwate_week_2
|
881dc9c85404c886283a3e023ab0ed07b46b0317
|
[
"MIT"
] | null | null | null |
OOP/2.1 OOP - Part 1 - Assignment.ipynb
|
Sarthak-GitHub/SarthakNiwate_week_2
|
881dc9c85404c886283a3e023ab0ed07b46b0317
|
[
"MIT"
] | null | null | null |
OOP/2.1 OOP - Part 1 - Assignment.ipynb
|
Sarthak-GitHub/SarthakNiwate_week_2
|
881dc9c85404c886283a3e023ab0ed07b46b0317
|
[
"MIT"
] | null | null | null | 30.596886 | 420 | 0.547498 |
[
[
[
"## Week 2: 2.1 OOP : Part 1\n**by Sarthak Niwate (Intern at Chistats)**",
"_____no_output_____"
],
[
"#### 1,2,3. What is class, object and reference variable in the python ",
"_____no_output_____"
],
[
"#### Class\nA class is a bundle of attributes/variables by instance and methods to define the type of object. A class can be viewed as a template of the objects. Variables of a class are termed as attributes and functions in the classes are called as methods.\n\n#### Object\nAn object is an instance of a class with a specific set of attributes. Thus, one can create as many objects as needed from the same class. \n\n#### Reference Variables\nClass variables are shared across all objects while instance variables are for data unique to each instance. Instance variable overrides the Class variables having same name which can show unusual behaviour in output.\n\n**Class Variables**: Declared inside the class definition (but outside any of the instance methods). They are not tied to any particular object of the class, hence shared across all the objects of the class. Modifying a class variable affects all objects instance at the same time.\n\n**Instance Variable**: Declared inside the constructor method of class (the __init__ method). They are tied to the particular object instance of the class, hence the contents of an instance variable are completely independent from one object instance to the other.",
"_____no_output_____"
],
[
"**All the below three questions answered together**\n#### 4. How to defin a class, define a student class with instance variables as StdName, RollNo. and StdGender. Create Constructor ( Ref. __init__(self) ) \n\n#### 5. Using Que 4, defin a method which takes self as a parameter and print the StdName, RollNo. and StdGender",
"_____no_output_____"
]
],
[
[
"class student5:\n def __init__(self):\n self.StdName = 'Sarthak'\n self.RollNo = 45\n self.StdGender = 'Male'\n \n def display_data(self):\n return f\"The name of the student is {self.StdName} and Roll No. is {self.RollNo}. The gender is {self.StdGender}.\"\n \n \ns1 = student5()\ns1.display_data()",
"_____no_output_____"
]
],
[
[
"#### 6. Create object of the student class and call display method",
"_____no_output_____"
]
],
[
[
"class student6:\n def __init__(self, StdName, RollNo, StdGender):\n self.StdName = StdName\n self.RollNo = RollNo\n self.StdGender = StdGender\n \n def display_data(self):\n return f\"The name of the student is {self.StdName} and Roll No. is {self.RollNo}. The gender is {self.StdGender}.\"\n \n \ns1 = student6('Sarthak',45,'Male')\ns1.display_data()",
"_____no_output_____"
]
],
[
[
"#### 7. What is self variable",
"_____no_output_____"
]
],
[
[
"The .__init__() method is indented four spaces in a class. The inner main body of the .__init__ method is two tab spaces. In python, this indentation helps us understand that the method belongs to the defined class in which it is being written.\nIn a body of .__init__ method, there is parameter self all the time along with variables. The term ‘self’ in the attributes refers to the corresponding instances (objects).",
"_____no_output_____"
]
],
[
[
"#### 8. What is difference between Parameterized and Non Parameterized Constructor\n\nWe can use Paramtrized constructors to set custom values for instance variables. ",
"_____no_output_____"
]
],
[
[
"class parametrizedConst:\n def __init__(self,company,model):\n self.company=company\n self.model=model\n def order(self):\n print(f\"Thank you for buying from {self.company}. Order successfully placed for {self.model}\")\np = parametrizedConst('Apple','Macbook Pro HUINX786KOLS')\np.order()",
"Thank you for buying from Apple. Order successfully placed for Macbook Pro HUINX786KOLS\n"
]
],
[
[
"We can use Non-Parametrized constructor to set values that we want.",
"_____no_output_____"
]
],
[
[
"class nonparametrizedConst:\n def __init__(self):\n self.company='Apple'\n self.model='Macbook Pro HUINX786KOLS'\n def order(self):\n print(f\"Thank you for buying from {self.company}. Order successfully placed for {self.model}\")\nnp = nonparametrizedConst()\nnp.order()",
"Thank you for buying from Apple. Order successfully placed for Macbook Pro HUINX786KOLS\n"
]
],
[
[
"#### 9. Create Parameterized constructor using class fro Que 4 and initialize the instance variables and print in the display method.",
"_____no_output_____"
]
],
[
[
"class student9:\n def __init__(self, StdName, RollNo, StdGender):\n self.StdName = StdName\n self.RollNo = RollNo\n self.StdGender = StdGender\n \n def display_data(self):\n return f\"The name of the student is {self.StdName} and Roll No. is {self.RollNo}. The gender is {self.StdGender}.\"\n \n \ns1 = student9('Sarthak',45,'Male')\ns1.display_data()",
"_____no_output_____"
]
],
[
[
"#### 10. WAP to demonstrate that constructor will execute only once per object ",
"_____no_output_____"
]
],
[
[
"About __new__ and __init__:\n\n__new__ is a constructor which typically returns an instance of cls, its first argument.\nBy __new__ returning an instance of class, __new__ causes Python to call __init__.\n__init__ is an initializer. It modifies the instance (self) returned by __new__. It does not need to return self.",
"_____no_output_____"
]
],
[
[
"def __new__(cls, *args, **kwargs):\n obj = object.__new__(cls, *args, **kwargs)\n obj.__init__(*args, **kwargs)\n return obj\n",
"_____no_output_____"
]
],
[
[
"The __new__ method is called with the class as its first argument; its responsibility is to return a new instance of that class.\n\nCompare this to __init__:__init__ is called with an instance as its first argument, and it doesn't return anything; its responsibility is to initialize the instance.\n\nAll this is done so that immutable types can preserve their immutability while allowing subclassing.\n\nThe immutable types (int, long, float, complex, str, unicode, and tuple) have a dummy __init__, while the mutable types (dict, list, file, and also super, classmethod, staticmethod, and property) have a dummy __new__.",
"_____no_output_____"
]
],
[
[
"class MyClass(object):\n def __init__(self, data):\n self.data = data\n\n def __getitem__(self, index):\n return type(self)(self.data[index])\n\n\nx = MyClass(range(10))\nx2 = x[0:2]",
"_____no_output_____"
],
[
"x2",
"_____no_output_____"
]
],
[
[
"#### 11. WAP to demonstrate where can we declare the instance variables\n\t1. inside constructer\n\t2. insite instance method \n\t3. ouside class ny using object reference variable\n##### Use of __dict__ and ways of declaring instance variables",
"_____no_output_____"
]
],
[
[
"class Television:\n def __init__(self):\n self.company = 'Panasonic' # Declare instance variables in constructor\n self.model = 'PNSCO741U-XBUR'\n\n def amount(self):\n self.price = 31250 # Declare instance variable in an instance method\n \nt=Television()\nprint(t.__dict__)\nt.amount()\nprint(t.__dict__)\nt.orderid = 7896 # Declare instance variable from outside of the class using object reference\nprint(t.__dict__)",
"{'company': 'Panasonic', 'model': 'PNSCO741U-XBUR'}\n{'company': 'Panasonic', 'model': 'PNSCO741U-XBUR', 'price': 31250}\n{'company': 'Panasonic', 'model': 'PNSCO741U-XBUR', 'price': 31250, 'orderid': 7896}\n"
]
],
[
[
"#### 12. Using variables declared in Que 4, \n\t1. Print using self\n\t2. delete using self \n\t3. delete using object reference\n\t4. Update the value of RollNo and print the object",
"_____no_output_____"
]
],
[
[
"class student12:\n def __init__(self, StdName, RollNo, StdGender):\n self.StdName = StdName\n self.RollNo = RollNo\n self.StdGender = StdGender\n \n def display_data(self):\n return f\"The name of the student is {self.StdName} and Roll No. is {self.RollNo}. The gender is {self.StdGender}.\"\n \n def delVariableInstance(self):\n del self.RollNo # Method for deleting Instance variable inside a class\n \ns = student12('Sarthak',45,'Male')\nprint(s.display_data())\ns.delVariableInstance()\nprint(s.__dict__)\ndel s.StdGender # Deleting Instance variable outside the class\nprint(t.__dict__)",
"The name of the student is Sarthak and Roll No. is 45. The gender is Male.\n{'StdName': 'Sarthak', 'StdGender': 'Male'}\n{'price': 31250}\n"
]
],
[
[
"#### 13. Write short note on static variables",
"_____no_output_____"
],
[
"Static variables are those variables which remain same for all objects and don't change like instance variables. ",
"_____no_output_____"
]
],
[
[
"class student13:\n \n StdName = 'Sarthak'\n RollNo = 45\n \n def __init__(self):\n self.StdGender = 'Male'\n \n @classmethod \n def display_data(clone):\n return f\"The name of the student is {student13.StdName} and Roll No. is {clone.RollNo}.\"\n\ns = student13()\nprint(s.display_data())\nprint(student13.display_data())",
"The name of the student is Sarthak and Roll No. is 45.\nThe name of the student is Sarthak and Roll No. is 45.\n"
]
],
[
[
"In the above code snippet, we have created multiple objects of class Student and for all of them student name remains the same. Only one copy for the static variable will be created and will be shared with other objects. This also improves performance.\nStatic variables can be accessed using Class name or Object reference.\nWe can declare static variables:\nInside a class but outside any method or constructor, Inside constructor using classname, Inside instance method using class name, Inside class method using class name or cls variable, Inside static method by using class name, From outside the class by using class name.",
"_____no_output_____"
],
[
"#### 14. WAP to declare the static variable as school name in above Student class \n\t1. Declare within class and outside the method body\n\t2. inside constructor using class name\n\t3. inside method using class name\n\t4. inside class method using class name or cls variable5. insite static methos using class name ",
"_____no_output_____"
],
[
"#### 15. WAP to access the static variable\n\t1. inside constructor using self or classname\n\t2. inside instance methos using self or classname\n\t3. inside class method using cls variable or classname\n\t4. inside static method using classname \n\t5. from outside of the class using reference is classname",
"_____no_output_____"
]
],
[
[
"class student14:\n schoolName = 'Rose Mary School' # Declaring outside any method / constructor\n def __init__(self,name):\n self.name=name # Accessing inside instance method using self\n student14.address = 'Shillong' # Declaring inside a constructor using class name\n \n def showDetails(self):\n student14.rollno = 45 # Declaring inside an instance method using class name\n \n @classmethod\n def examCenter(cls):\n student14.center_name = 'Holish Due Wih' # Declaring inside a class method using classname\n cls.center_id = 'X896' # Declaring inside a class method using cls\n print(f\"Exam Center loaction is {student14.center_name}\") # Accessing inside a method using classname\n\n @staticmethod\n def studExamid():\n student14.exam_id = 121212 # Declaring inside a static method using classname\n \ns=student14('Pranay')\ns.showDetails()\n\ns.principal='Neha Biswas' # Declaring outside the class using object name\n\nstudent14.studExamid() # Calling static method\nstudent14.examCenter() # Calling class method\n\n\nprint(\"Exam center id is: \", student14.center_id) # Accesing outside class using classname\nprint(\"Student's exam id is: \", student14.exam_id) # Accesing outside class using classname\n\nprint(student14.examCenter())",
"Exam Center loaction is Holish Due Wih\nExam center id is: X896\nStudent's exam id is: 121212\nExam Center loaction is Holish Due Wih\nNone\n"
]
],
[
[
"#### 16. Modify the value of School name and observe the behaviour\n\t1. Modify using class name \n\t2. Modify using cls variable ",
"_____no_output_____"
]
],
[
[
"class student14:\n schoolName = 'Rose Mary School' \n def __init__(self,name):\n self.name=name \n student14.address = 'Shillong' \n \n def showDetails(self):\n student14.rollno = 45 \n \n @classmethod\n def examCenter(cls):\n student14.center_name = 'Holish Due Wih' \n cls.center_id = 'X896' \n \n print(f\"School name is: {cls.schoolName}\")\n cls.schoolName = 'Jony Fen Holigreek' # wrong way\n print(f\"School name is: {cls.schoolName}\")\n \n\n @staticmethod\n def studExamid():\n student14.exam_id = 121212 \n \ns = student14('Sarthak')\nprint(s.examCenter())\n\nstudent14.schoolName = 'Keliyo Unda Funk'\n\nprint(s.examCenter())\n\n",
"School name is: Rose Mary School\nSchool name is: Jony Fen Holigreek\nNone\nSchool name is: Keliyo Unda Funk\nSchool name is: Jony Fen Holigreek\nNone\n"
]
],
[
[
"#### 17. WAP to delete the value of School name and observe the behaviour\n\t1. using classname.variable name \n\t2. using cls",
"_____no_output_____"
]
],
[
[
"class student17:\n schoolName = 'Rose Mary School'\n \n def __init__(self, StdName, RollNo, StdGender):\n self.StdName = StdName\n self.RollNo = RollNo\n self.StdGender = StdGender\n \n def display_data(self):\n return f\"The name of the student is {self.StdName} and Roll No. is {self.RollNo}. The gender is {self.StdGender}.\"\n @classmethod\n def delVariableInstance(cls):\n return f\"Old: {cls.schoolName}\"\n del cls.schoolName # Method for deleting Instance variable inside a class\n print(f\"New {cls.schoolName}\")\n \ns = student17('Sarthak',45,'Male')\nprint(s.display_data())\nprint(s.__dict__)\nprint(s.delVariableInstance())",
"The name of the student is Sarthak and Roll No. is 45. The gender is Male.\n{'StdName': 'Sarthak', 'RollNo': 45, 'StdGender': 'Male'}\nOld: Rose Mary School\n"
]
],
[
[
"#### 18. Using Instance method: WAP using below details\n\t1. Create a student class having name and marks as parameters\n\t2. Create display method to display name and marks of student\n\t3. CReate method grade which will take marks as parameters and displays the grade of the student. Ex. if marks > 60 then First grade if marke are greter than 50 then Second grade else Student us failed\n\t4. Use setter and getter to initialize the instance variables",
"_____no_output_____"
]
],
[
[
"class student18:\n def __init__(self, name, marks):\n self.name = name\n self.marks = marks\n \n @property\n def get_info(self):\n print('Getter method called')\n if (self.marks > 60):\n return \"First Grade\"\n elif (self.marks > 50 and self.marks < 60):\n return \"Second Grade\"\n else:\n return'failed'\n \n @get_info.setter\n def get_info(self, a):\n print(\"Setter method called\")\n self.marks = a\n \n \ns1 = student18('Sarthak',56)\nprint(s1.get_info)\ns2 = student18('Sarthak',82)\nprint(s2.get_info)\ns3 = student18('Sarthak',32)\nprint(s3.get_info)",
"Getter method called\nSecond Grade\nGetter method called\nFirst Grade\nGetter method called\nfailed\n"
]
],
[
[
"#### 19. Using class method: WAP to get number of objectes created for a class ",
"_____no_output_____"
]
],
[
[
"class student18:\n counter = 0\n def __init__(self, name, marks):\n self.name = name\n self.marks = marks\n student18.counter += 1\n \n @property\n def get_info(self):\n print('Getter method called')\n if (self.marks > 60):\n return \"First Grade\"\n elif (self.marks > 50 and self.marks < 60):\n return \"Second Grade\"\n else:\n return'failed'\n \n @get_info.setter\n def get_info(self, a):\n print(\"Setter method called\")\n self.marks = a\n \n \ns1 = student18('Sarthak',56)\nprint(s1.get_info)\ns2 = student18('Sarthak',82)\nprint(s2.get_info)\ns3 = student18('Sarthak',32)\nprint(s3.get_info)\nprint(student18.counter)",
"Getter method called\nSecond Grade\nGetter method called\nFirst Grade\nGetter method called\nfailed\n3\n"
]
],
[
[
"#### 20. Using class method: WAP to print the given number if odd or even",
"_____no_output_____"
]
],
[
[
"class oddEven(object):\n\n @classmethod\n def get_info(cls, number):\n if (number%2 == 0):\n return \"Even\"\n else:\n return \"Odd\"\n\nprint(oddEven.get_info(2))\nprint(oddEven.get_info(3))\nprint(oddEven.get_info(5))\nprint(oddEven.get_info(8))",
"Even\nOdd\nOdd\nEven\n"
]
],
[
[
"#### 21. Using Static method: WAP to print addition, substraction and product of two numbers",
"_____no_output_____"
]
],
[
[
"class arithmetic(object):\n\n @staticmethod\n def operations(num1,num2):\n add = num1 + num2\n sub = num1 - num2\n mul = num1 * num2\n return f\"The addition: {add}, the subtraction: {sub}, the multiplication: {mul}.\"\n\narithmetic.operations(3,4) ",
"_____no_output_____"
]
],
[
[
"#### 22. Pass members of one class to other class: Use below details \n\t1. Create class \"Student\" with Student name, roll number and marks. Define display method.\n\t2. Create class \"StudentModifier\" and define modify method which will update the student marks(marks + 10) and prints the updted marks using display method. ",
"_____no_output_____"
]
],
[
[
"class studentModifier:\n def __init__(self,name,roll_no,marks):\n self.name=name\n self.roll_no=roll_no\n self.marks=marks\n def display_method(self):\n return f\"The name of the student is {self.name} and Roll No. is {self.roll_no}. The marks are {self.marks}.\"\n def modify(self):\n marks1 = self.marks*(self.marks+10)\n return f\"Updated marks are {marks1}\"\n \nclass student22(studentModifier):\n def display(self):\n print(\"This is on lass\")",
"_____no_output_____"
],
[
"s = student22('Name',45,100)\nprint(s.display_method())\nprint(s.modify())",
"The name of the student is Name and Roll No. is 45. The marks are 100.\nUpdated marks are 11000\n"
]
],
[
[
"23. Using Inner class: WAP using below details \n\t1. Create class \"Student\" with Student name and roll number. Define display method.\n\t2. Inside Student class create inner class as Address which will be having localoty, district, state and pin as instance variables \n\t3. Create instance of student class and print the student details \n\t4. Inside Student class create another inner class as Marks which will be having marks of Physics, Chem and Maths as instance variables \n\t5. Create instance of student class and print the student details ",
"_____no_output_____"
]
],
[
[
"class student23:\n def __init__(self):\n self.name='Sarthak'\n self.roll_no=45\n self.add = self.Address()\n self.marks=self.Marks()\n \n def display_method(self):\n return f\"The name of the student is {self.name} and Roll No. is {self.roll_no}.\"\n \n class Address:\n def __init__(self):\n self.locality='Anmol Pride'\n self.district='Mumbai Subarban'\n self.state='MH'\n self.pin=400104\n \n def display_method(self):\n return f\"The locality is {self.locality} district is {self.district}, state is {self.state}, pin is {self.pin}\"\n\n class Marks:\n def __init__(self):\n self.Physics=80\n self.Chem=85\n self.Maths=78\n \n def display_method(self):\n return f\"The marks in physics are {self.Physics}, chemistry are {self.Chem}, maths are {self.Maths}\"\n \n \n\ns = student23()\nprint(s.display_method())\n\ns1 = s.add\nprint(s1.display_method())\n\ns2 = s.marks\nprint(s2.display_method())",
"The name of the student is Sarthak and Roll No. is 45.\nThe locality is Anmol Pride district is Mumbai Subarban, state is MH, pin is 400104\nThe marks in physics are 80, chemistry are 85, maths are 78\n"
]
],
[
[
"24. Garbage Collection: WAP to enable, disable GC and check if GC is enabled or not ",
"_____no_output_____"
]
],
[
[
"import gc\nobj = 2\nx = 1\ngarbage = gc.collect()\n\ngc.disable() # Disable the collector\nprint(\"Automatic garbage collection is on ?\",gc.isenabled()) # Check status\n\ngc.enable() # Enabled again\ngc.collect()\nprint(\"Automatic garbage collection is on ?\",gc.isenabled()) # Check status",
"Automatic garbage collection is on ?\nFalse\nAutomatic garbage collection is on ?\nTrue\n"
]
],
[
[
"25. Write a short not on Garbage Collection",
"_____no_output_____"
],
[
"Garbage Collection System (GCS):\nGenerally, when a program is not being used the interpreter of python frees the memory. The reason behind this capability of Python is because the developer of Python implemented a special system at the backend which is known as Garbage Collector. This system follows a technique knows as ‘reference counting’ in which objects are deallocated or ‘freed’ when there is no longer use or reference to it in a program.",
"_____no_output_____"
],
[
"26. WAP to demonstrate use of __del__ i.e. destructor method",
"_____no_output_____"
]
],
[
[
"__del__ is a destructor method which is called as soon as all references of the object are deleted i.e when an object is garbage The __del__ method is a special method of a class. It is also called the destructor method and it is called (invoked) when the instance (object) of the class is about to get destroyed.",
"_____no_output_____"
]
],
[
[
"class Robot():\n \n def __init__(self, name):\n print(name + \" has been created!\")\n \n def __del__(self):\n print (\"Thing has been destroyed\")\n \nK = Robot(\"Kunal\")\nA = Robot(\"Ankit\")\nNew = K\nprint(\"Deleting K\")\ndel K\nprint(\"Deleting A\")\ndel New\ndel A",
"Kunal has been created!\nAnkit has been created!\nDeleting K\nDeleting A\nThing has been destroyed\nThing has been destroyed\n"
]
],
[
[
"27. WAP to check number of references a Student object is having. Use Que 23.",
"_____no_output_____"
]
],
[
[
"class student23:\n def __init__(self):\n self.name='Sarthak'\n self.roll_no=45\n self.add = self.Address()\n self.marks=self.Marks()\n \n def display_method(self):\n return f\"The name of the student is {self.name} and Roll No. is {self.roll_no}.\"\n \n class Address:\n def __init__(self):\n self.locality='Anmol Pride'\n self.district='Mumbai Subarban'\n self.state='MH'\n self.pin=400104\n \n def display_method(self):\n return f\"The locality is {self.locality} district is {self.district}, state is {self.state}, pin is {self.pin}\"\n\n class Marks:\n def __init__(self):\n self.Physics=80\n self.Chem=85\n self.Maths=78\n \n def display_method(self):\n return f\"The marks in physics are {self.Physics}, chemistry are {self.Chem}, maths are {self.Maths}\"\n \n\ns = student23()\nprint(s.display_method())\n\ns1 = s.add\nprint(s1.display_method())\n\ns2 = s.marks\nprint(s2.display_method())\n\ni = 0\nfor r in gc.get_referents(s):\n i += 1\nprint(\"The no. of reference of object s is\", i)",
"The name of the student is Sarthak and Roll No. is 45.\nThe locality is Anmol Pride district is Mumbai Subarban, state is MH, pin is 400104\nThe marks in physics are 80, chemistry are 85, maths are 78\nThe no. of reference of object s is 2\n"
]
],
[
[
"## Thank You",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"raw",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"raw",
"code",
"raw",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"raw",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"raw"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"raw"
],
[
"code"
],
[
"raw"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"raw"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aaa11733c3b515d9cb26bf9c9602f2586efbaaa
| 18,530 |
ipynb
|
Jupyter Notebook
|
notebooks/Pythonic_Data_Analysis/Advanced Pythonic Data Analysis.ipynb
|
fuyihang98/python-workshop
|
018a0b45893f141a89bf99e1a4f3eb12a8046776
|
[
"MIT"
] | 84 |
2015-02-17T20:48:52.000Z
|
2018-10-04T09:32:49.000Z
|
notebooks/Pythonic_Data_Analysis/Advanced Pythonic Data Analysis.ipynb
|
fuyihang98/python-workshop
|
018a0b45893f141a89bf99e1a4f3eb12a8046776
|
[
"MIT"
] | 258 |
2015-02-02T20:49:11.000Z
|
2018-10-04T22:04:47.000Z
|
notebooks/Pythonic_Data_Analysis/Advanced Pythonic Data Analysis.ipynb
|
fuyihang98/python-workshop
|
018a0b45893f141a89bf99e1a4f3eb12a8046776
|
[
"MIT"
] | 65 |
2015-02-04T18:48:42.000Z
|
2018-10-03T18:33:39.000Z
| 30.032415 | 436 | 0.548786 |
[
[
[
"<a name=\"top\"></a>\n<div style=\"width:1000 px\">\n\n<div style=\"float:right; width:98 px; height:98px;\">\n<img src=\"https://raw.githubusercontent.com/Unidata/MetPy/master/metpy/plots/_static/unidata_150x150.png\" alt=\"Unidata Logo\" style=\"height: 98px;\">\n</div>\n\n<h1>Advanced Pythonic Data Analysis</h1>\n<h3>Unidata Python Workshop</h3>\n\n<div style=\"clear:both\"></div>\n</div>\n\n<hr style=\"height:2px;\">\n\n<div style=\"float:right; width:250 px\"><img src=\"http://matplotlib.org/_images/date_demo.png\" alt=\"METAR\" style=\"height: 300px;\"></div>\n\n\n## Overview:\n\n* **Teaching:** 45 minutes\n* **Exercises:** 45 minutes\n\n### Questions\n1. How can we improve upon the versatility of the plotter developed in the basic time series notebook?\n1. How can we iterate over all data file in a directory?\n1. How can data processing functions be applied on a variable-by-variable basis?\n\n### Objectives\n1. <a href=\"#basicfunctionality\">From Time Series Plotting Episode</a>\n1. <a href=\"#parameterdict\">Dictionaries of Parameters</a>\n1. <a href=\"#multipledict\">Multiple Dictionaries</a>\n1. <a href=\"#functions\">Function Application</a>\n1. <a href=\"#glob\">Glob and Multiple Files</a>",
"_____no_output_____"
],
[
"<a name=\"basicfunctionality\"></a>\n## From Time Series Plotting Episode\nHere's the basic set of imports and data reading functionality that we established in the [Basic Time Series Plotting](../Time_Series/Basic%20Time%20Series%20Plotting.ipynb) notebook.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.dates import DateFormatter, DayLocator\nfrom siphon.simplewebservice.ndbc import NDBC\n\n%matplotlib inline",
"_____no_output_____"
],
[
"def format_varname(varname):\n \"\"\"Format the variable name nicely for titles and labels.\"\"\"\n parts = varname.split('_')\n title = parts[0].title()\n label = varname.replace('_', ' ').title()\n return title, label",
"_____no_output_____"
],
[
"def read_buoy_data(buoy, days=7): \n # Read in some data\n df = NDBC.realtime_observations(buoy)\n\n # Trim to the last 7 days\n df = df[df['time'] > (pd.Timestamp.utcnow() - pd.Timedelta(days=days))]\n return df",
"_____no_output_____"
]
],
[
[
"<a href=\"#top\">Top</a>\n<hr style=\"height:2px;\">",
"_____no_output_____"
],
[
"<a name=\"parameterdict\"></a>\n## Dictionaries of Parameters\n\nWhen we left off last time, we had created dictionaries that stored line colors and plot properties in a key value pair. To further simplify things, we can actually pass a dictionary of arguements to the plot call. Enter the dictionary of dictionaries. Each key has a value that is a dictionary itself with it's key value pairs being the arguements to each plot call. Notice that different variables can have different arguements!",
"_____no_output_____"
]
],
[
[
"df = read_buoy_data('42039')",
"_____no_output_____"
],
[
"# Dictionary of plotting parameters by variable name\nstyles = {'wind_speed': dict(color='tab:orange'),\n 'wind_gust': dict(color='tab:olive', linestyle='None', marker='o', markersize=2),\n 'pressure': dict(color='black')}\n\nplot_variables = [['wind_speed', 'wind_gust'], ['pressure']]",
"_____no_output_____"
],
[
"fig, axes = plt.subplots(1, len(plot_variables), sharex=True, figsize=(14, 5))\n\nfor col, var_names in enumerate(plot_variables):\n ax = axes[col]\n for var_name in var_names:\n title, label = format_varname(var_name)\n ax.plot(df.time, df[var_name], **styles[var_name])\n\n ax.set_ylabel(title)\n ax.set_title('Buoy 42039 {}'.format(title))\n\n ax.grid(True)\n ax.set_xlabel('Time')\n ax.xaxis.set_major_formatter(DateFormatter('%m/%d'))\n ax.xaxis.set_major_locator(DayLocator())",
"_____no_output_____"
]
],
[
[
"<a href=\"#top\">Top</a>\n<hr style=\"height:2px;\">",
"_____no_output_____"
],
[
"<a name=\"multipledict\"></a>\n## Multiple Dictionaries\n\nWe can even use multiple dictionaries to define styles for types of observations and then specific observation properties such as levels, sources, etc. One common use case of this would be plotting all temperature data as red, but with different linestyles for an isobaric level and the surface. ",
"_____no_output_____"
]
],
[
[
"type_styles = {'Temperature': dict(color='red', marker='o'),\n 'Relative humidity': dict(color='green', marker='s')}\n\nlevel_styles = {'isobaric': dict(linestyle='-', linewidth=2),\n 'surface': dict(linestyle=':', linewidth=3)}",
"_____no_output_____"
],
[
"my_style = type_styles['Temperature']\nprint(my_style)",
"_____no_output_____"
],
[
"my_style.update(level_styles['isobaric'])\nprint(my_style)",
"_____no_output_____"
]
],
[
[
"If we look back at the original entry in `type_styles` we see it was updated too! That may not be the expected or even the desired behavior. ",
"_____no_output_____"
]
],
[
[
"type_styles['Temperature']",
"_____no_output_____"
]
],
[
[
"We can use the `copy` method to make a copy of the element and avoid update the original.",
"_____no_output_____"
]
],
[
[
"type_styles = {'Temperature': dict(color='red', marker='o'),\n 'Relative humidity': dict(color='green', marker='s')}\n\nlevel_styles = {'isobaric': dict(linestyle='-', linewidth=2),\n 'surface': dict(linestyle=':', linewidth=3)}\n\nmy_style = type_styles['Temperature'].copy() # Avoids altering the original entry\nmy_style.update(level_styles['isobaric'])\nprint(my_style)",
"_____no_output_____"
],
[
"type_styles['Temperature']",
"_____no_output_____"
]
],
[
[
"Since we don't have data from different levels, we'll work with wind measurements and pressure data. Our <code>format_varname</code> function returns a title and full variable name label.",
"_____no_output_____"
],
[
"<div class=\"alert alert-success\">\n <b>EXERCISE</b>:\n <ul>\n <li>Create a type styles dictionary of dictionaries with the variable title as the key that has styles for `Wind` and `Pressure` data. The pressure should be a solid black line. Wind should be a solid line.</li>\n <li>Create a variable style dictionary of dictionaries with the variable name as the key that specifies an orange line of width 2 for wind speed, olive line of width 0.5 for gusts, and no additional information for pressure.</li>\n <li>Update the plotting code below to use the new type and variable styles dictionary.\n </ul>\n</div>",
"_____no_output_____"
]
],
[
[
"# Your code goes here (modify the skeleton below)\ntype_styles = {}\n\nvariable_styles = {}\n\nfig, axes = plt.subplots(1, len(plot_variables), sharex=True, figsize=(14, 5))\n\nfor col, var_names in enumerate(plot_variables):\n ax = axes[col]\n for var_name in var_names:\n title, label = format_varname(var_name)\n ax.plot(df.time, df[var_name], **styles[var_name])\n\n ax.set_ylabel(title)\n ax.set_title('Buoy 42039 {}'.format(title))\n\n ax.grid(True)\n ax.set_xlabel('Time')\n ax.xaxis.set_major_formatter(DateFormatter('%m/%d'))\n ax.xaxis.set_major_locator(DayLocator())",
"_____no_output_____"
]
],
[
[
"#### Solution",
"_____no_output_____"
]
],
[
[
"# %load solutions/dict_args.py",
"_____no_output_____"
]
],
[
[
"<a href=\"#top\">Top</a>\n<hr style=\"height:2px;\">",
"_____no_output_____"
],
[
"<a name=\"functions\"></a>\n## Function Application\n\nThere are times where we might want to apply a certain amount of pre-processing to the data before they are plotted. Maybe we want to do a unit conversion, scale the data, or filter it. We can create a dictionary in which functions are the values and variable names are the keys.\n\nFor example, let's define a function that uses the running median to filter the wind data (effectively a low-pass). We'll also make a do nothing function for data we don't want to alter.",
"_____no_output_____"
]
],
[
[
"from scipy.signal import medfilt\n\ndef filter_wind(a):\n return medfilt(a, 7)\n\ndef donothing(a):\n return a",
"_____no_output_____"
],
[
"converters = {'Wind': filter_wind, 'Pressure': donothing}",
"_____no_output_____"
],
[
"type_styles = {'Pressure': dict(color='black'),\n 'Wind': dict(linestyle='-')}\n\nvariable_styles = {'pressure': dict(),\n 'wind_speed': dict(color='tab:orange', linewidth=2),\n 'wind_gust': dict(color='tab:olive', linewidth=0.5)}\n\nfig, axes = plt.subplots(1, len(plot_variables), sharex=True, figsize=(14, 5))\n\nfor col, var_names in enumerate(plot_variables):\n ax = axes[col]\n for var_name in var_names:\n title, label = format_varname(var_name)\n \n # Apply our pre-processing\n var_data = converters[title](df[var_name])\n \n style = type_styles[title].copy() # So the next line doesn't change the original\n style.update(variable_styles[var_name])\n ax.plot(df.time, var_data, **style)\n\n ax.set_ylabel(title)\n ax.set_title('Buoy 42039 {}'.format(title))\n\n ax.grid(True)\n ax.set_xlabel('Time')\n ax.xaxis.set_major_formatter(DateFormatter('%m/%d'))\n ax.xaxis.set_major_locator(DayLocator())",
"_____no_output_____"
]
],
[
[
"<div class=\"alert alert-success\">\n <b>EXERCISE</b>:\n <ul>\n <li>Write a function to convert the pressure data to bars. (**Hint**: 1 bar = 100000 Pa)</li>\n <li>Apply your converter in the code below and replot the data.</li>\n </ul>\n</div>",
"_____no_output_____"
]
],
[
[
"# Your code goes here (modify the code below)\n\nconverters = {'Wind': filter_wind, 'Pressure': donothing}\n\ntype_styles = {'Pressure': dict(color='black'),\n 'Wind': dict(linestyle='-')}\n\nvariable_styles = {'pressure': dict(),\n 'wind_speed': dict(color='tab:orange', linewidth=2),\n 'wind_gust': dict(color='tab:olive', linewidth=0.5)}\n\nfig, axes = plt.subplots(1, len(plot_variables), sharex=True, figsize=(14, 5))\n\nfor col, var_names in enumerate(plot_variables):\n ax = axes[col]\n for var_name in var_names:\n title, label = format_varname(var_name)\n \n # Apply our pre-processing\n var_data = converters[title](df[var_name])\n \n style = type_styles[title].copy() # So the next line doesn't change the original\n style.update(variable_styles[var_name])\n ax.plot(df.time, var_data, **style)\n\n ax.set_ylabel(title)\n ax.set_title('Buoy 42039 {}'.format(title))\n\n ax.grid(True)\n ax.set_xlabel('Time')\n ax.xaxis.set_major_formatter(DateFormatter('%m/%d'))\n ax.xaxis.set_major_locator(DayLocator())",
"_____no_output_____"
]
],
[
[
"#### Solution\n\n<div class=\"alert alert-info\">\n <b>REMINDER</b>:\n You should be using the unit library to convert between various physical units, this is simply for demonstration purposes!\n</div>",
"_____no_output_____"
]
],
[
[
"# %load solutions/function_application.py",
"_____no_output_____"
]
],
[
[
"<a href=\"#top\">Top</a>\n<hr style=\"height:2px;\">",
"_____no_output_____"
],
[
"<a name=\"glob\"></a>\n## Multiple Buoys",
"_____no_output_____"
],
[
"We can now use the techniques we've seen before to make a plot of multiple buoys in a single figure.",
"_____no_output_____"
]
],
[
[
"buoys = ['42039', '42022']",
"_____no_output_____"
],
[
"type_styles = {'Pressure': dict(color='black'),\n 'Wind': dict(linestyle='-')}\n\nvariable_styles = {'pressure': dict(),\n 'wind_speed': dict(color='tab:orange', linewidth=2),\n 'wind_gust': dict(color='tab:olive', linewidth=0.5)}\n\nfig, axes = plt.subplots(len(buoys), len(plot_variables), sharex=True, figsize=(14, 10))\n\nfor row, buoy in enumerate(buoys):\n df = read_buoy_data(buoy)\n for col, var_names in enumerate(plot_variables):\n ax = axes[row, col]\n for var_name in var_names:\n title, label = format_varname(var_name)\n style = type_styles[title].copy() # So the next line doesn't change the original\n style.update(variable_styles[var_name])\n ax.plot(df.time, df[var_name], **style)\n\n ax.set_ylabel(title)\n ax.set_title('Buoy {} {}'.format(buoy, title))\n\n ax.grid(True)\n ax.set_xlabel('Time')\n ax.xaxis.set_major_formatter(DateFormatter('%m/%d'))\n ax.xaxis.set_major_locator(DayLocator())",
"_____no_output_____"
]
],
[
[
"<a href=\"#top\">Top</a>\n<hr style=\"height:2px;\">",
"_____no_output_____"
],
[
"<div class=\"alert alert-success\">\n <b>EXERCISE</b>: As a final exercise, use a dictionary to allow all of the plots to share common y axis limits based on the variable title.\n</div>",
"_____no_output_____"
]
],
[
[
"# Your code goes here\n",
"_____no_output_____"
]
],
[
[
"#### Solution",
"_____no_output_____"
]
],
[
[
"# %load solutions/final.py",
"_____no_output_____"
]
],
[
[
"<a href=\"#top\">Top</a>\n<hr style=\"height:2px;\">",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aaa374ad8539db822b2e3dc0392df5b02a31ef8
| 813,544 |
ipynb
|
Jupyter Notebook
|
BucksCovid.ipynb
|
jbochanski/BucksCovid
|
51ced17757d134be1e6f10e46e7c86afa0635fe9
|
[
"MIT"
] | null | null | null |
BucksCovid.ipynb
|
jbochanski/BucksCovid
|
51ced17757d134be1e6f10e46e7c86afa0635fe9
|
[
"MIT"
] | null | null | null |
BucksCovid.ipynb
|
jbochanski/BucksCovid
|
51ced17757d134be1e6f10e46e7c86afa0635fe9
|
[
"MIT"
] | null | null | null | 3,307.089431 | 123,689 | 0.59038 |
[
[
[
"from urllib import request\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport json\nimport mpld3\nfrom datetime import date\n\n\n%matplotlib inline\nmpld3.enable_notebook()\n",
"_____no_output_____"
],
[
"def check_bucks_covid(keyword):\n \n #Data on deaths and cases\n if keyword=='daily':\n #response = request.urlopen('https://services3.arcgis.com/SP47Tddf7RK32lBU/arcgis/rest/services/Buck_County_COVID_Case_Dates_VIEW_2/FeatureServer/0/query?f=json&where=1%3D1&returnGeometry=false&spatialRel=esriSpatialRelIntersects&outFields=*&orderByFields=Date%20asc&resultOffset=0&resultRecordCount=32000&resultType=standard&cacheHint=true')\n response = request.urlopen('https://services1.arcgis.com/Nifc7wlHaBPig3Q3/arcgis/rest/services/Covid_Cases_County/FeatureServer/0/query?f=json&where=county%3D%27Bucks%27&returnGeometry=false&spatialRel=esriSpatialRelIntersects&outFields=ObjectId%2Ccases%2Cdate&orderByFields=date%20asc&resultOffset=0&resultRecordCount=32000&resultType=standard&cacheHint=true')\n dat = response.read()\n data = json.loads(dat)\n df = pd.json_normalize(data['features'])\n df['date'] = pd.to_datetime(df['attributes.date'],unit='ms')\n \n\t#Data on onset of cases\n if keyword=='onset':\n response = request.urlopen('https://services3.arcgis.com/SP47Tddf7RK32lBU/arcgis/rest/services/Bucks_County_COVID_Cases_by_Onset_Date_VIEW/FeatureServer/0/query?f=json&where=1%3D1&returnGeometry=false&spatialRel=esriSpatialRelIntersects&outFields=*&orderByFields=Date%20asc&resultOffset=0&resultRecordCount=32000&resultType=standard&cacheHint=true')\n dat = response.read()\n data = json.loads(dat)\n df = pd.json_normalize(data['features'])\n df['date'] = pd.to_datetime(df['attributes.Date'],unit='ms')\n \n \n\n if keyword=='daily':\n df['cases']= df['attributes.cases']\n df['ma3']= df['attributes.cases'].rolling(3).mean()\n df['ma7']= df['attributes.cases'].rolling(7).mean()\n df['ma11']= df['attributes.cases'].rolling(11).mean()\n\n if keyword=='onset':\n df['cases']= df['attributes.Onset']\n df['ma3']= df['attributes.Onset'].rolling(3).mean()\n df['ma7']= df['attributes.Onset'].rolling(7).mean()\n df['ma11']= df['attributes.Onset'].rolling(11).mean()\n\n \n fig, ax = plt.subplots(figsize=(10,5))\n\n bar = ax.bar('date', 'cases', data=df, label='Daily Count', alpha=0.7)\n l1 = ax.plot(df['date'], df['cases'], marker='o', markersize=8, alpha=0.00)\n labels =[str(df['cases'][i]) for i in range(len(df['cases']))]\n tt = mpld3.plugins.PointLabelTooltip(l1[0], labels=labels)\n mpld3.plugins.connect(fig, tt)\n\n #l2 = ax.plot(df['date'], df['ma3'], label='3 Day Rolling Average',color='C1', linewidth=3)\n l3 = ax.plot(df['date'], df['ma7'], label='7 Day Rolling Average',color='C2', linewidth=3)\n #l4 = ax.plot('date', 'ma11', data=df, label='11 Day Rolling Average',color='C3', linewidth=3)\n\n plt.title(keyword.capitalize() + ' accessed on '+str(date.today()))\n\n\n plt.ylabel('Daily Cases')\n plt.xlabel('Date')\n plt.legend()\n plt.show()",
"_____no_output_____"
],
[
"check_bucks_covid('daily')",
"_____no_output_____"
],
[
"check_bucks_covid('onset')",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
4aaa604a7d608343663db7e79dc787b3ac3074bf
| 70,090 |
ipynb
|
Jupyter Notebook
|
notebooks/community/gapic/automl/showcase_automl_text_sentiment_analysis_batch.ipynb
|
nayaknishant/vertex-ai-samples
|
3ce120b953f1cdc2ec2c5a3f4509cfeab106b7d0
|
[
"Apache-2.0"
] | 213 |
2021-06-10T20:05:20.000Z
|
2022-03-31T16:09:29.000Z
|
notebooks/community/gapic/automl/showcase_automl_text_sentiment_analysis_batch.ipynb
|
nayaknishant/vertex-ai-samples
|
3ce120b953f1cdc2ec2c5a3f4509cfeab106b7d0
|
[
"Apache-2.0"
] | 343 |
2021-07-25T22:55:25.000Z
|
2022-03-31T23:58:47.000Z
|
notebooks/community/gapic/automl/showcase_automl_text_sentiment_analysis_batch.ipynb
|
nayaknishant/vertex-ai-samples
|
3ce120b953f1cdc2ec2c5a3f4509cfeab106b7d0
|
[
"Apache-2.0"
] | 143 |
2021-07-21T17:27:47.000Z
|
2022-03-29T01:20:43.000Z
| 39.420697 | 374 | 0.549907 |
[
[
[
"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# Vertex client library: AutoML text sentiment analysis model for batch prediction\n\n<table align=\"left\">\n <td>\n <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/automl/showcase_automl_text_sentiment_analysis_batch.ipynb\">\n <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n </a>\n </td>\n <td>\n <a href=\"https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/automl/showcase_automl_text_sentiment_analysis_batch.ipynb\">\n <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n View on GitHub\n </a>\n </td>\n</table>\n<br/><br/><br/>",
"_____no_output_____"
],
[
"## Overview\n\n\nThis tutorial demonstrates how to use the Vertex client library for Python to create text sentiment analysis models and do batch prediction using Google Cloud's [AutoML](https://cloud.google.com/vertex-ai/docs/start/automl-users).",
"_____no_output_____"
],
[
"### Dataset\n\nThe dataset used for this tutorial is the [Crowdflower Claritin-Twitter dataset](https://data.world/crowdflower/claritin-twitter) from [data.world Datasets](https://data.world). The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket.",
"_____no_output_____"
],
[
"### Objective\n\nIn this tutorial, you create an AutoML text sentiment analysis model from a Python script, and then do a batch prediction using the Vertex client library. You can alternatively create and deploy models using the `gcloud` command-line tool or online using the Google Cloud Console.\n\nThe steps performed include:\n\n- Create a Vertex `Dataset` resource.\n- Train the model.\n- View the model evaluation.\n- Make a batch prediction.\n\nThere is one key difference between using batch prediction and using online prediction:\n\n* Prediction Service: Does an on-demand prediction for the entire set of instances (i.e., one or more data items) and returns the results in real-time.\n\n* Batch Prediction Service: Does a queued (batch) prediction for the entire set of instances in the background and stores the results in a Cloud Storage bucket when ready.",
"_____no_output_____"
],
[
"### Costs\n\nThis tutorial uses billable components of Google Cloud (GCP):\n\n* Vertex AI\n* Cloud Storage\n\nLearn about [Vertex AI\npricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage\npricing](https://cloud.google.com/storage/pricing), and use the [Pricing\nCalculator](https://cloud.google.com/products/calculator/)\nto generate a cost estimate based on your projected usage.",
"_____no_output_____"
],
[
"## Installation\n\nInstall the latest version of Vertex client library.",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\n\n# Google Cloud Notebook\nif os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n USER_FLAG = \"--user\"\nelse:\n USER_FLAG = \"\"\n\n! pip3 install -U google-cloud-aiplatform $USER_FLAG",
"_____no_output_____"
]
],
[
[
"Install the latest GA version of *google-cloud-storage* library as well.",
"_____no_output_____"
]
],
[
[
"! pip3 install -U google-cloud-storage $USER_FLAG",
"_____no_output_____"
]
],
[
[
"### Restart the kernel\n\nOnce you've installed the Vertex client library and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages.",
"_____no_output_____"
]
],
[
[
"if not os.getenv(\"IS_TESTING\"):\n # Automatically restart kernel after installs\n import IPython\n\n app = IPython.Application.instance()\n app.kernel.do_shutdown(True)",
"_____no_output_____"
]
],
[
[
"## Before you begin\n\n### GPU runtime\n\n*Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU**\n\n### Set up your Google Cloud project\n\n**The following steps are required, regardless of your notebook environment.**\n\n1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n\n2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n\n3. [Enable the Vertex APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component)\n\n4. [The Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Google Cloud Notebook.\n\n5. Enter your project ID in the cell below. Then run the cell to make sure the\nCloud SDK uses the right project for all the commands in this notebook.\n\n**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.",
"_____no_output_____"
]
],
[
[
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}",
"_____no_output_____"
],
[
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n # Get your GCP project id from gcloud\n shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n PROJECT_ID = shell_output[0]\n print(\"Project ID:\", PROJECT_ID)",
"_____no_output_____"
],
[
"! gcloud config set project $PROJECT_ID",
"_____no_output_____"
]
],
[
[
"#### Region\n\nYou can also change the `REGION` variable, which is used for operations\nthroughout the rest of this notebook. Below are regions supported for Vertex. We recommend that you choose the region closest to you.\n\n- Americas: `us-central1`\n- Europe: `europe-west4`\n- Asia Pacific: `asia-east1`\n\nYou may not use a multi-regional bucket for training with Vertex. Not all regions provide support for all Vertex services. For the latest support per region, see the [Vertex locations documentation](https://cloud.google.com/vertex-ai/docs/general/locations)",
"_____no_output_____"
]
],
[
[
"REGION = \"us-central1\" # @param {type: \"string\"}",
"_____no_output_____"
]
],
[
[
"#### Timestamp\n\nIf you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial.",
"_____no_output_____"
]
],
[
[
"from datetime import datetime\n\nTIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")",
"_____no_output_____"
]
],
[
[
"### Authenticate your Google Cloud account\n\n**If you are using Google Cloud Notebook**, your environment is already authenticated. Skip this step.\n\n**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n\n**Otherwise**, follow these steps:\n\nIn the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n\n**Click Create service account**.\n\nIn the **Service account name** field, enter a name, and click **Create**.\n\nIn the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex\" into the filter box, and select **Vertex Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n\nClick Create. A JSON file that contains your key downloads to your local environment.\n\nEnter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell.",
"_____no_output_____"
]
],
[
[
"# If you are running this notebook in Colab, run this cell and follow the\n# instructions to authenticate your GCP account. This provides access to your\n# Cloud Storage bucket and lets you submit training jobs and prediction\n# requests.\n\n# If on Google Cloud Notebook, then don't execute this code\nif not os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n if \"google.colab\" in sys.modules:\n from google.colab import auth as google_auth\n\n google_auth.authenticate_user()\n\n # If you are running this notebook locally, replace the string below with the\n # path to your service account key and run this cell to authenticate your GCP\n # account.\n elif not os.getenv(\"IS_TESTING\"):\n %env GOOGLE_APPLICATION_CREDENTIALS ''",
"_____no_output_____"
]
],
[
[
"### Create a Cloud Storage bucket\n\n**The following steps are required, regardless of your notebook environment.**\n\nThis tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.\n\nSet the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization.",
"_____no_output_____"
]
],
[
[
"BUCKET_NAME = \"gs://[your-bucket-name]\" # @param {type:\"string\"}",
"_____no_output_____"
],
[
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"gs://[your-bucket-name]\":\n BUCKET_NAME = \"gs://\" + PROJECT_ID + \"aip-\" + TIMESTAMP",
"_____no_output_____"
]
],
[
[
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket.",
"_____no_output_____"
]
],
[
[
"! gsutil mb -l $REGION $BUCKET_NAME",
"_____no_output_____"
]
],
[
[
"Finally, validate access to your Cloud Storage bucket by examining its contents:",
"_____no_output_____"
]
],
[
[
"! gsutil ls -al $BUCKET_NAME",
"_____no_output_____"
]
],
[
[
"### Set up variables\n\nNext, set up some variables used throughout the tutorial.\n### Import libraries and define constants",
"_____no_output_____"
],
[
"#### Import Vertex client library\n\nImport the Vertex client library into our Python environment.",
"_____no_output_____"
]
],
[
[
"import time\n\nfrom google.cloud.aiplatform import gapic as aip\nfrom google.protobuf import json_format\nfrom google.protobuf.json_format import MessageToJson, ParseDict\nfrom google.protobuf.struct_pb2 import Struct, Value",
"_____no_output_____"
]
],
[
[
"#### Vertex constants\n\nSetup up the following constants for Vertex:\n\n- `API_ENDPOINT`: The Vertex API service endpoint for dataset, model, job, pipeline and endpoint services.\n- `PARENT`: The Vertex location root path for dataset, model, job, pipeline and endpoint resources.",
"_____no_output_____"
]
],
[
[
"# API service endpoint\nAPI_ENDPOINT = \"{}-aiplatform.googleapis.com\".format(REGION)\n\n# Vertex location root path for your dataset, model and endpoint resources\nPARENT = \"projects/\" + PROJECT_ID + \"/locations/\" + REGION",
"_____no_output_____"
]
],
[
[
"#### AutoML constants\n\nSet constants unique to AutoML datasets and training:\n\n- Dataset Schemas: Tells the `Dataset` resource service which type of dataset it is.\n- Data Labeling (Annotations) Schemas: Tells the `Dataset` resource service how the data is labeled (annotated).\n- Dataset Training Schemas: Tells the `Pipeline` resource service the task (e.g., classification) to train the model for.",
"_____no_output_____"
]
],
[
[
"# Text Dataset type\nDATA_SCHEMA = \"gs://google-cloud-aiplatform/schema/dataset/metadata/text_1.0.0.yaml\"\n# Text Labeling type\nLABEL_SCHEMA = \"gs://google-cloud-aiplatform/schema/dataset/ioformat/text_sentiment_io_format_1.0.0.yaml\"\n# Text Training task\nTRAINING_SCHEMA = \"gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_text_sentiment_1.0.0.yaml\"",
"_____no_output_____"
]
],
[
[
"#### Hardware Accelerators\n\nSet the hardware accelerators (e.g., GPU), if any, for prediction.\n\nSet the variable `DEPLOY_GPU/DEPLOY_NGPU` to use a container image supporting a GPU and the number of GPUs allocated to the virtual machine (VM) instance. For example, to use a GPU container image with 4 Nvidia Telsa K80 GPUs allocated to each VM, you would specify:\n\n (aip.AcceleratorType.NVIDIA_TESLA_K80, 4)\n\nFor GPU, available accelerators include:\n - aip.AcceleratorType.NVIDIA_TESLA_K80\n - aip.AcceleratorType.NVIDIA_TESLA_P100\n - aip.AcceleratorType.NVIDIA_TESLA_P4\n - aip.AcceleratorType.NVIDIA_TESLA_T4\n - aip.AcceleratorType.NVIDIA_TESLA_V100\n\nOtherwise specify `(None, None)` to use a container image to run on a CPU.",
"_____no_output_____"
]
],
[
[
"if os.getenv(\"IS_TESTING_DEPOLY_GPU\"):\n DEPLOY_GPU, DEPLOY_NGPU = (\n aip.AcceleratorType.NVIDIA_TESLA_K80,\n int(os.getenv(\"IS_TESTING_DEPOLY_GPU\")),\n )\nelse:\n DEPLOY_GPU, DEPLOY_NGPU = (aip.AcceleratorType.NVIDIA_TESLA_K80, 1)",
"_____no_output_____"
]
],
[
[
"#### Container (Docker) image\n\nFor AutoML batch prediction, the container image for the serving binary is pre-determined by the Vertex prediction service. More specifically, the service will pick the appropriate container for the model depending on the hardware accelerator you selected.",
"_____no_output_____"
],
[
"#### Machine Type\n\nNext, set the machine type to use for prediction.\n\n- Set the variable `DEPLOY_COMPUTE` to configure the compute resources for the VM you will use for prediction.\n - `machine type`\n - `n1-standard`: 3.75GB of memory per vCPU.\n - `n1-highmem`: 6.5GB of memory per vCPU\n - `n1-highcpu`: 0.9 GB of memory per vCPU\n - `vCPUs`: number of \\[2, 4, 8, 16, 32, 64, 96 \\]\n\n*Note: You may also use n2 and e2 machine types for training and deployment, but they do not support GPUs*",
"_____no_output_____"
]
],
[
[
"if os.getenv(\"IS_TESTING_DEPLOY_MACHINE\"):\n MACHINE_TYPE = os.getenv(\"IS_TESTING_DEPLOY_MACHINE\")\nelse:\n MACHINE_TYPE = \"n1-standard\"\n\nVCPU = \"4\"\nDEPLOY_COMPUTE = MACHINE_TYPE + \"-\" + VCPU\nprint(\"Deploy machine type\", DEPLOY_COMPUTE)",
"_____no_output_____"
]
],
[
[
"# Tutorial\n\nNow you are ready to start creating your own AutoML text sentiment analysis model.",
"_____no_output_____"
],
[
"## Set up clients\n\nThe Vertex client library works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the Vertex server.\n\nYou will use different clients in this tutorial for different steps in the workflow. So set them all up upfront.\n\n- Dataset Service for `Dataset` resources.\n- Model Service for `Model` resources.\n- Pipeline Service for training.\n- Job Service for batch prediction and custom training.",
"_____no_output_____"
]
],
[
[
"# client options same for all services\nclient_options = {\"api_endpoint\": API_ENDPOINT}\n\n\ndef create_dataset_client():\n client = aip.DatasetServiceClient(client_options=client_options)\n return client\n\n\ndef create_model_client():\n client = aip.ModelServiceClient(client_options=client_options)\n return client\n\n\ndef create_pipeline_client():\n client = aip.PipelineServiceClient(client_options=client_options)\n return client\n\n\ndef create_job_client():\n client = aip.JobServiceClient(client_options=client_options)\n return client\n\n\nclients = {}\nclients[\"dataset\"] = create_dataset_client()\nclients[\"model\"] = create_model_client()\nclients[\"pipeline\"] = create_pipeline_client()\nclients[\"job\"] = create_job_client()\n\nfor client in clients.items():\n print(client)",
"_____no_output_____"
]
],
[
[
"## Dataset\n\nNow that your clients are ready, your first step in training a model is to create a managed dataset instance, and then upload your labeled data to it.\n\n### Create `Dataset` resource instance\n\nUse the helper function `create_dataset` to create the instance of a `Dataset` resource. This function does the following:\n\n1. Uses the dataset client service.\n2. Creates an Vertex `Dataset` resource (`aip.Dataset`), with the following parameters:\n - `display_name`: The human-readable name you choose to give it.\n - `metadata_schema_uri`: The schema for the dataset type.\n3. Calls the client dataset service method `create_dataset`, with the following parameters:\n - `parent`: The Vertex location root path for your `Database`, `Model` and `Endpoint` resources.\n - `dataset`: The Vertex dataset object instance you created.\n4. The method returns an `operation` object.\n\nAn `operation` object is how Vertex handles asynchronous calls for long running operations. While this step usually goes fast, when you first use it in your project, there is a longer delay due to provisioning.\n\nYou can use the `operation` object to get status on the operation (e.g., create `Dataset` resource) or to cancel the operation, by invoking an operation method:\n\n| Method | Description |\n| ----------- | ----------- |\n| result() | Waits for the operation to complete and returns a result object in JSON format. |\n| running() | Returns True/False on whether the operation is still running. |\n| done() | Returns True/False on whether the operation is completed. |\n| canceled() | Returns True/False on whether the operation was canceled. |\n| cancel() | Cancels the operation (this may take up to 30 seconds). |",
"_____no_output_____"
]
],
[
[
"TIMEOUT = 90\n\n\ndef create_dataset(name, schema, labels=None, timeout=TIMEOUT):\n start_time = time.time()\n try:\n dataset = aip.Dataset(\n display_name=name, metadata_schema_uri=schema, labels=labels\n )\n\n operation = clients[\"dataset\"].create_dataset(parent=PARENT, dataset=dataset)\n print(\"Long running operation:\", operation.operation.name)\n result = operation.result(timeout=TIMEOUT)\n print(\"time:\", time.time() - start_time)\n print(\"response\")\n print(\" name:\", result.name)\n print(\" display_name:\", result.display_name)\n print(\" metadata_schema_uri:\", result.metadata_schema_uri)\n print(\" metadata:\", dict(result.metadata))\n print(\" create_time:\", result.create_time)\n print(\" update_time:\", result.update_time)\n print(\" etag:\", result.etag)\n print(\" labels:\", dict(result.labels))\n return result\n except Exception as e:\n print(\"exception:\", e)\n return None\n\n\nresult = create_dataset(\"claritin-\" + TIMESTAMP, DATA_SCHEMA)",
"_____no_output_____"
]
],
[
[
"Now save the unique dataset identifier for the `Dataset` resource instance you created.",
"_____no_output_____"
]
],
[
[
"# The full unique ID for the dataset\ndataset_id = result.name\n# The short numeric ID for the dataset\ndataset_short_id = dataset_id.split(\"/\")[-1]\n\nprint(dataset_id)",
"_____no_output_____"
]
],
[
[
"### Data preparation\n\nThe Vertex `Dataset` resource for text has a couple of requirements for your text data.\n\n- Text examples must be stored in a CSV or JSONL file.",
"_____no_output_____"
],
[
"#### CSV\n\nFor text sentiment analysis, the CSV file has a few requirements:\n\n- No heading.\n- First column is the text example or Cloud Storage path to text file.\n- Second column the label (i.e., sentiment).\n- Third column is the maximum sentiment value. For example, if the range is 0 to 3, then the maximum value is 3.",
"_____no_output_____"
],
[
"#### Location of Cloud Storage training data.\n\nNow set the variable `IMPORT_FILE` to the location of the CSV index file in Cloud Storage.",
"_____no_output_____"
]
],
[
[
"IMPORT_FILE = \"gs://cloud-samples-data/language/claritin.csv\"\nSENTIMENT_MAX = 4",
"_____no_output_____"
]
],
[
[
"#### Quick peek at your data\n\nYou will use a version of the Crowdflower Claritin-Twitter dataset that is stored in a public Cloud Storage bucket, using a CSV index file.\n\nStart by doing a quick peek at the data. You count the number of examples by counting the number of rows in the CSV index file (`wc -l`) and then peek at the first few rows.",
"_____no_output_____"
]
],
[
[
"if \"IMPORT_FILES\" in globals():\n FILE = IMPORT_FILES[0]\nelse:\n FILE = IMPORT_FILE\n\ncount = ! gsutil cat $FILE | wc -l\nprint(\"Number of Examples\", int(count[0]))\n\nprint(\"First 10 rows\")\n! gsutil cat $FILE | head",
"_____no_output_____"
]
],
[
[
"### Import data\n\nNow, import the data into your Vertex Dataset resource. Use this helper function `import_data` to import the data. The function does the following:\n\n- Uses the `Dataset` client.\n- Calls the client method `import_data`, with the following parameters:\n - `name`: The human readable name you give to the `Dataset` resource (e.g., claritin).\n - `import_configs`: The import configuration.\n\n- `import_configs`: A Python list containing a dictionary, with the key/value entries:\n - `gcs_sources`: A list of URIs to the paths of the one or more index files.\n - `import_schema_uri`: The schema identifying the labeling type.\n\nThe `import_data()` method returns a long running `operation` object. This will take a few minutes to complete. If you are in a live tutorial, this would be a good time to ask questions, or take a personal break.",
"_____no_output_____"
]
],
[
[
"def import_data(dataset, gcs_sources, schema):\n config = [{\"gcs_source\": {\"uris\": gcs_sources}, \"import_schema_uri\": schema}]\n print(\"dataset:\", dataset_id)\n start_time = time.time()\n try:\n operation = clients[\"dataset\"].import_data(\n name=dataset_id, import_configs=config\n )\n print(\"Long running operation:\", operation.operation.name)\n\n result = operation.result()\n print(\"result:\", result)\n print(\"time:\", int(time.time() - start_time), \"secs\")\n print(\"error:\", operation.exception())\n print(\"meta :\", operation.metadata)\n print(\n \"after: running:\",\n operation.running(),\n \"done:\",\n operation.done(),\n \"cancelled:\",\n operation.cancelled(),\n )\n\n return operation\n except Exception as e:\n print(\"exception:\", e)\n return None\n\n\nimport_data(dataset_id, [IMPORT_FILE], LABEL_SCHEMA)",
"_____no_output_____"
]
],
[
[
"## Train the model\n\nNow train an AutoML text sentiment analysis model using your Vertex `Dataset` resource. To train the model, do the following steps:\n\n1. Create an Vertex training pipeline for the `Dataset` resource.\n2. Execute the pipeline to start the training.",
"_____no_output_____"
],
[
"### Create a training pipeline\n\nYou may ask, what do we use a pipeline for? You typically use pipelines when the job (such as training) has multiple steps, generally in sequential order: do step A, do step B, etc. By putting the steps into a pipeline, we gain the benefits of:\n\n1. Being reusable for subsequent training jobs.\n2. Can be containerized and ran as a batch job.\n3. Can be distributed.\n4. All the steps are associated with the same pipeline job for tracking progress.\n\nUse this helper function `create_pipeline`, which takes the following parameters:\n\n- `pipeline_name`: A human readable name for the pipeline job.\n- `model_name`: A human readable name for the model.\n- `dataset`: The Vertex fully qualified dataset identifier.\n- `schema`: The dataset labeling (annotation) training schema.\n- `task`: A dictionary describing the requirements for the training job.\n\nThe helper function calls the `Pipeline` client service'smethod `create_pipeline`, which takes the following parameters:\n\n- `parent`: The Vertex location root path for your `Dataset`, `Model` and `Endpoint` resources.\n- `training_pipeline`: the full specification for the pipeline training job.\n\nLet's look now deeper into the *minimal* requirements for constructing a `training_pipeline` specification:\n\n- `display_name`: A human readable name for the pipeline job.\n- `training_task_definition`: The dataset labeling (annotation) training schema.\n- `training_task_inputs`: A dictionary describing the requirements for the training job.\n- `model_to_upload`: A human readable name for the model.\n- `input_data_config`: The dataset specification.\n - `dataset_id`: The Vertex dataset identifier only (non-fully qualified) -- this is the last part of the fully-qualified identifier.\n - `fraction_split`: If specified, the percentages of the dataset to use for training, test and validation. Otherwise, the percentages are automatically selected by AutoML.",
"_____no_output_____"
]
],
[
[
"def create_pipeline(pipeline_name, model_name, dataset, schema, task):\n\n dataset_id = dataset.split(\"/\")[-1]\n\n input_config = {\n \"dataset_id\": dataset_id,\n \"fraction_split\": {\n \"training_fraction\": 0.8,\n \"validation_fraction\": 0.1,\n \"test_fraction\": 0.1,\n },\n }\n\n training_pipeline = {\n \"display_name\": pipeline_name,\n \"training_task_definition\": schema,\n \"training_task_inputs\": task,\n \"input_data_config\": input_config,\n \"model_to_upload\": {\"display_name\": model_name},\n }\n\n try:\n pipeline = clients[\"pipeline\"].create_training_pipeline(\n parent=PARENT, training_pipeline=training_pipeline\n )\n print(pipeline)\n except Exception as e:\n print(\"exception:\", e)\n return None\n return pipeline",
"_____no_output_____"
]
],
[
[
"### Construct the task requirements\n\nNext, construct the task requirements. Unlike other parameters which take a Python (JSON-like) dictionary, the `task` field takes a Google protobuf Struct, which is very similar to a Python dictionary. Use the `json_format.ParseDict` method for the conversion.\n\nThe minimal fields we need to specify are:\n\n- `sentiment_max`: The maximum value for the sentiment (e.g., 4).\n\nFinally, create the pipeline by calling the helper function `create_pipeline`, which returns an instance of a training pipeline object.",
"_____no_output_____"
]
],
[
[
"PIPE_NAME = \"claritin_pipe-\" + TIMESTAMP\nMODEL_NAME = \"claritin_model-\" + TIMESTAMP\n\ntask = json_format.ParseDict(\n {\n \"sentiment_max\": SENTIMENT_MAX,\n },\n Value(),\n)\n\nresponse = create_pipeline(PIPE_NAME, MODEL_NAME, dataset_id, TRAINING_SCHEMA, task)",
"_____no_output_____"
]
],
[
[
"Now save the unique identifier of the training pipeline you created.",
"_____no_output_____"
]
],
[
[
"# The full unique ID for the pipeline\npipeline_id = response.name\n# The short numeric ID for the pipeline\npipeline_short_id = pipeline_id.split(\"/\")[-1]\n\nprint(pipeline_id)",
"_____no_output_____"
]
],
[
[
"### Get information on a training pipeline\n\nNow get pipeline information for just this training pipeline instance. The helper function gets the job information for just this job by calling the the job client service's `get_training_pipeline` method, with the following parameter:\n\n- `name`: The Vertex fully qualified pipeline identifier.\n\nWhen the model is done training, the pipeline state will be `PIPELINE_STATE_SUCCEEDED`.",
"_____no_output_____"
]
],
[
[
"def get_training_pipeline(name, silent=False):\n response = clients[\"pipeline\"].get_training_pipeline(name=name)\n if silent:\n return response\n\n print(\"pipeline\")\n print(\" name:\", response.name)\n print(\" display_name:\", response.display_name)\n print(\" state:\", response.state)\n print(\" training_task_definition:\", response.training_task_definition)\n print(\" training_task_inputs:\", dict(response.training_task_inputs))\n print(\" create_time:\", response.create_time)\n print(\" start_time:\", response.start_time)\n print(\" end_time:\", response.end_time)\n print(\" update_time:\", response.update_time)\n print(\" labels:\", dict(response.labels))\n return response\n\n\nresponse = get_training_pipeline(pipeline_id)",
"_____no_output_____"
]
],
[
[
"# Deployment\n\nTraining the above model may take upwards of 180 minutes time.\n\nOnce your model is done training, you can calculate the actual time it took to train the model by subtracting `end_time` from `start_time`. For your model, you will need to know the fully qualified Vertex Model resource identifier, which the pipeline service assigned to it. You can get this from the returned pipeline instance as the field `model_to_deploy.name`.",
"_____no_output_____"
]
],
[
[
"while True:\n response = get_training_pipeline(pipeline_id, True)\n if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED:\n print(\"Training job has not completed:\", response.state)\n model_to_deploy_id = None\n if response.state == aip.PipelineState.PIPELINE_STATE_FAILED:\n raise Exception(\"Training Job Failed\")\n else:\n model_to_deploy = response.model_to_upload\n model_to_deploy_id = model_to_deploy.name\n print(\"Training Time:\", response.end_time - response.start_time)\n break\n time.sleep(60)\n\nprint(\"model to deploy:\", model_to_deploy_id)",
"_____no_output_____"
]
],
[
[
"## Model information\n\nNow that your model is trained, you can get some information on your model.",
"_____no_output_____"
],
[
"## Evaluate the Model resource\n\nNow find out how good the model service believes your model is. As part of training, some portion of the dataset was set aside as the test (holdout) data, which is used by the pipeline service to evaluate the model.",
"_____no_output_____"
],
[
"### List evaluations for all slices\n\nUse this helper function `list_model_evaluations`, which takes the following parameter:\n\n- `name`: The Vertex fully qualified model identifier for the `Model` resource.\n\nThis helper function uses the model client service's `list_model_evaluations` method, which takes the same parameter. The response object from the call is a list, where each element is an evaluation metric.\n\nFor each evaluation -- you probably only have one, we then print all the key names for each metric in the evaluation, and for a small set (`meanAbsoluteError` and `precision`) you will print the result.",
"_____no_output_____"
]
],
[
[
"def list_model_evaluations(name):\n response = clients[\"model\"].list_model_evaluations(parent=name)\n for evaluation in response:\n print(\"model_evaluation\")\n print(\" name:\", evaluation.name)\n print(\" metrics_schema_uri:\", evaluation.metrics_schema_uri)\n metrics = json_format.MessageToDict(evaluation._pb.metrics)\n for metric in metrics.keys():\n print(metric)\n print(\"meanAbsoluteError\", metrics[\"meanAbsoluteError\"])\n print(\"precision\", metrics[\"precision\"])\n\n return evaluation.name\n\n\nlast_evaluation = list_model_evaluations(model_to_deploy_id)",
"_____no_output_____"
]
],
[
[
"## Model deployment for batch prediction\n\nNow deploy the trained Vertex `Model` resource you created for batch prediction. This differs from deploying a `Model` resource for on-demand prediction.\n\nFor online prediction, you:\n\n1. Create an `Endpoint` resource for deploying the `Model` resource to.\n\n2. Deploy the `Model` resource to the `Endpoint` resource.\n\n3. Make online prediction requests to the `Endpoint` resource.\n\nFor batch-prediction, you:\n\n1. Create a batch prediction job.\n\n2. The job service will provision resources for the batch prediction request.\n\n3. The results of the batch prediction request are returned to the caller.\n\n4. The job service will unprovision the resoures for the batch prediction request.",
"_____no_output_____"
],
[
"## Make a batch prediction request\n\nNow do a batch prediction to your deployed model.",
"_____no_output_____"
],
[
"### Get test item(s)\n\nNow do a batch prediction to your Vertex model. You will use arbitrary examples out of the dataset as a test items. Don't be concerned that the examples were likely used in training the model -- we just want to demonstrate how to make a prediction.",
"_____no_output_____"
]
],
[
[
"test_items = ! gsutil cat $IMPORT_FILE | head -n2\n\nif len(test_items[0]) == 4:\n _, test_item_1, test_label_1, _ = str(test_items[0]).split(\",\")\n _, test_item_2, test_label_2, _ = str(test_items[1]).split(\",\")\nelse:\n test_item_1, test_label_1, _ = str(test_items[0]).split(\",\")\n test_item_2, test_label_2, _ = str(test_items[1]).split(\",\")\n\n\nprint(test_item_1, test_label_1)\nprint(test_item_2, test_label_2)",
"_____no_output_____"
]
],
[
[
"### Make the batch input file\n\nNow make a batch input file, which you will store in your local Cloud Storage bucket. The batch input file can only be in JSONL format. For JSONL file, you make one dictionary entry per line for each data item (instance). The dictionary contains the key/value pairs:\n\n- `content`: The Cloud Storage path to the file with the text item.\n- `mime_type`: The content type. In our example, it is an `text` file.\n\nFor example:\n\n {'content': '[your-bucket]/file1.txt', 'mime_type': 'text'}",
"_____no_output_____"
]
],
[
[
"import json\n\nimport tensorflow as tf\n\ngcs_test_item_1 = BUCKET_NAME + \"/test1.txt\"\nwith tf.io.gfile.GFile(gcs_test_item_1, \"w\") as f:\n f.write(test_item_1 + \"\\n\")\ngcs_test_item_2 = BUCKET_NAME + \"/test2.txt\"\nwith tf.io.gfile.GFile(gcs_test_item_2, \"w\") as f:\n f.write(test_item_2 + \"\\n\")\n\ngcs_input_uri = BUCKET_NAME + \"/test.jsonl\"\nwith tf.io.gfile.GFile(gcs_input_uri, \"w\") as f:\n data = {\"content\": gcs_test_item_1, \"mime_type\": \"text/plain\"}\n f.write(json.dumps(data) + \"\\n\")\n data = {\"content\": gcs_test_item_2, \"mime_type\": \"text/plain\"}\n f.write(json.dumps(data) + \"\\n\")\n\nprint(gcs_input_uri)\n! gsutil cat $gcs_input_uri",
"_____no_output_____"
]
],
[
[
"### Compute instance scaling\n\nYou have several choices on scaling the compute instances for handling your batch prediction requests:\n\n- Single Instance: The batch prediction requests are processed on a single compute instance.\n - Set the minimum (`MIN_NODES`) and maximum (`MAX_NODES`) number of compute instances to one.\n\n- Manual Scaling: The batch prediction requests are split across a fixed number of compute instances that you manually specified.\n - Set the minimum (`MIN_NODES`) and maximum (`MAX_NODES`) number of compute instances to the same number of nodes. When a model is first deployed to the instance, the fixed number of compute instances are provisioned and batch prediction requests are evenly distributed across them.\n\n- Auto Scaling: The batch prediction requests are split across a scaleable number of compute instances.\n - Set the minimum (`MIN_NODES`) number of compute instances to provision when a model is first deployed and to de-provision, and set the maximum (`MAX_NODES) number of compute instances to provision, depending on load conditions.\n\nThe minimum number of compute instances corresponds to the field `min_replica_count` and the maximum number of compute instances corresponds to the field `max_replica_count`, in your subsequent deployment request.",
"_____no_output_____"
]
],
[
[
"MIN_NODES = 1\nMAX_NODES = 1",
"_____no_output_____"
]
],
[
[
"### Make batch prediction request\n\nNow that your batch of two test items is ready, let's do the batch request. Use this helper function `create_batch_prediction_job`, with the following parameters:\n\n- `display_name`: The human readable name for the prediction job.\n- `model_name`: The Vertex fully qualified identifier for the `Model` resource.\n- `gcs_source_uri`: The Cloud Storage path to the input file -- which you created above.\n- `gcs_destination_output_uri_prefix`: The Cloud Storage path that the service will write the predictions to.\n- `parameters`: Additional filtering parameters for serving prediction results.\n\nThe helper function calls the job client service's `create_batch_prediction_job` metho, with the following parameters:\n\n- `parent`: The Vertex location root path for Dataset, Model and Pipeline resources.\n- `batch_prediction_job`: The specification for the batch prediction job.\n\nLet's now dive into the specification for the `batch_prediction_job`:\n\n- `display_name`: The human readable name for the prediction batch job.\n- `model`: The Vertex fully qualified identifier for the `Model` resource.\n- `dedicated_resources`: The compute resources to provision for the batch prediction job.\n - `machine_spec`: The compute instance to provision. Use the variable you set earlier `DEPLOY_GPU != None` to use a GPU; otherwise only a CPU is allocated.\n - `starting_replica_count`: The number of compute instances to initially provision, which you set earlier as the variable `MIN_NODES`.\n - `max_replica_count`: The maximum number of compute instances to scale to, which you set earlier as the variable `MAX_NODES`.\n- `model_parameters`: Additional filtering parameters for serving prediction results. *Note*, text models do not support additional parameters.\n- `input_config`: The input source and format type for the instances to predict.\n - `instances_format`: The format of the batch prediction request file: `jsonl` only supported.\n - `gcs_source`: A list of one or more Cloud Storage paths to your batch prediction requests.\n- `output_config`: The output destination and format for the predictions.\n - `prediction_format`: The format of the batch prediction response file: `jsonl` only supported.\n - `gcs_destination`: The output destination for the predictions.\n\nThis call is an asychronous operation. You will print from the response object a few select fields, including:\n\n- `name`: The Vertex fully qualified identifier assigned to the batch prediction job.\n- `display_name`: The human readable name for the prediction batch job.\n- `model`: The Vertex fully qualified identifier for the Model resource.\n- `generate_explanations`: Whether True/False explanations were provided with the predictions (explainability).\n- `state`: The state of the prediction job (pending, running, etc).\n\nSince this call will take a few moments to execute, you will likely get `JobState.JOB_STATE_PENDING` for `state`.",
"_____no_output_____"
]
],
[
[
"BATCH_MODEL = \"claritin_batch-\" + TIMESTAMP\n\n\ndef create_batch_prediction_job(\n display_name,\n model_name,\n gcs_source_uri,\n gcs_destination_output_uri_prefix,\n parameters=None,\n):\n\n if DEPLOY_GPU:\n machine_spec = {\n \"machine_type\": DEPLOY_COMPUTE,\n \"accelerator_type\": DEPLOY_GPU,\n \"accelerator_count\": DEPLOY_NGPU,\n }\n else:\n machine_spec = {\n \"machine_type\": DEPLOY_COMPUTE,\n \"accelerator_count\": 0,\n }\n\n batch_prediction_job = {\n \"display_name\": display_name,\n # Format: 'projects/{project}/locations/{location}/models/{model_id}'\n \"model\": model_name,\n \"model_parameters\": json_format.ParseDict(parameters, Value()),\n \"input_config\": {\n \"instances_format\": IN_FORMAT,\n \"gcs_source\": {\"uris\": [gcs_source_uri]},\n },\n \"output_config\": {\n \"predictions_format\": OUT_FORMAT,\n \"gcs_destination\": {\"output_uri_prefix\": gcs_destination_output_uri_prefix},\n },\n \"dedicated_resources\": {\n \"machine_spec\": machine_spec,\n \"starting_replica_count\": MIN_NODES,\n \"max_replica_count\": MAX_NODES,\n },\n }\n response = clients[\"job\"].create_batch_prediction_job(\n parent=PARENT, batch_prediction_job=batch_prediction_job\n )\n print(\"response\")\n print(\" name:\", response.name)\n print(\" display_name:\", response.display_name)\n print(\" model:\", response.model)\n try:\n print(\" generate_explanation:\", response.generate_explanation)\n except:\n pass\n print(\" state:\", response.state)\n print(\" create_time:\", response.create_time)\n print(\" start_time:\", response.start_time)\n print(\" end_time:\", response.end_time)\n print(\" update_time:\", response.update_time)\n print(\" labels:\", response.labels)\n return response\n\n\nIN_FORMAT = \"jsonl\"\nOUT_FORMAT = \"jsonl\" # [jsonl]\n\nresponse = create_batch_prediction_job(\n BATCH_MODEL, model_to_deploy_id, gcs_input_uri, BUCKET_NAME, None\n)",
"_____no_output_____"
]
],
[
[
"Now get the unique identifier for the batch prediction job you created.",
"_____no_output_____"
]
],
[
[
"# The full unique ID for the batch job\nbatch_job_id = response.name\n# The short numeric ID for the batch job\nbatch_job_short_id = batch_job_id.split(\"/\")[-1]\n\nprint(batch_job_id)",
"_____no_output_____"
]
],
[
[
"### Get information on a batch prediction job\n\nUse this helper function `get_batch_prediction_job`, with the following paramter:\n\n- `job_name`: The Vertex fully qualified identifier for the batch prediction job.\n\nThe helper function calls the job client service's `get_batch_prediction_job` method, with the following paramter:\n\n- `name`: The Vertex fully qualified identifier for the batch prediction job. In this tutorial, you will pass it the Vertex fully qualified identifier for your batch prediction job -- `batch_job_id`\n\nThe helper function will return the Cloud Storage path to where the predictions are stored -- `gcs_destination`.",
"_____no_output_____"
]
],
[
[
"def get_batch_prediction_job(job_name, silent=False):\n response = clients[\"job\"].get_batch_prediction_job(name=job_name)\n if silent:\n return response.output_config.gcs_destination.output_uri_prefix, response.state\n\n print(\"response\")\n print(\" name:\", response.name)\n print(\" display_name:\", response.display_name)\n print(\" model:\", response.model)\n try: # not all data types support explanations\n print(\" generate_explanation:\", response.generate_explanation)\n except:\n pass\n print(\" state:\", response.state)\n print(\" error:\", response.error)\n gcs_destination = response.output_config.gcs_destination\n print(\" gcs_destination\")\n print(\" output_uri_prefix:\", gcs_destination.output_uri_prefix)\n return gcs_destination.output_uri_prefix, response.state\n\n\npredictions, state = get_batch_prediction_job(batch_job_id)",
"_____no_output_____"
]
],
[
[
"### Get the predictions\n\nWhen the batch prediction is done processing, the job state will be `JOB_STATE_SUCCEEDED`.\n\nFinally you view the predictions stored at the Cloud Storage path you set as output. The predictions will be in a JSONL format, which you indicated at the time you made the batch prediction job, under a subfolder starting with the name `prediction`, and under that folder will be a file called `predictions*.jsonl`.\n\nNow display (cat) the contents. You will see multiple JSON objects, one for each prediction.\n\nThe first field `text_snippet` is the text file you did the prediction on, and the second field `annotations` is the prediction, which is further broken down into:\n\n- `sentiment`: The predicted sentiment level.",
"_____no_output_____"
]
],
[
[
"def get_latest_predictions(gcs_out_dir):\n \"\"\" Get the latest prediction subfolder using the timestamp in the subfolder name\"\"\"\n folders = !gsutil ls $gcs_out_dir\n latest = \"\"\n for folder in folders:\n subfolder = folder.split(\"/\")[-2]\n if subfolder.startswith(\"prediction-\"):\n if subfolder > latest:\n latest = folder[:-1]\n return latest\n\n\nwhile True:\n predictions, state = get_batch_prediction_job(batch_job_id, True)\n if state != aip.JobState.JOB_STATE_SUCCEEDED:\n print(\"The job has not completed:\", state)\n if state == aip.JobState.JOB_STATE_FAILED:\n raise Exception(\"Batch Job Failed\")\n else:\n folder = get_latest_predictions(predictions)\n ! gsutil ls $folder/prediction*.jsonl\n\n ! gsutil cat $folder/prediction*.jsonl\n break\n time.sleep(60)",
"_____no_output_____"
]
],
[
[
"# Cleaning up\n\nTo clean up all GCP resources used in this project, you can [delete the GCP\nproject](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n\nOtherwise, you can delete the individual resources you created in this tutorial:\n\n- Dataset\n- Pipeline\n- Model\n- Endpoint\n- Batch Job\n- Custom Job\n- Hyperparameter Tuning Job\n- Cloud Storage Bucket",
"_____no_output_____"
]
],
[
[
"delete_dataset = True\ndelete_pipeline = True\ndelete_model = True\ndelete_endpoint = True\ndelete_batchjob = True\ndelete_customjob = True\ndelete_hptjob = True\ndelete_bucket = True\n\n# Delete the dataset using the Vertex fully qualified identifier for the dataset\ntry:\n if delete_dataset and \"dataset_id\" in globals():\n clients[\"dataset\"].delete_dataset(name=dataset_id)\nexcept Exception as e:\n print(e)\n\n# Delete the training pipeline using the Vertex fully qualified identifier for the pipeline\ntry:\n if delete_pipeline and \"pipeline_id\" in globals():\n clients[\"pipeline\"].delete_training_pipeline(name=pipeline_id)\nexcept Exception as e:\n print(e)\n\n# Delete the model using the Vertex fully qualified identifier for the model\ntry:\n if delete_model and \"model_to_deploy_id\" in globals():\n clients[\"model\"].delete_model(name=model_to_deploy_id)\nexcept Exception as e:\n print(e)\n\n# Delete the endpoint using the Vertex fully qualified identifier for the endpoint\ntry:\n if delete_endpoint and \"endpoint_id\" in globals():\n clients[\"endpoint\"].delete_endpoint(name=endpoint_id)\nexcept Exception as e:\n print(e)\n\n# Delete the batch job using the Vertex fully qualified identifier for the batch job\ntry:\n if delete_batchjob and \"batch_job_id\" in globals():\n clients[\"job\"].delete_batch_prediction_job(name=batch_job_id)\nexcept Exception as e:\n print(e)\n\n# Delete the custom job using the Vertex fully qualified identifier for the custom job\ntry:\n if delete_customjob and \"job_id\" in globals():\n clients[\"job\"].delete_custom_job(name=job_id)\nexcept Exception as e:\n print(e)\n\n# Delete the hyperparameter tuning job using the Vertex fully qualified identifier for the hyperparameter tuning job\ntry:\n if delete_hptjob and \"hpt_job_id\" in globals():\n clients[\"job\"].delete_hyperparameter_tuning_job(name=hpt_job_id)\nexcept Exception as e:\n print(e)\n\nif delete_bucket and \"BUCKET_NAME\" in globals():\n ! gsutil rm -r $BUCKET_NAME",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aaa60964f03fa582ce662a7ed0a329fa84674b0
| 59,855 |
ipynb
|
Jupyter Notebook
|
notebooks/eXate_samples/pysyft/duet_multi/4.0-mg-australian-bank.ipynb
|
pbaiz/mmlspark
|
ab13ad658563da0b1c65636f9c92d9a02b637404
|
[
"MIT"
] | null | null | null |
notebooks/eXate_samples/pysyft/duet_multi/4.0-mg-australian-bank.ipynb
|
pbaiz/mmlspark
|
ab13ad658563da0b1c65636f9c92d9a02b637404
|
[
"MIT"
] | null | null | null |
notebooks/eXate_samples/pysyft/duet_multi/4.0-mg-australian-bank.ipynb
|
pbaiz/mmlspark
|
ab13ad658563da0b1c65636f9c92d9a02b637404
|
[
"MIT"
] | null | null | null | 80.020053 | 34,072 | 0.756779 |
[
[
[
"# Syft Duet for Federated Learning - Data Owner (Australian Bank)\n\n## Setup\n\nFirst we need to install syft 0.3.0 because for every other syft project in this repo we have used syft 0.2.9. However, a recent update has removed a lot of the old features and replaced them with this new 'Duet' function. To do this go into your terminal and cd into the repo directory and run:\n\n> pip uninstall syft\n\nThen confirm with 'y' and hit enter.\n\n> pip install syft==0.3.0\n\nNOTE: Make sure that you uninstall syft 0.3.0 and reinstall syft 0.2.9 if you want to run any of the other projects in this repo. Unfortunately when PySyft updated from 0.2.9 to 0.3.0 it removed all of the previous functionalities for the FL, DP, and HE that have previously been iplemented.",
"_____no_output_____"
]
],
[
[
"# Double check you are using syft 0.3.0 not 0.2.9\n# !pip show syft",
"_____no_output_____"
],
[
"import syft as sy\nimport torch as th\nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"## Initialising Duet\n\nFor each bank there will be this same initialisation step. Ensure that you run the below code. This should produce a Syft logo and some information. The important part is the lines of code;\n```python\nimport syft as sy\nduet = sy.duet(\"xxxxxxxxxxxxxxxxxxxxxxxxxxx\")\n```\nWhere the x's are some combination of letters and numbers. You need to take this key and paste it in to the respective banks duet code in the central aggregator. This should be clear and detailed in the central aggregator notebook. In essence, this is similar to the specific banks generating a server and key, and sending the key to the aggregator to give them access to this joint, secure, server process.\n\nOnce you have run the key in the code on the aggregator side, it will give you a similar key which it tells you to input on this side. There will be a box within the Syft logo/information output on this notebook to input the key. Once you enter it and hit enter then the connection for this bank should be established.",
"_____no_output_____"
]
],
[
[
"# We now run the initialisation of the duet\n# Note: this can be run with a specified network if required\n# For exmaple, if you don't trust the netwrok provided by pysyft \n# to not look at the data\n\nduet = sy.duet()\nsy.logging(file_path=\"./syft_do.log\")",
"_____no_output_____"
]
],
[
[
">If the connection is established then there should be a green message above saying 'CONNECTED!'. Similarly, there should also be a Live Status indicating the number of objects, requests, and messages on the duet.",
"_____no_output_____"
],
[
"# Import Australian Bank Data ",
"_____no_output_____"
]
],
[
[
"data = pd.read_csv('datasets/australian-bank-data.csv', sep = ',')\ntarget = pd.read_csv('datasets/australian-bank-target.csv', sep = ',')\ndata.head()",
"_____no_output_____"
],
[
"data = th.tensor(data.values).float()\ndata",
"_____no_output_____"
],
[
"target = th.tensor(target.values).float()\ntarget",
"_____no_output_____"
],
[
"from sklearn.preprocessing import StandardScaler\n\nsc_X = StandardScaler()\ndata = sc_X.fit_transform(data)\ndata = th.tensor(data).float()\ndata",
"♫♫♫ > DUET LIVE STATUS * Objects: 0 Requests: 0 Messages: 0 "
]
],
[
[
"## Label and Send Data to Server\n\nHere we are tagging, and labeling the specific banks data. Although we are sending the data, this does not mean that it is accessible by the central aggregator. We are sending this data to a trusted network server - hence, the reason we can specify our own when establishing the duet, just in case we don't trust the default one. This specific network should reside in the country of the data, more specifically wihtin the banks own network, therefore adhering to all regulations where neccessary.",
"_____no_output_____"
]
],
[
[
"data = data.tag(\"data\")\ndata.describe(\"Australian Bank Training Data\")\ntarget = target.tag(\"target\")\ntarget.describe(\"Australian Bank Training Target\")\n\n# Once we have sent the data we are left with a pointer to the data\ndata_ptr = data.send(duet, searchable=True)\ntarget_ptr = target.send(duet, searchable=True)",
"_____no_output_____"
],
[
"# Detail what is stored \nduet.store.pandas",
"_____no_output_____"
]
],
[
[
">NOTE: Although the data has been sent to this 'store' the other end of the connection cannot access/see the data without requesting it from you. However, from this side, because we sent the data, we can retrieve it whenever we want without rewuesting permission. Simply run the following code;\n\n```python\nduet.store[\"tag\"].get()\n```\n\n>Where you replace the 'tag' with whatever the tag of the data you wish to get. Once you run this, the data will be removed from the store and brought back locally here.",
"_____no_output_____"
]
],
[
[
"# Detail any requests from client side. As mentioned above\n# on the other end they need to request access to data/anything \n# on duet server/store. This si where you can list any requests\n# outstanding.\nduet.requests.pandas",
"_____no_output_____"
],
[
"# Because on the other end of the connection they/we plan on\n# running a model (with lots of requests) we can set up some\n# request handlers that will automatically accept/deny certain\n# labeled requests.\nduet.requests.add_handler(\n name=\"loss\",\n action=\"accept\",\n timeout_secs=-1, # no timeout\n print_local=True # print the result in your notebook\n)\n\nduet.requests.add_handler(\n name=\"model_download\",\n action=\"accept\",\n print_local=True # print the result in your notebook\n)",
"_____no_output_____"
],
[
"duet.requests.handlers",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
4aaa6bb3531ee2680192f1abeb6dca7510d94a65
| 7,860 |
ipynb
|
Jupyter Notebook
|
notebooks/ensemble_introduction.ipynb
|
leonsor/scikit-learn-mooc
|
27c5caf7b0d2f0cc734baee59ad65efc263704cd
|
[
"CC-BY-4.0"
] | null | null | null |
notebooks/ensemble_introduction.ipynb
|
leonsor/scikit-learn-mooc
|
27c5caf7b0d2f0cc734baee59ad65efc263704cd
|
[
"CC-BY-4.0"
] | null | null | null |
notebooks/ensemble_introduction.ipynb
|
leonsor/scikit-learn-mooc
|
27c5caf7b0d2f0cc734baee59ad65efc263704cd
|
[
"CC-BY-4.0"
] | null | null | null | 33.164557 | 101 | 0.616921 |
[
[
[
"# Introductory example to ensemble models\n\nThis first notebook aims at emphasizing the benefit of ensemble methods over\nsimple models (e.g. decision tree, linear model, etc.). Combining simple\nmodels result in more powerful and robust models with less hassle.\n\nWe will start by loading the california housing dataset. We recall that the\ngoal in this dataset is to predict the median house value in some district\nin California based on demographic and geographic data.",
"_____no_output_____"
],
[
"<div class=\"admonition note alert alert-info\">\n<p class=\"first admonition-title\" style=\"font-weight: bold;\">Note</p>\n<p class=\"last\">If you want a deeper overview regarding this dataset, you can refer to the\nAppendix - Datasets description section at the end of this MOOC.</p>\n</div>",
"_____no_output_____"
]
],
[
[
"from sklearn.datasets import fetch_california_housing\n\ndata, target = fetch_california_housing(as_frame=True, return_X_y=True)\ntarget *= 100 # rescale the target in k$",
"_____no_output_____"
]
],
[
[
"We will check the generalization performance of decision tree regressor with\ndefault parameters.",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_validate\nfrom sklearn.tree import DecisionTreeRegressor\n\ntree = DecisionTreeRegressor(random_state=0)\ncv_results = cross_validate(tree, data, target, n_jobs=2)\nscores = cv_results[\"test_score\"]\n\nprint(f\"R2 score obtained by cross-validation: \"\n f\"{scores.mean():.3f} +/- {scores.std():.3f}\")",
"R2 score obtained by cross-validation: 0.354 +/- 0.087\n"
]
],
[
[
"We obtain fair results. However, as we previously presented in the \"tree in\ndepth\" notebook, this model needs to be tuned to overcome over- or\nunder-fitting. Indeed, the default parameters will not necessarily lead to an\noptimal decision tree. Instead of using the default value, we should search\nvia cross-validation the optimal value of the important parameters such as\n`max_depth`, `min_samples_split`, or `min_samples_leaf`.\n\nWe recall that we need to tune these parameters, as decision trees tend to\noverfit the training data if we grow deep trees, but there are no rules on\nwhat each parameter should be set to. Thus, not making a search could lead us\nto have an underfitted or overfitted model.\n\nNow, we make a grid-search to tune the hyperparameters that we mentioned\nearlier.",
"_____no_output_____"
]
],
[
[
"%%time\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.tree import DecisionTreeRegressor\n\nparam_grid = {\n \"max_depth\": [5, 8, None],\n \"min_samples_split\": [2, 10, 30, 50],\n \"min_samples_leaf\": [0.01, 0.05, 0.1, 1]}\ncv = 3\n\ntree = GridSearchCV(DecisionTreeRegressor(random_state=0),\n param_grid=param_grid, cv=cv, n_jobs=2)\ncv_results = cross_validate(tree, data, target, n_jobs=2,\n return_estimator=True)\nscores = cv_results[\"test_score\"]\n\nprint(f\"R2 score obtained by cross-validation: \"\n f\"{scores.mean():.3f} +/- {scores.std():.3f}\")",
"R2 score obtained by cross-validation: 0.523 +/- 0.107\nWall time: 6.06 s\n"
]
],
[
[
"We see that optimizing the hyperparameters will have a positive effect\non the generalization performance. However, it comes with a higher computational\ncost.",
"_____no_output_____"
],
[
"We can create a dataframe storing the important information collected during\nthe tuning of the parameters and investigate the results.\n\nNow we will use an ensemble method called bagging. More details about this\nmethod will be discussed in the next section. In short, this method will use\na base regressor (i.e. decision tree regressors) and will train several of\nthem on a slightly modified version of the training set. Then, the\npredictions of all these base regressors will be combined by averaging.\n\nHere, we will use 20 decision trees and check the fitting time as well as the\ngeneralization performance on the left-out testing data. It is important to note\nthat we are not going to tune any parameter of the decision tree.",
"_____no_output_____"
]
],
[
[
"%%time\nfrom sklearn.ensemble import BaggingRegressor\n\nbase_estimator = DecisionTreeRegressor(random_state=0)\nbagging_regressor = BaggingRegressor(\n base_estimator=base_estimator, n_estimators=20, random_state=0)\n\ncv_results = cross_validate(bagging_regressor, data, target, n_jobs=8)\nscores = cv_results[\"test_score\"]\n\nprint(f\"R2 score obtained by cross-validation: \"\n f\"{scores.mean():.3f} +/- {scores.std():.3f}\")",
"R2 score obtained by cross-validation: 0.642 +/- 0.083\nWall time: 2.29 s\n"
]
],
[
[
"Without searching for optimal hyperparameters, the overall generalization\nperformance of the bagging regressor is better than a single decision tree.\nIn addition, the computational cost is reduced in comparison of seeking\nfor the optimal hyperparameters.\n\nThis shows the motivation behind the use of an ensemble learner: it gives a\nrelatively good baseline with decent generalization performance without any\nparameter tuning.\n\nNow, we will discuss in detail two ensemble families: bagging and\nboosting:\n\n* ensemble using bootstrap (e.g. bagging and random-forest);\n* ensemble using boosting (e.g. adaptive boosting and gradient-boosting\n decision tree).",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aaa6d8f24c46dcc39511fca3a3d58252641b147
| 11,973 |
ipynb
|
Jupyter Notebook
|
02_usecases/06_Text_Classification_Prepare_Dataset.ipynb
|
ZaferUz/workshop
|
63962664d1b4040287a992f54b7b171f7de81601
|
[
"Apache-2.0"
] | 1 |
2021-08-21T04:19:16.000Z
|
2021-08-21T04:19:16.000Z
|
02_usecases/06_Text_Classification_Prepare_Dataset.ipynb
|
ganjingcatherine/workshop
|
1dc7bee71c0042b64b5c03958b17fc08c0bd5ec5
|
[
"Apache-2.0"
] | null | null | null |
02_usecases/06_Text_Classification_Prepare_Dataset.ipynb
|
ganjingcatherine/workshop
|
1dc7bee71c0042b64b5c03958b17fc08c0bd5ec5
|
[
"Apache-2.0"
] | null | null | null | 25.693133 | 152 | 0.565105 |
[
[
[
"# Prepare Dataset for Model Training and Evaluating",
"_____no_output_____"
],
[
"# Amazon Customer Reviews Dataset\n\nhttps://s3.amazonaws.com/amazon-reviews-pds/readme.html\n\n## Schema\n\n- `marketplace`: 2-letter country code (in this case all \"US\").\n- `customer_id`: Random identifier that can be used to aggregate reviews written by a single author.\n- `review_id`: A unique ID for the review.\n- `product_id`: The Amazon Standard Identification Number (ASIN). `http://www.amazon.com/dp/<ASIN>` links to the product's detail page.\n- `product_parent`: The parent of that ASIN. Multiple ASINs (color or format variations of the same product) can roll up into a single parent.\n- `product_title`: Title description of the product.\n- `product_category`: Broad product category that can be used to group reviews (in this case digital videos).\n- `star_rating`: The review's rating (1 to 5 stars).\n- `helpful_votes`: Number of helpful votes for the review.\n- `total_votes`: Number of total votes the review received.\n- `vine`: Was the review written as part of the [Vine](https://www.amazon.com/gp/vine/help) program?\n- `verified_purchase`: Was the review from a verified purchase?\n- `review_headline`: The title of the review itself.\n- `review_body`: The text of the review.\n- `review_date`: The date the review was written.",
"_____no_output_____"
]
],
[
[
"import boto3\nimport sagemaker\nimport pandas as pd\n\nsess = sagemaker.Session()\nbucket = sess.default_bucket()\nrole = sagemaker.get_execution_role()\nregion = boto3.Session().region_name",
"_____no_output_____"
]
],
[
[
"## Download\n\nLet's start by retrieving a subset of the Amazon Customer Reviews dataset.",
"_____no_output_____"
]
],
[
[
"!aws s3 cp 's3://amazon-reviews-pds/tsv/amazon_reviews_us_Digital_Software_v1_00.tsv.gz' ./data/",
"_____no_output_____"
],
[
"import csv\n\ndf = pd.read_csv(\n \"./data/amazon_reviews_us_Digital_Software_v1_00.tsv.gz\",\n delimiter=\"\\t\",\n quoting=csv.QUOTE_NONE,\n compression=\"gzip\",\n)\ndf.shape",
"_____no_output_____"
],
[
"df.head(5)",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\n\n%matplotlib inline\n%config InlineBackend.figure_format='retina'\n\ndf[[\"star_rating\", \"review_id\"]].groupby(\"star_rating\").count().plot(kind=\"bar\", title=\"Breakdown by Star Rating\")\nplt.xlabel(\"Star Rating\")\nplt.ylabel(\"Review Count\")",
"_____no_output_____"
]
],
[
[
"# Balance the Dataset",
"_____no_output_____"
]
],
[
[
"from sklearn.utils import resample\n\nfive_star_df = df.query(\"star_rating == 5\")\nfour_star_df = df.query(\"star_rating == 4\")\nthree_star_df = df.query(\"star_rating == 3\")\ntwo_star_df = df.query(\"star_rating == 2\")\none_star_df = df.query(\"star_rating == 1\")\n\n# Check which sentiment has the least number of samples\nminority_count = min(\n five_star_df.shape[0], four_star_df.shape[0], three_star_df.shape[0], two_star_df.shape[0], one_star_df.shape[0]\n)\n\nfive_star_df = resample(five_star_df, replace=False, n_samples=minority_count, random_state=27)\n\nfour_star_df = resample(four_star_df, replace=False, n_samples=minority_count, random_state=27)\n\nthree_star_df = resample(three_star_df, replace=False, n_samples=minority_count, random_state=27)\n\ntwo_star_df = resample(two_star_df, replace=False, n_samples=minority_count, random_state=27)\n\none_star_df = resample(one_star_df, replace=False, n_samples=minority_count, random_state=27)\n\ndf_balanced = pd.concat([five_star_df, four_star_df, three_star_df, two_star_df, one_star_df])\ndf_balanced = df_balanced.reset_index(drop=True)\n\ndf_balanced.shape",
"_____no_output_____"
],
[
"df_balanced[[\"star_rating\", \"review_id\"]].groupby(\"star_rating\").count().plot(\n kind=\"bar\", title=\"Breakdown by Star Rating\"\n)\nplt.xlabel(\"Star Rating\")\nplt.ylabel(\"Review Count\")",
"_____no_output_____"
],
[
"df_balanced.head(5)",
"_____no_output_____"
]
],
[
[
"# Split the Data into Train, Validation, and Test Sets",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\n\n# Split all data into 90% train and 10% holdout\ndf_train, df_holdout = train_test_split(df_balanced, test_size=0.10, stratify=df_balanced[\"star_rating\"])\n\n# Split holdout data into 50% validation and 50% test\ndf_validation, df_test = train_test_split(df_holdout, test_size=0.50, stratify=df_holdout[\"star_rating\"])",
"_____no_output_____"
],
[
"# Pie chart, where the slices will be ordered and plotted counter-clockwise:\nlabels = [\"Train\", \"Validation\", \"Test\"]\nsizes = [len(df_train.index), len(df_validation.index), len(df_test.index)]\nexplode = (0.1, 0, 0)\n\nfig1, ax1 = plt.subplots()\n\nax1.pie(sizes, explode=explode, labels=labels, autopct=\"%1.1f%%\", startangle=90)\n\n# Equal aspect ratio ensures that pie is drawn as a circle.\nax1.axis(\"equal\")\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"# Show 90% Train Data Split",
"_____no_output_____"
]
],
[
[
"df_train.shape",
"_____no_output_____"
],
[
"df_train[[\"star_rating\", \"review_id\"]].groupby(\"star_rating\").count().plot(\n kind=\"bar\", title=\"90% Train Breakdown by Star Rating\"\n)",
"_____no_output_____"
]
],
[
[
"# Show 5% Validation Data Split",
"_____no_output_____"
]
],
[
[
"df_validation.shape",
"_____no_output_____"
],
[
"df_validation[[\"star_rating\", \"review_id\"]].groupby(\"star_rating\").count().plot(\n kind=\"bar\", title=\"5% Validation Breakdown by Star Rating\"\n)",
"_____no_output_____"
]
],
[
[
"# Show 5% Test Data Split",
"_____no_output_____"
]
],
[
[
"df_test.shape",
"_____no_output_____"
],
[
"df_test[[\"star_rating\", \"review_id\"]].groupby(\"star_rating\").count().plot(\n kind=\"bar\", title=\"5% Test Breakdown by Star Rating\"\n)",
"_____no_output_____"
]
],
[
[
"# Select `star_rating` and `review_body` for Training",
"_____no_output_____"
]
],
[
[
"df_train = df_train[[\"star_rating\", \"review_body\"]]\ndf_train.shape",
"_____no_output_____"
],
[
"df_train.head(5)",
"_____no_output_____"
]
],
[
[
"# Write a CSV With No Header for Comprehend ",
"_____no_output_____"
]
],
[
[
"comprehend_train_path = \"./amazon_reviews_us_Digital_Software_v1_00_comprehend.csv\"\ndf_train.to_csv(comprehend_train_path, index=False, header=False)",
"_____no_output_____"
]
],
[
[
"# Upload Train Data to S3 for Comprehend",
"_____no_output_____"
]
],
[
[
"train_s3_prefix = \"data\"\ncomprehend_train_s3_uri = sess.upload_data(path=comprehend_train_path, key_prefix=train_s3_prefix)\ncomprehend_train_s3_uri",
"_____no_output_____"
],
[
"!aws s3 ls $comprehend_train_s3_uri",
"_____no_output_____"
]
],
[
[
"# Store the location of our train data in our notebook server to be used next",
"_____no_output_____"
]
],
[
[
"%store comprehend_train_s3_uri",
"_____no_output_____"
],
[
"%store",
"_____no_output_____"
]
],
[
[
"# Release Resources",
"_____no_output_____"
]
],
[
[
"%%html\n\n<p><b>Shutting down your kernel for this notebook to release resources.</b></p>\n<button class=\"sm-command-button\" data-commandlinker-command=\"kernelmenu:shutdown\" style=\"display:none;\">Shutdown Kernel</button>\n \n<script>\ntry {\n els = document.getElementsByClassName(\"sm-command-button\");\n els[0].click();\n}\ncatch(err) {\n // NoOp\n} \n</script>",
"_____no_output_____"
],
[
"%%javascript\n\ntry {\n Jupyter.notebook.save_checkpoint();\n Jupyter.notebook.session.delete();\n}\ncatch(err) {\n // NoOp\n}",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4aaa6fc67938975b2b46fdd8fc23806d7b8e848c
| 15,237 |
ipynb
|
Jupyter Notebook
|
pyspark_google_colab.ipynb
|
leandrosacramento/PySpark
|
6dbc398ecbe37f061035ef8830e26e10ff5aa0aa
|
[
"MIT"
] | null | null | null |
pyspark_google_colab.ipynb
|
leandrosacramento/PySpark
|
6dbc398ecbe37f061035ef8830e26e10ff5aa0aa
|
[
"MIT"
] | null | null | null |
pyspark_google_colab.ipynb
|
leandrosacramento/PySpark
|
6dbc398ecbe37f061035ef8830e26e10ff5aa0aa
|
[
"MIT"
] | null | null | null | 27.957798 | 274 | 0.37783 |
[
[
[
"#**PySpark no Google Colab**\n---",
"_____no_output_____"
],
[
"####Configurando o Google Colab para habilitar o uso do PySpark",
"_____no_output_____"
]
],
[
[
"# Instala o Java JDK 8\n!apt-get install openjdk-8-jdk-headless -qq > /dev/null",
"_____no_output_____"
],
[
"# Download do Apache Spark 3.1.2\n!wget -q https://downloads.apache.org/spark/spark-3.1.2/spark-3.1.2-bin-hadoop3.2.tgz",
"_____no_output_____"
],
[
"# Descompacta o Apache Spark 3.1.2\n!tar xf spark-3.1.2-bin-hadoop3.2.tgz",
"_____no_output_____"
],
[
"# Remove o arquivo compactado do Apache Spark 3.1.2\n!rm -rf spark-3.1.2-bin-hadoop3.2.tgz",
"_____no_output_____"
],
[
"# Instala os módulos FindSpark e PySpark\n!pip install -q findspark\n!pip install -q pyspark",
"\u001b[K |████████████████████████████████| 281.3 MB 41 kB/s \n\u001b[K |████████████████████████████████| 198 kB 38.0 MB/s \n\u001b[?25h Building wheel for pyspark (setup.py) ... \u001b[?25l\u001b[?25hdone\n"
]
],
[
[
"####Configurando o ambiente para uso do PySpark",
"_____no_output_____"
]
],
[
[
"# Importa os módulos\nimport os\nimport findspark\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import functions as F",
"_____no_output_____"
],
[
"# Define as variáveis ambientes Home do Java e Spark\nos.environ[\"JAVA_HOME\"] = \"/usr/lib/jvm/java-8-openjdk-amd64\"\nos.environ[\"SPARK_HOME\"] = \"/content/spark-3.1.2-bin-hadoop3.2\"",
"_____no_output_____"
],
[
"# Inicia o FindSpark e cria a instância da sessão Spark\nfindspark.init()\nspark = SparkSession.builder.master(\"local[*]\").getOrCreate()",
"_____no_output_____"
]
],
[
[
"####PySpark pronto para uso, divirta-se!",
"_____no_output_____"
]
],
[
[
"dataset = spark.read.format(\"json\") \\\n .option(\"multiLine\",True) \\\n .load(\"sample_data/anscombe.json\")",
"_____no_output_____"
],
[
"dataset.columns",
"_____no_output_____"
],
[
"dataset.show(10)",
"+------+----+-----+\n|Series| X| Y|\n+------+----+-----+\n| I|10.0| 8.04|\n| I| 8.0| 6.95|\n| I|13.0| 7.58|\n| I| 9.0| 8.81|\n| I|11.0| 8.33|\n| I|14.0| 9.96|\n| I| 6.0| 7.24|\n| I| 4.0| 4.26|\n| I|12.0|10.84|\n| I| 7.0| 4.81|\n+------+----+-----+\nonly showing top 10 rows\n\n"
],
[
"dataset.printSchema()",
"root\n |-- Series: string (nullable = true)\n |-- X: double (nullable = true)\n |-- Y: double (nullable = true)\n\n"
],
[
"dataset_agrupado = dataset \\\n .groupBy(\"Series\") \\\n .agg(F.avg(\"X\").alias(\"X_agrupado\")\n , F.avg(\"Y\").alias(\"Y_agrupado\")) \\\n .orderBy(\"Series\")",
"_____no_output_____"
]
],
[
[
"dataset_agrupado.show()",
"_____no_output_____"
]
],
[
[
"dataset_agrupado.explain()",
"== Physical Plan ==\n*(3) Sort [Series#0 ASC NULLS FIRST], true, 0\n+- Exchange rangepartitioning(Series#0 ASC NULLS FIRST, 200), ENSURE_REQUIREMENTS, [id=#38]\n +- *(2) HashAggregate(keys=[Series#0], functions=[avg(X#1), avg(Y#2)])\n +- Exchange hashpartitioning(Series#0, 200), ENSURE_REQUIREMENTS, [id=#34]\n +- *(1) HashAggregate(keys=[Series#0], functions=[partial_avg(X#1), partial_avg(Y#2)])\n +- FileScan json [Series#0,X#1,Y#2] Batched: false, DataFilters: [], Format: JSON, Location: InMemoryFileIndex[file:/content/sample_data/anscombe.json], PartitionFilters: [], PushedFilters: [], ReadSchema: struct<Series:string,X:double,Y:double>\n\n\n"
],
[
"df = spark.createDataFrame(\n [ (1., 4.)\n , (2., 5.)\n , (3., 6.)]\n , [\"A\", \"B\"])",
"_____no_output_____"
],
[
"df.show()",
"+---+---+\n| A| B|\n+---+---+\n|1.0|4.0|\n|2.0|5.0|\n|3.0|6.0|\n+---+---+\n\n"
],
[
"df = spark.createDataFrame(\n [\n ('864.754.453-33,565.878.787-43',)\n , ('565.878.787-43 864.754.453-33 565.878.787-43',)\n , ('333.444.555-66 222.222.222-33',)\n ]\n , [\"cpf\",])",
"_____no_output_____"
],
[
"df.show(10,False)",
"+--------------------------------------------+\n|cpf |\n+--------------------------------------------+\n|864.754.453-33,565.878.787-43 |\n|565.878.787-43 864.754.453-33 565.878.787-43|\n|333.444.555-66 222.222.222-33 |\n+--------------------------------------------+\n\n"
],
[
"df.select(\n df.cpf\n , F.length(F.regexp_replace(df.cpf, r'\\d+\\.\\d+\\.\\d+\\-\\d+', '')).alias('reg1')\n , F.length(F.regexp_replace(df.cpf, r'\\d{3}\\.\\d{3}\\.\\d{3}\\-\\d{2}', '')).alias('reg2')\n , df.cpf.rlike(r'\\d{3}\\.\\d{3}\\.\\d{3}\\-\\d{2}').alias('reg3')\n).show(10, False)",
"+--------------------------------------------+----+----+----+\n|cpf |reg1|reg2|reg3|\n+--------------------------------------------+----+----+----+\n|864.754.453-33,565.878.787-43 |1 |1 |true|\n|565.878.787-43 864.754.453-33 565.878.787-43|2 |2 |true|\n|333.444.555-66 222.222.222-33 |1 |1 |true|\n+--------------------------------------------+----+----+----+\n\n"
],
[
"df2 = spark.createDataFrame(\n [\n ('http://site.com:8080/',)\n , ('http://localhost.com:8080/?pub=200',)\n , ('http://server.com:1234',)\n , ('http://server.com',)\n ]\n , [\"url\",])",
"_____no_output_____"
],
[
"df2.show(10,False)",
"+----------------------------------+\n|url |\n+----------------------------------+\n|http://site.com:8080/ |\n|http://localhost.com:8080/?pub=200|\n|http://server.com:1234 |\n|http://server.com |\n+----------------------------------+\n\n"
],
[
"df2.select(\n df2.url\n , df2.url.rlike(r'https?:[\\/]{2}\\s+').alias('reg1')\n , df2.url.rlike(r'https?:[\\/]{2}([a-zA-Z0-9]+\\.[a-zA-Z]{2,4})(:[0-9]+)?').alias('reg2')\n , df2.url.rlike(r'https?:[\\/]{2}([a-zA-Z0-9]+\\.[a-zA-Z]{2,4})(:[0-9]+)').alias('reg3')\n , df2.url.rlike(r'https?:\\/{2}').alias('reg4')\n).show(10, False)",
"+----------------------------------+-----+----+-----+----+\n|url |reg1 |reg2|reg3 |reg4|\n+----------------------------------+-----+----+-----+----+\n|http://site.com:8080/ |false|true|true |true|\n|http://localhost.com:8080/?pub=200|false|true|true |true|\n|http://server.com:1234 |false|true|true |true|\n|http://server.com |false|true|false|true|\n+----------------------------------+-----+----+-----+----+\n\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aaaa5e19ab9336920dd5ab0eaf6a6b4f2ccfe35
| 1,264 |
ipynb
|
Jupyter Notebook
|
week2/Quiz_2_KevinZielin_Assignment_Q7.ipynb
|
zielin0802/Data-Analytics-Using-Python
|
a24e5fdaa44da96746962fcb4919e7245836fa03
|
[
"MIT"
] | null | null | null |
week2/Quiz_2_KevinZielin_Assignment_Q7.ipynb
|
zielin0802/Data-Analytics-Using-Python
|
a24e5fdaa44da96746962fcb4919e7245836fa03
|
[
"MIT"
] | 2 |
2021-07-15T19:44:52.000Z
|
2021-07-21T22:40:26.000Z
|
week2/Quiz_2_KevinZielin_Assignment_Q7.ipynb
|
zielin0802/Data-Analytics-Using-Python
|
a24e5fdaa44da96746962fcb4919e7245836fa03
|
[
"MIT"
] | null | null | null | 23.849057 | 122 | 0.482595 |
[
[
[
"\"\"\"\nQuestion 7\n\n# Write a Python program def get_element(tuple) to get the 4th element and 4th element from the last of a tuple, \n# and store the element in a new tuple and return it (It is guarantee that the tuple has at least 4 element)\n\nExample\ntuple= (\"w\", 3, \"r\", \"e\", \"s\", \"o\", \"u\", \"r\", \"c\", \"e\")\noutput:('e', 'u')\n\"\"\"\ndef get_element(tuple):\n return (tuple[3], tuple[-4])\n\nget_element((\"w\", 3, \"r\", \"e\", \"s\", \"o\", \"u\", \"r\", \"c\", \"e\"))",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
4aaaabe53146ee9de1238e8e9837d67bc63ba242
| 39,135 |
ipynb
|
Jupyter Notebook
|
drop/multilabel_classification/kaggle.ipynb
|
MRD-Git/Huggingface-course
|
7c0440584e630cb8885c2a237bc6e8213cfd5572
|
[
"MIT"
] | null | null | null |
drop/multilabel_classification/kaggle.ipynb
|
MRD-Git/Huggingface-course
|
7c0440584e630cb8885c2a237bc6e8213cfd5572
|
[
"MIT"
] | null | null | null |
drop/multilabel_classification/kaggle.ipynb
|
MRD-Git/Huggingface-course
|
7c0440584e630cb8885c2a237bc6e8213cfd5572
|
[
"MIT"
] | null | null | null | 91.223776 | 1,589 | 0.639606 |
[
[
[
"https://huggingface.co/docs/transformers/main_classes/output",
"_____no_output_____"
],
[
"https://www.kaggle.com/code/debarshichanda/bert-multi-label-text-classification/notebook",
"_____no_output_____"
]
],
[
[
"import os\nimport re\nimport string\nimport json\n#import emoji\nimport numpy as np\nimport pandas as pd\nfrom sklearn import metrics\nfrom bs4 import BeautifulSoup\nimport transformers\nimport torch\nfrom torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler\nfrom transformers import BertTokenizer, AutoTokenizer, BertModel, BertConfig, AutoModel, AdamW\nimport warnings\nwarnings.filterwarnings('ignore')\n\npd.set_option(\"display.max_columns\", None)",
"_____no_output_____"
],
[
"df_train = pd.read_csv(\"train.csv\")\ndf_dev = pd.read_csv(\"val.csv\")\n#df_train = pd.read_csv(\"train.csv\", header=None, names=['Text', 'Class', 'ID'])\n#df_dev = pd.read_csv(\"val.csv\", sep='\\t', header=None, names=['Text', 'Class', 'ID'])\ndf_train, df_dev",
"_____no_output_____"
],
[
"#def list_of_classes(row):\n# classes = [\"anger\", \"fear\", \"joy\", \"sadness\", \"surprise\"]\n# arr = [1 if emotion==\"1\" else 0 for emotion in classes]\n# print(arr)\n# return arr\n#df_train = df_train.apply(list_of_classes, axis=1, result_type='expand')\n#df_train['Len of classes'] = df_train['List of classes'].apply(lambda x: len(x))\n#df_dev['List of classes'] = df_dev['Class'].apply(lambda x: x.split(','))\n#df_dev['Len of classes'] = df_dev['List of classes'].apply(lambda x: len(x))\n#df_train.head(10)",
"_____no_output_____"
],
[
"device = 'cuda' if torch.cuda.is_available() else 'cpu'\ndevice",
"_____no_output_____"
],
[
"MAX_LEN = 200\nTRAIN_BATCH_SIZE = 64\nVALID_BATCH_SIZE = 64\nEPOCHS = 10\nLEARNING_RATE = 2e-5\ntokenizer = AutoTokenizer.from_pretrained('roberta-base')\ntarget_cols = [col for col in df_train.columns if col not in ['Text', 'ID']]\ntarget_cols",
"_____no_output_____"
],
[
"class BERTDataset(Dataset):\n def __init__(self, df, tokenizer, max_len):\n self.df = df\n self.max_len = max_len\n self.text = df.Text\n self.tokenizer = tokenizer\n self.targets = df[target_cols].values\n \n def __len__(self):\n return len(self.df)\n \n def __getitem__(self, index):\n text = self.text[index]\n inputs = self.tokenizer.encode_plus(\n text,\n truncation=True,\n add_special_tokens=True,\n max_length=self.max_len,\n padding='max_length',\n return_token_type_ids=True\n )\n ids = inputs['input_ids']\n mask = inputs['attention_mask']\n token_type_ids = inputs[\"token_type_ids\"]\n \n return {\n 'ids': torch.tensor(ids, dtype=torch.long),\n 'mask': torch.tensor(mask, dtype=torch.long),\n 'token_type_ids': torch.tensor(token_type_ids, dtype=torch.long),\n 'targets': torch.tensor(self.targets[index], dtype=torch.float)\n }",
"_____no_output_____"
],
[
"train_dataset = BERTDataset(df_train, tokenizer, MAX_LEN)\nvalid_dataset = BERTDataset(df_dev, tokenizer, MAX_LEN)",
"_____no_output_____"
],
[
"train_loader = DataLoader(train_dataset, batch_size=TRAIN_BATCH_SIZE, num_workers=4, shuffle=True, pin_memory=True)\nvalid_loader = DataLoader(valid_dataset, batch_size=VALID_BATCH_SIZE, num_workers=4, shuffle=False, pin_memory=True)",
"_____no_output_____"
],
[
"# Creating the customized model, by adding a drop out and a dense layer on top of distil bert to get the final output for the model. \n\nclass BERTClass(torch.nn.Module):\n def __init__(self):\n super(BERTClass, self).__init__()\n self.roberta = AutoModel.from_pretrained('roberta-base')\n# self.l2 = torch.nn.Dropout(0.3)\n self.fc = torch.nn.Linear(768,5)\n \n def forward(self, ids, mask, token_type_ids):\n _, features = self.roberta(ids, attention_mask = mask, token_type_ids = token_type_ids, return_dict=False)\n# output_2 = self.l2(output_1)\n output = self.fc(features)\n return output\n\nmodel = BERTClass()\nmodel.to(device);",
"Some weights of the model checkpoint at roberta-base were not used when initializing RobertaModel: ['lm_head.layer_norm.bias', 'lm_head.bias', 'lm_head.dense.bias', 'lm_head.decoder.weight', 'lm_head.layer_norm.weight', 'lm_head.dense.weight']\n- This IS expected if you are initializing RobertaModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n- This IS NOT expected if you are initializing RobertaModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n"
],
[
"def loss_fn(outputs, targets):\n return torch.nn.BCEWithLogitsLoss()(outputs, targets)\noptimizer = AdamW(params=model.parameters(), lr=LEARNING_RATE, weight_decay=1e-6)",
"_____no_output_____"
],
[
"enumerate(train_loader, 0)",
"_____no_output_____"
],
[
"i_break = 2\ndef train(epoch):\n model.train()\n for i, data in enumerate(train_loader, 0):\n print(f\"Epoch {epoch}, step {i}\")\n ids = data['ids'].to(device, dtype = torch.long)\n mask = data['mask'].to(device, dtype = torch.long)\n token_type_ids = data['token_type_ids'].to(device, dtype = torch.long)\n targets = data['targets'].to(device, dtype = torch.float)\n outputs = model(ids, mask, token_type_ids)\n loss = loss_fn(outputs, targets)\n if i%i_break==0:\n print(f'Epoch: {epoch}, Loss: {loss.item()}')\n break\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\nfor epoch in range(EPOCHS):\n train(epoch)",
"_____no_output_____"
],
[
"def validation():\n model.eval()\n fin_targets=[]\n fin_outputs=[]\n with torch.no_grad():\n for _, data in enumerate(valid_loader, 0):\n ids = data['ids'].to(device, dtype = torch.long)\n mask = data['mask'].to(device, dtype = torch.long)\n token_type_ids = data['token_type_ids'].to(device, dtype = torch.long)\n targets = data['targets'].to(device, dtype = torch.float)\n outputs = model(ids, mask, token_type_ids)\n fin_targets.extend(targets.cpu().detach().numpy().tolist())\n fin_outputs.extend(torch.sigmoid(outputs).cpu().detach().numpy().tolist())\n return fin_outputs, fin_targets",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aaab05c8d2d243541da1aea0b8cdb8dea133c1b
| 18,323 |
ipynb
|
Jupyter Notebook
|
examples/03_cross_validation.ipynb
|
TomMonks/forecast-tools
|
f947ebc95980b8462afd3d1f0672361462272b13
|
[
"MIT"
] | 2 |
2020-08-01T20:52:41.000Z
|
2021-01-05T14:53:24.000Z
|
examples/03_cross_validation.ipynb
|
TomMonks/forecast-tools
|
f947ebc95980b8462afd3d1f0672361462272b13
|
[
"MIT"
] | 24 |
2020-05-09T20:24:48.000Z
|
2022-02-04T10:06:06.000Z
|
examples/03_cross_validation.ipynb
|
TomMonks/forecast-tools
|
f947ebc95980b8462afd3d1f0672361462272b13
|
[
"MIT"
] | 1 |
2020-10-30T17:09:48.000Z
|
2020-10-30T17:09:48.000Z
| 24.07753 | 642 | 0.489549 |
[
[
[
"# Time Series Cross Validation",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\n\n#suppress ARIMA warnings\nimport warnings\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
]
],
[
[
"Up till now we have used a single validation period to select our best model. The weakness of that approach is that it gives you a sample size of 1 (that's better than nothing, but generally poor statistics!). Time series cross validation is an approach to provide more data points when comparing models. In the classicial time series literature time series cross validation is called a **Rolling Forecast Origin**. There may also be benefit of taking a **sliding window** approach to cross validaiton. This second approach maintains a fixed sized training set. I.e. it drops older values from the time series during validation.\n\n## Rolling Forecast Origin\n\nThe following code and output provide a simplified view of how rolling forecast horizons work in practice.",
"_____no_output_____"
]
],
[
[
"def rolling_forecast_origin(train, min_train_size, horizon):\n '''\n Rolling forecast origin generator.\n '''\n for i in range(len(train) - min_train_size - horizon + 1):\n split_train = train[:min_train_size+i]\n split_val = train[min_train_size+i:min_train_size+i+horizon]\n yield split_train, split_val",
"_____no_output_____"
],
[
"full_series = [2502, 2414, 2800, 2143, 2708, 1900, 2333, 2222, 1234, 3456]\n\ntest = full_series[-2:]\ntrain = full_series[:-2]\nprint('full training set: {0}'.format(train))\nprint('hidden test set: {0}'.format(test))",
"full training set: [2502, 2414, 2800, 2143, 2708, 1900, 2333, 2222]\nhidden test set: [1234, 3456]\n"
],
[
"cv_rolling = rolling_forecast_origin(train, min_train_size=4, horizon=2)\ncv_rolling",
"_____no_output_____"
],
[
"i = 0\nfor cv_train, cv_val in cv_rolling:\n print(f'CV[{i+1}]')\n print(f'Train:\\t{cv_train}')\n print(f'Val:\\t{cv_val}')\n print('-----')\n i += 1",
"CV[1]\nTrain:\t[2502, 2414, 2800, 2143]\nVal:\t[2708, 1900]\n-----\nCV[2]\nTrain:\t[2502, 2414, 2800, 2143, 2708]\nVal:\t[1900, 2333]\n-----\nCV[3]\nTrain:\t[2502, 2414, 2800, 2143, 2708, 1900]\nVal:\t[2333, 2222]\n-----\n"
]
],
[
[
"## Sliding Window Cross Validation",
"_____no_output_____"
]
],
[
[
"def sliding_window(train, window_size, horizon, step=1):\n '''\n sliding window generator.\n \n Parameters:\n --------\n train: array-like\n training data for time series method\n \n window_size: int\n lookback - how much data to include.\n \n horizon: int\n forecast horizon\n \n step: int, optional (default=1)\n step=1 means that a single additional data point is added to the time\n series. increase step to run less splits.\n \n Returns:\n array-like, array-like\n \n split_training, split_validation\n '''\n for i in range(0, len(train) - window_size - horizon + 1, step):\n split_train = train[i:window_size+i]\n split_val = train[i+window_size:window_size+i+horizon]\n yield split_train, split_val",
"_____no_output_____"
]
],
[
[
"This code tests its with `step=1`",
"_____no_output_____"
]
],
[
[
"cv_sliding = sliding_window(train, window_size=4, horizon=1)\n\nprint('full training set: {0}\\n'.format(train))\n\ni = 0\nfor cv_train, cv_val in cv_sliding:\n print(f'CV[{i+1}]')\n print(f'Train:\\t{cv_train}')\n print(f'Val:\\t{cv_val}')\n print('-----')\n i += 1",
"full training set: [2502, 2414, 2800, 2143, 2708, 1900, 2333, 2222]\n\nCV[1]\nTrain:\t[2502, 2414, 2800, 2143]\nVal:\t[2708]\n-----\nCV[2]\nTrain:\t[2414, 2800, 2143, 2708]\nVal:\t[1900]\n-----\nCV[3]\nTrain:\t[2800, 2143, 2708, 1900]\nVal:\t[2333]\n-----\nCV[4]\nTrain:\t[2143, 2708, 1900, 2333]\nVal:\t[2222]\n-----\n"
]
],
[
[
"The following code tests it with `step=2`. Note that you get less splits. The code is less computationally expensive at the cost of less data. That is probably okay.",
"_____no_output_____"
]
],
[
[
"cv_sliding = sliding_window(train, window_size=4, horizon=1, step=2)\n\nprint('full training set: {0}\\n'.format(train))\n\ni = 0\nfor cv_train, cv_val in cv_sliding:\n print(f'CV[{i+1}]')\n print(f'Train:\\t{cv_train}')\n print(f'Val:\\t{cv_val}')\n print('-----')\n i += 1",
"full training set: [2502, 2414, 2800, 2143, 2708, 1900, 2333, 2222]\n\nCV[1]\nTrain:\t[2502, 2414, 2800, 2143]\nVal:\t[2708]\n-----\nCV[2]\nTrain:\t[2800, 2143, 2708, 1900]\nVal:\t[2333]\n-----\n"
]
],
[
[
"# Parallel Cross Validation Example using Naive1",
"_____no_output_____"
]
],
[
[
"from forecast_tools.baseline import SNaive, Naive1\nfrom forecast_tools.datasets import load_emergency_dept\n#optimised version of the functions above...\nfrom forecast_tools.model_selection import (rolling_forecast_origin, \n sliding_window,\n cross_validation_score)\nfrom sklearn.metrics import mean_absolute_error",
"_____no_output_____"
],
[
"train = load_emergency_dept()",
"_____no_output_____"
],
[
"model = Naive1()",
"_____no_output_____"
],
[
"#%%timeit runs the code multiple times to get an estimate of runtime.\n#comment if out to run the code only once.",
"_____no_output_____"
]
],
[
[
"Run on a single core",
"_____no_output_____"
]
],
[
[
"%%time\ncv = sliding_window(train, window_size=14, horizon=7, step=1)\nresults_1 = cross_validation_score(model, train, cv, mean_absolute_error, \n n_jobs=1)",
"CPU times: user 812 ms, sys: 0 ns, total: 812 ms\nWall time: 809 ms\n"
]
],
[
[
"Run across multiple cores by setting `n_jobs=-1`",
"_____no_output_____"
]
],
[
[
"%%time \ncv = sliding_window(train, window_size=14, horizon=7, step=1)\nresults_2 = cross_validation_score(model, train, cv, mean_absolute_error,\n n_jobs=-1)",
"CPU times: user 369 ms, sys: 71.5 ms, total: 440 ms\nWall time: 990 ms\n"
],
[
"results_1.shape",
"_____no_output_____"
],
[
"results_2.shape",
"_____no_output_____"
],
[
"print(results_1.mean(), results_1.std())",
"26.653439153439148 10.346957901088238\n"
]
],
[
[
"just to illustrate that the results are the same - the difference is runtime.",
"_____no_output_____"
]
],
[
[
"print(results_2.mean(), results_2.std())",
"26.653439153439148 10.346957901088238\n"
]
],
[
[
"# Cross validation with multiple forecast horizons",
"_____no_output_____"
]
],
[
[
"horizons = [7, 14, 21]\ncv = sliding_window(train, window_size=14, horizon=max(horizons), step=1)\n#note that we now pass in the horizons list to cross_val_score\nresults_h = cross_validation_score(model, train, cv, mean_absolute_error,\n horizons=horizons, n_jobs=-1)",
"_____no_output_____"
],
[
"#results are returned as numpy array - easy to cast to dataframe and display\npd.DataFrame(results_h, columns=['7days', '14days', '21days']).head()",
"_____no_output_____"
]
],
[
[
"## Cross validation example using ARIMA - does it speed up when CV run in Parallel?",
"_____no_output_____"
]
],
[
[
"#use ARIMA from pmdarima as that has a similar interface to baseline models.\nfrom pmdarima import ARIMA, auto_arima",
"_____no_output_____"
],
[
"#ato_model = auto_arima(train, suppress_warnings=True, n_jobs=-1, m=7)",
"_____no_output_____"
],
[
"#auto_model",
"_____no_output_____"
],
[
"#create arima model - reasonably complex model\n#order=(1, 1, 2), seasonal_order=(2, 0, 2, 7)\nargs = {'order':(1, 1, 2), 'seasonal_order':(2, 0, 2, 7)}\nmodel = ARIMA(order=args['order'], seasonal_order=args['seasonal_order'],\n enforce_stationarity=False, suppress_warnings=True)",
"_____no_output_____"
],
[
"%%time\ncv = rolling_forecast_origin(train, min_train_size=320, horizon=7)\nresults_1 = cross_validation_score(model, train, cv, mean_absolute_error, \n n_jobs=1)",
"CPU times: user 39.8 s, sys: 373 ms, total: 40.1 s\nWall time: 13.4 s\n"
]
],
[
[
"comment out %%timeit to run the code only once!\n\nyou should see a big improvement in performance. mine went \nfrom 12.3 seconds to 2.4 seconds.",
"_____no_output_____"
]
],
[
[
"%%time\ncv = rolling_forecast_origin(train, min_train_size=320, horizon=7)\nresults_2 = cross_validation_score(model, train, cv, mean_absolute_error, \n n_jobs=-1)",
"CPU times: user 1.63 s, sys: 252 ms, total: 1.88 s\nWall time: 4.32 s\n"
],
[
"results_1.shape",
"_____no_output_____"
],
[
"results_2.shape",
"_____no_output_____"
],
[
"results_1.mean()",
"_____no_output_____"
],
[
"results_2.mean()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
4aaabb3e27c43b513aa3ce3ddb5343a3d1d9745d
| 26,775 |
ipynb
|
Jupyter Notebook
|
site/pt/r1/tutorials/keras/basic_text_classification.ipynb
|
sriyogesh94/docs
|
b2e7670f95d360c64493d1b3a9ff84c96d285ca4
|
[
"Apache-2.0"
] | 2 |
2019-09-11T03:14:24.000Z
|
2019-09-11T03:14:28.000Z
|
site/pt/r1/tutorials/keras/basic_text_classification.ipynb
|
sriyogesh94/docs
|
b2e7670f95d360c64493d1b3a9ff84c96d285ca4
|
[
"Apache-2.0"
] | null | null | null |
site/pt/r1/tutorials/keras/basic_text_classification.ipynb
|
sriyogesh94/docs
|
b2e7670f95d360c64493d1b3a9ff84c96d285ca4
|
[
"Apache-2.0"
] | 1 |
2019-09-15T17:30:32.000Z
|
2019-09-15T17:30:32.000Z
| 36.982044 | 530 | 0.552269 |
[
[
[
"##### Copyright 2018 The TensorFlow Authors.",
"_____no_output_____"
]
],
[
[
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
],
[
"#@title MIT License\n#\n# Copyright (c) 2017 François Chollet\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.",
"_____no_output_____"
]
],
[
[
"# Classificação de texto com avaliações de filmes",
"_____no_output_____"
],
[
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/pt/r1/tutorials/keras/basic_text_classification.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Execute em Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/pt/r1/tutorials/keras/basic_text_classification.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />Veja a fonte em GitHub</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"\nEste *notebook* classifica avaliações de filmes como **positiva** ou **negativa** usando o texto da avaliação. Isto é um exemplo de classificação *binária* —ou duas-classes—, um importante e bastante aplicado tipo de problema de aprendizado de máquina.\n\nUsaremos a base de dados [IMDB](https://www.tensorflow.org/api_docs/python/tf/keras/datasets/imdb) que contém avaliaçòes de mais de 50000 filmes do bando de dados [Internet Movie Database](https://www.imdb.com/). A base é dividida em 25000 avaliações para treinamento e 25000 para teste. Os conjuntos de treinamentos e testes são *balanceados*, ou seja, eles possuem a mesma quantidade de avaliações positivas e negativas.\n\nO notebook utiliza [tf.keras](https://www.tensorflow.org/r1/guide/keras), uma API alto-nível para construir e treinar modelos com TensorFlow. Para mais tutoriais avançados de classificação de textos usando `tf.keras`, veja em [MLCC Text Classification Guide](https://developers.google.com/machine-learning/guides/text-classification/).",
"_____no_output_____"
]
],
[
[
"# keras.datasets.imdb está quebrado em 1.13 e 1.14, pelo np 1.16.3\n!pip install tf_nightly",
"_____no_output_____"
],
[
"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\nimport numpy as np\n\nprint(tf.__version__)",
"_____no_output_____"
]
],
[
[
"## Baixe a base de dados IMDB\n\nA base de dados vem empacotada com TensorFlow. Ele já vem pré-processado de forma que as avaliações (sequências de palavras) foi convertida em sequências de inteiros, onde cada inteiro representa uma palavra específica no dicionário.\n\nO código abaixo baixa a base de dados IMDB para a sua máquina (ou usa a cópia em *cache*, caso já tenha baixado):",
"_____no_output_____"
]
],
[
[
"imdb = keras.datasets.imdb\n\n(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)",
"_____no_output_____"
]
],
[
[
"O argumento `num_words=10000` mantém as 10000 palavras mais frequentes no conjunto de treinamento. As palavras mais raras são descartadas para preservar o tamanho dos dados de forma maleável.",
"_____no_output_____"
],
[
"## Explore os dados\n\nVamos parar um momento para entender o formato dos dados. O conjunto de dados vem pré-processado: cada exemplo é um *array* de inteiros representando as palavras da avaliação do filme. Cada *label* é um inteiro com valor ou de 0 ou 1, onde 0 é uma avaliação negativa e 1 é uma avaliação positiva.",
"_____no_output_____"
]
],
[
[
"print(\"Training entries: {}, labels: {}\".format(len(train_data), len(train_labels)))",
"_____no_output_____"
]
],
[
[
"O texto das avaliações foi convertido para inteiros, onde cada inteiro representa uma palavra específica no dicionário. Isso é como se parece a primeira revisão:",
"_____no_output_____"
]
],
[
[
"print(train_data[0])",
"_____no_output_____"
]
],
[
[
"As avaliações dos filmes têm diferentes tamanhos. O código abaixo mostra o número de palavras da primeira e segunda avaliação. Sabendo que o número de entradas da rede neural tem que ser de mesmo também, temos que resolver isto mais tarde.",
"_____no_output_____"
]
],
[
[
"len(train_data[0]), len(train_data[1])",
"_____no_output_____"
]
],
[
[
"### Converta os inteiros de volta a palavras\n\nÉ util saber como converter inteiros de volta a texto. Aqui, criaremos uma função de ajuda para consultar um objeto *dictionary* que contenha inteiros mapeados em strings:",
"_____no_output_____"
]
],
[
[
"# Um dicionário mapeando palavras em índices inteiros\nword_index = imdb.get_word_index()\n\n# Os primeiros índices são reservados\nword_index = {k:(v+3) for k,v in word_index.items()}\nword_index[\"<PAD>\"] = 0\nword_index[\"<START>\"] = 1\nword_index[\"<UNK>\"] = 2 # unknown\nword_index[\"<UNUSED>\"] = 3\n\nreverse_word_index = dict([(value, key) for (key, value) in word_index.items()])\n\ndef decode_review(text):\n return ' '.join([reverse_word_index.get(i, '?') for i in text])",
"_____no_output_____"
]
],
[
[
"Agora, podemos usar a função `decode_review` para mostrar o texto da primeira avaliação:",
"_____no_output_____"
]
],
[
[
"decode_review(train_data[0])",
"_____no_output_____"
]
],
[
[
"## Prepare os dados\n\nAs avaliações—o *arrays* de inteiros— deve ser convertida em tensores (*tensors*) antes de alimentar a rede neural. Essa conversão pode ser feita de duas formas:\n\n* Converter os arrays em vetores de 0s e 1s indicando a ocorrência da palavra, similar com *one-hot encoding*. Por exemplo, a sequência [3, 5] se tornaria um vetor de 10000 dimensões, onde todos seriam 0s, tirando 3 would become a 10,000-dimensional vector that is all zeros except for indices 3 and 5, which are ones. Then, make this the first layer in our network—a Dense layer—that can handle floating point vector data. This approach is memory intensive, though, requiring a `num_words * num_reviews` size matrix.\n\n* Alternatively, we can pad the arrays so they all have the same length, then create an integer tensor of shape `max_length * num_reviews`. We can use an embedding layer capable of handling this shape as the first layer in our network.\n\nIn this tutorial, we will use the second approach.\n\nSince the movie reviews must be the same length, we will use the [pad_sequences](https://keras.io/preprocessing/sequence/#pad_sequences) function to standardize the lengths:",
"_____no_output_____"
]
],
[
[
"train_data = keras.preprocessing.sequence.pad_sequences(train_data,\n value=word_index[\"<PAD>\"],\n padding='post',\n maxlen=256)\n\ntest_data = keras.preprocessing.sequence.pad_sequences(test_data,\n value=word_index[\"<PAD>\"],\n padding='post',\n maxlen=256)",
"_____no_output_____"
]
],
[
[
"Let's look at the length of the examples now:",
"_____no_output_____"
]
],
[
[
"len(train_data[0]), len(train_data[1])",
"_____no_output_____"
]
],
[
[
"And inspect the (now padded) first review:",
"_____no_output_____"
]
],
[
[
"print(train_data[0])",
"_____no_output_____"
]
],
[
[
"## Construindo o modelo\n\nA rede neural é criada por camadas empilhadas —isso necessita duas decisões arquiteturais principais:\n\n* Quantas camadas serão usadas no modelo?\n* Quantas *hidden units* são usadas em cada camada?\n\nNeste exemplo, os dados de entrada são um *array* de palavras-índices. As *labels* para predizer são ou 0 ou 1. Vamos construir um modelo para este problema:",
"_____no_output_____"
]
],
[
[
"# O formato de entrada é a contagem vocabulário usados pelas avaliações dos filmes (10000 palavras)\nvocab_size = 10000\n\nmodel = keras.Sequential()\nmodel.add(keras.layers.Embedding(vocab_size, 16))\nmodel.add(keras.layers.GlobalAveragePooling1D())\nmodel.add(keras.layers.Dense(16, activation=tf.nn.relu))\nmodel.add(keras.layers.Dense(1, activation=tf.nn.sigmoid))\n\nmodel.summary()",
"_____no_output_____"
]
],
[
[
"As camadas são empilhadas sequencialmente para construir o classificador:\n\n1. A primeira camada é uma camada `Embedding` layer (*`Embedding` layer*). Essa camada pega o vocabulário em inteiros e olha o vetor *embedding* em cada palavra-index. Esses vetores são aprendidos pelo modelo, ao longo do treinamento. Os vetores adicionam a dimensão ao *array* de saída. As dimensões resultantes são: `(batch, sequence, embedding)`.\n2. Depois, uma camada `GlobalAveragePooling1D` retorna um vetor de saída com comprimento fixo para cada exemplo fazendo a média da sequência da dimensão. Isso permite o modelo de lidar com entradas de tamanhos diferentes da maneira mais simples possível.\n3. Esse vetor de saída com tamanho fixo passa por uma camada *fully-connected* (`Dense`) layer com 16 *hidden units*.\n4. A última camada é uma *densely connected* com um único nó de saída. Usando uma função de ativação `sigmoid`, esse valor é um float que varia entre 0 e 1, representando a probabilidade, ou nível de confiança.",
"_____no_output_____"
],
[
"### Hidden units\n\nO modelo abaixo tem duas camadas intermediárias ou _\"hidden\"_ (hidden layers), entre a entrada e saída. O número de saídas (unidades— *units*—, nós ou neurônios) é a dimensão do espaço representacional para a camada. Em outras palavras, a quantidade de liberdade que a rede é permitida enquanto aprende uma representação interna.\n\nSe o modelo tem mais *hidden units* (um espaço representacional de maior dimensão), e/ou mais camadas, então a rede pode aprender representações mais complexas. Entretanto, isso faz com que a rede seja computacionamente mais custosa e pode levar o aprendizado de padrões não desejados— padrões que melhoram a performance com os dados de treinamento, mas não com os de teste. Isso se chama *overfitting*, e exploraremos mais tarde.",
"_____no_output_____"
],
[
"### Função Loss e otimizadores (optimizer)\n\nO modelo precisa de uma função *loss* e um otimizador (*optimizer*) para treinamento. Já que é um problema de classificação binário e o modelo tem com saída uma probabilidade (uma única camada com ativação sigmoide), usaremos a função loss `binary_crossentropy`.\n\nEssa não é a única escolha de função loss, você poderia escolher, no lugar, a `mean_squared_error`. Mas, geralmente, `binary_crossentropy` é melhor para tratar probabilidades— ela mede a \"distância\" entre as distribuições de probabilidade, ou, no nosso caso, sobre a distribuição real e as previsões.\n\nMais tarde, quando explorarmos problemas de regressão (como, predizer preço de uma casa), veremos como usar outra função loss chamada *mean squared error*.\n\nAgora, configure o modelo para usar o *optimizer* a função loss:",
"_____no_output_____"
]
],
[
[
"model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['acc'])",
"_____no_output_____"
]
],
[
[
"### Crie um conjunto de validação\n\nQuando treinando. queremos checar a acurácia do modelo com os dados que ele nunca viu. Crie uma conjunto de *validação* tirando 10000 exemplos do conjunto de treinamento original. (Por que não usar o de teste agora? Nosso objetivo é desenvolver e melhorar (tunar) nosso modelo usando somente os dados de treinamento, depois usar o de teste uma única vez para avaliar a acurácia).",
"_____no_output_____"
]
],
[
[
"x_val = train_data[:10000]\npartial_x_train = train_data[10000:]\n\ny_val = train_labels[:10000]\npartial_y_train = train_labels[10000:]",
"_____no_output_____"
]
],
[
[
"## Treine o modelo\n\nTreine o modelo em 40 *epochs* com *mini-batches* de 512 exemplos. Essas 40 iterações sobre todos os exemplos nos tensores `x_train` e `y_train`. Enquanto treina, monitore os valores do loss e da acurácia do modelo nos 10000 exemplos do conjunto de validação:",
"_____no_output_____"
]
],
[
[
"history = model.fit(partial_x_train,\n partial_y_train,\n epochs=40,\n batch_size=512,\n validation_data=(x_val, y_val),\n verbose=1)",
"_____no_output_____"
]
],
[
[
"## Avalie o modelo\n\nE vamos ver como o modelo se saiu. Dois valores serão retornados. Loss (um número que representa o nosso erro, valores mais baixos são melhores), e acurácia.",
"_____no_output_____"
]
],
[
[
"results = model.evaluate(test_data, test_labels)\n\nprint(results)",
"_____no_output_____"
]
],
[
[
"Está é uma aproximação ingênua que conseguiu uma acurácia de 87%. Com mais abordagens avançadas, o modelo deve chegar em 95%.",
"_____no_output_____"
],
[
"## Crie um gráfico de acurácia e loss por tempo\n\n`model.fit()` retorna um objeto `History` que contém um dicionário de tudo o que aconteceu durante o treinamento:",
"_____no_output_____"
]
],
[
[
"history_dict = history.history\nhistory_dict.keys()",
"_____no_output_____"
]
],
[
[
"Tem 4 entradas: uma para cada métrica monitorada durante a validação e treinamento. Podemos usá-las para plotar a comparação do loss de treinamento e validação, assim como a acurácia de treinamento e validação:",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n\nacc = history_dict['acc']\nval_acc = history_dict['val_acc']\nloss = history_dict['loss']\nval_loss = history_dict['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\n# \"bo\" de \"blue dot\" ou \"ponto azul\"\nplt.plot(epochs, loss, 'bo', label='Training loss')\n# b de \"solid blue line\" \"linha azul\"\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.show()",
"_____no_output_____"
],
[
"plt.clf() # limpa a figura\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"No gráfico, os pontos representam o loss e acurácia de treinamento, e as linhas são o loss e a acurácia de validação.\n\nNote que o loss de treinamento *diminui* a cada *epoch* e a acurácia *aumenta*. Isso é esperado quando usado um gradient descent optimization—ele deve minimizar a quantidade desejada a cada iteração.\n\nEsse não é o caso do loss e da acurácia de validação— eles parecem ter um pico depois de 20 epochs. Isso é um exemplo de *overfitting*: o modelo desempenha melhor nos dados de treinamento do que quando usado com dados nunca vistos. Depois desse ponto, o modelo otimiza além da conta e aprende uma representação *especifica* para os dados de treinamento e não *generaliza* para os dados de teste.\n\nPara esse caso particular, podemos prevenir o *overfitting* simplesmente parando o treinamento após mais ou menos 20 epochs. Depois, você verá como fazer isso automaticamente com um *callback*.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
4aaac0512764639124022958b8091ee752989e2f
| 3,404 |
ipynb
|
Jupyter Notebook
|
line_regression.ipynb
|
The1GrayGhost/astr-119-day-19
|
fd6fdd41dd193648f881e180764bb501cc4cc2a3
|
[
"MIT"
] | null | null | null |
line_regression.ipynb
|
The1GrayGhost/astr-119-day-19
|
fd6fdd41dd193648f881e180764bb501cc4cc2a3
|
[
"MIT"
] | null | null | null |
line_regression.ipynb
|
The1GrayGhost/astr-119-day-19
|
fd6fdd41dd193648f881e180764bb501cc4cc2a3
|
[
"MIT"
] | null | null | null | 20.142012 | 67 | 0.511751 |
[
[
[
"# Example of linear regression",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np",
"_____no_output_____"
],
[
"np.random.seed(119)\nnpoints=50\nx=np.linspace(0,10.,npoints)\nm=2.0\nb=1.0\nsigma=2.0\ny=m*x+b+np.random.normal(scale=sigma,size=npoints)\ny_err=np.full(npoints,sigma)",
"_____no_output_____"
]
],
[
[
"## Let's just plot the data first",
"_____no_output_____"
]
],
[
[
"f=plt.figure(figsize=(7,7))\nplt.errorbar(x,y,yerr=y_err,fmt='o')\nplt.xlabel('x')\nplt.ylabel('y')",
"_____no_output_____"
]
],
[
[
"## Method #1, polyfit()",
"_____no_output_____"
]
],
[
[
"m_fit,b_fit=np.poly1d(np.polyfit(x,y,1,w=1./y_err))\nprint(m_fit,b_fit)\ny_fit=m_fit*x+b_fit",
"_____no_output_____"
]
],
[
[
"## Plot result",
"_____no_output_____"
]
],
[
[
"f=plt.figure(figsize=(7,7))\nplt.errorbar(x,y,yerr=y_err,fmt='o',label='data')\nplt.plot(x,y_fit,label='fit')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend(loc=2,frameon=False)",
"_____no_output_____"
]
],
[
[
"## A new hope: line regression",
"_____no_output_____"
]
],
[
[
"m_A=0.0\nm_B=0.0\nm_C=0.0\nm_D=0.0\nm_A=np.sum(x*y)\nm_B=np.sum(x)*np.sum(y)\nm_C=np.sum(x*x)\nm_D=np.sum(x)**2\nm_fit_lr=(float(npoints)*m_A-m_B)/(float(npoints)*m_C-m_D)\ny_mean=np.mean(y)\nx_mean=np.mean(x)\nb_fit_lr=y_mean-m_fit_lr*x_mean\ny_fit_lr=m_fit_lr*x+b_fit_lr\nprint(m_fit_lr,b_fit_lr)",
"_____no_output_____"
],
[
"f=plt.figure(figsize=(7,7))\nplt.errorbar(x,y,yerr=y_err,fmt='o',label='data')\nplt.plot(x,y_fit_lr,'o',label='linear reg')\nplt.plot(x,y_fit,label='fit')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend(loc=2,frameon=False)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4aaac1fe68a84406499638a81cdfcf0668bce486
| 14,231 |
ipynb
|
Jupyter Notebook
|
notebooks/T7 - Ensemble [Monte-Carlo] approach.ipynb
|
brajard/DA-tutorials
|
f02ccc0d7e83dc4008a458aacabd05cb2e4d53ea
|
[
"MIT"
] | null | null | null |
notebooks/T7 - Ensemble [Monte-Carlo] approach.ipynb
|
brajard/DA-tutorials
|
f02ccc0d7e83dc4008a458aacabd05cb2e4d53ea
|
[
"MIT"
] | null | null | null |
notebooks/T7 - Ensemble [Monte-Carlo] approach.ipynb
|
brajard/DA-tutorials
|
f02ccc0d7e83dc4008a458aacabd05cb2e4d53ea
|
[
"MIT"
] | 3 |
2021-08-21T05:32:21.000Z
|
2022-01-24T07:18:24.000Z
| 31.208333 | 366 | 0.531164 |
[
[
[
"from resources.workspace import *",
"_____no_output_____"
]
],
[
[
"$\n% START OF MACRO DEF\n% DO NOT EDIT IN INDIVIDUAL NOTEBOOKS, BUT IN macros.py\n%\n\\newcommand{\\Reals}{\\mathbb{R}}\n\\newcommand{\\Expect}[0]{\\mathbb{E}}\n\\newcommand{\\NormDist}{\\mathcal{N}}\n%\n\\newcommand{\\DynMod}[0]{\\mathscr{M}}\n\\newcommand{\\ObsMod}[0]{\\mathscr{H}}\n%\n\\newcommand{\\mat}[1]{{\\mathbf{{#1}}}} \n%\\newcommand{\\mat}[1]{{\\pmb{\\mathsf{#1}}}}\n\\newcommand{\\bvec}[1]{{\\mathbf{#1}}} \n%\n\\newcommand{\\trsign}{{\\mathsf{T}}} \n\\newcommand{\\tr}{^{\\trsign}} \n\\newcommand{\\tn}[1]{#1} \n\\newcommand{\\ceq}[0]{\\mathrel{≔}}\n%\n\\newcommand{\\I}[0]{\\mat{I}} \n\\newcommand{\\K}[0]{\\mat{K}}\n\\newcommand{\\bP}[0]{\\mat{P}}\n\\newcommand{\\bH}[0]{\\mat{H}}\n\\newcommand{\\bF}[0]{\\mat{F}}\n\\newcommand{\\R}[0]{\\mat{R}}\n\\newcommand{\\Q}[0]{\\mat{Q}}\n\\newcommand{\\B}[0]{\\mat{B}}\n\\newcommand{\\C}[0]{\\mat{C}}\n\\newcommand{\\Ri}[0]{\\R^{-1}}\n\\newcommand{\\Bi}[0]{\\B^{-1}}\n\\newcommand{\\X}[0]{\\mat{X}}\n\\newcommand{\\A}[0]{\\mat{A}}\n\\newcommand{\\Y}[0]{\\mat{Y}}\n\\newcommand{\\E}[0]{\\mat{E}}\n\\newcommand{\\U}[0]{\\mat{U}}\n\\newcommand{\\V}[0]{\\mat{V}}\n%\n\\newcommand{\\x}[0]{\\bvec{x}}\n\\newcommand{\\y}[0]{\\bvec{y}}\n\\newcommand{\\z}[0]{\\bvec{z}}\n\\newcommand{\\q}[0]{\\bvec{q}}\n\\newcommand{\\br}[0]{\\bvec{r}}\n\\newcommand{\\bb}[0]{\\bvec{b}}\n%\n\\newcommand{\\bx}[0]{\\bvec{\\bar{x}}}\n\\newcommand{\\by}[0]{\\bvec{\\bar{y}}}\n\\newcommand{\\barB}[0]{\\mat{\\bar{B}}}\n\\newcommand{\\barP}[0]{\\mat{\\bar{P}}}\n\\newcommand{\\barC}[0]{\\mat{\\bar{C}}}\n\\newcommand{\\barK}[0]{\\mat{\\bar{K}}}\n%\n\\newcommand{\\D}[0]{\\mat{D}}\n\\newcommand{\\Dobs}[0]{\\mat{D}_{\\text{obs}}}\n\\newcommand{\\Dmod}[0]{\\mat{D}_{\\text{obs}}}\n%\n\\newcommand{\\ones}[0]{\\bvec{1}} \n\\newcommand{\\AN}[0]{\\big( \\I_N - \\ones \\ones\\tr / N \\big)}\n%\n% END OF MACRO DEF\n$\n# The ensemble (Monte-Carlo) approach\nis an approximate method for doing Bayesian inference. Instead of computing the full (gridvalues, or parameters, of the) posterior distributions, we instead try to generate ensembles from them.\n\nAn ensemble is an *iid* sample. I.e. a set of \"members\" (\"particles\", \"realizations\", or \"sample points\") that have been drawn (\"sampled\") independently from the same distribution. With the EnKF, these assumptions are generally tenous, but pragmatic.\n\nEnsembles can be used to characterize uncertainty: either by reconstructing (estimating) the distribution from which it is assumed drawn, or by computing various *statistics* such as the mean, median, variance, covariance, skewness, confidence intervals, etc (any function of the ensemble can be seen as a \"statistic\"). This is illustrated by the code below.",
"_____no_output_____"
]
],
[
[
"# Parameters\nb = 0\nB = 25 \nB12 = sqrt(B)\n\ndef true_pdf(x):\n return ss.norm.pdf(x,b,sqrt(B))\n\n# Plot true pdf\nxx = 3*linspace(-B12,B12,201)\nfig, ax = plt.subplots()\nax.plot(xx,true_pdf(xx),label=\"True\");\n\n# Sample and plot ensemble\nM = 1 # length of state vector\nN = 100 # ensemble size\nE = b + B12*randn((N,M))\nax.plot(E, zeros(N), '|k', alpha=0.3, ms=100)\n\n# Plot histogram\nnbins = max(10,N//30)\nheights, bins, _ = ax.hist(E,density=1,bins=nbins,label=\"Histogram estimate\")\n\n# Plot parametric estimate\nx_bar = np.mean(E)\nB_bar = np.var(E)\nax.plot(xx,ss.norm.pdf(xx,x_bar,sqrt(B_bar)),label=\"Parametric estimate\")\n\nax.legend();\n\n# Uncomment AFTER Exc 4:\n# dx = bins[1]-bins[0]\n# c = 0.5/sqrt(2*pi*B)\n# for height, x in zip(heights,bins):\n# ax.add_patch(mpl.patches.Rectangle((x,0),dx,c*height/true_pdf(x+dx/2),alpha=0.3))\n# Also set\n# * N = 10**4\n# * nbins = 50",
"_____no_output_____"
]
],
[
[
"The plot demonstrates that the true distribution can be represented by a sample thereof (since we can almost reconstruct the Gaussian distribution by estimating the moments from the sample). However, there are other ways to reconstruct (estimate) a distribution from a sample. For example: a histogram.\n\n**Exc 2:** Which approximation to the true pdf looks better: Histogram or the parametric? \nDoes one approximation actually start with more information? The EnKF takes advantage of this.",
"_____no_output_____"
],
[
"#### Exc 4*:\nUse the method of `gaussian_kde` from `scipy.stats` to make a \"continuous histogram\" and plot it above.\n`gaussian_kde` ",
"_____no_output_____"
]
],
[
[
"#show_answer(\"KDE\")",
"_____no_output_____"
]
],
[
[
"**Exc 5*:** Suppose the histogram bars get normalized (divided) by the value of the pdf at their location. \nHow do you expect the resulting histogram to look? \nTest your answer by uncommenting the block in the above code.",
"_____no_output_____"
],
[
"Being able to sample a Gaussian distribution is a building block of the EnKF.\nIn the previous example, we generated samples from a Gaussian distribution using the `randn` function.\nHowever, that was just for a scalar (univariate) case, i.e. with `M=1`. We need to be able to sample a multivariate Gaussian distribution. That is the objective of the following exercise.",
"_____no_output_____"
],
[
"**Exc 6 (Multivariate Gaussian sampling):**\nSuppose $\\z$ is a standard Gaussian,\ni.e. $p(\\z) = \\mathcal{N}(\\z \\mid \\bvec{0},\\I_M)$,\nwhere $\\I_M$ is the $M$-dimensional identity matrix. \nLet $\\x = \\mat{L}\\z + \\bb$. \nRecall [Exc 3.7](T3%20-%20Univariate%20Kalman%20filtering.ipynb#Exc-3.7:-The-forecast-step:),\nwhich yields $p(\\x) = \\mathcal{N}(\\x \\mid \\bb, \\mat{L}^{}\\mat{L}^T)$.\n \n * (a). $\\z$ can be sampled using `randn((M,1))`. How (where) is `randn` defined?\n * (b). Consider the above definition of $\\x$ and the code below.\n Complete it so as to generate a random realization of $\\x$. \n Hint: matrix-vector multiplication can be done using the symbol `@`. ",
"_____no_output_____"
]
],
[
[
"M = 3 # ndim\nb = 10*ones(M)\nB = diag(1+arange(M))\nL = np.linalg.cholesky(B) # B12\nprint(\"True mean and cov:\")\nprint(b)\nprint(B)\n\n### INSERT ANSWER (b) ###",
"_____no_output_____"
],
[
"#show_answer('Gaussian sampling a')",
"_____no_output_____"
],
[
"#show_answer('Gaussian sampling b')",
"_____no_output_____"
]
],
[
[
" * (c). In the code cell below, sample $N = 100$ realizations of $\\x$\n and collect them in an $M$-by-$N$ \"ensemble matrix\" $\\E$. \n - Try to avoid `for` loops (the main thing to figure out is: how to add a (mean) vector to a matrix).\n - Run the cell and inspect the computed mean and covariance to see if they're close to the true values, printed in the cell above.",
"_____no_output_____"
]
],
[
[
"N = 100 # ensemble size\n\nE = ### INSERT ANSWER (c) ###\n\n# Use the code below to assess whether you got it right\nx_bar = np.mean(E,axis=1)\nB_bar = np.cov(E)\n\nwith printoptions(precision=1):\n print(\"Estimated mean:\")\n print(x_bar)\n print(\"Estimated covariance:\")\n print(B_bar)\nplt.matshow(B_bar,cmap=\"Blues\"); plt.grid('off'); plt.colorbar()",
"_____no_output_____"
],
[
"#show_answer('Gaussian sampling c')",
"_____no_output_____"
]
],
[
[
"**Exc 8*:** How erroneous are the ensemble estimates on average?",
"_____no_output_____"
]
],
[
[
"#show_answer('Average sampling error')",
"_____no_output_____"
]
],
[
[
"**Exc 10:** Above, we used numpy's (`np`) functions to compute the sample-estimated mean and covariance matrix,\n$\\bx$ and $\\barB$,\nfrom the ensemble matrix $\\E$.\nNow, instead, implement these estimators yourself:\n$$\\begin{align}\\bx &\\ceq \\frac{1}{N} \\sum_{n=1}^N \\x_n \\, , \\\\\n \\barB &\\ceq \\frac{1}{N-1} \\sum_{n=1}^N (\\x_n - \\bx) (\\x_n - \\bx)^T \\, . \\end{align}$$",
"_____no_output_____"
]
],
[
[
"# Don't use numpy's mean, cov\ndef estimate_mean_and_cov(E):\n M, N = E.shape\n \n ### INSERT ANSWER ###\n \n return x_bar, B_bar\n\nx_bar, B_bar = estimate_mean_and_cov(E)\nwith printoptions(precision=1):\n print(x_bar)\n print(B_bar)",
"_____no_output_____"
],
[
"#show_answer('ensemble moments')",
"_____no_output_____"
]
],
[
[
"**Exc 12:** Why is the normalization by $(N-1)$ for the covariance computation?",
"_____no_output_____"
]
],
[
[
"#show_answer('Why (N-1)')",
"_____no_output_____"
]
],
[
[
"**Exc 14:** Like Matlab, Python (numpy) is quicker if you \"vectorize\" loops.\nThis is emminently possible with computations of ensemble moments. \nLet $\\X \\ceq \n\\begin{bmatrix}\n\t\t\\x_1 -\\bx, & \\ldots & \\x_n -\\bx, & \\ldots & \\x_N -\\bx\n\t\\end{bmatrix} \\, .$\n * (a). Show that $\\X = \\E \\AN$, where $\\ones$ is the column vector of length $N$ with all elements equal to $1$. \n Hint: consider column $n$ of $\\X$.\n * (b). Show that $\\barB = \\X \\X^T /(N-1)$.\n * (c). Code up this, latest, formula for $\\barB$ and insert it in `estimate_mean_and_cov(E)`",
"_____no_output_____"
]
],
[
[
"#show_answer('ensemble moments vectorized')",
"_____no_output_____"
]
],
[
[
"**Exc 16:** The cross-covariance between two random vectors, $\\bx$ and $\\by$, is given by\n$$\\begin{align}\n\\barC_{\\x,\\y}\n&\\ceq \\frac{1}{N-1} \\sum_{n=1}^N \n(\\x_n - \\bx) (\\y_n - \\by)^T \\\\\\\n&= \\X \\Y^T /(N-1)\n\\end{align}$$\nwhere $\\Y$ is, similar to $\\X$, the matrix whose columns are $\\y_n - \\by$ for $n=1,\\ldots,N$. \nNote that this is simply the covariance formula, but for two different variables. \nI.e. if $\\Y = \\X$, then $\\barC_{\\x,\\y} = \\barC_{\\x}$ (which we have denoted $\\barB$ in the above).\n\nImplement the cross-covariance estimator in the code-cell below.",
"_____no_output_____"
]
],
[
[
"def estimate_cross_cov(Ex,Ey):\n ### INSERT ANSWER ###",
"_____no_output_____"
],
[
"#show_answer('estimate cross')",
"_____no_output_____"
]
],
[
[
"**Exc 18 (error notions)*:**\n * (a). What's the difference between error residual?\n * (b). What's the difference between error and bias?\n * (c). Show `MSE = RMSE^2 = Bias^2 + Var`",
"_____no_output_____"
]
],
[
[
"#show_answer('errors')",
"_____no_output_____"
]
],
[
[
"### Next: [Writing your own EnKF](T8%20-%20Writing%20your%20own%20EnKF.ipynb)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aaad181bf0572d642a6400612ee90f0be7de7b2
| 356 |
ipynb
|
Jupyter Notebook
|
code.ipynb
|
Mahdikhansari/GithubTest
|
43b25a0bd4188d1863026f9f440210e467cc959d
|
[
"MIT"
] | null | null | null |
code.ipynb
|
Mahdikhansari/GithubTest
|
43b25a0bd4188d1863026f9f440210e467cc959d
|
[
"MIT"
] | null | null | null |
code.ipynb
|
Mahdikhansari/GithubTest
|
43b25a0bd4188d1863026f9f440210e467cc959d
|
[
"MIT"
] | null | null | null | 14.24 | 46 | 0.488764 |
[
[
[
"# test code file. This is from GitHub\n# From VScode\n# Mahdi\n\n",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
4aaadaed0f4c0ac1beac181341bc9d93e6c804ac
| 273,773 |
ipynb
|
Jupyter Notebook
|
exploratory_data_analysis.ipynb
|
MingalievDinar/adverity
|
6a0d659b65ebb84be7c724ec803b88f6b812dd75
|
[
"MIT"
] | 1 |
2021-01-31T17:35:02.000Z
|
2021-01-31T17:35:02.000Z
|
exploratory_data_analysis.ipynb
|
MingalievDinar/adverity
|
6a0d659b65ebb84be7c724ec803b88f6b812dd75
|
[
"MIT"
] | null | null | null |
exploratory_data_analysis.ipynb
|
MingalievDinar/adverity
|
6a0d659b65ebb84be7c724ec803b88f6b812dd75
|
[
"MIT"
] | null | null | null | 296.933839 | 92,860 | 0.918436 |
[
[
[
"\n# Exploratory data analysis\n\nExploratory data analysis is an important part of any data science projects. According to [Forbs](https://www.forbes.com/sites/gilpress/2016/03/23/data-preparation-most-time-consuming-least-enjoyable-data-science-task-survey-says/?sh=67e543e86f63), it accounts for about 80% of the work of data scientists. Thus, we are going to pay out attention to that part.\nIn the notebook are given data description, cleaning, variables preparation, and CTR calculation and visualization. \n\n---",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport random\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport gc\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"Given that file occupies 5.9G and has 40 mln rows we are going to read only a few rows to glimpse at data.",
"_____no_output_____"
]
],
[
[
"filename = 'data/train.csv'\n\n!echo 'Number of lines in \"train.csv\":'\n!wc -l {filename}\n!echo '\"train.csv\" file size:'\n!du -h {filename}",
"Number of lines in \"train.csv\":\n 40428968 data/train.csv\n\"train.csv\" file size:\n5.9G\tdata/train.csv\n"
],
[
"dataset_5 = pd.read_csv('data/train.csv', nrows=5)\ndataset_5.head()",
"_____no_output_____"
],
[
"print(\"Number of columns: {}\\n\".format(dataset_5.shape[1]))",
"Number of columns: 24\n\n"
]
],
[
[
"---\n## Data preparation\n\n* Column `Hour` has a format `YYMMDDHH` and has to be converted.\n* It is necessary to load only `click` and `hour` columns for `CTR` calculation. \n* For data exploration purposes we also calculate `hour` and build distributions of `CTR` by `hour` and `weekday`\n---",
"_____no_output_____"
]
],
[
[
"pd.to_datetime(dataset_5['hour'], format='%y%m%d%H')\n# custom_date_parser = lambda x: pd.datetime.strptime(x, '%y%m%d%H')",
"_____no_output_____"
],
[
"# The commented part is for preliminary analysis and reads only 10% of data\n\n# row_num = 40428967\n# to read 10% of data\n# skip = sorted(random.sample(range(1, row_num), round(0.9 * row_num)))\n# data_set = pd.read_csv('data/train.csv',\n# header=0,\n# skiprows=skip,\n# usecols=['click', 'hour'])\n\ndata_set = pd.read_csv('data/train.csv',\n header=0,\n usecols=['click', 'hour'])\n\ndata_set['hour'] = pd.to_datetime(data_set['hour'], format='%y%m%d%H')",
"_____no_output_____"
],
[
"data_set.isna().sum()",
"_____no_output_____"
],
[
"data_set.shape",
"_____no_output_____"
],
[
"round(100 * data_set.click.value_counts() / data_set.shape[0])",
"_____no_output_____"
],
[
"data_set.hour.dt.date.unique()",
"_____no_output_____"
]
],
[
[
"### Data preparation for CTR time series graph",
"_____no_output_____"
]
],
[
[
"df_CTR = data_set.groupby('hour').agg({\n 'click': ['count', 'sum']\n}).reset_index()\ndf_CTR.columns = ['hour', 'impressions', 'clicks']\ndf_CTR['CTR'] = df_CTR['clicks'] / df_CTR['impressions']",
"_____no_output_____"
],
[
"del data_set; gc.collect();",
"_____no_output_____"
],
[
"from pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\nplt.figure(figsize=[16, 8])\nsns.lineplot(x='hour', y='CTR', data=df_CTR, linewidth=3)\nplt.title('Hourly CTR for period 2014/10/21 and 2014/10/30', fontsize=20)",
"_____no_output_____"
]
],
[
[
"### Data preparation for CTR by hours graph",
"_____no_output_____"
]
],
[
[
"df_CTR['h'] = df_CTR.hour.dt.hour\ndf_CTR_h = df_CTR[['h', 'impressions',\n 'clicks']].groupby('h').sum().reset_index()\ndf_CTR_h['CTR'] = df_CTR_h['clicks'] / df_CTR_h['impressions']\n\ndf_CTR_h_melt = pd.melt(df_CTR_h,\n id_vars='h',\n value_vars=['impressions', 'clicks'],\n value_name='count',\n var_name='type')",
"_____no_output_____"
],
[
"plt.figure(figsize=[16, 8])\nsns.set_style(\"white\")\ng1 = sns.barplot(x='h',\n y='count',\n hue='type',\n data=df_CTR_h_melt,\n palette=\"deep\")\ng1.legend(loc=1).set_title(None)\nax2 = plt.twinx()\nsns.lineplot(x='h',\n y='CTR',\n data=df_CTR_h,\n palette=\"deep\",\n marker='o',\n ax=ax2,\n label='CTR',\n linewidth=5,\n color='lightblue')\nplt.title('CTR, Number of Imressions and Clicks by hours', fontsize=20)\nax2.legend(loc=5)\nplt.tight_layout()",
"_____no_output_____"
]
],
[
[
"### Data preparation for CTR by weekday graph",
"_____no_output_____"
]
],
[
[
"df_CTR['weekday'] = df_CTR.hour.dt.day_name()\ndf_CTR['weekday_num'] = df_CTR.hour.dt.weekday\ndf_CTR_w = df_CTR[['weekday', 'impressions',\n 'clicks']].groupby('weekday').sum().reset_index()\ndf_CTR_w['CTR'] = df_CTR_w['clicks'] / df_CTR_w['impressions']\ndf_CTR_w_melt = pd.melt(df_CTR_w,\n id_vars='weekday',\n value_vars=['impressions', 'clicks'],\n value_name='count',\n var_name='type')",
"_____no_output_____"
],
[
"plt.figure(figsize=[16, 8])\nsns.set_style(\"white\")\ng1 = sns.barplot(x='weekday',\n y='count',\n hue='type',\n data=df_CTR_w_melt.sort_values('weekday'),\n palette=\"deep\",\n order=[\n 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',\n 'Saturday', 'Sunday'\n ])\ng1.legend(loc=1).set_title(None)\nax2 = plt.twinx()\nsns.lineplot(x='weekday',\n y='CTR',\n data=df_CTR.sort_values(by='weekday_num'),\n palette=\"deep\",\n marker='o',\n ax=ax2,\n label='CTR',\n linewidth=5,\n sort=False)\nplt.title('CTR, Number of Imressions and Clicks by weekday', fontsize=20)\nax2.legend(loc=5)\nplt.tight_layout()",
"_____no_output_____"
]
],
[
[
"### Normality test",
"_____no_output_____"
]
],
[
[
"from scipy.stats import normaltest, shapiro\n\n\ndef test_interpretation(stat, p, alpha=0.05):\n \"\"\"\n Outputs the result of statistical test comparing test-statistic and p-value\n \"\"\"\n print('Statistics=%.3f, p-value=%.3f, alpha=%.2f' % (stat, p, alpha))\n if p > alpha:\n print('Sample looks like from normal distribution (fail to reject H0)')\n else:\n print('Sample is not from Normal distribution (reject H0)')",
"_____no_output_____"
],
[
"stat, p = shapiro(df_CTR.CTR)\ntest_interpretation(stat, p)",
"Statistics=0.978, p-value=0.001, alpha=0.05\nSample is not from Normal distribution (reject H0)\n"
],
[
"stat, p = normaltest(df_CTR.CTR)\ntest_interpretation(stat, p)",
"Statistics=10.090, p-value=0.006, alpha=0.05\nSample is not from Normal distribution (reject H0)\n"
]
],
[
[
"---\n## Summary\n\n* Number of rows: 40428967\n* Date duration: 10 days between 2014/10/21 and 2014/10/30. Each day has 24 hours\n* No missing values in variables `click` and `hour`\n* For simplicity, analysis is provided for 10% of the data. And as soon as the notebook is finalized, it will be re-run for all available data. And as soon as the hour aggregation takes place, the raw data source is deleted\n* Three graphs are provided: \n * CTR time serirs for all data duration\n * CTR, impressions, and click counts by hour\n * CTR, impressions, and click counts by weekday\n* Average `CTR` value is **17%**\n* Most of the `Impressions` and `Clicks` are appeared on Tuesday, Wednesday and Thursday. But highest `CTR` values is on Monday and Sunday\n* The normality in `CTR` time-series is **rejected** by two tests\n---\n\n## Hypothesis: \nThere is a seasonality in `CTR` by an `hour` and `weekday`. For instance, `CTR` at hour 21 is lower than `CTR` at hour 14 which can be observed from graphs. Ideally, it is necessary to use 24-hour lag for anomaly detection. It can be implemented by comparing, for instance, hour 1 at day 10 with an average value of hour 1 at days 3, 4, 5, 6, 7, 8, 9 (one week), etc. One week is chosen because averaging of whole week smooth weekday seasonality: Monday and Sunday are different from Tuesday and Wednesday, but there is no big difference between whole weeks. Additional improvement can be done by the use of the median for central tendency instead of a simple averaging because averaging is biased towards abnormal values.",
"_____no_output_____"
]
],
[
[
"# save the final aggregated data frame to use for anomaly detection in the corresponding notebook\ndf_CTR.to_pickle('./data/CTR_aggregated.pkl')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aaae20a6a626056c251e861d7e18057f85a231b
| 5,578 |
ipynb
|
Jupyter Notebook
|
15-Music-the-magic-of-12/15.3b-Looking-for-a-good-ratio.ipynb
|
misterhay/RabbitMath
|
8089e6cdf5ee0d70827b65c8be64619892b22b63
|
[
"MIT"
] | null | null | null |
15-Music-the-magic-of-12/15.3b-Looking-for-a-good-ratio.ipynb
|
misterhay/RabbitMath
|
8089e6cdf5ee0d70827b65c8be64619892b22b63
|
[
"MIT"
] | null | null | null |
15-Music-the-magic-of-12/15.3b-Looking-for-a-good-ratio.ipynb
|
misterhay/RabbitMath
|
8089e6cdf5ee0d70827b65c8be64619892b22b63
|
[
"MIT"
] | null | null | null | 25.705069 | 278 | 0.485837 |
[
[
[
"# Looking for a good ratio\n\nLet's start with what is surely the most important simple ratio, 3/2. We need to find numbers which are within ½% of 1.5. That is they have to be between the following two numbers:",
"_____no_output_____"
]
],
[
[
"1.5 * (1 - 0.005)",
"_____no_output_____"
],
[
"1.5 * (1 + 0.005)",
"_____no_output_____"
]
],
[
[
"Let's see if we can find values between 1.4925 and about 1.5075 in $2^{i/n}$:",
"_____no_output_____"
]
],
[
[
"ratio = 3/2\nbottom = ratio * (1 - 0.005)\ntop = ratio * (1 + 0.005)\n\nfor n in range(4, 17): # we'll check n values from 4 to 16\n for i in range(1, n+1): # for each i value up to n\n f = 2**(i/n) # calculate the frequency value\n if bottom <= f <= top: # if f is in the right range\n print('n =', n, 'and i =', i, 'so 2^(', i, '/', n, ')')",
"_____no_output_____"
]
],
[
[
"How many $n$ values contain a ratio of 1.5?",
"_____no_output_____"
],
[
"Let's try the next simplest ratio, 4:3.",
"_____no_output_____"
]
],
[
[
"ratio = 4/3\ntolarance = 0.005\nbottom = ratio * (1 - tolarance)\ntop = ratio * (1 + tolarance)\n\nfor n in range(4, 17):\n for i in range(1, n+1):\n f = 2**(i/n)\n if bottom <= f <= top:\n print('n =', n, 'and i =', i, 'so 2^(', i, '/', n, ')')",
"_____no_output_____"
]
],
[
[
"How many results this time?",
"_____no_output_____"
],
[
"If we look at the results for the ratio 5/3, there will also only be one note (this time in $n=15$, feel free to change the code above to check that).\n\nHowever if we increase our tolerance to 1% then:",
"_____no_output_____"
]
],
[
[
"ratio = 5/3\ntolarance = 0.01\nbottom = ratio * (1 - tolarance)\ntop = ratio * (1 + tolarance)\n\nfor n in range(4, 17):\n for i in range(1, n+1):\n f = 2**(i/n)\n if bottom <= f <= top:\n print('n =', n, 'and i =', i, 'so 2^(', i, '/', n, ')')",
"_____no_output_____"
]
],
[
[
"Again we see that there is a desirable ratio in $n=12$.\n\nLet's check the ratio 5/4, again with a 1% tolerance:",
"_____no_output_____"
]
],
[
[
"ratio = 5/4\ntolarance = 0.01\nbottom = ratio * (1 - tolarance)\ntop = ratio * (1 + tolarance)\n\nfor n in range(4, 17):\n for i in range(1, n+1):\n f = 2**(i/n)\n if bottom <= f <= top:\n print('n =', n, 'and i =', i, 'so 2^(', i, '/', n, ')')",
"_____no_output_____"
]
],
[
[
"And that is all of the possible ratios less than 2 (an octave) with integers that are 5 or less (simple).\n\nJust to review, let's calculate the number of simple ratios for each value of $n$:",
"_____no_output_____"
]
],
[
[
"ratioList = [3/2, 4/3, 5/3, 5/4]\ntolerance = 0.01\n\nfor n in range(4, 17):\n iList = []\n for ratio in ratioList:\n bottom = ratio * (1 - tolarance)\n top = ratio * (1 + tolarance)\n for i in range(1, n+1):\n f = 2**(i/n)\n if bottom <= f <= top:\n iList.append(i)\n #print('n =', n, 'and i =', i)\n print('n =', n, 'has', len(iList), 'simple ratio(s) with i =', iList)",
"_____no_output_____"
]
],
[
[
"So it looks like 12 is the winner, it has the most simple ratios of frequencies. So an octave with 12 notes will have the most pleasant-sounding intervals. Of course we could have guessed this because we know that 12 has more factors than any other number less than 60.\n\nMusic with 60 notes in an octave might be a little too complicated.",
"_____no_output_____"
],
[
"Go on to [15.4-Problems.ipynb](./15.4-Problems.ipynb)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
4aaae24fd68efd439ab272295b6c68dfb23109d7
| 697,855 |
ipynb
|
Jupyter Notebook
|
jupyter/enterprise/healthcare/24.Improved_Entity_Resolvers_in_SparkNLP_with_sBert.ipynb
|
iamvarol/spark-nlp-workshop
|
73a9064bd47d4dc0692f0297748eb43cd094aabd
|
[
"Apache-2.0"
] | null | null | null |
jupyter/enterprise/healthcare/24.Improved_Entity_Resolvers_in_SparkNLP_with_sBert.ipynb
|
iamvarol/spark-nlp-workshop
|
73a9064bd47d4dc0692f0297748eb43cd094aabd
|
[
"Apache-2.0"
] | null | null | null |
jupyter/enterprise/healthcare/24.Improved_Entity_Resolvers_in_SparkNLP_with_sBert.ipynb
|
iamvarol/spark-nlp-workshop
|
73a9064bd47d4dc0692f0297748eb43cd094aabd
|
[
"Apache-2.0"
] | null | null | null | 348,927.5 | 697,854 | 0.561008 |
[
[
[
"",
"_____no_output_____"
],
[
"[](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Healthcare/24.Improved_Entity_Resolvers_in_SparkNLP_with_sBert.ipynb)",
"_____no_output_____"
],
[
"# 24. Improved Entity Resolvers in Spark NLP with sBert",
"_____no_output_____"
]
],
[
[
"import sys\nimport json\nimport os\nwith open('license.json') as f:\n license_keys = json.load(f)\n \nimport os\nlocals().update(license_keys)\nos.environ.update(license_keys)",
"_____no_output_____"
],
[
"# Installing pyspark and spark-nlp\n! pip install --upgrade -q pyspark==3.1.2 spark-nlp==$PUBLIC_VERSION\n\n# Installing Spark NLP Healthcare\n! pip install --upgrade -q spark-nlp-jsl==$JSL_VERSION --extra-index-url https://pypi.johnsnowlabs.com/$SECRET\n\n# Installing Spark NLP Display Library for visualization\n! pip install -q spark-nlp-display",
"_____no_output_____"
],
[
"import json\nimport os\n\nfrom pyspark.ml import Pipeline, PipelineModel\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import functions as F\n\nimport sparknlp_jsl\nimport sparknlp\n\nfrom sparknlp.annotator import *\nfrom sparknlp_jsl.annotator import *\nfrom sparknlp.base import *\nfrom sparknlp.util import *\nfrom sparknlp.pretrained import ResourceDownloader\n\n\nparams = {\"spark.driver.memory\":\"16G\",\n\"spark.kryoserializer.buffer.max\":\"2000M\",\n\"spark.driver.maxResultSize\":\"2000M\"}\n\nspark = sparknlp_jsl.start(license_keys['SECRET'],params=params)\n\nprint (\"Spark NLP Version :\", sparknlp.version())\nprint (\"Spark NLP_JSL Version :\", sparknlp_jsl.version())\n\nspark",
"Spark NLP Version : 3.4.2\nSpark NLP_JSL Version : 3.5.0\n"
]
],
[
[
"<h1>!!! Warning !!!</h1>\n\n**If you get an error related to Java port not found 55, it is probably because that the Colab memory cannot handle the model and the Spark session died. In that case, try on a larger machine or restart the kernel at the top and then come back here and rerun.**",
"_____no_output_____"
],
[
"## ICD10CM pipeline",
"_____no_output_____"
]
],
[
[
"documentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"ner_chunk\")\n\nsbert_embedder = BertSentenceEmbeddings\\\n .pretrained('sbiobert_base_cased_mli', 'en','clinical/models')\\\n .setInputCols([\"ner_chunk\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\n \nicd10_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_icd10cm_augmented\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"icd10cm_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nicd_pipelineModel = PipelineModel(\n stages = [\n documentAssembler,\n sbert_embedder,\n icd10_resolver])\n\nicd_lp = LightPipeline(icd_pipelineModel)\n",
"sbiobert_base_cased_mli download started this may take some time.\nApproximate size to download 384.3 MB\n[OK!]\nsbiobertresolve_icd10cm_augmented download started this may take some time.\nApproximate size to download 1.3 GB\n[OK!]\n"
]
],
[
[
"## ICD10CM-HCC pipeline",
"_____no_output_____"
]
],
[
[
"documentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"ner_chunk\")\n\nsbert_embedder = BertSentenceEmbeddings\\\n .pretrained('sbiobert_base_cased_mli', 'en','clinical/models')\\\n .setInputCols([\"ner_chunk\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\n \nhcc_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_icd10cm_augmented_billable_hcc\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"icd10cm_hcc_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nhcc_pipelineModel = PipelineModel(\n stages = [\n documentAssembler,\n sbert_embedder,\n hcc_resolver])\n\nhcc_lp = LightPipeline(hcc_pipelineModel)",
"sbiobert_base_cased_mli download started this may take some time.\nApproximate size to download 384.3 MB\n[OK!]\nsbiobertresolve_icd10cm_augmented_billable_hcc download started this may take some time.\nApproximate size to download 1.4 GB\n[OK!]\n"
]
],
[
[
"## RxNorm pipeline",
"_____no_output_____"
]
],
[
[
"documentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"ner_chunk\")\n\nsbert_embedder = BertSentenceEmbeddings\\\n .pretrained('sbiobert_base_cased_mli', 'en','clinical/models')\\\n .setInputCols([\"ner_chunk\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\n \nrxnorm_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_rxnorm_augmented\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"rxnorm_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nrxnorm_pipelineModel = PipelineModel(\n stages = [\n documentAssembler,\n sbert_embedder,\n rxnorm_resolver])\n\nrxnorm_lp = LightPipeline(rxnorm_pipelineModel)\n",
"sbiobert_base_cased_mli download started this may take some time.\nApproximate size to download 384.3 MB\n[OK!]\nsbiobertresolve_rxnorm_augmented download started this may take some time.\nApproximate size to download 930.9 MB\n[OK!]\n"
]
],
[
[
"## NDC pipeline",
"_____no_output_____"
]
],
[
[
"documentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"ner_chunk\")\n\nsbert_embedder = BertSentenceEmbeddings\\\n .pretrained('sbiobert_base_cased_mli', 'en','clinical/models')\\\n .setInputCols([\"ner_chunk\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\n \nndc_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_ndc\", \"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"ndc_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nndc_pipelineModel = PipelineModel(\n stages = [\n documentAssembler,\n sbert_embedder,\n ndc_resolver])\n\nndc_lp = LightPipeline(ndc_pipelineModel)",
"sbiobert_base_cased_mli download started this may take some time.\nApproximate size to download 384.3 MB\n[OK!]\nsbiobertresolve_ndc download started this may take some time.\nApproximate size to download 391.4 MB\n[OK!]\n"
]
],
[
[
"## CPT pipeline",
"_____no_output_____"
]
],
[
[
"documentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"ner_chunk\")\n\nsbert_embedder = BertSentenceEmbeddings\\\n .pretrained('sbiobert_base_cased_mli', 'en','clinical/models')\\\n .setInputCols([\"ner_chunk\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\n \ncpt_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_cpt_procedures_augmented\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"cpt_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\ncpt_pipelineModel = PipelineModel(\n stages = [\n documentAssembler,\n sbert_embedder,\n cpt_resolver])\n\ncpt_lp = LightPipeline(cpt_pipelineModel)\n",
"sbiobert_base_cased_mli download started this may take some time.\nApproximate size to download 384.3 MB\n[OK!]\nsbiobertresolve_cpt_procedures_augmented download started this may take some time.\nApproximate size to download 78.3 MB\n[OK!]\n"
]
],
[
[
"## SNOMED pipeline",
"_____no_output_____"
]
],
[
[
"documentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"ner_chunk\")\n\nsbert_embedder = BertSentenceEmbeddings\\\n .pretrained('sbiobert_base_cased_mli', 'en','clinical/models')\\\n .setInputCols([\"ner_chunk\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\n \nsnomed_ct_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_snomed_findings_aux_concepts\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"snomed_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nsnomed_pipelineModel = PipelineModel(\n stages = [\n documentAssembler,\n sbert_embedder,\n snomed_ct_resolver])\n\nsnomed_lp = LightPipeline(snomed_pipelineModel)\n",
"sbiobert_base_cased_mli download started this may take some time.\nApproximate size to download 384.3 MB\n[OK!]\nsbiobertresolve_snomed_findings_aux_concepts download started this may take some time.\nApproximate size to download 4.3 GB\n[OK!]\n"
]
],
[
[
"## LOINC Pipeline",
"_____no_output_____"
]
],
[
[
"documentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"ner_chunk\")\n\nsbert_embedder = BertSentenceEmbeddings\\\n .pretrained('sbiobert_base_cased_mli', 'en','clinical/models')\\\n .setInputCols([\"ner_chunk\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\n \nloinc_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_loinc_augmented\", \"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"loinc_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nloinc_pipelineModel = PipelineModel(\n stages = [\n documentAssembler,\n sbert_embedder,\n loinc_resolver])\n\nloinc_lp = LightPipeline(loinc_pipelineModel)",
"sbiobert_base_cased_mli download started this may take some time.\nApproximate size to download 384.3 MB\n[OK!]\nsbiobertresolve_loinc_augmented download started this may take some time.\nApproximate size to download 1.4 GB\n[OK!]\n"
]
],
[
[
"## HCPCS Pipeline",
"_____no_output_____"
]
],
[
[
"documentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"ner_chunk\")\n\nsbert_embedder = BertSentenceEmbeddings\\\n .pretrained('sbiobert_base_cased_mli', 'en','clinical/models')\\\n .setInputCols([\"ner_chunk\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\n \nhcpcs_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_hcpcs\", \"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"hcpcs_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nhcpcs_pipelineModel = PipelineModel(\n stages = [\n documentAssembler,\n sbert_embedder,\n hcpcs_resolver])\n\nhcpcs_lp = LightPipeline(hcpcs_pipelineModel)",
"sbiobert_base_cased_mli download started this may take some time.\nApproximate size to download 384.3 MB\n[OK!]\nsbiobertresolve_hcpcs download started this may take some time.\nApproximate size to download 18.3 MB\n[OK!]\n"
]
],
[
[
"## UMLS Pipeline",
"_____no_output_____"
]
],
[
[
"documentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"ner_chunk\")\n\nsbert_embedder = BertSentenceEmbeddings\\\n .pretrained('sbiobert_base_cased_mli', 'en','clinical/models')\\\n .setInputCols([\"ner_chunk\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\n \numls_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_umls_major_concepts\", \"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"umls_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\numls_pipelineModel = PipelineModel(\n stages = [\n documentAssembler,\n sbert_embedder,\n umls_resolver])\n\numls_lp = LightPipeline(umls_pipelineModel)",
"sbiobert_base_cased_mli download started this may take some time.\nApproximate size to download 384.3 MB\n[OK!]\nsbiobertresolve_umls_major_concepts download started this may take some time.\nApproximate size to download 761 MB\n[OK!]\n"
]
],
[
[
"## MeSH pipeline",
"_____no_output_____"
]
],
[
[
"documentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"ner_chunk\")\n\nsbert_embedder = BertSentenceEmbeddings\\\n .pretrained('sbiobert_base_cased_mli', 'en','clinical/models')\\\n .setInputCols([\"ner_chunk\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\n \nmesh_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_mesh\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"mesh_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nmesh_pipelineModel = PipelineModel(\n stages = [\n documentAssembler,\n sbert_embedder,\n mesh_resolver])\n\nmesh_lp = LightPipeline(mesh_pipelineModel)\n",
"sbiobert_base_cased_mli download started this may take some time.\nApproximate size to download 384.3 MB\n[OK!]\nsbiobertresolve_mesh download started this may take some time.\nApproximate size to download 964.8 MB\n[OK!]\n"
]
],
[
[
"## HPO Pipeline",
"_____no_output_____"
]
],
[
[
"documentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"ner_chunk\")\n\nsbert_embedder = BertSentenceEmbeddings\\\n .pretrained('sbiobert_base_cased_mli', 'en','clinical/models')\\\n .setInputCols([\"ner_chunk\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\n \nhpo_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_HPO\", \"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"umls_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nhpo_pipelineModel = PipelineModel(\n stages = [\n documentAssembler,\n sbert_embedder,\n hpo_resolver])\n\nhpo_lp = LightPipeline(hpo_pipelineModel)",
"sbiobert_base_cased_mli download started this may take some time.\nApproximate size to download 384.3 MB\n[OK!]\nsbiobertresolve_HPO download started this may take some time.\nApproximate size to download 97.9 MB\n[OK!]\n"
]
],
[
[
"## All the resolvers in the same pipeline \n### (just to show how it is done.. will not be used in this notebook)",
"_____no_output_____"
]
],
[
[
"\ndocumentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"ner_chunk\")\n\nsbert_embedder = BertSentenceEmbeddings\\\n .pretrained('sbiobert_base_cased_mli', 'en','clinical/models')\\\n .setInputCols([\"ner_chunk\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\n \nsnomed_ct_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_snomed_findings\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"snomed_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nicd10_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_icd10cm_augmented\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"icd10cm_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nrxnorm_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_rxnorm_augmented\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"rxnorm_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\ncpt_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_cpt_procedures_augmented\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"cpt_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nhcc_resolver = SentenceEntityResolverModel.pretrained(\"sbert_biobertresolve_icd10cm_augmented_billable_hcc\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"icd10cm_hcc_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nloinc_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_loinc_augmented\", \"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"loinc_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nhcpcs_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_hcpcs\", \"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"hcpcs_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\numls_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_umls_major_concepts\", \"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"umls_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nhpo_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_HPO\", \"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"umls_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nmesh_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_mesh\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"mesh_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\nndc_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_ndc\", \"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"ndc_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n\n\nresolver_pipelineModel = PipelineModel(\n stages = [\n documentAssembler,\n sbert_embedder,\n icd10_resolver,\n hcc_resolver,\n rxnorm_resolver,\n ndc_resolver,\n cpt_resolver,\n snomed_ct_resolver,\n loinc_resolver,\n hcpcs_resolver,\n umls_resolver,\n mesh_resolver\n hpo_resolver])\n\nresolver_lp = LightPipeline(resolver_pipelineModel)\n",
"_____no_output_____"
]
],
[
[
"## Utility functions",
"_____no_output_____"
]
],
[
[
"import pandas as pd\n\npd.set_option('display.max_colwidth', 0)\n\n\ndef get_codes (lp, text, vocab='icd10cm_code', hcc=False, aux_label=False):\n \n full_light_result = lp.fullAnnotate(text)\n\n chunks = []\n codes = []\n begin = []\n end = []\n resolutions=[]\n all_distances =[]\n all_codes=[]\n all_cosines = []\n all_k_aux_labels=[]\n\n for chunk, code in zip(full_light_result[0]['ner_chunk'], full_light_result[0][vocab]):\n \n begin.append(chunk.begin)\n end.append(chunk.end)\n chunks.append(chunk.result)\n codes.append(code.result) \n all_codes.append(code.metadata['all_k_results'].split(':::'))\n resolutions.append(code.metadata['all_k_resolutions'].split(':::'))\n all_distances.append(code.metadata['all_k_distances'].split(':::'))\n all_cosines.append(code.metadata['all_k_cosine_distances'].split(':::'))\n \n if hcc:\n try:\n all_k_aux_labels.append(code.metadata['all_k_aux_labels'].split(':::'))\n except:\n all_k_aux_labels.append([])\n \n elif aux_label:\n try:\n all_k_aux_labels.append(code.metadata['all_k_aux_labels'].split(':::'))\n except:\n all_k_aux_labels.append([])\n else:\n all_k_aux_labels.append([])\n\n df = pd.DataFrame({'chunks':chunks, 'begin': begin, 'end':end, 'code':codes,'all_codes':all_codes, \n 'resolutions':resolutions, 'all_k_aux_labels':all_k_aux_labels,'all_distances':all_cosines})\n \n if hcc:\n\n df['billable'] = df['all_k_aux_labels'].apply(lambda x: [i.split('||')[0] for i in x])\n df['hcc_status'] = df['all_k_aux_labels'].apply(lambda x: [i.split('||')[1] for i in x])\n df['hcc_score'] = df['all_k_aux_labels'].apply(lambda x: [i.split('||')[2] for i in x])\n \n elif aux_label:\n\n df['gt'] = df['all_k_aux_labels'].apply(lambda x: [i.split('|')[0] for i in x])\n df['concept'] = df['all_k_aux_labels'].apply(lambda x: [i.split('|')[1] for i in x])\n df['aux'] = df['all_k_aux_labels'].apply(lambda x: [i.split('|')[2] for i in x])\n\n df = df.drop(['all_k_aux_labels'], axis=1)\n \n return df\n\n",
"_____no_output_____"
]
],
[
[
"## Getting some predictions from resolvers",
"_____no_output_____"
]
],
[
[
"text = 'bladder cancer'\n\n%time get_codes (icd_lp, text, vocab='icd10cm_code')",
"CPU times: user 68.2 ms, sys: 11.2 ms, total: 79.5 ms\nWall time: 7.6 s\n"
],
[
"text = 'severe stomach pain'\n\n%time get_codes (icd_lp, text, vocab='icd10cm_code')",
"CPU times: user 13.8 ms, sys: 3 ms, total: 16.8 ms\nWall time: 1.07 s\n"
],
[
"text = 'bladder cancer'\n\n%time get_codes (hcc_lp, text, vocab='icd10cm_hcc_code', hcc=True)",
"CPU times: user 24.9 ms, sys: 4.48 ms, total: 29.4 ms\nWall time: 1.38 s\n"
],
[
"text = 'severe stomach pain'\n\n%time get_codes (hcc_lp, text, vocab='icd10cm_hcc_code', hcc=True)",
"CPU times: user 20.7 ms, sys: 1.73 ms, total: 22.4 ms\nWall time: 1.39 s\n"
],
[
"text = 'metformin 100 mg'\n\n%time get_codes (rxnorm_lp, text, vocab='rxnorm_code')",
"CPU times: user 66.5 ms, sys: 7.31 ms, total: 73.8 ms\nWall time: 7.04 s\n"
],
[
"text = 'Advil Allergy Sinus'\n\n%time get_codes (rxnorm_lp, text, vocab='rxnorm_code')",
"CPU times: user 20.7 ms, sys: 0 ns, total: 20.7 ms\nWall time: 1.11 s\n"
],
[
"text = 'metformin 500 mg'\n\n%time get_codes (ndc_lp, text, vocab='ndc_code')",
"CPU times: user 19.6 ms, sys: 1.84 ms, total: 21.4 ms\nWall time: 1.01 s\n"
],
[
"text = 'aspirin 81 mg'\n\n%time get_codes (ndc_lp, text, vocab='ndc_code')",
"CPU times: user 18.7 ms, sys: 2.09 ms, total: 20.8 ms\nWall time: 993 ms\n"
],
[
"text = 'heart surgery'\n\n%time get_codes (cpt_lp, text, vocab='cpt_code')",
"CPU times: user 10.6 ms, sys: 887 µs, total: 11.5 ms\nWall time: 202 ms\n"
],
[
"text = 'ct abdomen'\n\n%time get_codes (cpt_lp, text, vocab='cpt_code')",
"CPU times: user 11.3 ms, sys: 821 µs, total: 12.1 ms\nWall time: 225 ms\n"
],
[
"text = 'Left heart cath'\n\n%time get_codes (cpt_lp, text, vocab='cpt_code')",
"CPU times: user 8.65 ms, sys: 3.35 ms, total: 12 ms\nWall time: 208 ms\n"
],
[
"text = 'bladder cancer'\n\n%time get_codes (snomed_lp, text, vocab='snomed_code', aux_label=True)",
"CPU times: user 17.3 ms, sys: 176 µs, total: 17.5 ms\nWall time: 3 s\n"
],
[
"text = 'schizophrenia'\n\n%time get_codes (snomed_lp, text, vocab='snomed_code', aux_label=True)",
"CPU times: user 16.1 ms, sys: 1.89 ms, total: 18 ms\nWall time: 3.01 s\n"
],
[
"text = 'FLT3 gene mutation analysis'\n\n%time get_codes (loinc_lp, text, vocab='loinc_code')",
"CPU times: user 51.7 ms, sys: 8.43 ms, total: 60.1 ms\nWall time: 6.36 s\n"
],
[
"text = 'Hematocrit'\n\n%time get_codes (loinc_lp, text, vocab='loinc_code')",
"CPU times: user 19.7 ms, sys: 1.92 ms, total: 21.6 ms\nWall time: 1.24 s\n"
],
[
"text = 'urine test'\n\n%time get_codes (loinc_lp, text, vocab='loinc_code')",
"CPU times: user 20.6 ms, sys: 2.57 ms, total: 23.2 ms\nWall time: 1.38 s\n"
],
[
"text = [\"Breast prosthesis, mastectomy bra, with integrated breast prosthesis form, unilateral, any size, any type\"]\n\n%time get_codes (hcpcs_lp, text, vocab='hcpcs_code')",
"CPU times: user 13.6 ms, sys: 99 µs, total: 13.7 ms\nWall time: 238 ms\n"
],
[
"text= [\"Dietary consultation for carbohydrate counting for type I diabetes.\"]\n%time get_codes (hcpcs_lp, text, vocab='hcpcs_code')",
"CPU times: user 10.5 ms, sys: 2.47 ms, total: 13 ms\nWall time: 229 ms\n"
],
[
"text= [\"Psychiatric consultation for alcohol withdrawal and dependance.\"]\n%time get_codes (hcpcs_lp, text, vocab='hcpcs_code')",
"CPU times: user 8.09 ms, sys: 2.23 ms, total: 10.3 ms\nWall time: 200 ms\n"
],
[
"# medical device\ntext = 'X-Ray'\n\n%time get_codes (umls_lp, text, vocab='umls_code')",
"CPU times: user 13.1 ms, sys: 2.2 ms, total: 15.3 ms\nWall time: 672 ms\n"
],
[
"# Injuries & poisoning\ntext = 'out-of-date food poisoning'\n\n%time get_codes (umls_lp, text, vocab='umls_code')",
"CPU times: user 14.6 ms, sys: 346 µs, total: 14.9 ms\nWall time: 731 ms\n"
],
[
"# clinical findings\ntext = 'type two diabetes mellitus'\n\n%time get_codes (umls_lp, text, vocab='umls_code')",
"CPU times: user 20.2 ms, sys: 1.4 ms, total: 21.6 ms\nWall time: 822 ms\n"
],
[
"text = 'chest pain '\n\n%time get_codes (mesh_lp, text, vocab='mesh_code')",
"CPU times: user 23.4 ms, sys: 1.44 ms, total: 24.8 ms\nWall time: 1.09 s\n"
],
[
"text = 'pericardectomy'\n\n%time get_codes (mesh_lp, text, vocab='mesh_code')",
"CPU times: user 19.2 ms, sys: 912 µs, total: 20.1 ms\nWall time: 1.02 s\n"
],
[
"text = 'bladder cancer'\n\n%time get_codes (hpo_lp, text, vocab='umls_code')",
"CPU times: user 9.74 ms, sys: 1.96 ms, total: 11.7 ms\nWall time: 260 ms\n"
],
[
"text = 'bipolar disorder'\n\n%time get_codes (hpo_lp, text, vocab='umls_code')",
"CPU times: user 14 ms, sys: 8.15 ms, total: 22.2 ms\nWall time: 277 ms\n"
],
[
"text = 'schizophrenia '\n\n%time get_codes (hpo_lp, text, vocab='umls_code')",
"CPU times: user 14.6 ms, sys: 2.5 ms, total: 17.1 ms\nWall time: 280 ms\n"
],
[
"icd_chunks = ['advanced liver disease',\n'advanced lung disease',\n'basal cell carcinoma of skin',\n'acute maxillary sinusitis',\n'chronic kidney disease stage',\n'diabetes mellitus type 2',\n'lymph nodes of multiple sites',\n'other chronic pain',\n'severe abdominal pain',\n'squamous cell carcinoma of skin',\n'type 2 diabetes mellitus']\n\nsnomed_chunks= ['down syndrome', 'adenocarcinoma', 'aortic valve stenosis',\n 'atherosclerosis', 'atrial fibrillation',\n 'hypertension', 'lung cancer', 'seizure',\n 'squamous cell carcinoma', 'stage IIIB', 'mediastinal lymph nodes']",
"_____no_output_____"
],
[
"from IPython.display import display\n\nfor chunk in icd_chunks:\n\n print ('>> ',chunk)\n display(get_codes (icd_lp, chunk, vocab='icd10cm_code'))",
">> advanced liver disease\n"
],
[
"for chunk in snomed_chunks:\n\n print ('>> ',chunk)\n display(get_codes (snomed_lp, chunk, vocab='snomed_code', aux_label=True))",
">> down syndrome\n"
],
[
"clinical_chunks = ['bladder cancer',\n 'anemia in chronic kidney disease',\n 'castleman disease',\n 'congestive heart failure',\n 'diabetes mellitus type 2',\n 'lymph nodes of multiple sites',\n 'malignant melanoma of skin',\n 'malignant neoplasm of lower lobe, bronchus',\n 'metastatic lung cancer',\n 'secondary malignant neoplasm of bone',\n 'type 2 diabetes mellitus',\n 'type 2 diabetes mellitus/insulin',\n 'unsp malignant neoplasm of lymph node']\n\n\nfor chunk in clinical_chunks:\n\n print ('>> ',chunk)\n \n print ('icd10cm_code')\n display(get_codes (hcc_lp, chunk, vocab='icd10cm_hcc_code', hcc=True))\n \n print ('snomed_code')\n display(get_codes (snomed_lp, chunk, vocab='snomed_code', aux_label=True))",
">> bladder cancer\nicd10cm_code\n"
]
],
[
[
"## How to integrate resolvers with NER models in the same pipeline\n",
"_____no_output_____"
]
],
[
[
"documentAssembler = DocumentAssembler()\\\n .setInputCol(\"text\")\\\n .setOutputCol(\"document\")\n\nsentenceDetector = SentenceDetectorDLModel.pretrained()\\\n .setInputCols([\"document\"])\\\n .setOutputCol(\"sentence\")\n\ntokenizer = Tokenizer()\\\n .setInputCols([\"sentence\"])\\\n .setOutputCol(\"token\")\\\n\nword_embeddings = WordEmbeddingsModel.pretrained(\"embeddings_clinical\", \"en\", \"clinical/models\")\\\n .setInputCols([\"sentence\", \"token\"])\\\n .setOutputCol(\"embeddings\")\n\nclinical_ner = MedicalNerModel.pretrained(\"ner_clinical\", \"en\", \"clinical/models\") \\\n .setInputCols([\"sentence\", \"token\", \"embeddings\"]) \\\n .setOutputCol(\"ner\")\n\nner_converter = NerConverter() \\\n .setInputCols([\"sentence\", \"token\", \"ner\"]) \\\n .setOutputCol(\"ner_chunk\")\\\n .setWhiteList(['PROBLEM'])\n\nc2doc = Chunk2Doc()\\\n .setInputCols(\"ner_chunk\")\\\n .setOutputCol(\"ner_chunk_doc\") \n\nsbert_embedder = BertSentenceEmbeddings\\\n .pretrained(\"sbiobert_base_cased_mli\",'en','clinical/models')\\\n .setInputCols([\"ner_chunk_doc\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\n\nicd10_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_icd10cm_augmented\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"icd10cm_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n \nsbert_resolver_pipeline = Pipeline(\n stages = [\n documentAssembler,\n sentenceDetector,\n tokenizer,\n word_embeddings,\n clinical_ner,\n ner_converter,\n c2doc,\n sbert_embedder,\n icd10_resolver])\n\ndata_ner = spark.createDataFrame([[\"\"]]).toDF(\"text\")\n\nsbert_models = sbert_resolver_pipeline.fit(data_ner)",
"sentence_detector_dl download started this may take some time.\nApproximate size to download 354.6 KB\n[OK!]\nembeddings_clinical download started this may take some time.\nApproximate size to download 1.6 GB\n[OK!]\nner_clinical download started this may take some time.\nApproximate size to download 13.9 MB\n[OK!]\nsbiobert_base_cased_mli download started this may take some time.\nApproximate size to download 384.3 MB\n[OK!]\nsbiobertresolve_icd10cm_augmented download started this may take some time.\nApproximate size to download 1.3 GB\n[OK!]\n"
],
[
"clinical_note = 'A 28-year-old female with a history of gestational diabetes mellitus diagnosed eight years prior to presentation and subsequent type two diabetes mellitus (T2DM), one prior episode of HTG-induced pancreatitis three years prior to presentation, associated with an acute hepatitis, and obesity with a body mass index (BMI) of 33.5 kg/m2, presented with a one-week history of polyuria, polydipsia, poor appetite, and vomiting. Two weeks prior to presentation, she was treated with a five-day course of amoxicillin for a respiratory tract infection. She was on metformin, glipizide, and dapagliflozin for T2DM and atorvastatin and gemfibrozil for HTG. She had been on dapagliflozin for six months at the time of presentation. Physical examination on presentation was significant for dry oral mucosa; significantly, her abdominal examination was benign with no tenderness, guarding, or rigidity. Pertinent laboratory findings on admission were: serum glucose 111 mg/dl, bicarbonate 18 mmol/l, anion gap 20, creatinine 0.4 mg/dL, triglycerides 508 mg/dL, total cholesterol 122 mg/dL, glycated hemoglobin (HbA1c) 10%, and venous pH 7.27. Serum lipase was normal at 43 U/L. Serum acetone levels could not be assessed as blood samples kept hemolyzing due to significant lipemia. The patient was initially admitted for starvation ketosis, as she reported poor oral intake for three days prior to admission. However, serum chemistry obtained six hours after presentation revealed her glucose was 186 mg/dL, the anion gap was still elevated at 21, serum bicarbonate was 16 mmol/L, triglyceride level peaked at 2050 mg/dL, and lipase was 52 U/L. The β-hydroxybutyrate level was obtained and found to be elevated at 5.29 mmol/L - the original sample was centrifuged and the chylomicron layer removed prior to analysis due to interference from turbidity caused by lipemia again. The patient was treated with an insulin drip for euDKA and HTG with a reduction in the anion gap to 13 and triglycerides to 1400 mg/dL, within 24 hours. Her euDKA was thought to be precipitated by her respiratory tract infection in the setting of SGLT2 inhibitor use. The patient was seen by the endocrinology service and she was discharged on 40 units of insulin glargine at night, 12 units of insulin lispro with meals, and metformin 1000 mg two times a day. It was determined that all SGLT2 inhibitors should be discontinued indefinitely. She had close follow-up with endocrinology post discharge.'\n\nprint (clinical_note)\n\nclinical_note_df = spark.createDataFrame([[clinical_note]]).toDF(\"text\")\n",
"A 28-year-old female with a history of gestational diabetes mellitus diagnosed eight years prior to presentation and subsequent type two diabetes mellitus (T2DM), one prior episode of HTG-induced pancreatitis three years prior to presentation, associated with an acute hepatitis, and obesity with a body mass index (BMI) of 33.5 kg/m2, presented with a one-week history of polyuria, polydipsia, poor appetite, and vomiting. Two weeks prior to presentation, she was treated with a five-day course of amoxicillin for a respiratory tract infection. She was on metformin, glipizide, and dapagliflozin for T2DM and atorvastatin and gemfibrozil for HTG. She had been on dapagliflozin for six months at the time of presentation. Physical examination on presentation was significant for dry oral mucosa; significantly, her abdominal examination was benign with no tenderness, guarding, or rigidity. Pertinent laboratory findings on admission were: serum glucose 111 mg/dl, bicarbonate 18 mmol/l, anion gap 20, creatinine 0.4 mg/dL, triglycerides 508 mg/dL, total cholesterol 122 mg/dL, glycated hemoglobin (HbA1c) 10%, and venous pH 7.27. Serum lipase was normal at 43 U/L. Serum acetone levels could not be assessed as blood samples kept hemolyzing due to significant lipemia. The patient was initially admitted for starvation ketosis, as she reported poor oral intake for three days prior to admission. However, serum chemistry obtained six hours after presentation revealed her glucose was 186 mg/dL, the anion gap was still elevated at 21, serum bicarbonate was 16 mmol/L, triglyceride level peaked at 2050 mg/dL, and lipase was 52 U/L. The β-hydroxybutyrate level was obtained and found to be elevated at 5.29 mmol/L - the original sample was centrifuged and the chylomicron layer removed prior to analysis due to interference from turbidity caused by lipemia again. The patient was treated with an insulin drip for euDKA and HTG with a reduction in the anion gap to 13 and triglycerides to 1400 mg/dL, within 24 hours. Her euDKA was thought to be precipitated by her respiratory tract infection in the setting of SGLT2 inhibitor use. The patient was seen by the endocrinology service and she was discharged on 40 units of insulin glargine at night, 12 units of insulin lispro with meals, and metformin 1000 mg two times a day. It was determined that all SGLT2 inhibitors should be discontinued indefinitely. She had close follow-up with endocrinology post discharge.\n"
],
[
"icd10_result = sbert_models.transform(clinical_note_df)",
"_____no_output_____"
],
[
"pd.set_option(\"display.max_colwidth\",0)",
"_____no_output_____"
],
[
"import pandas as pd\n\npd.set_option('display.max_colwidth', 0)\n\ndef get_icd_codes(icd10_res):\n \n icd10_df = icd10_res.select(F.explode(F.arrays_zip('ner_chunk.result', \n 'ner_chunk.metadata', \n 'icd10cm_code.result', \n 'icd10cm_code.metadata')).alias(\"cols\")) \\\n .select(F.expr(\"cols['1']['sentence']\").alias(\"sent_id\"),\n F.expr(\"cols['0']\").alias(\"ner_chunk\"),\n F.expr(\"cols['1']['entity']\").alias(\"entity\"), \n F.expr(\"cols['2']\").alias(\"icd10_code\"),\n F.expr(\"cols['3']['all_k_results']\").alias(\"all_codes\"),\n F.expr(\"cols['3']['all_k_resolutions']\").alias(\"resolutions\")).toPandas()\n\n\n \n codes = []\n resolutions = []\n\n for code, resolution in zip(icd10_df['all_codes'], icd10_df['resolutions']):\n\n codes.append(code.split(':::'))\n resolutions.append(resolution.split(':::'))\n\n icd10_df['all_codes'] = codes \n icd10_df['resolutions'] = resolutions\n \n return icd10_df",
"_____no_output_____"
],
[
"%%time\n\nres_pd = get_icd_codes(icd10_result)",
"CPU times: user 796 ms, sys: 89.1 ms, total: 886 ms\nWall time: 2min 27s\n"
],
[
"res_pd.head(15)",
"_____no_output_____"
]
],
[
[
"Lets apply some HTML formating by using `sparknlp_display` library to see the results of the pipeline in a nicer layout:",
"_____no_output_____"
]
],
[
[
"from sparknlp_display import EntityResolverVisualizer\n\n# with light pipeline\nlight_model = LightPipeline(sbert_models)\n\nvis = EntityResolverVisualizer()\n\n# Change color of an entity label\nvis.set_label_colors({'PROBLEM':'#008080'})\n\nlight_data_icd = light_model.fullAnnotate(clinical_note)\n\nvis.display(light_data_icd[0], 'ner_chunk', 'icd10cm_code')\n",
"_____no_output_____"
]
],
[
[
"## BertSentenceChunkEmbeddings\n\nThis annotator let users to aggregate sentence embeddings and ner chunk embeddings to get more specific and accurate resolution codes. It works by averaging context and chunk embeddings to get contextual information. Input to this annotator is the context (sentence) and ner chunks, while the output is embedding for each chunk that can be fed to the resolver model. The `setChunkWeight` parameter can be used to control the influence of surrounding context. \n\nFor more information and examples of `BertSentenceChunkEmbeddings` annotator, you can check here: \n[24.1.Improved_Entity_Resolution_with_SentenceChunkEmbeddings.ipynb](https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Healthcare/24.1.Improved_Entity_Resolution_with_SentenceChunkEmbeddings.ipynb)",
"_____no_output_____"
],
[
"### ICD10CM with BertSentenceChunkEmbeddings\n\nLets do the same process by using `BertSentenceEmbeddings` annotator and compare the results. We will create a new pipeline by using this annotator with SentenceEntityResolverModel.",
"_____no_output_____"
]
],
[
[
"#Get average sentence-chunk Bert embeddings\nsentence_chunk_embeddings = BertSentenceChunkEmbeddings.pretrained(\"sbiobert_base_cased_mli\", \"en\", \"clinical/models\")\\\n .setInputCols([\"sentence\", \"ner_chunk\"])\\\n .setOutputCol(\"sbert_embeddings\")\\\n .setCaseSensitive(False)\\\n .setChunkWeight(0.5) #default : 0.5\n\n\nicd10_resolver = SentenceEntityResolverModel.pretrained(\"sbiobertresolve_icd10cm_augmented\",\"en\", \"clinical/models\") \\\n .setInputCols([\"ner_chunk\", \"sbert_embeddings\"]) \\\n .setOutputCol(\"icd10cm_code\")\\\n .setDistanceFunction(\"EUCLIDEAN\")\n \nresolver_pipeline_SCE = Pipeline(\n stages = [\n documentAssembler,\n sentenceDetector,\n tokenizer,\n word_embeddings,\n clinical_ner,\n ner_converter,\n sentence_chunk_embeddings,\n icd10_resolver])\n\n\nempty_data = spark.createDataFrame([['']]).toDF(\"text\")\nmodel_SCE = resolver_pipeline_SCE.fit(empty_data)",
"sbiobert_base_cased_mli download started this may take some time.\nApproximate size to download 384.3 MB\n[OK!]\nsbiobertresolve_icd10cm_augmented download started this may take some time.\nApproximate size to download 1.3 GB\n[OK!]\n"
],
[
"icd10_result_SCE = model_SCE.transform(clinical_note_df)",
"_____no_output_____"
],
[
"%%time\n\nres_SCE_pd = get_icd_codes(icd10_result_SCE)",
"CPU times: user 790 ms, sys: 102 ms, total: 892 ms\nWall time: 2min 28s\n"
],
[
"res_SCE_pd.head(15)",
"_____no_output_____"
],
[
"icd10_SCE_lp = LightPipeline(model_SCE)\n\nlight_result = icd10_SCE_lp.fullAnnotate(clinical_note)\n\nvisualiser = EntityResolverVisualizer()\n\n# Change color of an entity label\nvisualiser.set_label_colors({'PROBLEM':'#008080'})\n\nvisualiser.display(light_result[0], 'ner_chunk', 'icd10cm_code')",
"_____no_output_____"
]
],
[
[
"**Lets compare the results that we got from these two methods.**",
"_____no_output_____"
]
],
[
[
"sentence_df = icd10_result.select(F.explode(F.arrays_zip('sentence.metadata', 'sentence.result')).alias(\"cols\")) \\\n .select( F.expr(\"cols['0']['sentence']\").alias(\"sent_id\"),\n F.expr(\"cols['1']\").alias(\"sentence_all\")).toPandas()\n\ncomparison_df = pd.merge(res_pd.loc[:,'sent_id':'resolutions'],res_SCE_pd.loc[:,'sent_id':'resolutions'], on=['sent_id',\"ner_chunk\", \"entity\"], how='inner')\ncomparison_df.columns=['sent_id','ner_chunk', 'entity', 'icd10_code', 'all_codes', 'resolutions', 'icd10_code_SCE', 'all_codes_SCE', 'resolutions_SCE']\n\ncomparison_df = pd.merge(sentence_df, comparison_df,on=\"sent_id\").drop('sent_id', axis=1)\ncomparison_df.head(15)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aaae3fc9a8dae88bf31895924e7bc624e222a67
| 134,979 |
ipynb
|
Jupyter Notebook
|
M15_UF3_P8_1_EB.ipynb
|
Hacendado/calculadora-tk
|
3c84422dce16e57830594186df51c9c506cf90bd
|
[
"MIT"
] | null | null | null |
M15_UF3_P8_1_EB.ipynb
|
Hacendado/calculadora-tk
|
3c84422dce16e57830594186df51c9c506cf90bd
|
[
"MIT"
] | null | null | null |
M15_UF3_P8_1_EB.ipynb
|
Hacendado/calculadora-tk
|
3c84422dce16e57830594186df51c9c506cf90bd
|
[
"MIT"
] | null | null | null | 122.819836 | 68,498 | 0.843516 |
[
[
[
"# **TUTORIAL 1: PRIMER PROYECTO DE MACHINE LEARNING**",
"_____no_output_____"
],
[
"# 1. EJECUTAR PYTHON Y COMPROBAR VERSIONES\r\n",
"_____no_output_____"
],
[
"Importaremos las librerías necesarias para poder ejecutar todo el código.\r\n- SYS - Provee acceso afucniones y objetos del intérprete\r\n\r\n- SCIPY - Biblioteca de herramientas y algoritmos matemáticos en Python\r\n\r\n- NUMPY - Mayor soporte para vectores y matrices, constituyendo una biblioteca de funciones.\r\n\r\n- MATPLOTLIB - Permite generar gráficas a partir de datos cotenidos en listas o vectores\r\n\r\n- PANDAS - Ofrece estructura de datos y operaciones para manipular tablas numéricas y series temporales\r\n\r\n- SKLEARN - Librería orientada al machine learning que proporcionar algoritmos para realizar clasificaciones, regresiones, clustering...",
"_____no_output_____"
]
],
[
[
"import sys\r\nprint('Python: {}'.format(sys.version))\r\n\r\nimport scipy\r\nprint('scipy: {}'.format(scipy.__version__))\r\n\r\nimport numpy\r\nprint('numpy: {}'.format(numpy.__version__))\r\n\r\nimport matplotlib\r\nprint('matplotlib: {}'.format(matplotlib.__version__))\r\n\r\nimport pandas\r\nprint('pandas: {}'.format(pandas.__version__))\r\n\r\nimport sklearn\r\nprint('sklearn: {}'.format(sklearn.__version__))",
"Python: 3.6.9 (default, Oct 8 2020, 12:12:24) \n[GCC 8.4.0]\nscipy: 1.4.1\nnumpy: 1.19.5\nmatplotlib: 3.2.2\npandas: 1.1.5\nsklearn: 0.22.2.post1\n"
]
],
[
[
"# 2. CARGA DE DATOS E IMPORTACIÓN DE LIBRERÍAS",
"_____no_output_____"
]
],
[
[
"# Carga de librerías\r\nfrom pandas import read_csv\r\nfrom pandas.plotting import scatter_matrix\r\nfrom matplotlib import pyplot\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.svm import SVC",
"_____no_output_____"
],
[
"# Carga de datos\r\nurl = \"https://raw.githubusercontent.com/jbrownlee/Datasets/master/iris.csv\"\r\nnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']\r\ndataset = read_csv(url, names=names)",
"_____no_output_____"
],
[
"# Mostrar por pantalla el número de filas y columnas (tuple)\r\nprint(dataset.shape)",
"(150, 5)\n"
],
[
"# Mostrar por pantalla los primeros registros\r\nprint(dataset.head(3))",
" sepal-length sepal-width petal-length petal-width class\n0 5.1 3.5 1.4 0.2 Iris-setosa\n1 4.9 3.0 1.4 0.2 Iris-setosa\n2 4.7 3.2 1.3 0.2 Iris-setosa\n"
]
],
[
[
"# 3. RESUMEN ESTADÍSTICOS",
"_____no_output_____"
]
],
[
[
"# Datos estadísticos\r\nprint(dataset.describe())",
" sepal-length sepal-width petal-length petal-width\ncount 150.000000 150.000000 150.000000 150.000000\nmean 5.843333 3.054000 3.758667 1.198667\nstd 0.828066 0.433594 1.764420 0.763161\nmin 4.300000 2.000000 1.000000 0.100000\n25% 5.100000 2.800000 1.600000 0.300000\n50% 5.800000 3.000000 4.350000 1.300000\n75% 6.400000 3.300000 5.100000 1.800000\nmax 7.900000 4.400000 6.900000 2.500000\n"
]
],
[
[
"# 4. DISTRIBUCIÓN DE CLASE",
"_____no_output_____"
]
],
[
[
"# Número de registros para cada clase agrupados por clase\r\nprint(dataset.groupby('class').size())",
"class\nIris-setosa 50\nIris-versicolor 50\nIris-virginica 50\ndtype: int64\n"
]
],
[
[
"# 5. GRÁFICOS UNIVARIABLES",
"_____no_output_____"
]
],
[
[
"# Desplegamos 4 boxplots cada uno representando un anchura/altura de pétalo y sépalo\r\ndataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)",
"_____no_output_____"
],
[
"# Histogramas sobre anchura y altura de pétalos y sépalos de flores\r\ndataset.hist()\r\npyplot.show()",
"_____no_output_____"
]
],
[
[
"# 6. GRÁFICOS MULTIVARIABLES",
"_____no_output_____"
]
],
[
[
"# Diagrama de dispersión. Muy útil para ver la relación entre variables cuantitativas.\r\nscatter_matrix(dataset)\r\npyplot.show()",
"_____no_output_____"
]
],
[
[
"# 7. EVALUACIÓN DE ALGORITMOS\r\n",
"_____no_output_____"
]
],
[
[
"# Dividiremos la información en conjuntos de datos válidos. Un 80% de la información se usará para\r\n# guardar información, evaluarla y seleccionarla a lo largo de los modelos mientras\r\n# que un 20% se guardará como datos válidos\r\narray = dataset.values\r\nX = array[:,0:4]\r\ny = array[:,4]\r\nX_train, X_validation, Y_train, Y_validation = train_test_split(X, y, test_size=0.20, random_state=1)",
"_____no_output_____"
]
],
[
[
"# 8. CONSTRUCCIÓN DE MODELOS\r\n",
"_____no_output_____"
],
[
"El siguiente ejemplo muestra 6 ejemplos de algoritmos.\r\n- Logistic Regression\r\n- Linear Discriminant Analysis\r\n- K-Nearest Neighbors\r\n- Classification adn Regression Trees\r\n- Gaussian Naive Bayes\r\n- Support Vector Machines",
"_____no_output_____"
]
],
[
[
"# Agregamos al array 'models' cada uno de los algoritmos\r\nmodels = []\r\nmodels.append(('LR', LogisticRegression(solver='liblinear', multi_class='ovr')))\r\nmodels.append(('LDA', LinearDiscriminantAnalysis()))\r\nmodels.append(('KNN', KNeighborsClassifier()))\r\nmodels.append(('CART', DecisionTreeClassifier()))\r\nmodels.append(('NB', GaussianNB()))\r\nmodels.append(('SVM', SVC(gamma='auto')))\r\n# Evaluamos cada uno de los modelos\r\nresults = []\r\nnames = []\r\nfor name, model in models:\r\n\tkfold = StratifiedKFold(n_splits=10, random_state=1, shuffle=True)\r\n\tcv_results = cross_val_score(model, X_train, Y_train, cv=kfold, scoring='accuracy')\r\n\tresults.append(cv_results)\r\n\tnames.append(name)\r\n\tprint('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std()))",
"LR: 0.941667 (0.065085)\nLDA: 0.975000 (0.038188)\nKNN: 0.958333 (0.041667)\nCART: 0.941667 (0.053359)\nNB: 0.950000 (0.055277)\nSVM: 0.983333 (0.033333)\n"
]
],
[
[
"# 9. SELECCIONAR EL MEJOR MODELOS",
"_____no_output_____"
],
[
"Al tener cada uno de los modelos, podemos realizar una comparativa entre ellos para utilizar el más preciso y con ella, hacer predicciones.",
"_____no_output_____"
]
],
[
[
"#Una vez tengamos los modelos, los compararemos para seleccionar el más preciso.\r\npyplot.boxplot(results, labels=names)\r\npyplot.title('Algorithm Comparison')\r\npyplot.show()",
"_____no_output_____"
]
],
[
[
"# 10. REALIZAR PREDICCIONES",
"_____no_output_____"
]
],
[
[
"# Podemos hacer predicciones de nuestro conjunto de información. Igualamos nuestro\r\n# array de modelos, usamos Support Vector Classification y lo ajustamos al array.\r\n# Finalmente guardamos en una variable la predicción del array.\r\nmodel = SVC(gamma='auto')\r\nmodel.fit(X_train, Y_train)\r\npredictions = model.predict(X_validation)",
"_____no_output_____"
]
],
[
[
"# 11. EVALUAR PREDICCIONES",
"_____no_output_____"
],
[
"Evaluamos las predicciones comparandolos con resultados esperados en el conjunto de información y calculamos su precisión en la clasificacion y también un informe de clasificación o matriz de confusión.\r\n- En precisión obtenemos un 96% de todo el conjunto de información\r\n- La matriz nos indica los errores hechos\r\n- El informe desglosa información de cada clase por precisión, recall, f1-score y support",
"_____no_output_____"
]
],
[
[
"print(accuracy_score(Y_validation, predictions))\r\nprint(confusion_matrix(Y_validation, predictions))\r\nprint(classification_report(Y_validation, predictions))",
"0.9666666666666667\n[[11 0 0]\n [ 0 12 1]\n [ 0 0 6]]\n precision recall f1-score support\n\n Iris-setosa 1.00 1.00 1.00 11\nIris-versicolor 1.00 0.92 0.96 13\n Iris-virginica 0.86 1.00 0.92 6\n\n accuracy 0.97 30\n macro avg 0.95 0.97 0.96 30\n weighted avg 0.97 0.97 0.97 30\n\n"
]
],
[
[
"# **TUTORIAL 2: CÓMO HACER PREDICCIONES CON SCIKIT-LEARN**",
"_____no_output_____"
],
[
"Antes de comenzar a hacer predicciones, debemos hacer un modelo final. En el siguiente ejemplo haremos un modelo final mediante los recursos que nos proporciona Scikit-Learn. \r\n- LogisticRegression: Modelosde regresión para variables dependientes o de respuesta binomial. Útil para modelar la probabilidad de un evento teniendo en cuenta otros factores\r\n- make_blobs: Genera un cluster de objetos binarios a partir de un conjunto de datos. Estos datos son usado para evaluar su rendimiento en los modelos de machine learning.\r\n - n_features: Determina la cantidad de columnas que se van a generar\r\n - centers: Corresponde al número de clases generados\r\n - n_samples: número total de puntos dividido a lo largo de clusters\r\n - random_state: Especifica si, cada vez que ejecutamos el programa, usamos o no, los mismos valores generados en el conjunto de datos.\r\n\r\nPor último destacar que existen 2 tipos de predicciones para un modelo final. Estos son las predicciones de clase y las prediccioes de probabilidad.",
"_____no_output_____"
],
[
"# 1. PREDICCIONES DE CLASES\r\n",
"_____no_output_____"
],
[
"# PREDICCIONES DE MÚLTIPLES CLASES\r\nPodemos realizar una predicción de múltiples instancias a la vez. Estas las indicaremos mediante make_blobs.",
"_____no_output_____"
]
],
[
[
"# Ejemplo de entrenar un modelo de clasificación final.\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.datasets import make_blobs\r\n# Generamos una clasificación de un conjunto de datos en 2d\r\nX, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1)\r\n# ajustamos el modelo final\r\nmodel = LogisticRegression()\r\nmodel.fit(X, y)\r\n# Instancias donde no sabemos la respuesta, indicamos '_' como segundo parámetro para\r\n# indicar que queremos ignorar 'ynew' al utilizar make_blobs\r\nXnew, _ = make_blobs(n_samples=3, centers=2, n_features=2, random_state=1)\r\n# Hacemos las predicciones de Xnew mediante la función predict()\r\nynew = model.predict(Xnew)\r\n# Mostramos las predicciones de las 3 instancias creadas \r\nfor i in range(len(Xnew)):\r\n\tprint(\"X=%s, Predicted=%s\" % (Xnew[i], ynew[i]))",
"X=[-0.79415228 2.10495117], Predicted=0\nX=[-8.25290074 -4.71455545], Predicted=1\nX=[-2.18773166 3.33352125], Predicted=0\n"
]
],
[
[
"# PREDICCIÓN DE UNA SOLA CLASE\r\nSi solo tenemos una instancia, podemos definirla dentro del array 'Xnew' que posteriormente pasaremos por parámetro hacia la función predict().",
"_____no_output_____"
]
],
[
[
"# Usamos los recursos de Scikit_Learn \r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.datasets import make_blobs\r\n# Generamos la clasificacion del conjunto de datos en 2d\r\nX, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1)\r\n# Ajustamos el modelo final\r\nmodel = LogisticRegression()\r\nmodel.fit(X, y)\r\n# Definimos una sola instancia\r\nXnew = [[-0.79415228, 2.10495117]]\r\n# Hacemos la predicción y mostramos el resultado\r\nynew = model.predict(Xnew)\r\nprint(\"X=%s, Predicted=%s\" % (Xnew[0], ynew[0]))",
"X=[-0.79415228, 2.10495117], Predicted=0\n"
]
],
[
[
"# 2. PREDICCIONES DE PROBABILIDAD\r\nA diferencia de las predicciones de clases, una predicción de probabilidad, donde se proporciona una instancia, el modelo devuelve la probabilidad de cada resultado sobre una clase con un valor entre 0 y 1. El siguiente ejemplo realizará una predicción de probabilidad de cada ejemplo en el array de Xnew.",
"_____no_output_____"
]
],
[
[
"# Usamos los recursos de Scikit_Learn \r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.datasets import make_blobs\r\n# Generamos la clasificacion del conjunto de datos en 2d\r\nX, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1)\r\n# Ajustamos el modelo final\r\nmodel = LogisticRegression()\r\nmodel.fit(X, y)\r\n# Instancias donde no sabemos la respuesta\r\nXnew, _ = make_blobs(n_samples=3, centers=2, n_features=2, random_state=1)\r\n# Realizamos la predicción mediante la función predict_proba()\r\nynew = model.predict_proba(Xnew)\r\n# Mostramos las predicciones de probabilidad sobre las instancias.\r\n# En este caso las predicciones se devovlerá con un valor entre 0 y 1.\r\nfor i in range(len(Xnew)):\r\n\tprint(\"X=%s, Predicted=%s\" % (Xnew[i], ynew[i]))",
"X=[-0.79415228 2.10495117], Predicted=[0.99467199 0.00532801]\nX=[-8.25290074 -4.71455545], Predicted=[0.00223842 0.99776158]\nX=[-2.18773166 3.33352125], Predicted=[0.99389073 0.00610927]\n"
]
],
[
[
"# CÓMO HACER PREDICCIONES CON MODELOS DE REGRESIÓN\r\nEn el siguiente ejemplo, utilizaremos el modelo Linear Regression para predecir cantidades mediante un modelo de regresión finalizado llamando a la función predict(). A diferencia del make_blobs, añadimos el parámetro \"noise\" que se encarga de establecer la dispersión que hay en un gráfico de regresión lineal.",
"_____no_output_____"
]
],
[
[
"# Usamos recursos de Scikit-Learn\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.datasets import make_regression\r\n# Generamos una regresión de conjunto de datos \r\nX, y = make_regression(n_samples=100, n_features=2, noise=0.1, random_state=1)\r\n# Ajustamoe el modelo final\r\nmodel = LinearRegression()\r\nmodel.fit(X, y)",
"_____no_output_____"
]
],
[
[
"# PREDICCIONES DE REGRESIÓN MÚLTIPLE\r\nEl siguiente ejemplo demuestra cómo hacer predicciones de regresión sobre instancias con resultados esperados desconocidos.",
"_____no_output_____"
]
],
[
[
"# Usamos recursos de Scikit-Learn\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.datasets import make_regression\r\n# Generamos una regresión de conjunto de datos \r\nX, y = make_regression(n_samples=100, n_features=2, noise=0.1)\r\n# Ajustamoe el modelo final\r\nmodel = LinearRegression()\r\nmodel.fit(X, y)\r\n# Nuevas instancias sin saber su respuesta.\r\nXnew, _ = make_regression(n_samples=3, n_features=2, noise=0.1, random_state=1)\r\n# Realiza un predicción\r\nynew = model.predict(Xnew)\r\n# Muestra los resultados por pantalla.\r\nfor i in range(len(Xnew)):\r\n\tprint(\"X=%s, Predicted=%s\" % (Xnew[i], ynew[i]))",
"X=[-1.07296862 -0.52817175], Predicted=-99.9469820757586\nX=[-0.61175641 1.62434536], Predicted=7.308755823826123\nX=[-2.3015387 0.86540763], Predicted=-147.67978719437392\n"
]
],
[
[
"# PREDICCIÓN DE REGRESIÓN SIMPLE\r\nAl igual que con las clases de predicción, también podemos hacer una predicción de regresión a una única instancia por ejemplo, sobre un array.\r\n",
"_____no_output_____"
]
],
[
[
"# Importamos los recursos de Scikit-Learn\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.datasets import make_regression\r\n# Generamos un conjuntos de datos de regresión\r\nX, y = make_regression(n_samples=100, n_features=2, noise=0.1)\r\n# Ajusamos el modelo final\r\nmodel = LinearRegression()\r\nmodel.fit(X, y)\r\n# Definimos una instancia en la variable Xnew\r\nXnew = [[-1.07296862, -0.52817175]]\r\n# Realizamos una predicción\r\nynew = model.predict(Xnew)\r\n# Mostramos los resultados por pantallas\r\nprint(\"X=%s, Predicted=%s\" % (Xnew[0], ynew[0]))",
"X=[-1.07296862, -0.52817175], Predicted=-118.67030900286555\n"
]
],
[
[
"# **TUTORIAL 3: Guardar y cargar modelos de Machine Learning**\r\n",
"_____no_output_____"
],
[
"# Guarda tu modelo con Pickle\r\nPickle es un manera standard de serializar objetos en Python. Con esto pasaremos una clase u objeto de Python a un formato serializado en un archivo como puede ser JSON o XML.",
"_____no_output_____"
]
],
[
[
"# Guardar modelo usando Picke\r\n# Importamos la librería pandas y los recuros de SciKit-learn\r\n# E importamos pickle\r\nimport pandas\r\nfrom sklearn import model_selection\r\nfrom sklearn.linear_model import LogisticRegression\r\nimport pickle\r\n# Declaramos variables URL conteniendo el archivo, un array de nombre y cargamos el\r\n# archivo guardandolo en una variable dataframe.\r\nurl = \"https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv\"\r\nnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\r\ndataframe = pandas.read_csv(url, names=names)\r\narray = dataframe.values\r\n# Seleccionamos los registros que queremos visualizar en los ejes X e Y\r\nX = array[:,0:8]\r\nY = array[:,8]\r\n# Establecemos un tamaño a la fuente y una semilla\r\ntest_size = 0.33\r\nseed = 7\r\nX_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed)\r\n# Ajusta el modelo en un conjunto de entrenamiento\r\nmodel = LogisticRegression()\r\nmodel.fit(X_train, Y_train)\r\n# Guarda el modelo en nuestro disco con Pickle usando la función dump() y open()\r\nfilename = 'finalized_model.sav'\r\npickle.dump(model, open(filename, 'wb'))\r\n# Cargamos el modelo del disco con Pickle\r\nloaded_model = pickle.load(open(filename, 'rb'))\r\nresult = loaded_model.score(X_test, Y_test)\r\nprint(result)",
"0.7874015748031497\n"
]
],
[
[
"# Guardar tu modelo con joblib",
"_____no_output_____"
]
],
[
[
"# Importamos librería pandas, recursos de SciKit-Learn y joblib\r\nimport pandas\r\nfrom sklearn import model_selection\r\nfrom sklearn.linear_model import LogisticRegression\r\nimport joblib\r\n# Declaramos variables URL conteniendo el archivo, un array de nombre y cargamos el\r\n# archivo guardandolo en una variable dataframe.\r\nurl = \"https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv\"\r\nnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\r\ndataframe = pandas.read_csv(url, names=names)\r\narray = dataframe.values\r\n# Seleccionamos los registros que queremos visualizar en los ejes X e Y\r\nX = array[:,0:8]\r\nY = array[:,8]\r\n# Establecemos un tamaño a la fuente y una semilla\r\ntest_size = 0.33\r\nseed = 7\r\nX_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed)\r\n# Ajusta el modelo en un conjunto de entrenamiento\r\nmodel = LogisticRegression()\r\nmodel.fit(X_train, Y_train)\r\n# Guarda el modelo en nuestro disco con Joblib\r\n# A diferencia de Picke, solo necesitaremos pasar por parámetro el modelo y el nombre\r\n# del archivo en la función dump() sin usar open() como en Joblib.\r\nfilename = 'finalized_model.sav'\r\njoblib.dump(model, filename) \r\n# Cargamos el modelo del disco con Joblib\r\nloaded_model = joblib.load(filename)\r\nresult = loaded_model.score(X_test, Y_test)\r\nprint(result)",
"0.7874015748031497\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aaae6a626367eea04af5ee8200e1ead24912ccd
| 65,457 |
ipynb
|
Jupyter Notebook
|
Notebooks/4.Math_Algebra.ipynb
|
MatSciEd/Machine-Learning
|
3f781f177f972bc56f0cad0e63bd8502d26352fe
|
[
"Apache-2.0"
] | null | null | null |
Notebooks/4.Math_Algebra.ipynb
|
MatSciEd/Machine-Learning
|
3f781f177f972bc56f0cad0e63bd8502d26352fe
|
[
"Apache-2.0"
] | null | null | null |
Notebooks/4.Math_Algebra.ipynb
|
MatSciEd/Machine-Learning
|
3f781f177f972bc56f0cad0e63bd8502d26352fe
|
[
"Apache-2.0"
] | null | null | null | 102.758242 | 25,608 | 0.819072 |
[
[
[
"# Math - Algebra\n\n[](https://colab.research.google.com/github/rhennig/EMA6938/blob/main/Notebooks/4.Math_Algebra.ipynb)\n\n(Based on https://online.stat.psu.edu/stat462/node/132/ and https://www.geeksforgeeks.org/ml-normal-equation-in-linear-regression)\n\nLinear algebra is the branch of mathematics concerning linear equations,\n$$\na_{1}x_{1}+\\cdots +a_{n}x_{n}=b,\n$$\nlinear maps ,\n$$\n(x_{1},\\ldots ,x_{n})\\mapsto a_{1}x_{1}+\\cdots +a_{n}x_{n},\n$$\nand their representations in vector spaces and through matrices. Linear algebra is a key foundation to the field of machine learning, from the notations used to describe the equations and operation of algorithms to the efficient implementation of algorithms in code.",
"_____no_output_____"
],
[
"## 1. Motivational Example of Linear Regression\n\nWe first derive the linear regression model in matrix form. In linear regression, we fit a linear function to a dataset of $N$ data points $(x_i, y_i)$. The linear model is given by\n$$\ny(x) = \\beta_0 + \\beta_1 x.\n$$\n\nLinear regression desscribes the data by minimizing the least squares deviation between the data and the linear model:\n$$\ny_i = \\beta_0 + \\beta_1 x_i + \\epsilon _i, \\, \\text{for }i = 1, \\dots , n.\n$$\nHere the $\\epsilon_i$ describes the deviation between the model and data and are assumed to be Gaussian distributed.\n\nWriting out the set of equations for $i = 1, \\dots, n$, we obtain $n$ equations:\n$$\ny_1 = \\beta_0 + \\beta_1 x_1 + \\epsilon _1 \\\\\ny_2 = \\beta_0 + \\beta_1 x_2 + \\epsilon _2 \\\\\n\\vdots \\\\\ny_n = \\beta_0 + \\beta_1 x_n + \\epsilon _n \\\\\n$$\n\nWe can formulate the above simple linear regression function in matrix notation:\n$$\n\\begin{bmatrix} y_1 \\\\ y_2 \\\\ \\vdots \\\\ y_n \\end{bmatrix} =\n\\begin{bmatrix}\n 1 & x_1 \\\\\n 1 & x_2 \\\\\n \\vdots \\\\\n 1 & x_n\n\\end{bmatrix}\n\\begin{bmatrix}\n \\beta_0 \\\\\n \\beta_1\n\\end{bmatrix} +\n\\begin{bmatrix}\n \\epsilon_1 \\\\\n \\epsilon_2 \\\\\n \\vdots \\\\\n \\epsilon_n\n\\end{bmatrix}.\n$$\n\nWe can write this matrix equation in a more compact form\n$$\n{\\bf Y} = {\\bf X} {\\bf \\beta} + {\\bf \\epsilon},\n$$\nwhere\n- **X** is an n × 2 matrix.\n- **Y** is an n × 1 column vector\n- **β** is a 2 × 1 column vector\n- **ε** is an n × 1 column vector.\n\nThe matrix **X** and vector **β** are multiplied together using the techniques of matrix multiplication.\nAnd, the vector **Xβ** is added to the vector **ε** using the techniques of matrix addition.\n\nLet's quickly review matrix algebra, the subject of mathematics that deals with operations of matrices, vectors, and tensors.",
"_____no_output_____"
],
[
"## 2. Definition of a matrix\n\nAn r × c matrix is a rectangular array of symbols or numbers arranged in r rows and c columns. A matrix is frequently denoted by a capital letter in boldface type.\n\nHere are three examples of simple matrices. The matrix **A** is a 2 × 2 square matrix containing numbers:\n$$\n{\\bf A} = \\begin{bmatrix} 23 & 9 \\\\ 20 & 7 \\end{bmatrix}.\n$$\n\nThe matrix **B** is a 5 × 3 matrix containing numbers:\n$$\n{\\bf B} = \\begin{bmatrix}\n 1 & 40 & 1.9 \\\\\n 1 & 65 & 2.5 \\\\\n 1 & 71 & 2.8 \\\\\n 1 & 80 & 3.4 \\\\\n 1 & 92 & 3.1\n\\end{bmatrix}.\n$$\n\nAnd, the matrix **X** is a 6 × 3 matrix containing a column of 1's and two columns of various x variables:\n$$\n{\\bf X} = \\begin{bmatrix}\n 1 & x_{11} & x_{12} \\\\\n 1 & x_{21} & x_{22} \\\\\n 1 & x_{31} & x_{32} \\\\\n 1 & x_{41} & x_{42} \\\\\n 1 & x_{51} & x_{52}\n\\end{bmatrix}.\n$$",
"_____no_output_____"
],
[
"## 3. Definition of a Vector and a Scalar\n\nA column vector is an r × 1 matrix, that is, a matrix with only one column. A vector is almost often denoted by a single lowercase letter in boldface type. The following vector **s** is a 3 × 1 column vector containing numbers:\n$$\n{\\bf s} = \\begin{bmatrix} 30 \\\\ 4 \\\\ 2013 \\end{bmatrix}.\n$$\n\nA row vector is an 1 × c matrix, that is, a matrix with only one row. The vector **m** is a 1 × 4 row vector containing numbers:\n$$\n{\\bf m} = \\begin{bmatrix} 23 & 9 & 20 & 7 \\end{bmatrix}.\n$$\n\nA 1 × 1 \"matrix\" is called a scalar, but it's just an ordinary number, such as 24 or $\\pi$.",
"_____no_output_____"
],
[
"## 4. Matrix Multiplication\n\nRecall the term **Xβ**, which appears in the regression function:\n$$\n{\\bf Y} = {\\bf X} {\\bf \\beta} + {\\bf \\epsilon}.\n$$\nThis is an example of a matrix multiplication. Since matrices have different numbers and columns, there are some constraints when multiplying matrices together. Two matrices can be multiplied together only if the **number of columns of the first matrix equals the number of rows of the second matrix**. \n\nWhen you multiply the two matrices:\n- the number of rows of the resulting matrix equals the number of rows of the first matrix, and\n- the number of columns of the resulting matrix equals the number of columns of the second matrix.\n\nFor example, if **A** is a 2 × 3 matrix and **B** is a 3 × 5 matrix, then the matrix multiplication **AB** is possible. The resulting matrix **C** = **AB** has 2 rows and 5 columns. That is, **C** is a 2 × 5 matrix. Note that the matrix multiplication **BA** is not possible.\n\nFor another example, if **X** is an n × (k+1) matrix and **β** is a (k+1) × 1 column vector, then the matrix multiplication **Xβ** is possible. The resulting matrix **Xβ** has n rows and 1 column. That is, **Xβ** is an n × 1 column vector.\n\nNow that we know when we can multiply two matrices together, here is the basic rule for multiplying **A** by **B** to get **C** = **AB**:\n\nThe entry in the i$^\\mathrm{th}$ row and j$^\\mathrm{th}$ column of **C** is the inner product — that is, element-by-element products added together — of the i$^\\mathrm{th}$ row of **A** with the j$^\\mathrm{th}$ column of **B**.\n\nFor example:\n$$\n A = \\begin{bmatrix} 1 & 9 & 7 \\\\ 8 & 1 & 2 \\end{bmatrix}\n$$\n\n$$\n B = \\begin{bmatrix} 3 & 2 & 1 & 5 \\\\ 5 & 4 & 7 & 3 \\\\ 6 & 9 & 6 & 8 \\end{bmatrix}\n$$\n\n$$\n C = A B =\n \\begin{bmatrix} 1 & 9 & 7 \\\\ 8 & 1 & 2 \\end{bmatrix} \n \\begin{bmatrix} 3 & 2 & 1 & 5 \\\\ 5 & 4 & 6 & 3 \\\\ 6 & 9 & 7 & 8 \\end{bmatrix}\n = \\begin{bmatrix} 90 & 101 & 106 & 88 \\\\ 41 & 38 & 27 & 59 \\end{bmatrix} \n$$",
"_____no_output_____"
]
],
[
[
"# Check the matrix multiplication result in Python using the numpy function matmul\nimport numpy as np\n\nA = np.array([[1, 9, 7], [8, 1, 2]])\nB = np.array([[3, 2, 1, 5], [5, 4, 7, 3], [6, 9, 6, 8]])\n\nprint(\"A = \\n\", A)\nprint(\"B = \\n\", B)\n# matmul multiplies two matrices\n# Remember that the operation \"*\" multiplies woi matrices element by element,\n# which is not a matrix multiplication\nC = np.matmul(A, B)\nprint(\"AB = \\n\", C)",
"A = \n [[1 9 7]\n [8 1 2]]\nB = \n [[3 2 1 5]\n [5 4 7 3]\n [6 9 6 8]]\nAB = \n [[ 90 101 106 88]\n [ 41 38 27 59]]\n"
]
],
[
[
"That is, the entry in the first row and first column of **C**, denoted $c_{11}$, is obtained by:\n$$\nc_{11} = 1(3) + 9(5) +7(6) = 90\n$$\n\nAnd, the entry in the first row and second column of **C**, denoted $c_{12}$, is obtained by:\n$$\nc_{12} = 1(2) + 9(4) + 7(9) = 101\n$$\n\nAnd, the entry in the second row and third column of C, denoted c23, is obtained by:\n$$\nc_{23} = 8(1) + 1(7) + 2(6) = 27\n$$",
"_____no_output_____"
],
[
"## 5. Matrix Addition\nRemember the expression **Xβ** + **ε** that appears in the regression function:\n$$\n{\\bf Y} = \\bf{X \\beta} + {\\bf \\epsilon}\n$$\nis an example of matrix addition. Again, there are some restrictions — you cannot just add any two matrices together. Two matrices can be added together only if they have the same number of rows and columns. Then, to add two matrices, simply add the corresponding elements of the two matrices.\n\nFor example:\n$$\n{\\bf C} = {\\bf A} + {\\bf B} =\n\\begin{bmatrix} 2 & 1 & 3 \\\\ 4 & 8 & 5 \\\\ -1 & 7 & 6 \\end{bmatrix}\n+\n\\begin{bmatrix} 7 & 9 & 2 \\\\ 5 & -3 & 1 \\\\ 2 & 1 & 8 \\end{bmatrix}\n=\n\\begin{bmatrix} 9 & 10 & 5 \\\\ 9 & 5 & 6 \\\\ 1 & 8 & 14\\end{bmatrix}\n$$",
"_____no_output_____"
]
],
[
[
"# Check the matrix addition result in Python using the numpy addition operation\nimport numpy as np\n\nA = np.array([[2, 1, 3], [4, 8, 5], [-1, 7, 6]])\nB = np.array([[7, 9, 2], [5, -3, 1], [2, 1, 8]])\n\nprint(\"A = \\n\", A)\nprint(\"B = \\n\", B)\nC = A + B\nprint(\"AB = \\n\", C)",
"A = \n [[ 2 1 3]\n [ 4 8 5]\n [-1 7 6]]\nB = \n [[ 7 9 2]\n [ 5 -3 1]\n [ 2 1 8]]\nAB = \n [[ 9 10 5]\n [ 9 5 6]\n [ 1 8 14]]\n"
]
],
[
[
"## 6. Least Squares Estimates of Linear Regression Coefficients\n\nAs we will discuss later, minimizing the mean squared error of model prediction and data leads to the following equation for the coefficient vector ${\\bf \\beta}$:\n$$\n{\\bf \\beta} = \\begin{bmatrix} \\beta_0 \\\\ \\vdots \\\\ \\beta_k \\end{bmatrix}\n= ({\\bf X}' {\\bf X})^{-1} {\\bf X}' {\\bf Y},\n$$\nwhere\n- $({\\bf X}' {\\bf X})^{-1}$ is the inverse of the ${\\bf X}' {\\bf X}$ matrix, and\n- ${\\bf X}'$ is the transpose of the ${\\bf X}$ matrix.\n\nLet's remind ourselves of the transpose and inverse of a matrix.",
"_____no_output_____"
],
[
"## 7. Transpose of a Matrix\n\nThe transpose of a matrix **A** is a matrix, denoted as $\\bf A'$ or ${\\bf A}^T$, whose rows are the columns of ${\\bf A}$ and whose columns are the rows of ${\\bf A}$ — all in the same order.\n\nFor example, the transpose of the 3 × 2 matrix A:\n$$\n{\\bf A} = \\begin{bmatrix} 1 & 4 \\\\ 7 & 5 \\\\ 8 & 9 \\end{bmatrix}\n$$\nis the 2 × 3 matrix $\\bf A'$:\n$$\n{\\bf A}' = {\\bf A}^T = \\begin{bmatrix} 1 & 7 & 8 \\\\ 4 & 5 & 9 \\end{bmatrix}\n$$\n\nThe ${\\bf X}$ matrix in the simple linear regression setting is:\n$$\n{\\bf X} = \\begin{bmatrix}\n 1 & x_1 \\\\\n 1 & x_2 \\\\\n \\vdots \\\\\n 1 & x_n\n\\end{bmatrix}.\n$$\n\nHence, the ${\\bf X}'{\\bf X}$ matrix in the linear regression is:\n$$\n{\\bf X}'{\\bf X} = \\begin{bmatrix}\n 1 & 1 & \\dots & 1\\\\\n x_1 & x_2 & & x_n\n\\end{bmatrix}\n\\begin{bmatrix}\n 1 & x_1 \\\\\n 1 & x_2 \\\\\n \\vdots \\\\\n 1 & x_n\n\\end{bmatrix}\n= \\begin{bmatrix}\n1 & \\sum_{i=1}^n x_i \\\\ \\sum_{i=1}^n x_i & \\sum_{i=1}^n x_i^2\n\\end{bmatrix}.\n$$",
"_____no_output_____"
],
[
"## 8. The Inverse of a Matrix\n\nThe inverse ${\\bf A}^{-1}$ of a **square matrix A** is the unique matrix such that:\n$$\n{\\bf A}^{-1} {\\bf A} = {\\bf I} = {\\bf A} {\\bf A}^{-1}.\n$$\n\nThat is, the inverse of ${\\bf A}$ is the matrix ${\\bf A}^{-1}$ that you multiply ${\\bf A}$ by to obtain the identity matrix ${\\bf I}$. Note that the inverse only exists for square matrices.\n\nNow, finding inverses, particularly for large matrices, is a complicated task. We will use numpy to calculate the inverses.",
"_____no_output_____"
],
[
"## 9. Solution for Linear Regresssion\n\nWe will use a data set from the Python library sklearn for linear regression.",
"_____no_output_____"
]
],
[
[
"# import required modules\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import make_regression\n\n# Create data set\nx,y = make_regression(n_samples=100,n_features=1,n_informative=1,noise = 10,random_state=10)\n \n# Plot the generated data set\nplt.figure(figsize=(8, 6))\nplt.rcParams['font.size'] = '16'\nplt.scatter(x, y, s = 30, marker = 'o')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Scatter Data', fontsize=20)\nplt.show()\n \n# Convert the vector of y variables into a column vector\ny=y.reshape(100,1)",
"_____no_output_____"
],
[
"# Create matrix X by adding x0=1 to each instance of x and taking the transpose\nX = np.array([np.ones(len(x)), x.flatten()]).T\nprint(\"Matrix X =\\n\", X[1:5, :], \"\\n ...\\n\")\n\n# Determining the coefficients of linear regression\n# by calculating the inverse of (X'X) and multiplying it by X'Y.\n\nXTX = np.matmul(X.T, X)\nprint(\"Matrix X'X =\\n\", XTX, \"\\n\")\n\nXTXinv = np.linalg.inv(XTX)\nprint(\"Inverse of (X'X) =\\n\", XTXinv, \"\\n\")\n\nbeta = np.matmul(XTXinv, np.matmul(X.T, y))\n\n# Display best values obtained.\nprint(\"Regression coefficients\\n β0 = \", beta[0,0], \"\\n β1 = \", beta[1,0])",
"Matrix X =\n [[ 1. -1.41855603]\n [ 1. 1.74481415]\n [ 1. -0.23218226]\n [ 1. -0.48933722]] \n ...\n\nMatrix X'X =\n [[100. 7.94166629]\n [ 7.94166629 94.14723566]] \n\nInverse of (X'X) =\n [[ 0.01006744 -0.00084923]\n [-0.00084923 0.0106933 ]] \n\nRegression coefficients\n β0 = 0.5280415108758212 \n β1 = 30.658963373978573\n"
],
[
"# Predict the values for given data instance.\nx_sample=np.array([[-2.5],[3]])\nx_sample_new=np.array([np.ones(len(x_sample)),x_sample.flatten()]).T\ny_predicted = np.matmul(x_sample_new, beta)\n\n# Plot the generated data set\nplt.figure(figsize=(8, 6))\nplt.rcParams['font.size'] = '16'\nplt.scatter(x, y, s = 30, marker = 'o')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Scatter Data', fontsize=20)\nplt.plot(x_sample, y_predicted, color='orange')\nplt.show()",
"_____no_output_____"
],
[
"# Verification using scikit learn function for linear regression\nfrom sklearn.linear_model import LinearRegression\nlr = LinearRegression() # Object\nlr.fit(x, y) # Fit method.\n \n# Print obtained theta values.\nprint(\"β0 = \", lr.intercept_[0], \"\\nβ1 = \", lr.coef_[0,0])",
"β0 = 0.5280415108758181 \nβ1 = 30.65896337397858\n"
]
],
[
[
"## 10. Practice\n\nThe hat matrix converts values from the observed variable $y_i$ into the estimated values $\\hat y$ obtained with the least squares method. The hat matrix, $\\bf H$, is given by\n$$\n{\\bf H} = {\\bf X} ({\\bf X}' {\\bf X})^{-1} {\\bf X}'\n$$\n\nCalculate the hat matrix, $\\bf H$, and show that you obtain the predicted $y$-values by creating a plot.",
"_____no_output_____"
]
],
[
[
"# Calculate the hat matrix\n\n# Apply the hat matrix to the y-values to generate the y predictions\n\n# Plot the predicted and original y values vs. the x values\n",
"_____no_output_____"
]
],
[
[
"Knowning the hat matrix, $\\bf H$, we can also express the $R^2$ value for the linear regression using a matrix equation:\n$$\nR^2 = 1 - \\frac{{\\bf y}'({\\bf 1} - {\\bf H}){\\bf y}}{{\\bf y}'({\\bf 1} - {\\bf M}){\\bf y}}\n$$\nwhere $\\bf 1$ is the identity matrix,\n$$\n{\\bf M} = {\\bf l}({\\bf l}'{\\bf l})^{-1}{\\bf l}',\n$$\nand ${\\bf l}$ is a column vector of 1's.\n\nCalculate the $R^2$ value using the above matrix form of the equations.",
"_____no_output_____"
]
],
[
[
"# Create a column vector of 1's with length 100\n\n# Calculate the matrix M\n\n# Calculate R2\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aaaeb46e13d9e6d4529a7528ca3fb3a6fede799
| 19,376 |
ipynb
|
Jupyter Notebook
|
notebooks/connect.ipynb
|
Heerpa/quickndirtybot
|
d0ca6f2d0e33f2b7642c81efec7d4d406aa85a14
|
[
"BSD-3-Clause"
] | null | null | null |
notebooks/connect.ipynb
|
Heerpa/quickndirtybot
|
d0ca6f2d0e33f2b7642c81efec7d4d406aa85a14
|
[
"BSD-3-Clause"
] | null | null | null |
notebooks/connect.ipynb
|
Heerpa/quickndirtybot
|
d0ca6f2d0e33f2b7642c81efec7d4d406aa85a14
|
[
"BSD-3-Clause"
] | null | null | null | 99.876289 | 2,451 | 0.654986 |
[
[
[
"# connect to account\n",
"_____no_output_____"
]
],
[
[
"import ccxt\n\ndef get_exchange(key, secret, password):\n exchange = ccxt.gdax()\n exchange.apiKey = key\n exchange.secret = secret\n exchange.password = password\n return exchange\n",
"_____no_output_____"
],
[
"import json\n\ndef load_config(filename='config.json'):\n with open(filename, 'r') as f:\n config = json.load(f)\n# json_str = open(name, 'f')\n# print(json_str)\n# config = json.loads(json_str)\n return config\n\nprint(load_config('config_gdax.json'))",
"{'exchange': {'name': 'gdax', 'key': '0293115a0b6c3fcfcd0557353595ba1c', 'secret': 's6TbDsIGMsqN9/WYRbDKviwuLqBAnsiWaRJZSnu6IIO5epT5lWpuItluBu8EGSY0urkQosmjXuqPnup+CCKbwg==', 'password': 'Jmimswenu!?#'}}\n"
],
[
"import pprint\npp = pprint.PrettyPrinter(indent=2)\n\nconfig = load_config('config_gdax.json')\nexchange = get_exchange(config['exchange']['key'], config['exchange']['secret'], config['exchange']['password'])\npp.pprint (exchange.fetch_balance ())",
"{ 'BCH': {'free': 0.0, 'total': 0.0, 'used': 0.0},\n 'BTC': {'free': 0.07872286, 'total': 0.07872286, 'used': 0.0},\n 'ETH': {'free': 0.0, 'total': 0.0, 'used': 0.0},\n 'EUR': {'free': 307.4606288618, 'total': 307.4606288618, 'used': 0.0},\n 'LTC': {'free': 0.0, 'total': 0.0, 'used': 0.0},\n 'free': { 'BCH': 0.0,\n 'BTC': 0.07872286,\n 'ETH': 0.0,\n 'EUR': 307.4606288618,\n 'LTC': 0.0},\n 'info': [ { 'available': '0.07872286',\n 'balance': '0.0787228600000000',\n 'currency': 'BTC',\n 'hold': '0.0000000000000000',\n 'id': '23a376bb-4301-4f8c-8cf3-046bcfb8833d',\n 'profile_id': '68ff2f17-a8ab-488f-9f50-753df475ab28'},\n { 'available': '0',\n 'balance': '0.0000000000000000',\n 'currency': 'LTC',\n 'hold': '0.0000000000000000',\n 'id': '7a88a224-8142-4a59-b006-5f2220009009',\n 'profile_id': '68ff2f17-a8ab-488f-9f50-753df475ab28'},\n { 'available': '307.4606288618',\n 'balance': '307.4606288618000000',\n 'currency': 'EUR',\n 'hold': '0.0000000000000000',\n 'id': '559be7d5-5478-43a1-9d1a-60c86b3dc68d',\n 'profile_id': '68ff2f17-a8ab-488f-9f50-753df475ab28'},\n { 'available': '0',\n 'balance': '0.0000000000000000',\n 'currency': 'ETH',\n 'hold': '0.0000000000000000',\n 'id': 'c746e53d-4c6e-46d7-bd25-9f964e38f7bc',\n 'profile_id': '68ff2f17-a8ab-488f-9f50-753df475ab28'},\n { 'available': '0',\n 'balance': '0.0000000000000000',\n 'currency': 'BCH',\n 'hold': '0.0000000000000000',\n 'id': 'b194bac8-fffc-4e88-8133-8477b87abfc6',\n 'profile_id': '68ff2f17-a8ab-488f-9f50-753df475ab28'}],\n 'total': { 'BCH': 0.0,\n 'BTC': 0.07872286,\n 'ETH': 0.0,\n 'EUR': 307.4606288618,\n 'LTC': 0.0},\n 'used': {'BCH': 0.0, 'BTC': 0.0, 'ETH': 0.0, 'EUR': 0.0, 'LTC': 0.0}}\n"
],
[
"# orders\nexchange.create_market_buy_order ('BTC/USD', 0) # buy 0 BTC and give away USD",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4aab1922c055aec62d59b65def96326f8060d046
| 21,214 |
ipynb
|
Jupyter Notebook
|
tensorflow_fold/g3doc/quick.ipynb
|
mudrat/fold
|
0e7ca14832a14a5f2009d4e0424783a80e7d7a2c
|
[
"Apache-2.0"
] | 2,020 |
2017-02-07T18:43:35.000Z
|
2022-03-19T11:54:04.000Z
|
tensorflow_fold/g3doc/quick.ipynb
|
mudrat/fold
|
0e7ca14832a14a5f2009d4e0424783a80e7d7a2c
|
[
"Apache-2.0"
] | 103 |
2017-02-08T11:07:27.000Z
|
2021-04-25T19:01:01.000Z
|
tensorflow_fold/g3doc/quick.ipynb
|
mudrat/fold
|
0e7ca14832a14a5f2009d4e0424783a80e7d7a2c
|
[
"Apache-2.0"
] | 346 |
2017-02-07T20:45:43.000Z
|
2022-03-02T15:11:11.000Z
| 26.190123 | 647 | 0.554445 |
[
[
[
"# TensorFlow Fold Quick Start\n\nTensorFlow Fold is a library for turning complicated Python data structures into TensorFlow Tensors.",
"_____no_output_____"
]
],
[
[
"# boilerplate\nimport random\nimport tensorflow as tf\nsess = tf.InteractiveSession()\nimport tensorflow_fold as td",
"_____no_output_____"
]
],
[
[
"The basic elements of Fold are *blocks*. We'll start with some blocks that work on simple data types.",
"_____no_output_____"
]
],
[
[
"scalar_block = td.Scalar()\nvector3_block = td.Vector(3)",
"_____no_output_____"
]
],
[
[
"Blocks are functions with associated input and output types.",
"_____no_output_____"
]
],
[
[
"def block_info(block):\n print(\"%s: %s -> %s\" % (block, block.input_type, block.output_type))\n \nblock_info(scalar_block)\nblock_info(vector3_block)",
"<td.Scalar dtype='float32'>: PyObjectType() -> TensorType((), 'float32')\n<td.Vector dtype='float32' size=3>: PyObjectType() -> TensorType((3,), 'float32')\n"
]
],
[
[
"We can use `eval()` to see what a block does with its input:",
"_____no_output_____"
]
],
[
[
"scalar_block.eval(42)",
"_____no_output_____"
],
[
"vector3_block.eval([1,2,3])",
"_____no_output_____"
]
],
[
[
"Not very exciting. We can compose simple blocks together with `Record`, like so:",
"_____no_output_____"
]
],
[
[
"record_block = td.Record({'foo': scalar_block, 'bar': vector3_block})\nblock_info(record_block)",
"<td.Record ordered=False>: PyObjectType() -> TupleType(TensorType((3,), 'float32'), TensorType((), 'float32'))\n"
]
],
[
[
"We can see that Fold's type system is a bit richer than vanilla TF; we have tuple types! Running a record block does what you'd expect:",
"_____no_output_____"
]
],
[
[
"record_block.eval({'foo': 1, 'bar': [5, 7, 9]})",
"_____no_output_____"
]
],
[
[
"One useful thing you can do with blocks is wire them up to create pipelines using the `>>` operator, which performs function composition. For example, we can take our two tuple tensors and compose it with `Concat`, like so:",
"_____no_output_____"
]
],
[
[
"record2vec_block = record_block >> td.Concat()\nrecord2vec_block.eval({'foo': 1, 'bar': [5, 7, 9]})",
"_____no_output_____"
]
],
[
[
"Note that because Python dicts are unordered, Fold always sorts the outputs of a record block by dictionary key. If you want to preserve order you can construct a Record block from an OrderedDict.\n\nThe whole point of Fold is to get your data into TensorFlow; the `Function` block lets you convert a TITO (Tensors In, Tensors Out) function to a block:",
"_____no_output_____"
]
],
[
[
"negative_block = record2vec_block >> td.Function(tf.negative)\nnegative_block.eval({'foo': 1, 'bar': [5, 7, 9]})",
"_____no_output_____"
]
],
[
[
"This is all very cute, but where's the beef? Things start to get interesting when our inputs contain sequences of indeterminate length. The `Map` block comes in handy here:",
"_____no_output_____"
]
],
[
[
"map_scalars_block = td.Map(td.Scalar())",
"_____no_output_____"
]
],
[
[
"There's no TF type for sequences of indeterminate length, but Fold has one:",
"_____no_output_____"
]
],
[
[
"block_info(map_scalars_block)",
"<td.Map element_block=<td.Scalar dtype='float32'>>: None -> SequenceType(TensorType((), 'float32'))\n"
]
],
[
[
"Right, but you've done the TF [RNN Tutorial](https://www.tensorflow.org/tutorials/recurrent/) and even poked at [seq-to-seq](https://www.tensorflow.org/tutorials/seq2seq/). You're a wizard with [dynamic rnns](https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn). What does Fold offer?\n\nWell, how about jagged arrays?",
"_____no_output_____"
]
],
[
[
"jagged_block = td.Map(td.Map(td.Scalar()))\nblock_info(jagged_block)",
"<td.Map element_block=<td.Map element_block=<td.Scalar dtype='float32'>>>: None -> SequenceType(SequenceType(TensorType((), 'float32')))\n"
]
],
[
[
"The Fold type system is fully compositional; any block you can create can be composed with `Map` to create a sequence, or `Record` to create a tuple, or both to create sequences of tuples or tuples of sequences:",
"_____no_output_____"
]
],
[
[
"seq_of_tuples_block = td.Map(td.Record({'foo': td.Scalar(), 'bar': td.Scalar()}))\nseq_of_tuples_block.eval([{'foo': 1, 'bar': 2}, {'foo': 3, 'bar': 4}])",
"_____no_output_____"
],
[
"tuple_of_seqs_block = td.Record({'foo': td.Map(td.Scalar()), 'bar': td.Map(td.Scalar())})\ntuple_of_seqs_block.eval({'foo': range(3), 'bar': range(7)})",
"_____no_output_____"
]
],
[
[
"Most of the time, you'll eventually want to get one or more tensors out of your sequence, for wiring up to your particular learning task. Fold has a bunch of built-in reduction functions for this that do more or less what you'd expect:",
"_____no_output_____"
]
],
[
[
"((td.Map(td.Scalar()) >> td.Sum()).eval(range(10)),\n (td.Map(td.Scalar()) >> td.Min()).eval(range(10)),\n (td.Map(td.Scalar()) >> td.Max()).eval(range(10)))\n ",
"_____no_output_____"
]
],
[
[
"The general form of such functions is `Reduce`:",
"_____no_output_____"
]
],
[
[
"(td.Map(td.Scalar()) >> td.Reduce(td.Function(tf.multiply))).eval(range(1,10))",
"_____no_output_____"
]
],
[
[
"If the order of operations is important, you should use `Fold` instead of `Reduce` (but if you can use `Reduce` you should, because it will be faster):",
"_____no_output_____"
]
],
[
[
"((td.Map(td.Scalar()) >> td.Fold(td.Function(tf.divide), tf.ones([]))).eval(range(1,5)),\n (td.Map(td.Scalar()) >> td.Reduce(td.Function(tf.divide), tf.ones([]))).eval(range(1,5))) # bad, not associative!",
"_____no_output_____"
]
],
[
[
"Now, let's do some learning! This is the part where \"magic\" happens; if you want a deeper understanding of what's happening here you might want to jump right to our more formal [blocks tutorial](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/blocks.md) or learn more about [running blocks in TensorFlow](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/running.md)",
"_____no_output_____"
]
],
[
[
"def reduce_net_block():\n net_block = td.Concat() >> td.FC(20) >> td.FC(1, activation=None) >> td.Function(lambda xs: tf.squeeze(xs, axis=1))\n return td.Map(td.Scalar()) >> td.Reduce(net_block)\n",
"_____no_output_____"
]
],
[
[
"The `reduce_net_block` function creates a block (`net_block`) that contains a two-layer fully connected (FC) network that takes a pair of scalar tensors as input and produces a scalar tensor as output. This network gets applied in a binary tree to reduce a sequence of scalar tensors to a single scalar tensor.\n\nOne thing to notice here is that we are calling [`tf.squeeze`](https://www.tensorflow.org/versions/r1.0/api_docs/python/array_ops/shapes_and_shaping#squeeze) with `axis=1`, even though the Fold output type of `td.FC(1, activation=None)` (and hence the input type of the enclosing `Function` block) is a `TensorType` with shape `(1)`. This is because all Fold blocks actually run on TF tensors with an implicit leading batch dimension, which enables execution via [*dynamic batching*](https://arxiv.org/abs/1702.02181). It is important to bear this in mind when creating `Function` blocks that wrap functions that are not applied elementwise.",
"_____no_output_____"
]
],
[
[
"def random_example(fn):\n length = random.randrange(1, 10)\n data = [random.uniform(0,1) for _ in range(length)]\n result = fn(data)\n return data, result",
"_____no_output_____"
]
],
[
[
"The `random_example` function generates training data consisting of `(example, fn(example))` pairs, where `example` is a random list of numbers, e.g.:",
"_____no_output_____"
]
],
[
[
"random_example(sum)",
"_____no_output_____"
],
[
"random_example(min)",
"_____no_output_____"
],
[
"def train(fn, batch_size=100):\n net_block = reduce_net_block()\n compiler = td.Compiler.create((net_block, td.Scalar()))\n y, y_ = compiler.output_tensors\n loss = tf.nn.l2_loss(y - y_)\n train = tf.train.AdamOptimizer().minimize(loss)\n sess.run(tf.global_variables_initializer())\n validation_fd = compiler.build_feed_dict(random_example(fn) for _ in range(1000))\n for i in range(2000):\n sess.run(train, compiler.build_feed_dict(random_example(fn) for _ in range(batch_size)))\n if i % 100 == 0:\n print(i, sess.run(loss, validation_fd))\n return net_block\n ",
"_____no_output_____"
]
],
[
[
"Now we're going to train a neural network to approximate a reduction function of our choosing. Calling `eval()` repeatedly is super-slow and cannot exploit batch-wise parallelism, so we create a [`Compiler`](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/py/td.md#compiler). See our page on [running blocks in TensorFlow](https://github.com/tensorflow/fold/blob/master/tensorflow_fold/g3doc/running.md) for more on Compilers and how to use them effectively.",
"_____no_output_____"
]
],
[
[
"sum_block = train(sum)",
"/usr/local/google/home/madscience/nuke/v3/local/lib/python2.7/site-packages/tensorflow/python/ops/gradients_impl.py:91: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.\n \"Converting sparse IndexedSlices to a dense Tensor of unknown shape. \"\n"
],
[
"sum_block.eval([1, 1])",
"_____no_output_____"
]
],
[
[
"Breaking news: deep neural network learns to calculate 1 + 1!!!!",
"_____no_output_____"
],
[
"Of course we've done something a little sneaky here by constructing a model that can only represent associative functions and then training it to compute an associative function. The technical term for being sneaky in machine learning is [inductive bias](https://en.wikipedia.org/wiki/Inductive_bias).",
"_____no_output_____"
]
],
[
[
"min_block = train(min)",
"(0, 499.09598)\n(100, 46.026665)\n(200, 25.741219)\n(300, 18.191158)\n(400, 14.682983)\n(500, 12.306305)\n(600, 10.402517)\n(700, 8.670351)\n(800, 6.9115524)\n(900, 5.1144924)\n(1000, 3.6718786)\n(1100, 2.6184769)\n(1200, 2.0114093)\n(1300, 1.6398822)\n(1400, 1.3298371)\n(1500, 1.0525734)\n(1600, 0.77793711)\n(1700, 0.55954146)\n(1800, 0.40301239)\n(1900, 0.2982769)\n"
],
[
"min_block.eval([2, -1, 4])",
"_____no_output_____"
]
],
[
[
"Oh noes! What went wrong? Note that we trained our network to compute `min` on positive numbers; negative numbers are outside of its input distribution.",
"_____no_output_____"
]
],
[
[
"min_block.eval([0.3, 0.2, 0.9])",
"_____no_output_____"
]
],
[
[
"Well, that's better. What happens if you train the network on negative numbers as well as on positives? What if you only train on short lists and then evaluate the net on long ones? What if you used a `Fold` block instead of a `Reduce`? ... Happy Folding!",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4aab1c45d126a5128767ab720e7f861d882cf46a
| 7,279 |
ipynb
|
Jupyter Notebook
|
Image/connected_pixel_count.ipynb
|
mllzl/earthengine-py-notebooks
|
cade6a81dd4dbbfb1b9b37aaf6955de42226cfc5
|
[
"MIT"
] | 1 |
2020-03-26T04:21:15.000Z
|
2020-03-26T04:21:15.000Z
|
Image/connected_pixel_count.ipynb
|
mllzl/earthengine-py-notebooks
|
cade6a81dd4dbbfb1b9b37aaf6955de42226cfc5
|
[
"MIT"
] | null | null | null |
Image/connected_pixel_count.ipynb
|
mllzl/earthengine-py-notebooks
|
cade6a81dd4dbbfb1b9b37aaf6955de42226cfc5
|
[
"MIT"
] | null | null | null | 45.49375 | 1,031 | 0.589092 |
[
[
[
"<table class=\"ee-notebook-buttons\" align=\"left\">\n <td><a target=\"_blank\" href=\"https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/connected_pixel_count.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n <td><a target=\"_blank\" href=\"https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Image/connected_pixel_count.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n <td><a target=\"_blank\" href=\"https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=Image/connected_pixel_count.ipynb\"><img width=58px src=\"https://mybinder.org/static/images/logo_social.png\" />Run in binder</a></td>\n <td><a target=\"_blank\" href=\"https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Image/connected_pixel_count.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n</table>",
"_____no_output_____"
],
[
"## Install Earth Engine API and geemap\nInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\nThe following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet.\n\n**Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60#issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.eefolium`](https://github.com/giswqs/geemap/blob/master/geemap/eefolium.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving).",
"_____no_output_____"
]
],
[
[
"# Installs geemap package\nimport subprocess\n\ntry:\n import geemap\nexcept ImportError:\n print('geemap package not installed. Installing ...')\n subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])\n\n# Checks whether this notebook is running on Google Colab\ntry:\n import google.colab\n import geemap.eefolium as emap\nexcept:\n import geemap as emap\n\n# Authenticates and initializes Earth Engine\nimport ee\n\ntry:\n ee.Initialize()\nexcept Exception as e:\n ee.Authenticate()\n ee.Initialize() ",
"_____no_output_____"
]
],
[
[
"## Create an interactive map \nThe default basemap is `Google Satellite`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py#L13) can be added using the `Map.add_basemap()` function. ",
"_____no_output_____"
]
],
[
[
"Map = emap.Map(center=[40,-100], zoom=4)\nMap.add_basemap('ROADMAP') # Add Google Map\nMap",
"_____no_output_____"
]
],
[
[
"## Add Earth Engine Python script ",
"_____no_output_____"
]
],
[
[
"# Add Earth Engine dataset\n# Image.ConnectedPixelCount example.\n\n# Split pixels of band 01 into \"bright\" (arbitrarily defined as\n# reflectance > 0.3) and \"dim\". Highlight small (<30 pixels)\n# standalone islands of \"bright\" or \"dim\" type.\nimg = ee.Image('MODIS/006/MOD09GA/2012_03_09') \\\n .select('sur_refl_b01') \\\n .multiply(0.0001)\n\n# Create a threshold image.\nbright = img.gt(0.3)\n\n# Compute connected pixel counts stop searching for connected pixels\n# once the size of the connected neightborhood reaches 30 pixels, and\n# use 8-connected rules.\nconn = bright.connectedPixelCount(**{\n 'maxSize': 30,\n 'eightConnected': True\n})\n\n# Make a binary image of small clusters.\nsmallClusters = conn.lt(30)\n\nMap.setCenter(-107.24304, 35.78663, 8)\nMap.addLayer(img, {'min': 0, 'max': 1}, 'original')\nMap.addLayer(smallClusters.updateMask(smallClusters),\n {'min': 0, 'max': 1, 'palette': 'FF0000'}, 'cc')\n",
"_____no_output_____"
]
],
[
[
"## Display Earth Engine data layers ",
"_____no_output_____"
]
],
[
[
"Map.addLayerControl() # This line is not needed for ipyleaflet-based Map.\nMap",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4aab1ebc1bb0466d64b93f05bb13bba28d67cd0d
| 20,767 |
ipynb
|
Jupyter Notebook
|
development_notebooks/chronicle_of_matlab_coffeeshop_code.ipynb
|
dlanier/FlyingMachineFractal
|
3889bfb8b8005717de83954d4a705154e908273b
|
[
"MIT"
] | 4 |
2017-03-27T19:50:37.000Z
|
2021-07-15T03:23:03.000Z
|
development_notebooks/chronicle_of_matlab_coffeeshop_code.ipynb
|
dlanier/FlyingMachineFractal
|
3889bfb8b8005717de83954d4a705154e908273b
|
[
"MIT"
] | null | null | null |
development_notebooks/chronicle_of_matlab_coffeeshop_code.ipynb
|
dlanier/FlyingMachineFractal
|
3889bfb8b8005717de83954d4a705154e908273b
|
[
"MIT"
] | 1 |
2017-03-27T19:50:54.000Z
|
2017-03-27T19:50:54.000Z
| 40.481481 | 234 | 0.449078 |
[
[
[
"# Experimental Mathimatics: Chronicle of Matlab code - 2008 - 2015\n\n##### Whereas the discovery of Chaos, Fractal Geometry and Non-Linear Dynamical Systems falls outside the domain of analytic function in mathematical terms the path to discovery is taken as experimental computer-programming. \n\n##### Whereas existing discoveries have been most delightfully difference equations this first effor concentrates on guided random search for equations and parameters of that type.\n\n### equation and parameters data were saved in tiff file headers, matlab/python extracted to:",
"_____no_output_____"
]
],
[
[
"import os\nimport pandas as pd\nspreadsheets_directory = '../data/Matlab_Chronicle_2008-2012/'\nimages_dataframe_filename = os.path.join(spreadsheets_directory, 'Of_tiff_headers.df')\nequations_dataframe_filename = os.path.join(spreadsheets_directory, 'Of_m_files.df')\nImages_Chronicle_df = pd.read_csv(images_dataframe_filename, sep='\\t', index_col=0)\nEquations_Chronicle_df = pd.read_csv(equations_dataframe_filename, sep='\\t', index_col=0)\n\ndef get_number_of_null_parameters(df, print_out=True):\n \"\"\" Usage good_null_bad_dict = get_number_of_null_parameters(df, print_out=True)\n \n function to show the number of Images with missing or bad parameters\n because they are only reproducable with both the equation and parameter set\n Args:\n df = dataframe in format of historical images - (not shown in this notebook)\n Returns:\n pars_contidtion_dict:\n pars_contidtion_dict['good_pars']: number of good parametrs\n pars_contidtion_dict['null_pars']: number of null parameters\n pars_contidtion_dict['bad_list']: list of row numbers with bad parameters - for numeric indexing\n \"\"\"\n null_pars = 0\n good_pars = 0\n bad_list = []\n for n, row in df.iterrows():\n if row['parameters'] == []:\n null_pars += 1\n bad_list.append(n)\n else:\n good_pars += 1\n if print_out:\n print('good_pars', good_pars, '\\nnull_pars', null_pars)\n \n return {'good_pars': good_pars, 'null_pars': null_pars, 'bad_list': bad_list}\n\ndef display_images_df_columns_definition():\n \"\"\" display an explanation of the images \"\"\"\n cols = {}\n cols['image_filename'] = 'the file name as found in the header'\n cols['function_name'] = 'm-file and function name'\n cols['parameters'] = 'function parameters used to produce the image'\n cols['max_iter'] = 'escape time algorithm maximum number of iterations'\n cols['max_dist'] = 'escape time algorithm quit distance'\n cols['Colormap'] = 'Name of colormap if logged'\n cols['Center'] = 'center of image location on complex plane'\n cols['bounds_box'] = '(upper left corner) ULC, URC, LLC, LRC'\n cols['Author'] = 'author name if provied'\n cols['location'] = 'file - subdirectory location'\n cols['date'] = 'date the image file was written'\n for k, v in cols.items():\n print('%18s: %s'%(k,v))\n \ndef display_equations_df_columns_definition():\n \"\"\" display an explanation of the images \"\"\"\n cols = {}\n cols['arg_in'] = 'Input signiture of the m-file'\n cols['arg_out'] = 'Output signiture of the m-file'\n cols['eq_string'] = 'The equation as written in MATLAB'\n cols['while_test'] = 'The loop test code'\n cols['param_iterator'] = 'If parameters are iterated in the while loop'\n cols['internal_vars'] = 'Variables that were set inside the m-file'\n cols['while_lines'] = 'The actual code of the while loop'\n \n for k, v in cols.items():\n print('%15s: %s'%(k,v))\n\nprint('\\n\\tdisplay_images_df_columns_definition\\n')\ndisplay_images_df_columns_definition()\n\nprint('\\n\\tdisplay_equations_df_columns_definition\\n')\ndisplay_equations_df_columns_definition()",
"\n\tdisplay_images_df_columns_definition\n\n image_filename: the file name as found in the header\n function_name: m-file and function name\n parameters: function parameters used to produce the image\n max_iter: escape time algorithm maximum number of iterations\n max_dist: escape time algorithm quit distance\n Colormap: Name of colormap if logged\n Center: center of image location on complex plane\n bounds_box: (upper left corner) ULC, URC, LLC, LRC\n Author: author name if provied\n location: file - subdirectory location\n date: date the image file was written\n\n\tdisplay_equations_df_columns_definition\n\n arg_in: Input signiture of the m-file\n arg_out: Output signiture of the m-file\n eq_string: The equation as written in MATLAB\n while_test: The loop test code\n param_iterator: If parameters are iterated in the while loop\n internal_vars: Variables that were set inside the m-file\n while_lines: The actual code of the while loop\n"
],
[
"print('shape:', \n Images_Chronicle_df.shape, \n 'Number of unique files:', \n Images_Chronicle_df['image_filename'].nunique())\n\nprint('Number of unique functions used:', \n Images_Chronicle_df['function_name'].nunique())\npar_stats_dict = get_number_of_null_parameters(Images_Chronicle_df) # show parameters data\nprint('\\nFirst 5 lines')\nImages_Chronicle_df.head() # show top 5 lines\n",
"shape: (3725, 11) Number of unique files: 3725\nNumber of unique functions used: 71\ngood_pars 3725 \nnull_pars 0\n\nFirst 5 lines\n"
],
[
"print(Equations_Chronicle_df.shape)\nEquations_Chronicle_df.head()",
"(522, 7)\n"
],
[
"cols = list(Equations_Chronicle_df.columns)\nfor c in cols:\n print(c)",
"arg_in\narg_out\neq_string\nwhile_test\nparam_iterator\ninternal_vars\nwhile_lines\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4aab36eaec1d03d8dc6d52784d5156b0b85c1687
| 34,285 |
ipynb
|
Jupyter Notebook
|
data/xml_data_parsing.ipynb
|
pgdeniverville/Hidden-Sector-Limits
|
3ee1377726b299883f5d31e58fa1b725aa406ff7
|
[
"MIT"
] | null | null | null |
data/xml_data_parsing.ipynb
|
pgdeniverville/Hidden-Sector-Limits
|
3ee1377726b299883f5d31e58fa1b725aa406ff7
|
[
"MIT"
] | null | null | null |
data/xml_data_parsing.ipynb
|
pgdeniverville/Hidden-Sector-Limits
|
3ee1377726b299883f5d31e58fa1b725aa406ff7
|
[
"MIT"
] | null | null | null | 34.736575 | 887 | 0.544057 |
[
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom scipy import interpolate as interp",
"_____no_output_____"
],
[
"def linear_translate(x1,x2,X1,X2):\n B=(X1-X2)/(x1-x2)\n A=X1-B*x1\n return [A,B]\ndef linear_translate_axis(Ax,Bx,arr):\n return Ax+Bx*arr\ndef log_translate_axis(Ax,Bx,arr):\n return 10**(Ax+Bx*arr)\ndef log_translate(x1,x2,X1,X2):\n B=np.log10(float(X1)/float(X2))/(x1-x2)\n A=np.log10(X1)-B*x1\n return [A,B]\ndef format_xml_arr(arr):\n for i in range(1,len(arr)):\n arr[i]+=arr[i-1]\ndef log_translate_arr(Ax,Bx,Ay,By,arr):\n return 10**([Ax,Ay]+[Bx,By]*arr)",
"_____no_output_____"
],
[
"def format_xml_file(file):\n arr=[[0,0]]\n with open(file) as f:\n dat=f.read().splitlines()\n hold=''\n delete_list=[0]\n for i in range(0,len(dat)):\n dat[i]=dat[i].split(',')\n #print(arr[-1],dat[i],hold)\n if dat[i][0].isalpha():\n hold=dat[i][0]\n else:\n if hold=='M':\n arr.append([float(dat[i][0]),float(dat[i][1])])\n elif hold=='m' or hold=='l':\n arr.append([arr[-1][0]+float(dat[i][0]),arr[-1][1]+float(dat[i][1])])\n elif hold=='H':\n arr.append([float(dat[i][0]),arr[-1][1]])\n elif hold=='h':\n arr.append([arr[-1][0]+float(dat[i][0]),arr[-1][1]])\n elif hold=='V':\n arr.append([arr[-1][0],float(dat[i][0])])\n elif hold=='v':\n arr.append([arr[-1][0],arr[-1][1]+float(dat[i][0])])\n \n del arr[0]\n return arr",
"_____no_output_____"
],
[
"def format_xml(file_in,file_out):\n a=format_xml_file(file_in)\n b=np.array(a)\n Ax,Bx=log_translate(x1,x2,X1,X2)\n Ay,By=log_translate(y1,y2,Y1,Y2)\n c=log_translate_arr(Ax,Bx,Ay,By,b)\n np.savetxt(file_out,c)",
"_____no_output_____"
],
[
"fp_in=\"vector_portal_visible_raw/\"\nfp_out=\"vector_portal_visible_formatted/\"",
"_____no_output_____"
],
[
"x1=102.117;x2=403.91;X1=1e-2;X2=1;\ny1=211.11;y2=98.4858;Y1=1e-3;Y2=2e-4;",
"_____no_output_____"
],
[
"format_xml(fp_in+\"BES3_1705.04265.dat\",fp_out+\"BES3_2017_formatted.dat\")",
"_____no_output_____"
],
[
"format_xml(fp_in+\"APEX1108.2750.dat\",fp_out+\"APEX2011_formatted.dat\")",
"_____no_output_____"
],
[
"#1906.00176\nx1=275.6694;x2=234.62337;X1=1;X2=1e-1;\ny1=59.555832;y2=130.28009;Y1=1e-5;Y2=1e-4;\nAx,Bx=log_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nNA64_2019=np.array(format_xml_file(\"NA64_2019_1906.00176.dat\"))\nNA64_2019[:,0]=log_translate_axis(Ax,Bx,NA64_2019[:,0])\nNA64_2019[:,1]=log_translate_axis(Ay,By,NA64_2019[:,1])\nnp.savetxt(\"NA64_2019_formatted.dat\",NA64_2019)",
"_____no_output_____"
],
[
"#1906.00176\nx1=145.30411;x2=234.62337;X1=1e-2;X2=1e-1;\ny1=96.63295;y2=67.436142;Y1=1e-13;Y2=1e-14;\nAx,Bx=log_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nNA64_2019=np.array(format_xml_file(\"NA64_2019_1906.00176_2.dat\"))\nNA64_2019[:,0]=log_translate_axis(Ax,Bx,NA64_2019[:,0])\nNA64_2019[:,1]=log_translate_axis(Ay,By,NA64_2019[:,1])\nnp.savetxt(\"NA64_2019_aD0.5_formatted.dat\",NA64_2019)",
"_____no_output_____"
],
[
"#1807.05884.dat\nx1=138.435;x2=376.021;X1=1e-2;X2=1e-1;\ny1=90.8576;y2=178.355;Y1=1e-14;Y2=1e-12;\nAx,Bx=log_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nE137_u=np.array(format_xml_file(\"E1371807.05884.dat\"))\nE137_u[:,0]=log_translate_axis(Ax,Bx,E137_u[:,0])\nE137_u[:,1]=log_translate_axis(Ay,By,E137_u[:,1])\nnp.savetxt(\"E137update_Y3_0.5.dat\",E137_u)",
"_____no_output_____"
],
[
"#1311.0216\nx1=1452.5;x2=4420;X1=0.1;X2=0.5;\ny1=2427.5;y2=3237.5;Y1=1e-4;Y2=1e-3;\nAx,Bx=linear_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nhadesa=np.array(format_xml_file(fp_in+\"HADES1311.0216.dat\"))\nhadesb=np.array(format_xml_file(fp_in+\"HADES1311.0216b.dat\"))\nhadesc=np.array(format_xml_file(fp_in+\"HADES1311.0216c.dat\"))\nhadesd=np.array(format_xml_file(fp_in+\"HADES1311.0216d.dat\"))\nhades=np.concatenate((hadesa,hadesb,hadesc,hadesd),axis=0)\nhades[:,0]=linear_translate_axis(Ax,Bx,hades[:,0])\nhades[:,1]=log_translate_axis(Ay,By,hades[:,1])\nhades[:,1]=[math.sqrt(y) for y in hades[:,1]]\nnp.savetxt(fp_out+\"HADES2013_formatted.dat\",hades)",
"_____no_output_____"
],
[
"#1409.0851\nx1=100.501;x2=489.907;X1=10;X2=90;\ny1=309.828;y2=91.8798;Y1=1e-5;Y2=1e-6;\nAx,Bx=linear_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nphenix=np.array(format_xml_file(fp_in+\"PHENIX1409.0851.dat\"))\nphenix[:,0]=linear_translate_axis(Ax,Bx,phenix[:,0])/1000\nphenix[:,1]=log_translate_axis(Ay,By,phenix[:,1])\nphenix[:,1]=[math.sqrt(y) for y in phenix[:,1]]\nnp.savetxt(fp_out+\"PHENIX2014_formatted.dat\",phenix)",
"_____no_output_____"
],
[
"#1304.0671\nx1=2152.5;x2=4772.5;X1=40;X2=100;\ny1=2220;y2=3805;Y1=1e-5;Y2=1e-4;\nAx,Bx=linear_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nwasa=np.array(format_xml_file(fp_in+\"WASA1304.0671.dat\"))\nwasa[:,0]=linear_translate_axis(Ax,Bx,wasa[:,0])/1000\nwasa[:,1]=log_translate_axis(Ay,By,wasa[:,1])\nwasa[:,1]=[math.sqrt(y) for y in wasa[:,1]]\nnp.savetxt(fp_out+\"WASA2013_formatted.dat\",wasa)",
"_____no_output_____"
],
[
"#1404.5502\nx1=906.883;x2=2133.43;X1=100;X2=300;\ny1=1421.71;y2=821.906;Y1=1e-5;Y2=1e-6;\nAx,Bx=linear_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\na1=format_xml_file(fp_in+\"A1_1404.5502.dat\")\na1=np.array(a1)\na1[:,0]=linear_translate_axis(Ax,Bx,a1[:,0])/1000\na1[:,1]=log_translate_axis(Ay,By,a1[:,1])\na1[:,1]=[math.sqrt(y) for y in a1[:,1]]\nnp.savetxt(fp_out+\"A12014_formatted.dat\",a1)",
"_____no_output_____"
],
[
"#0906.0580v1\nx1=154.293;x2=277.429;X1=1e-2;X2=1;\ny1=96.251;y2=208.027;Y1=1e-4;Y2=1e-8;\nformat_xml(fp_in+\"E774_0906.0580.dat\",fp_out+\"E774_formatted.dat\")\nformat_xml(fp_in+\"E141_0906.0580.dat\",fp_out+\"E141_formatted.dat\")\nformat_xml(fp_in+\"E137_0906.0580.dat\",fp_out+\"E137_formatted.dat\")",
"_____no_output_____"
],
[
"1504.00607\nx1=1375;x2=4242.5;X1=10;X2=100;\ny1=4020;y2=2405;Y1=1e-5;Y2=1e-6\nAx,Bx=log_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nna48=format_xml_file(fp_in+\"NA482_1504.00607.dat\")\nna48=np.array(na48)\nna48=log_translate_arr(Ax,Bx,Ay,By,na48)\nna48[:,0]=na48[:,0]/1000\nna48[:,1]=[math.sqrt(y) for y in na48[:,1]]\nnp.savetxt(fp_out+\"NA48_2_formatted.dat\",na48)",
"_____no_output_____"
],
[
"#1406.2980\nx1=250.888;x2=400.15;X1=1e-1;X2=1;\ny1=211.11;y2=98.4858;Y1=1e-3;Y2=2e-4;\nformat_xml(fp_in+\"babar1406.2980.dat\",fp_out+\"Babar2014_formatted.dat\")\nformat_xml(fp_in+\"babar0905.4539.dat\",fp_out+\"babar2009_formatted.dat\")",
"_____no_output_____"
],
[
"#1509.00740\nx1=96.3223;x2=151.6556;X1=10;X2=100;\ny1=107.91647;y2=35.94388;Y1=1e-5;Y2=1e-7;\nAx,Bx=log_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nkloe2015=np.array(format_xml_file(fp_in+\"KLOE1509.00740.dat\"))\nkloe2015=log_translate_arr(Ax,Bx,Ay,By,kloe2015)\nkloe2015[:,0]=kloe2015[:,0]/1000\nkloe2015[:,1]=[math.sqrt(y) for y in kloe2015[:,1]]\nnp.savetxt(fp_out+\"KLOE2015_formatted.dat\",kloe2015)\n\nkloe2013=np.array(format_xml_file(fp_in+\"KLOE1110.0411.dat\"))\nkloe2013=log_translate_arr(Ax,Bx,Ay,By,kloe2013)\nkloe2013[:,0]=kloe2013[:,0]/1000\nkloe2013[:,1]=[math.sqrt(y) for y in kloe2013[:,1]]\nnp.savetxt(fp_out+\"KLOE2013_formatted.dat\",kloe2013)\n\nkloe2014=np.array(format_xml_file(fp_in+\"KLOE1404.7772.dat\"))\nkloe2014=log_translate_arr(Ax,Bx,Ay,By,kloe2014)\nkloe2014[:,0]=kloe2014[:,0]/1000\nkloe2014[:,1]=[math.sqrt(y) for y in kloe2014[:,1]]\nnp.savetxt(fp_out+\"KLOE2014_formatted.dat\",kloe2014)",
"_____no_output_____"
],
[
"#1603.06086\nx1=0;x2=38.89273;X1=0;X2=200;\ny1=-376.57767;y2=-215.18724;Y1=1e-7;Y2=1e-4;\nAx,Bx=linear_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nkloe2016=np.array(format_xml_file(fp_in+\"KLOE1603.06086.dat\"))\nkloe2016[:,0]=linear_translate_axis(Ax,Bx,kloe2016[:,0])/1000\nkloe2016[:,1]=log_translate_axis(Ay,By,kloe2016[:,1])\nkloe2016[:,1]=[math.sqrt(y) for y in kloe2016[:,1]]\nnp.savetxt(fp_out+\"KLOE2016_formatted.dat\",kloe2016)",
"_____no_output_____"
],
[
"xenon10e=np.loadtxt(\"xenon10e.dat\",delimiter=',')\nformat_xml_arr(xenon10e)\nx1=159; x2=217; X1=0.010; X2=0.100\ny1=36; y2=83; Y1=1e-34; Y2=1e-36\nAx,Bx=log_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nxenon10e=log_translate_arr(Ax,Bx,Ay,By,xenon10e)",
"_____no_output_____"
],
[
"np.savetxt(\"xenon10e_formatted.csv\",xenon10e,delimiter=',')",
"_____no_output_____"
],
[
"#1703.00910\n#This is FDM=1 case, Xenon10. It basically beats Xenon100 everywhere.\nxenon10e2017=np.loadtxt(\"1703.00910.xenonelimits.dat\",delimiter=',')\nformat_xml_arr(xenon10e2017)\nx1=93.305; x2=195.719; X1=0.010; X2=0.100\ny1=86.695; y2=151.848; Y1=1e-38; Y2=1e-37\nAx,Bx=log_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nxenon10e2017=log_translate_arr(Ax,Bx,Ay,By,xenon10e2017)\nxenon100e2017=np.loadtxt(\"1703.00910.xenon100elimits.dat\",delimiter=',')\nformat_xml_arr(xenon100e2017)\nxenon100e2017=log_translate_arr(Ax,Bx,Ay,By,xenon100e2017)",
"_____no_output_____"
],
[
"np.savetxt(\"xenon10e_2017_formatted.csv\",xenon10e2017,delimiter=',')\nnp.savetxt(\"xenon100e_2017_formatted.csv\",xenon100e2017,delimiter=',')",
"_____no_output_____"
],
[
"babar2017=np.loadtxt(\"babar2017.dat\",delimiter=',')\nformat_xml_arr(babar2017)\ny1=211.843; y2=50.1547; Y1=1e-3; Y2=1e-4;\nx1=181.417; x2=430.866; X1=1e-2; X2=1.0\nAx,Bx=log_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nbabar2017_formatted=log_translate_arr(Ax,Bx,Ay,By,babar2017)",
"_____no_output_____"
],
[
"np.savetxt(\"babar2017_formatted.dat\",babar2017_formatted,delimiter=' ')",
"_____no_output_____"
],
[
"NA64_2016 = np.loadtxt(\"NA64_2016_data.dat\",delimiter=',')\nformat_xml_arr(NA64_2016)\nNA64_2017 = np.loadtxt(\"NA64_2017_data.dat\",delimiter=',')\nformat_xml_arr(NA64_2017)\nNA64_2018 = np.loadtxt(\"NA64_2018plus_data.dat\",delimiter=',')\nformat_xml_arr(NA64_2018)\ny1=186.935;y2=105.657;Y1=1e-4;Y2=2e-5;\nx1=202.677;x2=314.646;X1=1e-2;X2=1e-1;\nAx,Bx=log_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nNA64_2016_formatted=log_translate_arr(Ax,Bx,Ay,By,NA64_2016)\nNA64_2017_formatted=log_translate_arr(Ax,Bx,Ay,By,NA64_2017)\nNA64_2018_formatted=log_translate_arr(Ax,Bx,Ay,By,NA64_2018)",
"_____no_output_____"
],
[
"np.savetxt(\"NA64_2016_formatted.dat\",NA64_2016_formatted,delimiter=' ')\nnp.savetxt(\"NA64_2017_formatted.dat\",NA64_2017_formatted,delimiter=' ')\nnp.savetxt(\"NA64_2018_formatted.dat\",NA64_2018_formatted,delimiter=' ')",
"_____no_output_____"
],
[
"anomalon_1705_06726= np.loadtxt(\"Anomalon.dat\",delimiter=',')\nformat_xml_arr(anomalon_1705_06726)\nBtoKX_1705_06726= np.loadtxt(\"1705.06726.BtoKX.dat\",delimiter=',')\nformat_xml_arr(BtoKX_1705_06726)\nZtogammaX_1705_06726= np.loadtxt(\"1705.06726.ZtogammaX.dat\",delimiter=',')\nformat_xml_arr(ZtogammaX_1705_06726)\nKtopiX_1705_06726= np.loadtxt(\"1705.06726.KtopiX.dat\",delimiter=',')\nformat_xml_arr(KtopiX_1705_06726)\ny1=389.711;y2=188.273;Y1=10**-2;Y2=10**-5;\nx1=272.109;x2=478.285;X1=10**-2;X2=1;\nAx,Bx=log_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nanomalon_1705_06726_formatted=log_translate_arr(Ax,Bx,Ay,By,anomalon_1705_06726)\nBtoKX_1705_06726_formatted=log_translate_arr(Ax,Bx,Ay,By,BtoKX_1705_06726)\nZtogammaX_1705_06726_formatted=log_translate_arr(Ax,Bx,Ay,By,ZtogammaX_1705_06726)\nKtopiX_1705_06726_formatted=log_translate_arr(Ax,Bx,Ay,By,KtopiX_1705_06726)",
"_____no_output_____"
],
[
"np.savetxt(\"Anomalon_formatted.dat\",anomalon_1705_06726_formatted,delimiter=' ')\nnp.savetxt(\"1705.06726.BtoKX_formatted.dat\",BtoKX_1705_06726_formatted,delimiter=' ')\n np.savetxt(\"1705.06726.ZtogammaX_formatted.dat\",ZtogammaX_1705_06726_formatted,delimiter=' ')\nnp.savetxt(\"1705.06726.KtopiX_formatted.dat\",KtopiX_1705_06726_formatted,delimiter=' ')",
"_____no_output_____"
],
[
"anomalon_1705_06726_formatted[:,1]**2",
"_____no_output_____"
],
[
"NA64_2018 = np.loadtxt(\"NA64_2018.dat\",delimiter=',')\nformat_xml_arr(NA64_2018)\nx1=125.29126;x2=200.49438;X1=1e-2;X2=1e-1;\ny1=116.07875;y2=193.88962;Y1=1e-4;Y2=1e-3;\nAx,Bx=log_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nNA64_2018_formatted = log_translate_arr(Ax,Bx,Ay,By,NA64_2018)\nnp.savetxt(\"NA64_2017_formatted.dat\",NA64_2018_formatted,delimiter=' ')",
"_____no_output_____"
],
[
"CDMSelec = np.loadtxt(\"1804.10697.SuperCDMS.dat\",delimiter=',')\nformat_xml_arr(CDMSelec)\nx1=105.82982;x2=259.22375;X1=1e-3;X2=100e-3\ny1=264.07059;y2=80.258824;Y1=1e-27;Y2=1e-41\nAx,Bx=log_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nCDMSelec_2018_formatted=log_translate_arr(Ax,Bx,Ay,By,CDMSelec)\nnp.savetxt(\"CDMS_electron_2018_formatted.dat\",CDMSelec_2018_formatted,delimiter=' ')",
"_____no_output_____"
],
[
"SENSEI2018_1=np.loadtxt(\"SENSEI2018_1.dat\",delimiter=',')\nSENSEI2018_2=np.loadtxt(\"SENSEI2018_2.dat\",delimiter=',')\nSENSEI2018_3=np.loadtxt(\"SENSEI2018_3.dat\",delimiter=',')\nSENSEI2018_4=np.loadtxt(\"SENSEI2018_4.dat\",delimiter=',')\nSENSEI2018=[SENSEI2018_1,SENSEI2018_2,SENSEI2018_3,SENSEI2018_4]\nfor arr in SENSEI2018:\n format_xml_arr(arr)\nx_set=np.unique(np.append(np.append(np.append(SENSEI2018[0][:,0],SENSEI2018[1][:,0]),\n SENSEI2018[2][:,0]),SENSEI2018[3][:,0]))\ninterp_arr = [interp.interp1d(arr[:,0],arr[:,1],bounds_error=False,fill_value=10000) for arr in SENSEI2018]\nx_set=[x for x in x_set]\nSENSEI2018f=np.array([[x,min([func(x) for func in interp_arr]).tolist()] for x in x_set])\nx1=104.473;x2=192.09;X1=1e-3;X2=10e-3;\ny1=347.496;y2=318.992;Y1=1e-28;Y2=1e-29;\nAx,Bx=log_translate(x1,x2,X1,X2)\nAy,By=log_translate(y1,y2,Y1,Y2)\nSENSEI2018_formatted=log_translate_arr(Ax,Bx,Ay,By,SENSEI2018f)\nnp.savetxt(\"SENSEI2018_formatted.dat\",SENSEI2018_formatted,delimiter=' ')",
"_____no_output_____"
],
[
"interp_arr[0](1)",
"_____no_output_____"
],
[
"SENSEI2018f",
"_____no_output_____"
],
[
"x_set",
"_____no_output_____"
],
[
"SENSEI2018f=[[x[0],min([func(x) for func in interp_arr])[0]] for x in x_set]",
"_____no_output_____"
],
[
"x_set=map(np.unique,sorted(np.append(np.append(np.append(SENSEI2018[0][:,0],SENSEI2018[1][:,0]),\n SENSEI2018[2][:,0]),SENSEI2018[3][:,0])))",
"_____no_output_____"
],
[
"SENSEI2018",
"_____no_output_____"
],
[
"interp.interp1d(SENSEI2018[0]",
"_____no_output_____"
],
[
"sorted(np.append(np.append(np.append(SENSEI2018[0][:,0],SENSEI2018[1][:,0]),SENSEI2018[2][:,0]),SENSEI2018[3][:,0]))",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4aab5f6d73c12edbabbdb702d6feece1ff44a427
| 5,429 |
ipynb
|
Jupyter Notebook
|
NOTEBOOKS/beakerx/0.9.6/C4E Scala Epsilon Proximity.ipynb
|
Clustering4Ever/Notebooks
|
99575dcbb4d7bb2129b1be369685bfb5783d5eff
|
[
"Apache-2.0"
] | 3 |
2019-07-23T15:03:55.000Z
|
2019-07-26T20:49:26.000Z
|
NOTEBOOKS/beakerx/0.9.6/C4E Scala Epsilon Proximity.ipynb
|
Clustering4Ever/Notebooks
|
99575dcbb4d7bb2129b1be369685bfb5783d5eff
|
[
"Apache-2.0"
] | null | null | null |
NOTEBOOKS/beakerx/0.9.6/C4E Scala Epsilon Proximity.ipynb
|
Clustering4Ever/Notebooks
|
99575dcbb4d7bb2129b1be369685bfb5783d5eff
|
[
"Apache-2.0"
] | null | null | null | 23.102128 | 177 | 0.562535 |
[
[
[
"# [Clustering4Ever](https://github.com/Clustering4Ever/Clustering4Ever) by [LIPN](https://lipn.univ-paris13.fr/) [A3](https://lipn.univ-paris13.fr/accueil/equipe/a3/) team",
"_____no_output_____"
]
],
[
[
"%%classpath add mvn\norg.clustering4ever clustering4ever_2.11 0.9.6",
"_____no_output_____"
],
[
"%%classpath add mvn\norg.apache.spark spark-core_2.11 2.4.3",
"_____no_output_____"
]
],
[
[
"# C4E Scala Epsilon Proximity",
"_____no_output_____"
]
],
[
[
"import org.clustering4ever.clustering.epsilonproximity.scala.EpsilonProximityScalar\nimport org.clustering4ever.math.distances.scalar.Euclidean\nimport org.clustering4ever.clusterizables.EasyClusterizable\nimport org.clustering4ever.vectors.ScalarVector\nimport org.clustering4ever.clustering.indices.MultiExternalIndicesLocal\nimport scala.io.Source\nimport scala.collection.mutable\nimport scala.collection.parallel",
"_____no_output_____"
],
[
"%%bash\nwget -P /tmp/ http://www.clustering4ever.org/Datasets/Aggregation/aggregation.csv\nwget -P /tmp/ http://www.clustering4ever.org/Datasets/Aggregation/labels",
"_____no_output_____"
]
],
[
[
"### Load data",
"_____no_output_____"
]
],
[
[
"val path = \"/tmp/aggregation.csv\"\nval data = scala.io.Source.fromFile(path).getLines.toSeq.par\n .map( x => x.split(\",\").map(_.toDouble)).zipWithIndex\n .map{ case (v, id) => EasyClusterizable(id.toLong, ScalarVector(v)) }\nval labelsPath = \"/tmp/labels\"\nval labels = scala.io.Source.fromFile(labelsPath).getLines.toSeq.map(_.toInt)",
"_____no_output_____"
]
],
[
[
"## Parameters ",
"_____no_output_____"
]
],
[
[
"val metric = Euclidean(false)\nval eps = \"knn:25\"\nval eps2 = \"eps:1.5\"",
"_____no_output_____"
]
],
[
[
"## Run Epsilon Proximity ",
"_____no_output_____"
]
],
[
[
"val t1 = System.nanoTime\nval modelEps = EpsilonProximityScalar(eps, metric).fit(data)\nval t2 = System.nanoTime\n(t2 - t1) / 1000000000D",
"_____no_output_____"
],
[
"val clusterizedd = modelEps.obtainInputDataClustering(data)\nval rawd = clusterizedd.map(_.v.vector.toArray).toArray\nval labelsPred = clusterizedd.map(_.clusterIDs.last).toArray",
"_____no_output_____"
],
[
"val plot = new Plot()\n(rawd zip labelsPred).groupBy(_._2).values.foreach(x => {\n val Array(xx, yy) = x.map(_._1).transpose\n plot.add(new Points{x = xx\n y = yy})\n})\nplot",
"_____no_output_____"
]
],
[
[
"## Compute NMI with founded class",
"_____no_output_____"
]
],
[
[
"val indices = MultiExternalIndicesLocal(labelsPred zip labels)\nval nmi = indices.nmiSQRT",
"_____no_output_____"
],
[
"val arand = indices.arand",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4aab5fb965a3b90ced54f6f251e49c6d4365f68a
| 287,278 |
ipynb
|
Jupyter Notebook
|
ltv_prediction.ipynb
|
eugtanchik/tilting-point
|
75ed98ba03dc1622f9872ad3d520d79587770fc1
|
[
"MIT"
] | null | null | null |
ltv_prediction.ipynb
|
eugtanchik/tilting-point
|
75ed98ba03dc1622f9872ad3d520d79587770fc1
|
[
"MIT"
] | null | null | null |
ltv_prediction.ipynb
|
eugtanchik/tilting-point
|
75ed98ba03dc1622f9872ad3d520d79587770fc1
|
[
"MIT"
] | null | null | null | 104.388808 | 140,332 | 0.767615 |
[
[
[
"## Tilting Point Data Test (Part 2)\n- You are free to use any package that you deem necessary, the basic pacakge is already imported\n- After each question, there will be an answer area, you can add as many cells as you deem necessary between answer and following question\n- The accuracy is less important, the path to get there is what's important",
"_____no_output_____"
]
],
[
[
"import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.linear_model import LinearRegression, LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score, mean_squared_error\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"### Question: Data Analysis and Machine Learning",
"_____no_output_____"
],
[
"Attached is a Game of War type game, given the data, please build a model to predict players' LTV\n1. What kind of exploratory analysis would you want to conduct?\n2. What procedure would you take to build the model?\n3. How would you validate the result?\n4. Please choose one model, and perform from step 1 to step 3 in order\n5. How would you productionalize it?",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv(os.path.join('data', 'ltv_data.csv'))\ndf.head()",
"_____no_output_____"
]
],
[
[
"##### Answer below",
"_____no_output_____"
],
[
"### 1. What kind of exploratory analysis would you want to conduct?",
"_____no_output_____"
],
[
"I would like to conduct CRISP-DM approach for exploratory analysis of given data.",
"_____no_output_____"
],
[
"The CRISP-DM Process (Cross Industry Process for Data Mining). It mainly consists of the following parts:\n\n* Business Understanding\n* Data Understanding\n* Data Preparation\n* Data Modeling\n* Evaluation\n* Deployment\n",
"_____no_output_____"
],
[
"### Business Understading",
"_____no_output_____"
],
[
"It looks pretty obvious that we want to be able to predict our users LTV by some available data from game play, and to be confident in the prediction for better decision making. ",
"_____no_output_____"
],
[
"### Data Understanding",
"_____no_output_____"
],
[
"Let's have a look at given data. All its columns are numerical. We don't have any categorical data. It means that all our possible factors are quantitative.",
"_____no_output_____"
]
],
[
[
"df.describe()",
"_____no_output_____"
]
],
[
[
"**1.** Let's explore data shape",
"_____no_output_____"
]
],
[
[
"df.shape",
"_____no_output_____"
]
],
[
[
"**2.** Which columns had no missing values? Provide a set of column names that have no missing values.",
"_____no_output_____"
]
],
[
[
"no_nulls = set(df.dropna(axis='columns').columns.tolist())\nprint(no_nulls)",
"{'first_session_length'}\n"
]
],
[
[
"**3.** Which columns have the most missing values? Provide a set of column names that have more than 75% if their values missing.",
"_____no_output_____"
]
],
[
[
"missing_df = df.isnull().sum(axis=0) / len(df)\nmissing_df[missing_df > 0.75].index.tolist()",
"_____no_output_____"
],
[
"df['vip_level'].unique()",
"_____no_output_____"
],
[
"df['core_level'].unique()",
"_____no_output_____"
],
[
"vip_levels = df['vip_level'].value_counts()\n\n(vip_levels/df.shape[0]).plot(kind=\"bar\");\nplt.title(\"What kind of vip level have users mostly?\");",
"_____no_output_____"
],
[
"core_levels = df['core_level'].value_counts()\n\n(core_levels/df.shape[0]).plot(kind=\"bar\");\nplt.title(\"What kind of vip level have users mostly?\");",
"_____no_output_____"
]
],
[
[
"### 2. What procedure would you take to build the model?",
"_____no_output_____"
],
[
"#### Supervised ML Process\n\n* Instantiate Model\n* Fit Model\n* Predict on test set\n* Score Model using Metric",
"_____no_output_____"
],
[
"### Data Preparation",
"_____no_output_____"
],
[
"**4.** Mainly, we might answer the question, what columns relate to LTV?",
"_____no_output_____"
],
[
"For that purpose let's calculate the Correlation Matrix",
"_____no_output_____"
]
],
[
[
"corr = df.corr()\n\ncorr",
"_____no_output_____"
]
],
[
[
"And plot a heatmap of that matrix",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(figsize=(12, 9))\nsns.heatmap(\n corr, \n xticklabels=corr.columns, \n yticklabels=corr.columns, \n annot=True, \n fmt='.2f', \n linewidths=.5, \n ax=ax\n)",
"_____no_output_____"
]
],
[
[
"As we can see from the Correlation Matrix, the most relevant for LTV are `day7_rev` and `day30_rev`, as it was expected. Aslo `session_length` as well as `core_level` has a weak linear influence on LTV. Other factors are negligable. Of course, Correlation Matrix only describes possible close to linear relation between our numeric features and predictable variable. To get some non-linear relations we need to conduct more advanced analysis.",
"_____no_output_____"
],
[
"Let's plot some histograms on picked variables to see their distribution.",
"_____no_output_____"
]
],
[
[
"df[['day7_rev', 'day30_rev', 'session_length', 'core_level', 'ltv']].hist(figsize=(16, 9));",
"_____no_output_____"
]
],
[
[
"### Working with Missing Values\n\n* Remove\n* Impute\n* Work Around",
"_____no_output_____"
],
[
"**1.** What proportion of data is reported LTV?",
"_____no_output_____"
]
],
[
[
"df.ltv.notna()",
"_____no_output_____"
],
[
"prop_ltv = df.ltv.notna().mean()\n\nprop_ltv",
"_____no_output_____"
]
],
[
[
"**2.** Remove the rows with missing LTV values from dataset",
"_____no_output_____"
]
],
[
[
"ltv_rm = df.dropna(subset=['ltv'], axis=0)\n\nltv_rm",
"_____no_output_____"
],
[
"df.ltv.describe()",
"_____no_output_____"
],
[
"all_rm = df.dropna(axis=0)\n\nall_rm",
"_____no_output_____"
]
],
[
[
"### 3. How would you validate the result?",
"_____no_output_____"
],
[
"About the Coefficient of Determination or [R2 Score](https://en.wikipedia.org/wiki/Coefficient_of_determination)",
"_____no_output_____"
],
[
"### 4. Please choose one model, and perform from step 1 to step 3 in order",
"_____no_output_____"
],
[
"For the purpose of simplicity, let's consider **Linear Regression Model** to predict LTV. We are going to split randomly our dataset on `train` and `test` samples, fit our model on training part of the data, and validate the model on testing part. We will use **Coefficient of Determination** as our validation metric.",
"_____no_output_____"
]
],
[
[
"def test_linear_model(data_frame, features):\n X = data_frame[features] # create X using explanatory variables\n y = data_frame.ltv\n\n # split data into training and test data, and fit a linear model\n X_train, X_test, y_train, y_test = train_test_split(X, y , test_size=.30, random_state=42)\n lm_model = LinearRegression(normalize=True)\n\n lm_model.fit(X_train, y_train)\n\n y_test_preds = lm_model.predict(X_test) # predictions using X and lm_model\n rsquared_score = r2_score(y_test, y_test_preds) # rsquared for comparing test and preds from lm_model\n length_y_test = len(y_test) # num in y_test\n mse = mean_squared_error(y_test, y_test_preds)\n \n print(\"The r-squared score for the model was {} on {} values.\".format(rsquared_score, length_y_test))\n",
"_____no_output_____"
]
],
[
[
"Let's check our model on a dataset with completely removed missing values.",
"_____no_output_____"
]
],
[
[
"test_linear_model(all_rm, list(all_rm.columns)[:-1])\ntest_linear_model(all_rm, ['day7_rev', 'day30_rev', 'session_length', 'core_level'])",
"The r-squared score for the model was 0.2581861486815522 on 731 values.\nThe r-squared score for the model was 0.2617475150764016 on 731 values.\n"
]
],
[
[
"That's rather poor result. Let's consider some approaches to improve that.",
"_____no_output_____"
],
[
"### Common Imputation Methods\n\n* Mean\n* Median\n* Mode\n* Predict using other columns and a supervised model\n* Find similar rows and fill with their values (k-NN approach)\n\nBy imputing, we are diluting the impotrance of that feature. Variability in features is what allows us to use them to predict another variable well.",
"_____no_output_____"
]
],
[
[
"drop_ltv_df = df.dropna(subset=['ltv']) # drop the rows with missing ltv\n\n# test look\ndrop_ltv_df.head()",
"_____no_output_____"
],
[
"fill_df = drop_ltv_df.fillna(drop_ltv_df.mean()) # fill all missing values with the mean of the column.\n\n# test look\nfill_df.head()",
"_____no_output_____"
]
],
[
[
"By the way, imputing procedure in our case has not really changed Correlation Matrix.",
"_____no_output_____"
]
],
[
[
"fill_df.corr()",
"_____no_output_____"
]
],
[
[
"Now we managed to improve the quality of the model by mean imputation method for missing values in the dataset.",
"_____no_output_____"
]
],
[
[
"test_linear_model(all_rm, list(all_rm.columns)[:-1])\ntest_linear_model(fill_df, list(fill_df.columns)[:-1])\ntest_linear_model(fill_df, ['day7_rev', 'day30_rev', 'session_length', 'core_level'])",
"The r-squared score for the model was 0.2581861486815522 on 731 values.\nThe r-squared score for the model was 0.29776690954527874 on 959 values.\nThe r-squared score for the model was 0.3094896480770042 on 959 values.\n"
]
],
[
[
"### 5. How would you productionalize it?",
"_____no_output_____"
],
[
"This model could be productionalized by Python Package or Cloud micro-service depends on its possible usage.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.