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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4ac2a8243b4e1d439f8a1bcfac4b8f03ca7fab4c
| 39,627 |
ipynb
|
Jupyter Notebook
|
Code/Techne_ML_workbook.ipynb
|
nationalarchives/TechneTraining
|
e12fc71beaad2e3679eafdd2c44dc123a94b30f1
|
[
"MIT"
] | null | null | null |
Code/Techne_ML_workbook.ipynb
|
nationalarchives/TechneTraining
|
e12fc71beaad2e3679eafdd2c44dc123a94b30f1
|
[
"MIT"
] | null | null | null |
Code/Techne_ML_workbook.ipynb
|
nationalarchives/TechneTraining
|
e12fc71beaad2e3679eafdd2c44dc123a94b30f1
|
[
"MIT"
] | 1 |
2021-04-11T07:11:36.000Z
|
2021-04-11T07:11:36.000Z
| 37.956897 | 589 | 0.55283 |
[
[
[
"<a href=\"https://colab.research.google.com/github/nationalarchives/TechneTraining/blob/main/Code/Techne_ML_workbook.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Set up variables and install useful library code",
"_____no_output_____"
]
],
[
[
"import sys\ndata_source = \"Github\"\n!git clone https://github.com/nationalarchives/TechneTraining.git\nsys.path.insert(0, 'TechneTraining')\nsys.path.insert(0, 'TechneTraining/Code')\ngithub_data = \"TechneTraining/Data/TopicModelling/\"\nimport techne_library_code as tlc\nfrom IPython.display import display\nimport math\nTEST_MODE = False",
"_____no_output_____"
]
],
[
[
"# Topic Modelling",
"_____no_output_____"
],
[
"### Load word list from Topic Model built on 'regulation' related websites.\nDisplay words in table.\n\nA topic model is created from a corpus of text by an unsupervised machine learning algorithm. The process is non-deterministic which means the results will differ every time it is run. Below is on results from running the software MALLET over the 'regulation' corpus.\n\nThe primary output is a list of topics (in this case 8, one row each) and a list of words most representative of that topic. A word can appear in more than one topic.\n\nFrom this we can get a high level overview of a corpus of text.",
"_____no_output_____"
]
],
[
[
"topic_words = tlc.read_topic_list(github_data + \"topic_list.txt\")\nTOPICS = len(topic_words)\ntopic_table = tlc.pd.DataFrame([v[0:12] for v in topic_words.values()])\ntopic_table",
"_____no_output_____"
]
],
[
[
"Stop words are used in Natural Language Processing to filter out very common words, or those which may negatively affect the results.\n\nBelow is a list of example stop words.",
"_____no_output_____"
]
],
[
[
"stop_words = [\"i\",\"or\",\"which\",\"of\",\"and\",\"is\",\"the\",\"a\",\"you're\",\"you\",\"at\",\"his\",\"etc\",'an','where','when']",
"_____no_output_____"
]
],
[
[
"Exercise: Picking stop words\n\nWe can add more to this list by selecting from the following list. Which ones do you think might be worth filtering out?",
"_____no_output_____"
]
],
[
[
"additional_stops = ['medical','freight','pdf','plan','kb','regulation','risk']\nstop_word_select = tlc.widgets.SelectMultiple(options=additional_stops, rows=len(additional_stops))\nstop_word_select",
"_____no_output_____"
],
[
"for w in stop_word_select.value:\n print(\"Adding\",w,\"to stop words\")\n stop_words.append(w)",
"_____no_output_____"
]
],
[
[
"As well as a list of topics and related words, MALLET also produces a topic breakdown for each document in the corpus.\n\nHere we load the topic data and visualise some examples.",
"_____no_output_____"
]
],
[
[
"topics_per_doc = tlc.read_doc_topics(github_data + \"topics_per_doc.txt\")",
"_____no_output_____"
]
],
[
[
"The following plots show the proportion of each topic attributed to 4 different documents.\n\n\n\n1. Top Left: One topic clearly dominates\n2. Top Right: One dominant topic but a second topic is above the level of others\n3. Bottom Left: Two topics clearly above others\n4. Bottom Right: Topics close to being even",
"_____no_output_____"
]
],
[
[
"file_number_list = [212, 85, 9, 372]\nfig, ax = tlc.plot_doc_topics(file_number_list, topics_per_doc, TOPICS)\ntlc.pyplot.show()",
"_____no_output_____"
]
],
[
[
"### Exercise: From Topics to Classes\n\nFor this Machine Learning exercise we want to predict a Category of regulation (e.g. \"Medicine\" or \"Rail\"). The categories we may want to predict do not map one-to-one with the topics above. So first we need to create that mapping.\n\nFirstly we will define a list of possible categories. Sometimes the topics that come out may be worth ignoring (e.g. cookie information) but in this case all of them seem to be of interest.",
"_____no_output_____"
]
],
[
[
"topics_of_interest = [0,1,2,3,4,5,6,7]\nclass_names = {0:\"General\",1:\"Medicine\",2:\"Rail\",3:\"Safety\",4:\"Pensions\",5:\"Education\",6:\"Other\",-1:\"Unclassified\"}\ntopic_to_class = {}\nif TEST_MODE:\n topic_to_class = {0:1,1:0,2:2,3:3,4:4,5:4,6:2,7:2} #For testing",
"_____no_output_____"
]
],
[
[
"Using the dropdown and list selector below we can set the mapping from topic to Class (a term more commonly used in machine learning for category.",
"_____no_output_____"
]
],
[
[
"class_drop = tlc.widgets.Dropdown(options=[(v,k) for k,v in class_names.items()], \n value=topics_of_interest[0], rows = len(class_names))\ntopic_select = tlc.widgets.SelectMultiple(options=[(w[0:5],t) for t,w in topic_words.items()],\n value = [k for k,v in topic_to_class.items() if v == class_drop.value],\n rows = TOPICS+1, height=\"100%\")\n\nbutton = tlc.widgets.Button(description=\"Update\")\noutput = tlc.widgets.Output()\n\ndef on_button_clicked(b):\n for v in topic_select.value:\n topic_to_class[v] = class_drop.value\n print(\"Updated\")\n\nbutton.on_click(on_button_clicked)",
"_____no_output_____"
]
],
[
[
"### Exercise: Map topics to classes",
"_____no_output_____"
]
],
[
[
"V = tlc.widgets.VBox([class_drop, topic_select, button])\nV",
"_____no_output_____"
]
],
[
[
"Update the selected values here and then return to the dropdown until finished.",
"_____no_output_____"
],
[
"Display the resulting mappings from **Topic** to **Class**",
"_____no_output_____"
]
],
[
[
"tlc.pd.DataFrame([(\",\".join(topic_words[k][0:10]),class_names[v]) for k,v in topic_to_class.items()], columns=['Topic Words','Class'])",
"_____no_output_____"
]
],
[
[
"## Viewing document class proportions",
"_____no_output_____"
]
],
[
[
"classes_per_doc = tlc.topic_to_class_scores(topics_per_doc, topic_to_class)",
"_____no_output_____"
]
],
[
[
"Generally every document contains a bit of each topic. Before visualising the class breakdown for our sample documents, we can filter out lowest scoring classes and focus on the primary class(es) by zeroing all values below a threshold. We then **normalise** the probabilities to add to 1.\n\nRun the next piece of code to create a slider to set the threshold, and then the following one will draw graphs. To try a different threshold, adjust the slider and rerun the graph code.",
"_____no_output_____"
]
],
[
[
"class_threshold = tlc.widgets.FloatSlider(0.10, min=0.10, max=0.65, step=0.05)\nclass_threshold",
"_____no_output_____"
]
],
[
[
"This is the graph code. It shows Classes above the threshold defined by the slider for the four documents previously visualised. ",
"_____no_output_____"
]
],
[
[
"filtered_classes_per_doc = tlc.filter_topics_by_threshold(classes_per_doc, class_threshold.value)\nclass_count = len(filtered_classes_per_doc['file_1.txt'])\nfig, ax = tlc.plot_doc_topics(file_number_list, filtered_classes_per_doc, class_count, normalise=True)\ntlc.pyplot.show()",
"_____no_output_____"
]
],
[
[
"# Representing text as numbers\n\nThe next stage is to use the results of the topic modelling to train a Supervised Learning algorithm.\n\nSupervised Learning is learning by example. We label our data in advance with categories, and then the algorithm derives a function which will map an input data item to an output Class. The input data is usually termed **Features**, the outputs are often called **Responses**.\n\n",
"_____no_output_____"
],
[
"## Term Frequency-Inverse Document Frequency (TF-IDF)\n\nFor this exercise the features are the words in our documents. There is no semantic meaning attached, the words are no more than tokens. Imagine a spreadsheet where each row represents a document and each column represents a word from a fixed vocabulary.\n\nOne representation we could use would be to use a 1 to indicate a word appears in a document, and a 0 if it doesn't. This is simple but overly so. A better representation is TF-IDF which stands for Term Frequency-Inverse Document Frequency. It is a very simple idea but the general gist is that a word that appears in most documents will score lowly, while a word which appears in few documents will score highly (this is the Inverse Document Frequency part). The Term Frequency increases the score when it appears many times in the document.",
"_____no_output_____"
],
[
"Now that we've mapped topics and categories, it is time to prepare the text corpus (the document contents) for Machine Learning.\n\nFirst we load the content from a file.",
"_____no_output_____"
]
],
[
[
"D4ML = tlc.MLData()\nD4ML.load_content(github_data + \"tm_file_contents.txt\")\nD4ML.set_classes(classes_per_doc)",
"_____no_output_____"
]
],
[
[
"We have some influence over the parameters used to define the TFIDF representation of our corpus. How they are set can influence the results.\n\n1. Features: how many distinct words from the corpus to use for the Vocabulary\n2. Min Doc Frequency: minimum number of documents a word must appear in to be considered\n3. Max Doc Frequency: maximum number of documents a word must appear in to be considered\n",
"_____no_output_____"
]
],
[
[
"FEATURES=1000\nMIN_DOC_FREQ=4\nMAX_DOC_FREQ=100",
"_____no_output_____"
]
],
[
[
"Calculate the TF-IDF scores for each document and prepare some of the data for Machine Learning",
"_____no_output_____"
]
],
[
[
"D4ML.add_stop_words(*stop_words)\nD4ML.calc_tfidf(FEATURES, MIN_DOC_FREQ, MAX_DOC_FREQ)\nprint(\"Documents:\",D4ML.TFIDF.shape[0],\"\\tWords\",D4ML.TFIDF.shape[1])\ntraining_features, training_classes, training_ids = D4ML.get_ml_data()\ntraining_features.shape",
"_____no_output_____"
]
],
[
[
"Here we can see an example of the TF-IDF scores for a document. They are sorted in score order, the higher scores indicating a greater importance for that document.",
"_____no_output_____"
]
],
[
[
"EXAMPLE = 0 # 0 to 3 only\nvocabulary = D4ML.vectorizer.get_feature_names()\nexample_row = D4ML.TFIDF[D4ML.file_to_idx['file_' + str(file_number_list[EXAMPLE]) + '.txt']]\nexample_table = tlc.pd.DataFrame(zip([vocabulary[w] for w in example_row.nonzero()[1]],\n [int(example_row[0,v]*1000)/1000 for i,v in enumerate(example_row.nonzero()[1])]),\n columns = ['word','tfidf']).sort_values(by='tfidf', ascending=False)\nexample_table",
"_____no_output_____"
]
],
[
[
"# Supervised Machine Learning\n\nFor this exercise we will use the Naive Bayes algorithm. It is called Bayes because it uses Bayesian probability (named after the Reverend Thomas Bayes who discovered it). It is Naive because it assumes that all words in a document are independent of each other (think of the sentence \"my cat miaows when hungry\"). It seems like a bad assumption but actually works well in practice.\n\nBayesian probability is surprisingly simple and gives us the ability to flip probabilities around. From a corpus of text I can easily calculate the probability of the word \"Passenger\" appearing in a document about \"Railways\", and also in a document about \"Medicines\". What Bayes' rule does is allow me to then calculate the probability that a document is about \"Railways\" or \"Medicines\" given that it contains the word \"Passenger\". Very handy!",
"_____no_output_____"
],
[
"### Preparing training and test data\n\nBefore starting any Machine Learning we need to split our data into Training and Test datasets. The reason for this is that algorithms can appear to perform very well against the dataset they were trained with, but then perform very badly on new, unseen, data.\n\nThe algorithm will learn from the Training data and then we check its performance against the Test data.",
"_____no_output_____"
]
],
[
[
"TEST_PROPORTION = 0.6\nX_train, X_test, \\\ny_train, y_test, \\\nx_train_ids, x_test_ids = tlc.train_test_split(training_features, training_classes, training_ids,\n test_size = TEST_PROPORTION, \n random_state=42, stratify=training_classes)",
"_____no_output_____"
]
],
[
[
"### Training the Naive Bayes model\n\nNow we **fit** a Naive Bayes model to the training data. Two lines of code and it is done!",
"_____no_output_____"
]
],
[
[
"model = tlc.BernoulliNB()\nmodel.fit(X_train, y_train)",
"_____no_output_____"
]
],
[
[
"### Optional: Under the hood of Naive Bayes\nOne nice feature of Naive Bayes is we can see exactly what is going on internally and could recreate its results with a calculator, if we so wished.\n\nThe first part of the calculation is called the prior and is the probability of each class without any further information (i.e. without seeing the document content)\n\nThis corpus is heavily skewed so rail is dominant.",
"_____no_output_____"
]
],
[
[
"tlc.pyplot.bar(height=[math.exp(p) for p in model.class_log_prior_], \n x=[x for x in range(len(model.class_log_prior_))])\ntlc.pyplot.xticks([0,1,2,3,4],[class_names[c] for c in range(len(model.class_log_prior_))])\ntlc.pyplot.show()",
"_____no_output_____"
]
],
[
[
"We can also take a class and see which words have the highest probability within that class.",
"_____no_output_____"
]
],
[
[
"C = 1\nN = 10\nprint(\"Class:\",class_names[C])\ntopN = (-model.feature_log_prob_[C]).argsort()[0:N]\nwords = [vocabulary[w] for w in topN]\nprobs = tlc.np.exp(model.feature_log_prob_[C,topN])\ntlc.pyplot.bar(height=probs, \n x=[x for x in range(len(words))])\ntlc.pyplot.xticks(range(len(words)),words, rotation=45)\ntlc.pyplot.show()",
"_____no_output_____"
]
],
[
[
"We can then choose a word and see the probability of each class for that word. The final result is a combination of this and the prior.\n\nSince the prior is heavily in favour of one class, the word probabilities need to be strongly in favour of another to change the result.",
"_____no_output_____"
]
],
[
[
"W = 9\nprint(\"Word:\",vocabulary[topN[W]])\nw_probs = tlc.np.exp([model.feature_log_prob_[i,topN[W]] for i in range(len(model.class_log_prior_))])\ntlc.pyplot.bar(height=w_probs, \n x=[x for x in range(len(model.class_log_prior_))])\ntlc.pyplot.show()",
"_____no_output_____"
]
],
[
[
"### Evaluating the model's performance\n\nHaving created the model we now use it to generate predictions for the test dataset.\n\nWe have two ways of assessing the performance of the model. The first is to give an accuracy score, quite simply the percentage of predictions it has got right.",
"_____no_output_____"
]
],
[
[
"y_pred = model.predict(X_test)\ny_prob = model.predict_proba(X_test)\nprint(\"Prediction Accuracy:\",int(tlc.accuracy_score(y_test, y_pred)*1000)/10,'%')",
"_____no_output_____"
]
],
[
[
"A more granular method is to view what is quite rightly called a **Confusion Matrix**.\n\nA confusion matrix is a grid mapping 'correct' answers to predictions. The rows represent the class assigned in the test data and the columns represent predictions. The top left to bottom right diagonal shows us how many of each class have been predicted correctly. All of the other numbers count incorrect predictions. The number in row 2, column 3, will show how many documents of whatever the 2nd class represents (\"Medicine\") have been misclassified as the 3rd class (\"Rail\").\n\nIn this example we see that \"Rail\" documents tend to be classified correctly, but a lot of the other types are being also misclassified as \"Rail\".\n\nWe can see from the numbers that this dataset is highly imbalanced, so most of the records are \"Rail\". This may be responsible for the bias towards that class.",
"_____no_output_____"
]
],
[
[
"fig, ax = tlc.draw_confusion(y_test, y_pred, model, class_names)\ntlc.pyplot.show()",
"_____no_output_____"
]
],
[
[
"### Exploring individual predictions\nSimilar to the topic model output, the prediction also comes with probabilities. We can visualise these probabilites for a selection of predictions.",
"_____no_output_____"
]
],
[
[
"y_true_pred = [x for x in zip(range(len(y_test)),y_test, y_pred, y_prob)]\nincorrect_predictions = [(y[0],y[1],y[2],y[3]) for i,y in enumerate(y_true_pred) if y[1] != y[2]]\nincorrect_unsure = [x for x in incorrect_predictions if max(x[3]) < 0.8]",
"_____no_output_____"
],
[
"prediction_sample = tlc.random.sample(range(len(incorrect_unsure)), min(5, len(incorrect_unsure)))\nfig, ax = tlc.pyplot.subplots(min(5,len(prediction_sample)),1)\nfig.set_size_inches(5,7)\n\nfor i, sample_idx in enumerate(prediction_sample):\n prediction_row = incorrect_unsure[sample_idx]\n data_idx = prediction_row[0]\n true_class = prediction_row[1]\n predicted = prediction_row[2]\n tp = prediction_row[3]\n class_probs = [tp[0],tp[1],tp[2],tp[3],tp[4]]\n ax[i].set_ylim([0,1.0])\n ax[i].text(.4,0.8, str(data_idx) + \": True:\" + class_names[true_class] + \", Predicted:\" + class_names[predicted],\n horizontalalignment='center',\n transform=ax[i].transAxes)\n if i < 4:\n ax[i].set_xticks([])\n else:\n ax[i].set_xticks(ticks=[0,1,2,3,4])\n ax[i].set_xticklabels(labels=['General','Medicine','Rail', 'Safety', 'Pension'])\n ax[i].bar(x = [0,1,2,3,4], height = class_probs)\ntlc.pyplot.show()",
"_____no_output_____"
]
],
[
[
"If we look at probabilities in aggregate we see that generally high confidence predictions match the correct class, and lower confidence ones are more likely to be incorrect. This is desirable behaviour because it gives us more trust in the high confidence predictions.",
"_____no_output_____"
]
],
[
[
"\nprob_match_sum = tlc.np.zeros((11,4))\n\nfor i in range(11):\n prob_match_sum[i,0] = i/10\nfor row in y_true_pred:\n max_prob = int(max(row[3]) * 10)\n prob_match_sum[max_prob,int(row[1] == row[2])+1] += 1\n prob_match_sum[max_prob,3] += 1\n\nprob_match_sum = tlc.pd.DataFrame(prob_match_sum, columns=[\"Probability\", \"NoMatch\", \"Match\", \"Total\"])\n\nax = prob_match_sum.plot(x=\"Probability\", y=\"Total\", kind=\"bar\", color=\"blue\")\nax.legend(['Disagree', 'Match'])\nprob_match_sum.plot(x=\"Probability\", y=\"Match\", kind=\"bar\", ax=ax, color=\"orange\")\ntlc.pyplot.show()",
"_____no_output_____"
]
],
[
[
"We will now use another Machine Learning algorithm called Nearest Neighbours to help use classify some new training data.\n\nThis code prepares the data for the next section. Firstly the data is indexed to find similar documents quickly (KDTree), then we sort the predictions by their prediction probability (most confident first). Finally we create a sample of most and least confident predictions.",
"_____no_output_____"
]
],
[
[
"kdt = tlc.KDTree(training_features, leaf_size=30, metric='minkowski', p=2)\ntfidf_words = D4ML.vectorizer.get_feature_names()\nmax_sorted_asc = sorted(y_true_pred, key=lambda max_x : max(max_x[3]), reverse=True)\nsample_ids = (tlc.np.random.beta(0.55, 0.4, 50) * len(max_sorted_asc)).astype('int')\nsample_ids = list(set(sample_ids))\n#tlc.random.shuffle(sample_ids)\ns = 0",
"_____no_output_____"
]
],
[
[
"# Reviewing and correcting predictions",
"_____no_output_____"
],
[
"## Form setup code",
"_____no_output_____"
]
],
[
[
"output = tlc.widgets.Output()\n\nneighbour_list = []\nneighbour_idx = 0\nNUMBER_OF_NEIGHBOURS = 4\n\nhuman_classification = {}\n\ndef dropdown_update(change):\n\n check_row = change.new\n this_idx = max_sorted_asc[check_row][0]\n this_words = set([tfidf_words[w] for w in tlc.np.nonzero(X_test[this_idx])[1]])\n true_class_drop.value = y_test[this_idx]\n this_file_name = D4ML.idx_to_file[x_test_ids[this_idx]]\n file_name_text.set_state({'value':this_file_name})\n file_name_text.send_state('value')\n predicted_class_text.set_state({'value': class_names[y_pred[this_idx]]})\n predicted_class_text.send_state('value')\n prediction_prob = tlc.np.max(y_prob[this_idx])\n doc_pred_prob.set_state({'value': prediction_prob})\n doc_pred_prob.send_state('value')\n doc_words.set_state({'value': \",\".join(list(this_words))})\n doc_words.send_state('value')\n nn_dist, nn_ind = kdt.query(X_test[this_idx], k=NUMBER_OF_NEIGHBOURS)\n doc_contents.set_state({'value': D4ML.file_contents[this_file_name]})\n doc_contents.send_state('value')\n neighbour_count = 0\n global neighbour_list\n neighbour_list = []\n for i in range(len(nn_dist[0])):\n dist = nn_dist[0][i]\n idx = nn_ind[0][i]\n file_name = D4ML.idx_to_file[idx]\n if idx == x_test_ids[this_idx]:\n continue\n pred = model.predict(training_features[idx])\n neighbour_distance.set_state({'value':dist})\n neighbour_distance.send_state('value')\n true_class = -1\n words = set([tfidf_words[w] for w in tlc.np.nonzero(training_features[idx])[1]])\n if len(words) == 0:\n continue\n if file_name in class_probs:\n true_class = tlc.np.argmax(class_probs[file_list[idx]])\n overlap_words = \",\".join(list(words.intersection(this_words)))\n \n neighbour_list.append([idx, dist, file_name, overlap_words, D4ML.file_contents[file_name],\n true_class, class_names[pred[0]]])\n neighbour_count += 1\n accordion.set_title(3, \"Nearest Neighbours: \" + str(len(neighbour_list)))\n with output:\n output.clear_output()\n display(accordion)\n\n\nsample_dropdown = tlc.widgets.Dropdown(options=sample_ids, value=None, description='Choose a document',\n layout={'width':'100px'}, style={'description_width': 'initial'})\nsample_dropdown.observe(dropdown_update, 'value')\n\nfile_name_text = tlc.widgets.Text(value=None, description=\"File Name\")\nclass_options = [(v,k) for k,v in class_names.items()]\ntrue_class_drop = tlc.widgets.Dropdown(options=class_options,\n value = None, description='True Class')\nupdate_true = tlc.widgets.Button(description=\"Update\")\n\ndef on_true_pressed(b):\n human_classification[file_name_text.value] = true_class_drop.value\n\nupdate_true.on_click(on_true_pressed)\n\n#true_class_drop.observe(on_true_changed,'value')\npredicted_class_text = tlc.widgets.Text(value=None, description='Predicted class', style={'description_width': 'initial'})\ndoc_pred_prob = tlc.widgets.FloatText(value=None, description='Probability')\ndetails = tlc.widgets.VBox([file_name_text,\n tlc.widgets.HBox([true_class_drop, predicted_class_text, update_true]),\n doc_pred_prob])\n\nneighbour_overlap = tlc.widgets.Text(value=\"\", \n layout={'height': '100%', 'width': '700px'}, disabled=False)\nneighbour_distance = tlc.widgets.FloatText(value=None, description='Distance')\nneighbour_true_class = tlc.widgets.Dropdown(value=None, description=\"True\", options=class_options)\nneighbour_prediction = tlc.widgets.Text(value=None, description=\"Prediction\")\nneighbour_file = tlc.widgets.Text(value=None)\nneighbour_content = tlc.widgets.Textarea(value=None, layout={'height': '150px', 'width': '700px'})\n\ndef on_next_clicked(b):\n global neighbour_idx\n global neighbour_list\n if len(neighbour_list) == 0:\n return\n neighbour_idx += 1\n if neighbour_idx >= len(neighbour_list):\n neighbour_idx = 0\n neighbour_data = neighbour_list[neighbour_idx]\n neighbour_true_class.value = neighbour_data[5]\n neighbour_true_class.send_state('value')\n neighbour_prediction.set_state({'value':neighbour_data[6]})\n neighbour_prediction.send_state('value')\n neighbour_distance.set_state({'value':neighbour_data[1]})\n neighbour_distance.send_state('value')\n neighbour_file.set_state({'value':neighbour_data[2]})\n neighbour_file.send_state('value')\n neighbour_overlap.set_state({'value':neighbour_data[3]})\n neighbour_overlap.send_state('value')\n neighbour_content.set_state({'value':neighbour_data[4]})\n neighbour_content.send_state('value')\n\n\nnext_neighbour = tlc.widgets.Button(description=\"Next\", layout={'width':'100px'})\nnext_neighbour.on_click(on_next_clicked)\n\nneighbour_true_update = tlc.widgets.Button(description=\"Update\")\n\ndef on_neighbour_update_click(b):\n human_classification[neighbour_file.value] = neighbour_true_class.value\n\nneighbour_true_update.on_click(on_neighbour_update_click)\n\nneighbour_details = tlc.widgets.VBox([next_neighbour, neighbour_file, neighbour_distance,\n tlc.widgets.HBox([neighbour_true_class, neighbour_true_update]),\n neighbour_prediction])\n\ndoc_words = tlc.widgets.Text(value=None, layout={'height': '100%', 'width': '700px'}, disabled=False)\n#overlap.observe(sample_dropdown, on_button_clicked)\ndoc_contents = tlc.widgets.Textarea(value=None,\n layout={'height': '200px', 'width': '700px'})\nsub_accordion = tlc.widgets.Accordion(children=[neighbour_details, neighbour_overlap, neighbour_content])\naccordion = tlc.widgets.Accordion(children=[details,doc_words, doc_contents, sub_accordion])\naccordion.set_title(0,\"Details\")\naccordion.set_title(1,\"Document Features\")\naccordion.set_title(2,\"Document Contents\")\naccordion.set_title(3,\"Nearest Neighbours\")\nsub_accordion.set_title(0,\"Neighbour details\")\nsub_accordion.set_title(1,\"Word overlap\")\nsub_accordion.set_title(2,\"Neighbour content\")\n",
"_____no_output_____"
]
],
[
[
"## Refreshing the training data",
"_____no_output_____"
],
[
"Run the line of code below and then use the dropdown menu to select a sample document. The ids will be meaningless so pick any. This will open a form for viewing the classification results for the document. The form layout is called 'accordion' and you can click on any title and a different part of the form will open up. You can also change the 'true' classification and press update to save the new value. As well as checking the selected document classification, the form also shows the most similar documents (using nearest neighbours) to classify those at the same time.\n\nThe output from this exercise could be used in future to train a new classifier.",
"_____no_output_____"
]
],
[
[
"display(sample_dropdown, output)",
"_____no_output_____"
],
[
"human_classification",
"_____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",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
4ac2bb4fed4d1bdad0cdba773013e979b0087cc4
| 59,188 |
ipynb
|
Jupyter Notebook
|
notebooks/bacon-number.ipynb
|
kjahan/bacon-number
|
4afacf76078d273834b71f8632e9687f912e8b52
|
[
"Apache-2.0"
] | 1 |
2020-03-20T18:43:51.000Z
|
2020-03-20T18:43:51.000Z
|
notebooks/bacon-number.ipynb
|
kjahan/bacon-number
|
4afacf76078d273834b71f8632e9687f912e8b52
|
[
"Apache-2.0"
] | null | null | null |
notebooks/bacon-number.ipynb
|
kjahan/bacon-number
|
4afacf76078d273834b71f8632e9687f912e8b52
|
[
"Apache-2.0"
] | null | null | null | 35.168152 | 199 | 0.433568 |
[
[
[
"import re\nimport json\n\nimport pandas as pd\nimport numpy as np\n\nfrom collections import deque",
"_____no_output_____"
]
],
[
[
"## Process dataset",
"_____no_output_____"
]
],
[
[
"base_folder = \"../movies-dataset/\"\nmovies_metadata_fn = \"movies_metadata.csv\"\ncredits_fn = \"credits.csv\"\nlinks_fn = \"links.csv\"",
"_____no_output_____"
]
],
[
[
"## Process movies_metadata data structure/schema",
"_____no_output_____"
]
],
[
[
"metadata = pd.read_csv(base_folder + movies_metadata_fn)\nmetadata.head()",
"//anaconda/envs/bacon/lib/python3.7/site-packages/IPython/core/interactiveshell.py:3063: DtypeWarning: Columns (10) have mixed types.Specify dtype option on import or set low_memory=False.\n interactivity=interactivity, compiler=compiler, result=result)\n"
]
],
[
[
"## Cast id to int64 and drop any NAN values!",
"_____no_output_____"
]
],
[
[
"metadata.id = pd.to_numeric(metadata.id, downcast='signed', errors='coerce')",
"_____no_output_____"
],
[
"metadata = metadata[metadata['id'].notna()]",
"_____no_output_____"
],
[
"list(metadata.columns.values)",
"_____no_output_____"
],
[
"def CustomParser(data):\n obj = json.loads(data)\n return obj",
"_____no_output_____"
]
],
[
[
"We probably need id, title from this dataframe.",
"_____no_output_____"
],
[
"## Process credits data structure/schema",
"_____no_output_____"
]
],
[
[
"credits = pd.read_csv(base_folder + credits_fn)\n# credits = pd.read_csv(base_folder + credits_fn, converters={'cast':CustomParser}, header=0)\n# Cast id to int\ncredits.id = pd.to_numeric(credits.id, downcast='signed', errors='coerce')\ncredits.head()",
"_____no_output_____"
],
[
"# cast id to int64 for later join\nmetadata['id'] = metadata['id'].astype(np.int64)\ncredits['id'] = credits['id'].astype(np.int64)",
"_____no_output_____"
],
[
"metadata.dtypes",
"_____no_output_____"
],
[
"credits.dtypes",
"_____no_output_____"
],
[
"metadata.head(3)",
"_____no_output_____"
],
[
"credits.head(3)",
"_____no_output_____"
]
],
[
[
"## Let's join the two dataset based on movie id\n\nWe start with one example movie `Toy Story` with id = 862 in metadata dataset.",
"_____no_output_____"
]
],
[
[
"merged = pd.merge(metadata, credits, on='id')",
"_____no_output_____"
],
[
"merged.head(3)",
"_____no_output_____"
],
[
"toy_story_id = 862\nmerged.loc[merged['id'] == toy_story_id]",
"_____no_output_____"
]
],
[
[
"## Examine crew/cast json data schme for toy story",
"_____no_output_____"
]
],
[
[
"cast = merged.loc[merged['id'] == toy_story_id].cast\ncrew = merged.loc[merged['id'] == toy_story_id].crew",
"_____no_output_____"
],
[
"cast",
"_____no_output_____"
]
],
[
[
"## Find all movies Tom hanks has acted in",
"_____no_output_____"
]
],
[
[
"def has_played(actor_name, cast_data):\n for cast in cast_data:\n name = cast['name']\n actor_id = cast['id']\n cast_id = cast['cast_id']\n credit_id = cast['credit_id'] \n if actor_name.lower() == name.lower():\n print(\"name: {}, id: {}, cast_id: {}, credit_id: {}\".format(name, actor_id, cast_id, credit_id))\n return True\n return False",
"_____no_output_____"
]
],
[
[
"## Setup data structure",
"_____no_output_____"
]
],
[
[
"# a map from movie id to a list of actor id's\nmovie_actor_adj_list = {}\n# a map from actor id to a list of movie id's\nactor_movie_adj_list = {}\n# a map from movies id to their title\nmovies_map = {}\n# a map from actors id to their name\nactors_map = {}",
"_____no_output_____"
],
[
"cnt, errors = 0, 0\nfailed_movies = {}\nfor index, row in merged.iterrows():\n cnt += 1\n movie_id, movie_title = row['id'], row['title']\n if movie_id not in movies_map:\n movies_map[movie_id] = movie_title\n dirty_json = row['cast']\n try:\n regex_replace = [(r\"([ \\{,:\\[])(u)?'([^']+)'\", r'\\1\"\\3\"'), (r\" None\", r' null')]\n for r, s in regex_replace:\n dirty_json = re.sub(r, s, dirty_json)\n cast_data = json.loads(dirty_json)\n# if has_played('Tom Hanks', cast_data):\n# print(\"Movie id: {}, title: {}\".format(movie_id, movie_title))\n for cast in cast_data:\n actor_name = cast['name']\n actor_id = cast['id']\n if actor_id not in actors_map:\n actors_map[actor_id] = actor_name\n # build movie-actor adj list\n if movie_id not in movie_actor_adj_list:\n movie_actor_adj_list[movie_id] = [actor_id]\n else:\n movie_actor_adj_list[movie_id].append(actor_id)\n # build actor-movie adj list\n if actor_id not in actor_movie_adj_list:\n actor_movie_adj_list[actor_id] = [movie_id]\n else:\n actor_movie_adj_list[actor_id].append(movie_id)\n except json.JSONDecodeError as err:\n # print(\"JSONDecodeError: {}, Movie id: {}, title: {}\".format(err, movie_id, movie_title))\n failed_movies[movie_id] = True\n errors += 1\nprint(\"Parsed credist: {}, errors: {}\".format(cnt, errors))",
"name: Tom Hanks, id: 31, cast_id: 14, credit_id: 52fe4284c3a36847f8024f95\nMovie id: 862, title: Toy Story\nname: Tom Hanks, id: 31, cast_id: 21, credit_id: 52fe452fc3a36847f80c1111\nMovie id: 9800, title: Philadelphia\nname: Tom Hanks, id: 31, cast_id: 13, credit_id: 52fe4283c3a36847f8024bd9\nMovie id: 858, title: Sleepless in Seattle\nname: Tom Hanks, id: 31, cast_id: 8, credit_id: 554f734e92514162f2001889\nMovie id: 32562, title: The Celluloid Closet\nname: Tom Hanks, id: 31, cast_id: 10, credit_id: 52fe4283c3a36847f8024aef\nMovie id: 857, title: Saving Private Ryan\nname: Tom Hanks, id: 31, cast_id: 8, credit_id: 52fe44ad9251416c7503d27b\nMovie id: 11974, title: The 'Burbs\nname: Tom Hanks, id: 31, cast_id: 1, credit_id: 52fe4360c3a36847f804faaf\nMovie id: 2619, title: Splash\nname: Tom Hanks, id: 31, cast_id: 2, credit_id: 52fe4608c3a368484e07ceef\nMovie id: 29968, title: Nothing in Common\nname: Tom Hanks, id: 31, cast_id: 1, credit_id: 52fe44fec3a36847f80b660d\nMovie id: 9489, title: You've Got Mail\nname: Tom Hanks, id: 31, cast_id: 1, credit_id: 52fe450dc3a36847f80b9965\nMovie id: 9586, title: The Bonfire of the Vanities\nname: Tom Hanks, id: 31, cast_id: 1, credit_id: 52fe47ca9251416c750a58d9\nMovie id: 19259, title: Volunteers\nname: Tom Hanks, id: 31, cast_id: 1, credit_id: 52fe44da9251416c7504336f\nMovie id: 12309, title: Bachelor Party\nname: Tom Hanks, id: 31, cast_id: 4, credit_id: 52fe45a5c3a36847f80d29f9\nMovie id: 40820, title: Punchline\nname: Tom Hanks, id: 31, cast_id: 3, credit_id: 52fe44a2c3a36847f80a14df\nMovie id: 8358, title: Cast Away\nname: Tom Hanks, id: 31, cast_id: 1, credit_id: 52fe446ac3a36847f8094a57\nMovie id: 6951, title: Turner & Hooch\nname: Tom Hanks, id: 31, cast_id: 8, credit_id: 52fe4703c3a368484e0b053b\nMovie id: 65262, title: He Knows You're Alone\nname: Tom Hanks, id: 31, cast_id: 1, credit_id: 52fe435dc3a36847f804ec5d\nMovie id: 2565, title: Joe Versus the Volcano\nname: Tom Hanks, id: 31, cast_id: 13, credit_id: 52fe43aec3a36847f80678c7\nMovie id: 4147, title: Road to Perdition\nname: Tom Hanks, id: 31, cast_id: 24, credit_id: 52fe4263c3a36847f801a643\nMovie id: 640, title: Catch Me If You Can\nname: Tom Hanks, id: 31, cast_id: 7, credit_id: 52fe43f8c3a368484e0088bd\nMovie id: 20763, title: Radio Flyer\nname: Tom Hanks, id: 31, cast_id: 2, credit_id: 52fe430a9251416c75001163\nMovie id: 10023, title: Dragnet\nname: Tom Hanks, id: 31, cast_id: 14, credit_id: 52fe440bc3a36847f807ef5f\nMovie id: 5516, title: The Ladykillers\nname: Tom Hanks, id: 31, cast_id: 4, credit_id: 52fe4259c3a36847f801762f\nMovie id: 594, title: The Terminal\nname: Tom Hanks, id: 31, cast_id: 1, credit_id: 52fe43cd9251416c7501ec1f\nMovie id: 10905, title: The Man with One Red Shoe\nname: Tom Hanks, id: 31, cast_id: 26, credit_id: 52fe4400c3a36847f807c9c1\nMovie id: 5255, title: The Polar Express\nname: Tom Hanks, id: 31, cast_id: 2, credit_id: 52fe44529251416c9100c9e9\nMovie id: 30983, title: From the Earth to the Moon\nname: Tom Hanks, id: 31, cast_id: 33, credit_id: 52fe4259c3a36847f8017445\nMovie id: 591, title: The Da Vinci Code\nname: Tom Hanks, id: 31, cast_id: 67, credit_id: 550da08dc3a368487d006282\nMovie id: 920, title: Cars\nname: Tom Hanks, id: 31, cast_id: 5, credit_id: 52fe45739251416c75056f47\nMovie id: 13508, title: Who Killed the Electric Car?\nname: Tom Hanks, id: 31, cast_id: 22, credit_id: 52fe4211c3a36847f8001551\nMovie id: 35, title: The Simpsons Movie\nname: Tom Hanks, id: 31, cast_id: 1, credit_id: 52fe46bf9251416c75082477\nMovie id: 16279, title: The Great Buck Howard\nname: Tom Hanks, id: 31, cast_id: 4, credit_id: 52fe45699251416c75055939\nMovie id: 13448, title: Angels & Demons\nname: Tom Hanks, id: 31, cast_id: 9, credit_id: 52fe441ac3a36847f8082507\nMovie id: 5707, title: Shooting War\nname: Tom Hanks, id: 31, cast_id: 6, credit_id: 52fe433f9251416c7500915d\nMovie id: 10193, title: Toy Story 3\nname: Tom Hanks, id: 31, cast_id: 9, credit_id: 543ae4340e0a2649ab00378c\nMovie id: 15302, title: The Pixar Story\nname: Tom Hanks, id: 31, cast_id: 3, credit_id: 52fe499dc3a36847f81a3b1f\nMovie id: 59861, title: Larry Crowne\nname: Tom Hanks, id: 31, cast_id: 1, credit_id: 52fe46e4c3a368484e0a9869\nMovie id: 64685, title: Extremely Loud & Incredibly Close\nname: Tom Hanks, id: 31, cast_id: 4, credit_id: 590de8509251414e9200ff5b\nMovie id: 208988, title: The War\nname: Tom Hanks, id: 31, cast_id: 1, credit_id: 52fe48a89251416c91094135\nMovie id: 83542, title: Cloud Atlas\nname: Tom Hanks, id: 31, cast_id: 10, credit_id: 52fe4ab5c3a36847f81dd51d\nMovie id: 109424, title: Captain Phillips\nname: Tom Hanks, id: 31, cast_id: 6, credit_id: 52fe4dbec3a368484e1fac11\nMovie id: 213121, title: Toy Story of Terror!\nname: Tom Hanks, id: 31, cast_id: 11, credit_id: 52fe4a9c9251416c750e8175\nMovie id: 140823, title: Saving Mr. Banks\nname: Tom Hanks, id: 31, cast_id: 6, credit_id: 52fe4cf0c3a36847f8245b71\nMovie id: 170039, title: Killing Lincoln\nname: Tom Hanks, id: 31, cast_id: 12, credit_id: 52fe4982c3a368484e12f03b\nMovie id: 77887, title: Hawaiian Vacation\nname: Tom Hanks, id: 31, cast_id: 3, credit_id: 52fe48509251416c91087f67\nMovie id: 82424, title: Small Fry\nname: Tom Hanks, id: 31, cast_id: 6, credit_id: 52fe465e9251416c9105233d\nMovie id: 37641, title: Elvis Has Left the Building\nname: Tom Hanks, id: 31, cast_id: 3, credit_id: 52fe4b68c3a368484e18793f\nMovie id: 130925, title: Partysaurus Rex\nname: Tom Hanks, id: 31, cast_id: 0, credit_id: 543d70930e0a266f8400032c\nMovie id: 256835, title: Toy Story That Time Forgot\nname: Tom Hanks, id: 31, cast_id: 1, credit_id: 55528c9bc3a368426f0054e9\nMovie id: 339988, title: The Circle\nname: Tom Hanks, id: 31, cast_id: 0, credit_id: 54304fd80e0a26464c000ffd\nMovie id: 296098, title: Bridge of Spies\nname: Tom Hanks, id: 31, cast_id: 2, credit_id: 55e4f02992514137970003f3\nMovie id: 357125, title: The Sixties\nname: Tom Hanks, id: 31, cast_id: 2, credit_id: 5374eb17c3a3681509002f2d\nMovie id: 270010, title: A Hologram for the King\nname: Tom Hanks, id: 31, cast_id: 7, credit_id: 52fe49b19251416c910b596d\nMovie id: 87061, title: The Extraordinary Voyage\nname: Tom Hanks, id: 31, cast_id: 0, credit_id: 5475a40dc3a3687fd9000e10\nMovie id: 207932, title: Inferno\nname: Tom Hanks, id: 31, cast_id: 23, credit_id: 52fe4a909251416c750e6647\nMovie id: 140465, title: Prohibition\nname: Tom Hanks, id: 31, cast_id: 14, credit_id: 547200b79251411752000075\nMovie id: 305642, title: Ithaca\nParsed credist: 45538, errors: 9496\n"
],
[
"movie_actor_adj_list[862]",
"_____no_output_____"
],
[
"inv_actors_map = {v: k for k, v in actors_map.items()}\ninv_movies_map = {v: k for k, v in movies_map.items()}",
"_____no_output_____"
],
[
"kevin_id = inv_actors_map['Kevin Bacon']\nprint(kevin_id)",
"4724\n"
],
[
"DEBUG = False\nq = deque()\nq.append(kevin_id)\nbacon_degrees = {kevin_id: 0}\nvisited = {}\ndegree = 1\n\nwhile q:\n u = q.popleft()\n if DEBUG:\n print(\"u: {}\".format(u))\n# print(q)\n if u not in visited:\n visited[u] = True\n if DEBUG:\n print(\"degree(u): {}\".format(bacon_degrees[u]))\n if bacon_degrees[u] % 2 == 0:\n # actor type node\n neighbors = actor_movie_adj_list[u]\n if DEBUG:\n print(\"actor type, neighbors: {}\".format(neighbors))\n else:\n # movie type node\n neighbors = movie_actor_adj_list[u]\n if DEBUG:\n print(\"movie type, neighbors: {}\".format(neighbors))\n for v in neighbors:\n if v not in visited:\n q.append(v)\n if v not in bacon_degrees:\n bacon_degrees[v] = bacon_degrees[u] + 1",
"_____no_output_____"
],
[
"bacon_degrees[kevin_id]",
"_____no_output_____"
],
[
"actors_map[2224]",
"_____no_output_____"
],
[
"movies_map[9413]",
"_____no_output_____"
],
[
"actor_id = inv_actors_map['Tom Hanks']\nbacon_degrees[actor_id]",
"_____no_output_____"
],
[
"actor_id = inv_actors_map['Tom Cruise']\nbacon_degrees[actor_id]",
"_____no_output_____"
],
[
"movie_id = inv_movies_map['Apollo 13']\nfailed_movies[movie_id]",
"_____no_output_____"
],
[
"actor_id = inv_actors_map['Tom Cruise']\ntom_cruise_movies = actor_movie_adj_list[actor_id]",
"_____no_output_____"
],
[
"actor_id = inv_actors_map['Kevin Bacon']\nkevin_bacon_movies = actor_movie_adj_list[actor_id]",
"_____no_output_____"
],
[
"set(tom_cruise_movies).intersection(set(kevin_bacon_movies))",
"_____no_output_____"
],
[
"movies_map[881]",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac2bf406e175a45be62f11bf0c1c75a1f6ea98f
| 155,163 |
ipynb
|
Jupyter Notebook
|
finalScripts/Mainnet/get_mainnet_dao_treasury_information.ipynb
|
DiamondDAO/dao-treasury-analysis
|
d8f2b69251bb5bfd144481c0baa99351016ae2ba
|
[
"MIT"
] | null | null | null |
finalScripts/Mainnet/get_mainnet_dao_treasury_information.ipynb
|
DiamondDAO/dao-treasury-analysis
|
d8f2b69251bb5bfd144481c0baa99351016ae2ba
|
[
"MIT"
] | null | null | null |
finalScripts/Mainnet/get_mainnet_dao_treasury_information.ipynb
|
DiamondDAO/dao-treasury-analysis
|
d8f2b69251bb5bfd144481c0baa99351016ae2ba
|
[
"MIT"
] | null | null | null | 58.507919 | 233 | 0.714532 |
[
[
[
"import json\nimport os\nimport time\nimport requests",
"_____no_output_____"
],
[
"import psycopg2\nimport os\nimport json\n\ndatabase_dict = {\n \"database\": os.environ.get(\"POSTGRES_DB\"),\n \"user\": os.environ.get(\"POSTGRES_USERNAME\"),\n \"password\": os.environ.get(\"POSTGRES_PASSWORD\"),\n \"host\": os.environ.get(\"POSTGRES_WRITER\"),\n \"port\": os.environ.get(\"POSTGRES_PORT\"),\n }\nengine = psycopg2.connect(**database_dict)\ncur = engine.cursor()\n\ndef get_mainnet_daos(cur, engine):\n execute_string = f\"SELECT * FROM daohaus.dao\"\n cur.execute(execute_string)\n records = cur.fetchall()\n js = [];\n for x in records:\n if(x[5] == 1):\n curl = []\n curl.append(x[0])\n curl.append(x[1])\n js.append(curl)\n return js\n\ndef get_all_members(cur, engine):\n execute_string = f\"SELECT * FROM daohaus.member\"\n cur.execute(execute_string)\n records = cur.fetchall()\n js = [];\n for x in records:\n curl = []\n curl.append(x[1])\n curl.append(x[6])\n js.append(curl)\n return js\n\nmain_net_daos = get_mainnet_daos(cur, engine)\nall_members = get_all_members(cur, engine)",
"_____no_output_____"
],
[
"dict_of_main_net_daos = {}\nfor dao in main_net_daos:\n dict_of_main_net_daos[dao[0]] = dao[1]\nmain_net_members = []\nfor member in all_members:\n if member[0] in dict_of_main_net_daos:\n curl = []\n curl.append(dict_of_main_net_daos[member[0]])\n curl.append(member[1])\n main_net_members.append(curl)",
"_____no_output_____"
],
[
"main_net_members",
"_____no_output_____"
],
[
"API_KEY = \"ASKMW73735RNXSZCUDNZPFU1W2URIWYXRE\"",
"_____no_output_____"
],
[
"addresses = main_net_daos",
"_____no_output_____"
],
[
"all_tokens = set()\nlist_of_sets_tokens_in_each_address = []",
"_____no_output_____"
],
[
"counter = 0\nfor addy in addresses:\n address = str(addy[1])\n cur_add = address\n url = f\"https://api.etherscan.io/api?module=account&action=tokentx&address={address}&page=1&offset=100&startblock=0&endblock=27025780&sort=asc&apikey={API_KEY}\"\n response = requests.get(url)\n counter+=1\n if(response.status_code != 204 and response.headers[\"content-type\"].strip().startswith(\"application/json\")):\n test_data = response.json()\n else:\n break\n \n \n cd = dict()\n current_address_set_of_tokens = set()\n for transaction in test_data['result']:\n all_tokens.add(transaction['contractAddress'])\n current_address_set_of_tokens.add(transaction['contractAddress'])\n \n cd[str(cur_add)] = current_address_set_of_tokens\n list_of_sets_tokens_in_each_address.append(cd)\n if counter % 20 == 0:\n print(\"SLEPT\")\n time.sleep(1)",
"SLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\nSLEPT\n"
],
[
"all_tokens_with_spot_prices = {}\nfor token in all_tokens:\n all_tokens_with_spot_prices[str(token)] = 0\n \ndid_not_work_tokens = []",
"_____no_output_____"
],
[
"counter = 0\nfor token in all_tokens:\n fl = True\n response = requests.get(f\"https://api.etherscan.io/api?module=token&action=tokeninfo&contractaddress={token}&apikey={API_KEY}\")\n if not (response.status_code != 204 and response.headers[\"content-type\"].strip().startswith(\"application/json\")):\n time.sleep(1)\n response = requests.get(f\"https://api.etherscan.io/api?module=token&action=tokeninfo&contractaddress={token}&apikey={API_KEY}\")\n if not (response.status_code != 204 and response.headers[\"content-type\"].strip().startswith(\"application/json\")):\n time.sleep(1)\n response = requests.get(f\"https://api.etherscan.io/api?module=token&action=tokeninfo&contractaddress={token}&apikey={API_KEY}\")\n if not (response.status_code != 204 and response.headers[\"content-type\"].strip().startswith(\"application/json\")):\n did_not_work_tokens.append(token)\n fl = False\n else:\n test_data = response.json()\n else:\n test_data = response.json()\n else:\n test_data = response.json()\n \n if fl and test_data['message'] == \"OK\":\n if(len(test_data['result'])> 0):\n cd = {\"tokenPriceUSD\": test_data['result'][0]['tokenPriceUSD'], \"tokenName\" : test_data['result'][0]['tokenName'], \"divisor\":test_data['result'][0]['divisor'], \"symbol\" : test_data['result'][0]['symbol']}\n print(test_data['result'][0]['tokenPriceUSD'],test_data['result'][0]['tokenName'],test_data['result'][0]['divisor'])\n all_tokens_with_spot_prices[str(token)] = cd\n else:\n did_not_work_tokens.append(token)\n \n counter+=1\n if(counter % 2 == 1):\n time.sleep(1.5)",
"0.000000000000000000 Katerium.com 18\n1.000000000000000000 Tether USD 6\n1.000000000000000000 Sai Stablecoin v1.0 18\n13.690000000000000000 Uniswap 18\n1512.790000000000000000 ETH RSI 60/40 Yield II 18\n0.000000000000000000 Lux Expression 18\n1.240000000000000000 Chai 18\n0.000000000000000000 CyberFM 18\n0.997772000000000000 Dai Stablecoin 18\n0.000000000000000000 a!NEVER VISIT www.168pools.com to check DeFi ROi ! 0\n0.000000000000000000 Game Mine Alliance Community 18\n27971.000000000000000000 yearn.finance 18\n0.069907000000000000 BITTO 18\n8.720368254700000000 Index 18\n0.000000000000000000 DAOSquare 18\n0.997605000000000000 USD Coin 6\n0.000000079892000000 CyberFM Radio 18\n0.000000000000000000 A! WWW.SPACESWAP.APP ! TOP DEFI AGGREGATOR ! 0\n0.000000000000000000 Metta Token 2\n2731.100000000000000000 Wrapped Ether 18\n18.760000000000000000 ChainLink Token 18\n0.000000000000000000 Huh 18\n48.330000000000000000 MetaFactory 18\n0.000000000000000000 DSCVR 18\n0.000000000000000000 Fraktal 18\n0.000000000000000000 GENESIS 18\n0.000000000000000000 Sprout 18\n0.000000000000000000 SEED 18\n0.000000000000000000 Sprout 18\n0.006104061854140000 MachiX Token 18\n6.930000000000000000 DeFi Omega 18\n0.000000000000000000 Streamr (old) 18\n0.000000000000000000 POP (wen Protocol) 6\n0.000024500000000000 SHIBA INU 18\n0.000000000000000000 CASTLE LOOT 18\n0.000000000000000000 MetaFactory Pool Token 18\n"
],
[
"js_str = json.dumps(all_tokens_with_spot_prices)\njs_fin = json.loads(js_str)\nwith open('./list_of_all_mainnet_tokens_with_spot_prices_for_daos.json', 'w') as f:\n json.dump(js_fin, f)",
"_____no_output_____"
],
[
"md_of_dao_data_with_balances_of_each_token = {}",
"_____no_output_____"
],
[
"counter = 0\nfor member_dict in list_of_sets_tokens_in_each_address:\n list_of_all_tokens_with_balances_for_current_member = []\n for address in member_dict:\n for token in member_dict[address]:\n if(counter%20 == 0):\n time.sleep(1)\n cd = {}\n response = requests.get(f\"https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress={token}&address={address}&tag=latest&apikey={API_KEY}\")\n counter += 1\n if not (response.status_code != 204 and response.headers[\"content-type\"].strip().startswith(\"application/json\")):\n response = requests.get(f\"https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress={token}&address={address}&tag=latest&apikey={API_KEY}\")\n counter+=1\n test_data = response.json()\n else:\n test_data = response.json()\n cd[\"contract_address\"] = token\n cd[\"balance\"] = test_data['result']\n print(address, token, test_data[\"result\"])\n list_of_all_tokens_with_balances_for_current_member.append(cd)\n \n md_of_dao_data_with_balances_of_each_token[address] = list_of_all_tokens_with_balances_for_current_member",
"0x0557b380dd0f96d04829cfe7f8440d2b61bdb345 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0x016e79e9101a8eaa3e7f46d6d1c267819c09c939 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x016e79e9101a8eaa3e7f46d6d1c267819c09c939 0xd15ecdcf5ea68e3995b2d0527a0ae0a3258302f8 109103000037330037082820\n0x098eabc5cb8ca7d8aaeaf0a927a5c2bbcedffb30 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 100000000000000000\n0x0042dfb8301607df72ec9fdab39759371f827bb0 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0x0372f3696fa7dc99801f435fd6737e57818239f2 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x108e0ac5241dd65f1213396681a799ed049dd5dc 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0x1621e5d7b9bb0e1330897f4f5df1fba9eb399263 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 30000000000000000\n0x1bbab7783d2dbe69f636cfa182dbc67e3f6e5093 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0x1b3d7efb93ec432b0d1d56880c23303979b379e9 0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359 10000000000000000000\n0x1b3d7efb93ec432b0d1d56880c23303979b379e9 0x0f8b6440a1f7be3354fe072638a5c0f500b044be 777000000000000000000\n0x1b3d7efb93ec432b0d1d56880c23303979b379e9 0x6b175474e89094c44da98b954eedeac495271d0f 21999772000000000000\n0x1e5435f26bf2aebceb0adc2c888b98b9bddebff5 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0x2bf0689b22c1092aaf6a09437af316985e67ba12 0x4a621d9f1b19296d1c0f87637b3a8d4978e9bf82 38950002850000000000000000\n0x20aadbcef735356fffeb2f40519ac7105c0284b4 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 2060000000000000000\n0x20aadbcef735356fffeb2f40519ac7105c0284b4 0xa6a5deea66550772d4a2d77ecbe0187451a4f19e 10003523000000000000000000\n0x1fab0f9902a6a47c685d4aaa231a54e08184f89c 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 1200000000000000000\n0x2c0279d18317186c42fcf041bd427367b266fb4e 0x6b175474e89094c44da98b954eedeac495271d0f 20000000000000000000\n0x265989a4a7ce6f025db1618667495aa51c5121e9 0x6b175474e89094c44da98b954eedeac495271d0f 60200000000000000000\n0x1ba850cb53280d7f9987be283ff462038ec8abe2 0xec0b6afb3f9a609ceed67e2ca551a4c573fd45f7 3360000000000000000000\n0x22274338be63f4f3e01d51f23fc50be138ee0cae 0x6b175474e89094c44da98b954eedeac495271d0f 110000000000000000\n0x23fe7836da91f46051fb0fed622277fe93ddde39 0xe328d8daa44b766f8a2e04e0479f6b316c0bf290 325173503903338332463584\n0x23fe7836da91f46051fb0fed622277fe93ddde39 0x95ad61b0a150d79219dcf64e1e6cc01f0b64c4ce 2544902805184319082066123457\n0x1fd169a4f5c59acf79d0fd5d91d1201ef1bce9f1 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 100000000000000000000\n0x288f70137c4057550f2952468a68d1d223019073 0x6b175474e89094c44da98b954eedeac495271d0f 1000000000000000000\n0x2b0881c43467bb590a7339ff7afe494807f5f914 0x6b175474e89094c44da98b954eedeac495271d0f 10000000000000000000\n0x2e91c43ec620a0e5d2a3b7e2b5b0daeccd119df4 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x32e173fd9cb2a50bc39d313182bd484729c818b4 0x6b175474e89094c44da98b954eedeac495271d0f 5000000000000000\n0x32e173fd9cb2a50bc39d313182bd484729c818b4 0xf456b8b9e142bc50eca8b470c77c2a6571257c13 20000000000000000000000\n0x36dc48ae5e9ba9b752ab32589c9dd809a69cedba 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x3919c6afed517fd3fb193ddb4a1524cd267f0069 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 1000000000000000\n0x395ed08c20dc119478dc6cf6a16d94b377072379 0x06af07097c9eeb7fd685c692751d5c66db49c215 985726677000000000000\n0x3906aaf0bc3fda9ae37b2a33c29411f25c338998 0x88dafebb769311d7fbbeb9a21431fa026d4100d0 100000000000000000000\n0x3a268279cc57d669925e8b6eb5a7be7da6f18984 0x6b175474e89094c44da98b954eedeac495271d0f 335000000000000000000\n0x3cb79bcf7badb7eddf5b57d3b82e6727fa4a24e0 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 100000010000000000\n0x44b0fc4c6612a550104b074b240652f55d62fb68 0x514910771af9ca656af840dff83e8264ecf986ca 100000000000000000000\n0x3d83d62a11e6e55376a9f9604ff049b493450b85 0x6b175474e89094c44da98b954eedeac495271d0f 20000000000000000\n0x46c3e0ee080935768a0d97012841213e88b1fd91 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 30000000000000000\n0x486375801734a9c2a607687ec8f8df5886868f94 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x48c2f0a379f8cc93b1be3775964e242adebfd8dc 0x6b175474e89094c44da98b954eedeac495271d0f 1200000000000000000\n0x0b45a92c9d7f3e3a85d23e211b3061b3406a6029 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 100000000000000000\n0x4dee5bb2e919c5c123b74e7919f6c1984a6bc349 0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 845900000000\n0x4dee5bb2e919c5c123b74e7919f6c1984a6bc349 0x6b175474e89094c44da98b954eedeac495271d0f 9662000000000000000000\n0x4dee5bb2e919c5c123b74e7919f6c1984a6bc349 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 15870261000000000000\n0x519f9662798c2e07fbd5b30c1445602320c5cf5b 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 1749506534098708429527\n0x63e8579d08a0a02dcf1ae5940e3960a27d7374f1 0x47a7fe6e18a01c367a8ef32ee1943c923f3438e5 10000000000000000000\n0x63e8579d08a0a02dcf1ae5940e3960a27d7374f1 0x6b175474e89094c44da98b954eedeac495271d0f 100000000000000000000\n0x63e8579d08a0a02dcf1ae5940e3960a27d7374f1 0x0cf0ee63788a0849fe5297f3407f701e122cc023 2300002387216434020993\n0x501c4311350fe29ca477296a40b5c9dbefcb7517 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0x54a6b19d9611d60e0fca88506cbc93f1e8993535 0x6b175474e89094c44da98b954eedeac495271d0f 120000000000000000000\n0x5248ab2b7f0db71161f8fa975c49576a8e38a24f 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 100000000000000000\n0x5248ab2b7f0db71161f8fa975c49576a8e38a24f 0x9f49ed43c90a540d1cf12f6170ace8d0b88a14e6 206000000000000000\n0x65bdb6b65a7652c4529a92fe7340fa22e754da45 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 300000000000000000\n0x513838f426c3ace6c4930ae74617d2c5c584b648 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0x5eda5792125e4ad108454e6d607db156f10f7ec3 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 100000000000000000\n0x647d2460d8cb322fc5328afbf9dd402af2d1ba11 0x6b175474e89094c44da98b954eedeac495271d0f 10000000000000000000\n0x56e0840c1b86886a743cc8fb696bc9d45f867bfc 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0x684d023f458925ffd7d05566488bc101e5fc087e 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0x67b67c5b7384d6c1cdad1ed988b49183f4c59740 0x6b175474e89094c44da98b954eedeac495271d0f 99523809523809523810\n0x6bb7c65271a0210a62b015a8f4e9d2f529483cae 0x0df6b23127cfd1c931000cbb452a0d75a716c3cd 3300\n0x6c0345d1dae7fbf82b485844d1b2a72f220802e8 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x6c8b9d71bb6c29e0ac7a33ddaefcf0a0f3e88f8f 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 200000000000000000\n0x71bfa532de073440625d63fc8b55ee8c26230ae4 0x6b175474e89094c44da98b954eedeac495271d0f 100000000000000000\n0x75a660c394d69cf386d8cc290c2eca39faa72404 0x1f9840a85d5af5bf1d1762f925bdaddc4201f984 0\n0x7ae4bc22d038479c8ad21616450cd5e35d3f03cc 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 2990000000000000000\n0x7d58c962356ae66ba91b108751d67ae5d3b022fc 0x6b175474e89094c44da98b954eedeac495271d0f 52604202543271111228205\n0x7ef1a1f5a6b74d4d32366a416a2e8564225d3f85 0x6b175474e89094c44da98b954eedeac495271d0f 5000000000000000000\n0x827a9eeaece50deaf176b72a796ca216ab007680 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0x840931472dd1a8d925c7cfe972949427c9363876 0x6b175474e89094c44da98b954eedeac495271d0f 7000000000000000000\n0x8a4aab6f20e529f06e43dccb04abf50e37d2a30a 0x514910771af9ca656af840dff83e8264ecf986ca 300000000000000000\n0x8ead46289142f6b91483460494a02cf38e876a7a 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x933a3f1f8d6f41368bfc35ab7ae1640760c173a7 0x6b175474e89094c44da98b954eedeac495271d0f 40000000000000000000\n0x8c6f91cfa3a7f7998ec2d2af597d885bd3c1ea4a 0x6b175474e89094c44da98b954eedeac495271d0f 5000000000000000000\n0x8c07cac4e23915367f910282d546cfa832585845 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 8000000000000000\n0x8f56682a50becb1df2fb8136954f2062871bc7fc 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 7637097195174772483261\n0x95213610eeaa4f7fde7d47a216a367b7440b9ddb 0x6b175474e89094c44da98b954eedeac495271d0f 5\n0x9884a07537c0171ec472e3aa0b1b210d284db588 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x9884a07537c0171ec472e3aa0b1b210d284db588 0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e 0\n0x9a656048c4e56e4a9adce6439d9c2dfe733e80d6 0x6b175474e89094c44da98b954eedeac495271d0f 5000000000000000000\n0x9f8a1b78e081a0be1d773c375e215c6308bbdfc8 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 160000000000000000\n0x9f0db0380c45c509c886fcdea0cf21468c44a19d 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 400000000000000000\n0x9f0db0380c45c509c886fcdea0cf21468c44a19d 0xdac17f958d2ee523a2206206994597c13d831ec7 10000000\n0x358f82b15e58f9729695af01f8f9dde0d1bf366b 0xe328d8daa44b766f8a2e04e0479f6b316c0bf290 9395227874827614036728237\n0xa41558e787eea24fcbd2dff23b06843eadc25b8c 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0xa440cc047fd0bc519af1dab35d8d8fe558c358e3 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0xa4a83c5d1d92c23578689d93e4235ed45ce9fd8e 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0xb0d854aa93ffc875e9a3f589681d2a6a48b17948 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0xb0d854aa93ffc875e9a3f589681d2a6a48b17948 0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e 0\n0xb42616e266cb0c6d34c1434f09b95ed50bb551ed 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0xb549ec858cd0f4bdd0da02219fd0f1b1752cff10 0x6b175474e89094c44da98b954eedeac495271d0f 5000000000000000000\n0xbf7b847ff199802daf98d3026f84f0616fed30bf 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0xb5cef5887a0b46d895cb1893b3cddc9a31607261 0x6b175474e89094c44da98b954eedeac495271d0f 251146227043369900517\n0xb849a36afa2cf745d47f687d563b102c2ce5de0b 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x934d6b90e3f916a3ad5d080a674a1e953447dda3 0x6b175474e89094c44da98b954eedeac495271d0f 2120465217391304347827\n0xc379b99686f295247f306a2d357e1c0a138db15f 0x6b175474e89094c44da98b954eedeac495271d0f 5000000000000000000\n0xc2b856f2b64a8b287d936529f3646aa8443d885e 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0xc0cbf4c4867fc1a0d8d03c4f170dcff70810d8f2 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0xbd6fa666fbb6fdeb4fc5eb36cdd5c87b069b24c1 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0xbeb3e32355a933501c247e2dbde6e6ca2489bf3d 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 15915066728182422166\n0xc9aad3fba09f46532cfbadef3d885386ca1aa9fe 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 200000000000000000\n0xc9aad3fba09f46532cfbadef3d885386ca1aa9fe 0x32b87fb81674aa79214e51ae42d571136e29d385 5980000000000000000000\n0xc4cd59453b71ef6175dc3aa3393b7510ffa280a0 0x6b175474e89094c44da98b954eedeac495271d0f 100294705294705294706\n0xd2303440e177df44d5829ca35a42a4c1f421aaba 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 5000000000000000\n0xd2a39911e256da78a4759f992bdf55fbf89809f4 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 100000000000000000\n0xd2a39911e256da78a4759f992bdf55fbf89809f4 0x0954906da0bf32d5479e25f46056d22f08464cab 198990000000000000000\n0xd797787127f03012ca35363c06ee6f214df43205 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0xd7cb71297625ce3b1351be36ee6144d0c987f06f 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0xdbf066453ec7091bda004cf29d7faaebf920679f 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0xda6f46819152ce84a7e5f975024913320fe0007d 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0xda7b1338946913f395a0cb2e019bcd352da918cc 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 150000000000000000\n0xe1fa628c1bddca38bee6020e367fc0f7d35bf06c 0xa6a21313fe2fc6a5cf1e293dcbf99d180865babc 14000000000000000000000\n0xdec090a12f2e280b089daa225892d9efa8ed0ee8 0x6b175474e89094c44da98b954eedeac495271d0f 10126000000000000000000\n0xe3aa9ca8878efcde4990bcb6159445fe9843902f 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0xf0cbba291d9809569d0a74ea56cd20253a421f8d 0x6b175474e89094c44da98b954eedeac495271d0f 200000000000000000000\n0xfac8b74cfccbaf1c308d83f75832be860dd288c1 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0xec10a54c9ed76f29c9d469b64fd3b6a5fd69c34d 0xfb5453340c03db5ade474b27e68b6a9c6b2823eb 2355687233047363935663\n0xec10a54c9ed76f29c9d469b64fd3b6a5fd69c34d 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 271014294512785063\n0xec10a54c9ed76f29c9d469b64fd3b6a5fd69c34d 0xccf5575570fac94cec733a58ff91bb3d073085c7 1405378887604594966536\n0xe917c7c6932a1b9393e8f2df6e3c2531b58e37db 0x6e3ce0f2abe08539479139928eedddff41177144 2020000001\n0xee629a192374caf2a72cf1695c485c5c89611ef2 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 1207507255443081281\n0xe9d7e590171cb5080ab8dfd45850692a714260f0 0xee3b9b531f4c564c70e14b7b3bb7d516f33513ff 3481666666666666666670\n0xeb02a1b9981b771dbf53500a9ba9bc01469452c3 0x91fc82f5c588c00985aa264fc7b45ee680110703 41240738780552328155142\n0xfdd6d5c17d5d0fff346554a657f183b9a03720ea 0x42b54830bcbb0a240aa54cd3f8d1a4db00851fe3 199370293194307552292\n0xfc68a27ad5068ceacbc08a0d513f22a753878748 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0xf251bd64dc9bb8a9e0180b0adf414799101bc3e8 0x6b175474e89094c44da98b954eedeac495271d0f 6000000000000000000000\n0xfc3adcb73014163450d34d07f04c702e22176f92 0x6b175474e89094c44da98b954eedeac495271d0f 60000000000000000000\n0x36fab4ac1d36e5f1015236261e42365cb4feac52 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 193694068222361245442\n0xcfa7700f9c15f03e0ae81ebd524e4c2af915d13b 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 35483339130145448900\n0xcc7dcdb700eed457c8180406d7d699877f4eee24 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x26edf55480c50a2fab52d0d7bdf1dbbf2f4bb14f 0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 3000001000000\n0x26edf55480c50a2fab52d0d7bdf1dbbf2f4bb14f 0xa90d260c535b410843795a87d632865c64e0bbac 4000000000000000000000000\n0x4570b4faf71e23942b8b9f934b47ccedf7540162 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 3636110567115636356580\n0x014ded81ddb85f7d178a66bcdd6cd6ca89ba7cc5 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0x47b45f8b527a0dbcd315e4c9cee4b8ff118f8a31 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 975000000000000000\n0x47b45f8b527a0dbcd315e4c9cee4b8ff118f8a31 0x6b175474e89094c44da98b954eedeac495271d0f 1555000000000000000000\n0x96c8c63352d416378040a31ab8a231dd8104da58 0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359 0\n0xa8fc468da0417f71393523393bd7d57450143a62 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0xcea6952b9d31b29c056c7b15b76e728ee5312222 0x6b175474e89094c44da98b954eedeac495271d0f 9000000000000000000\n0x6680c3fd10d6449bb0a7617d7bbdc122dd417788 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 14900000000000000\n0x6680c3fd10d6449bb0a7617d7bbdc122dd417788 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0x6680c3fd10d6449bb0a7617d7bbdc122dd417788 0xf3942c3a0e225dc515ea734c87a544ddd7bd2fbf 90000000000000000000\n0x714879cb9028cb7577e1f35a31da7d8eaac15462 0x6b175474e89094c44da98b954eedeac495271d0f 6000000000000000000\n0x714879cb9028cb7577e1f35a31da7d8eaac15462 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x161e99f7467f20602c7ff9ff85f22be1ecc41b86 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x829c2b9cc07589f2accbfc84130f0534b3abbefe 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 90000000000000000\n0x6754bfb36f9d3d7771a4c3eb53507be7f1c09e49 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x071124f489b96101e4a6b1ce78a0c4b9eba881a2 0x32b87fb81674aa79214e51ae42d571136e29d385 1001000000000000000000000\n0xfc8eba8a52b21562f8b6843f545f4e744f0f0d41 0x6b175474e89094c44da98b954eedeac495271d0f 0\n0xfc8eba8a52b21562f8b6843f545f4e744f0f0d41 0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 454694010\n0xfc8eba8a52b21562f8b6843f545f4e744f0f0d41 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0x7bd649681fbdce257c115594c4c7d6bc6beea3e2 0x6b175474e89094c44da98b954eedeac495271d0f 21000000000000000000\n0xdecca5c1ed39d1b0948b97d6bcd31acf374efbc5 0x6b175474e89094c44da98b954eedeac495271d0f 660000000000000000000\n0x6165272c4351021b2b842a5c26cae3ebf16aba2f 0x6b175474e89094c44da98b954eedeac495271d0f 75000000000000000000\n0xcb46298767fb5d44c18313976c30d3eeb5071862 0x55a290f08bb4cae8dcf1ea5635a3fcfd4da60456 2200000000000000000\n0xcb46298767fb5d44c18313976c30d3eeb5071862 0xb07de4b2989e180f8907b8c7e617637c26ce2776 856420144564\n0xcb46298767fb5d44c18313976c30d3eeb5071862 0x6b175474e89094c44da98b954eedeac495271d0f 50676950998185117970\n0xcb46298767fb5d44c18313976c30d3eeb5071862 0xa9517b2e61a57350d6555665292dbc632c76adfe 856420144564\n0xcb46298767fb5d44c18313976c30d3eeb5071862 0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e 296551724137931036\n0x6c9b4f1bdddd7704a26a5caf5242e88501dc5f0b 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n0xa9ade79ab198a579772dd5e310ea28643e4a4421 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 0\n"
],
[
"all_wallet_totals = {}\nfinal_data_set = {}",
"_____no_output_____"
],
[
"for address in md_of_dao_data_with_balances_of_each_token:\n total = 0\n for token in md_of_dao_data_with_balances_of_each_token[address]:\n if(len(md_of_dao_data_with_balances_of_each_token[address]) > 0):\n if type(all_tokens_with_spot_prices[token['contract_address']]) is dict:\n price = float(all_tokens_with_spot_prices[token['contract_address']][\"tokenPriceUSD\"])\n divisor = int(all_tokens_with_spot_prices[token['contract_address']][\"divisor\"])\n balance = int(token['balance'])\n divided_balance = balance/ (10**divisor)\n value = divided_balance * price\n total+=value\n \n \n all_wallet_totals[address] = total",
"_____no_output_____"
],
[
"ml_of_all_addresses_and_token_info = []",
"_____no_output_____"
],
[
"for address in md_of_dao_data_with_balances_of_each_token:\n address_final_dict = {}\n address_final_dict[\"address\"] = address\n\n enriched_list_of_tokens = []\n for token in md_of_dao_data_with_balances_of_each_token[address]:\n if type(all_tokens_with_spot_prices[token['contract_address']]) is dict:\n cd = {}\n cd['contract_address'] = token['contract_address']\n cd['token_name'] = all_tokens_with_spot_prices[token['contract_address']][\"tokenName\"]\n cd['divisor'] = all_tokens_with_spot_prices[token['contract_address']][\"divisor\"]\n cd['symbol'] = all_tokens_with_spot_prices[token['contract_address']][\"symbol\"]\n cd['balance'] = token['balance']\n enriched_list_of_tokens.append(cd)\n\n address_final_dict[\"token_info\"] = enriched_list_of_tokens\n address_final_dict[\"wallet_total\"] = all_wallet_totals[address]\n address_final_dict[\"members\"] = []\n ml_of_all_addresses_and_token_info.append(address_final_dict)",
"_____no_output_____"
],
[
"for dao in ml_of_all_addresses_and_token_info:\n dao['members'] = []",
"_____no_output_____"
],
[
"for member in main_net_members:\n for dao in ml_of_all_addresses_and_token_info:\n if(dao['address'] == member[0]):\n dao['members'].append(member[1])",
"_____no_output_____"
],
[
"js_str = json.dumps(ml_of_all_addresses_and_token_info)\njs_fin = json.loads(js_str)\nwith open('./all_mainnet_dao_data_with_token_balances_and_wallet_totals.json', 'w') as f:\n json.dump(js_fin, f)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac2c5ba6aef80ddd9e332536b81ef722b63bd55
| 8,139 |
ipynb
|
Jupyter Notebook
|
M2AA3/M2AA3-Polynomials/Lesson 02 - Newton Method/Newton Tableau.ipynb
|
ImperialCollegeLondon/Random-Stuff
|
219bc0e26ea6f5ee7548009c849959b268f54821
|
[
"MIT"
] | 2 |
2021-05-16T04:08:34.000Z
|
2021-11-27T12:56:10.000Z
|
M2AA3/M2AA3-Polynomials/Lesson 02 - Newton Method/Newton Tableau.ipynb
|
ImperialCollegeLondon/Random-Stuff
|
219bc0e26ea6f5ee7548009c849959b268f54821
|
[
"MIT"
] | null | null | null |
M2AA3/M2AA3-Polynomials/Lesson 02 - Newton Method/Newton Tableau.ipynb
|
ImperialCollegeLondon/Random-Stuff
|
219bc0e26ea6f5ee7548009c849959b268f54821
|
[
"MIT"
] | 3 |
2020-03-31T00:23:13.000Z
|
2020-05-13T15:01:46.000Z
| 26.003195 | 270 | 0.467256 |
[
[
[
"import sympy as sp\nimport numpy as np",
"_____no_output_____"
],
[
"x = sp.symbols('x')\np = sp.Function('p')\nl = sp.Function('l')\npoly = sp.Function('poly')\np3 = sp.Function('p3')\np4 = sp.Function('p4')",
"_____no_output_____"
]
],
[
[
"# Introduction\n\nLast time we have used Lagrange basis to interpolate polynomial. However, it is not efficient to update the interpolating polynomial when a new data point is added. We look at an iterative approach.\n\nGiven points $\\{(z_i, f_i) \\}_{i=0}^{n-1}$, $z_i$ are distinct and $p_{n-1} \\in \\mathbb{C}[z]_{n-1}\\, , p_{n-1}(z_i) = f_i$. <br> We add a point $(z_n, f_n)$ and find a polynomial $p_n \\in \\mathbb{C}[x]_{n-1}$ which satisfies $\\{(z_i, f_i) \\}_{i=0}^{n}$. ",
"_____no_output_____"
],
[
"We assume $p_n(z)$ be the form\n\\begin{equation}\np_n(z) = p_{n-1}(z) + C\\prod_{i=0}^{n-1}(z - z_i)\n\\end{equation}\nso that the second term vanishes at $z = z_0,...,z_{n-1}$ and $p_n(z_i) = p_{n-1}(z_i), i = 0,...,n-1$. We also want $p_n(z_n) = f_n$ so we have\n\\begin{equation}\nf_n = p_{n-1}(z_n) + C\\prod_{i=0}^{n-1}(z_n - z_i) \\Rightarrow C = \\frac{f_n - p_{n-1}(z_n)}{\\prod_{i=0}^{n-1}(z_n - z_i)}\n\\end{equation}\nThus we may perform interpolation iteratively.",
"_____no_output_____"
],
[
"**Example:** Last time we have\n\\begin{equation}\n(z_0, f_0) = (-1,-3), \\quad\n(z_1, f_1) = (0,-1), \\quad\n(z_2, f_2) = (2,4), \\quad\n(z_3, f_3) = (5,1)\n\\end{equation}\nand \n\\begin{equation}\np_3(x) = \\frac{-13}{90}z^3 + \\frac{14}{45}z^2 + \\frac{221}{90}z - 1\n\\end{equation}",
"_____no_output_____"
]
],
[
[
"z0 = -1; f0 = -3; z1 = 0; f1 = -1; z2 = 2; f2 = 4; z3 = 5; f3 = 1; z4 = 1; f4 = 1\np3 = -13*x**3/90 + 14*x**2/45 + 221*x/90 - 1",
"_____no_output_____"
]
],
[
[
"We add a point $(z_4,f_4) = (1,1)$ and obtain $p_4(x)$",
"_____no_output_____"
]
],
[
[
"z4 = 1; f4 = 1",
"1 1\n"
],
[
"C = (f4 - p3.subs(x,z4))/((z4-z0)*(z4-z1)*(z4-z2)*(z4-z3))\nC",
"_____no_output_____"
],
[
"p4 = p3 + C*(x-z0)*(x-z1)*(x-z2)*(x-z3)\nsp.expand(p4)",
"_____no_output_____"
]
],
[
[
"**Remark:** the constant $C$ is usually written as $f[z_0,z_1,z_2,z_3,z_4]$. Moreover by iteration we have\n$$p_n(z) = \\sum_{i=0}^n f[z_0,...,z_n] \\prod_{j=0}^i (z - z_j)$$",
"_____no_output_____"
],
[
"# Newton Tableau",
"_____no_output_____"
],
[
"We look at efficient ways to compute $f[z_0,...,z_n]$, iteratively from $f[z_0,...,z_{n-1}]$ and $f[z_1,...,z_n]$. <br>\nWe may first construct $p_{n-1}$ and $q_{n-1}$ before constructing $p_n$ itself, where\n\\begin{gather}\np_{n-1}(z_i) = f_i \\quad i = 0,...,n-1\\\\\nq_{n-1}(z_i) = f_i \\quad i = 1,...,n\n\\end{gather}\n**Claim:** The following polynomial interpolate $\\{(z_i,f_i)\\}_{i=0}^n$\n\\begin{equation}\np_n(z_i) = \\frac{(z - z_n)p_{n-1}(z) - (z - z_0)q_{n-1}(z)}{z_0 - z_n}\n\\end{equation}\nSince interpolating polynomial is unique, by comparing coefficient of $z_n$, we have\n$$f[z_0,...,z_{n}] = \\frac{f[z_0,...,z_{n-1}]-f[z_1,...,z_{n}]}{z_0 - z_n}$$",
"_____no_output_____"
]
],
[
[
"def product(xs,key,i):\n \n #Key: Forward or Backward\n \n n = len(xs)-1\n l = 1\n \n for j in range(i):\n if key == 'forward':\n l *= (x - xs[j])\n else:\n l *= (x - xs[n-j])\n\n return l",
"_____no_output_____"
],
[
"def newton(xs,ys,key):\n \n # Key: Forward or Backward\n \n n = len(xs)-1\n # print(xs)\n print(ys)\n old_column = ys\n \n if key == 'forward':\n coeff = [fs[0]]\n elif key == 'backward':\n coeff = [fs[len(fs)-1]]\n else:\n return 'error'\n \n for i in range(1,n+1): # Column Index\n new_column = [(old_column[j+1] - old_column[j])/(xs[j+i] - xs[j]) for j in range(n-i+1)]\n print(new_column)\n if key == 'forward':\n coeff.append(new_column[0])\n else:\n coeff.append(new_column[len(new_column)-1])\n old_column = new_column\n \n # print(coeff)\n \n poly = 0\n for i in range(n+1):\n poly += coeff[i] * product(xs,key,i)\n \n return poly",
"_____no_output_____"
],
[
"zs = [1, 4/3, 5/3, 2]; fs = [np.sin(x) for x in zs]",
"_____no_output_____"
],
[
"p = newton(zs,fs,'backward')\nsp.simplify(p)",
"[0.8414709848078965, 0.9719379013633127, 0.9954079577517649, 0.9092974268256817]\n[0.3914007496662487, 0.07041016916535667, -0.25833159277824974]\n[-0.481485870751338, -0.4931126429154095]\n[-0.011626772164071542]\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4ac2ca882ada476aadc98d9980eb0b0d19876ada
| 196,924 |
ipynb
|
Jupyter Notebook
|
examples/lasso/Intersect polys.ipynb
|
gewitterblitz/lmatools
|
11a90921a827aaf89d925573c1a55088f4215dfd
|
[
"BSD-2-Clause"
] | 13 |
2015-02-27T20:45:06.000Z
|
2022-01-03T10:59:43.000Z
|
examples/lasso/Intersect polys.ipynb
|
gewitterblitz/lmatools
|
11a90921a827aaf89d925573c1a55088f4215dfd
|
[
"BSD-2-Clause"
] | 19 |
2015-03-27T03:09:03.000Z
|
2021-09-19T18:55:41.000Z
|
examples/lasso/Intersect polys.ipynb
|
gewitterblitz/lmatools
|
11a90921a827aaf89d925573c1a55088f4215dfd
|
[
"BSD-2-Clause"
] | 23 |
2015-03-27T17:02:27.000Z
|
2021-09-08T17:30:28.000Z
| 556.282486 | 88,498 | 0.747395 |
[
[
[
"import json, copy\nimport operator\nimport datetime\n",
"_____no_output_____"
],
[
"from KTAL.RadarAnalysis.GridLassoTools import read_polys\n\ntime_keys = {'frame_time':'%Y-%m-%dT%H:%M:%S'}\n\n# Read in some polygons\npolys = read_polys('/data/VORTEX-SE/NALMA/realtime/VSE3sticknetA-AL-20160331-polygon.txt', \n sort_key = 'frame_time', time_keys=time_keys)\n",
"/Users/ebruning/anaconda/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.\n warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')\n/Users/ebruning/anaconda/lib/python2.7/site-packages/matplotlib/__init__.py:1350: UserWarning: This call to matplotlib.use() has no effect\nbecause the backend has already been chosen;\nmatplotlib.use() must be called *before* pylab, matplotlib.pyplot,\nor matplotlib.backends is imported for the first time.\n\n warnings.warn(_use_error_msg)\n"
],
[
"for p in polys:\n print p",
"{u'y_verts': [35.370535714285715, 35.450892857142854, 35.2734375, 34.941964285714285, 34.720982142857146, 35.018973214285715, 35.229910714285715, 35.370535714285715], u'x_verts': [-87.74516129032259, -88.03548387096775, -88.17741935483872, -88.1483870967742, -87.93870967741935, -87.73870967741937, -87.66774193548387, -87.74516129032259], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 25, 57, 189000), u'frame_id': 1307, u'frame_time': datetime.datetime(2016, 3, 31, 21, 47), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.370535714285715, 35.450892857142854, 35.2734375, 34.941964285714285, 34.720982142857146, 35.018973214285715, 35.229910714285715, 35.370535714285715], u'x_verts': [-87.74516129032259, -88.03548387096775, -88.17741935483872, -88.1483870967742, -87.93870967741935, -87.73870967741937, -87.66774193548387, -87.74516129032259], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 25, 57, 189000), u'frame_id': 1307, u'frame_time': datetime.datetime(2016, 3, 31, 21, 47), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.410714285714285, 35.005580357142854, 34.871651785714285, 34.878348214285715, 35.10267857142857, 35.166294642857146, 35.357142857142854, 35.410714285714285], u'x_verts': [-88.08709677419355, -88.0967741935484, -88.09032258064516, -87.30967741935484, -87.30645161290323, -87.69032258064517, -87.72903225806452, -88.08709677419355], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 22, 438000), u'frame_id': 1312, u'frame_time': datetime.datetime(2016, 3, 31, 21, 52), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.410714285714285, 35.005580357142854, 34.871651785714285, 34.878348214285715, 35.10267857142857, 35.166294642857146, 35.357142857142854, 35.410714285714285], u'x_verts': [-88.08709677419355, -88.0967741935484, -88.09032258064516, -87.30967741935484, -87.30645161290323, -87.69032258064517, -87.72903225806452, -88.08709677419355], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 22, 438000), u'frame_id': 1312, u'frame_time': datetime.datetime(2016, 3, 31, 21, 52), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.4609375, 34.978794642857146, 34.7578125, 34.965401785714285, 35.306919642857146, 35.417410714285715, 35.42075892857143, 35.527901785714285, 35.4609375], u'x_verts': [-88.08709677419355, -88.09354838709677, -87.96451612903226, -87.35483870967742, -87.2741935483871, -87.59032258064516, -87.74516129032259, -87.89032258064516, -88.08709677419355], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 34, 274000), u'frame_id': 1313, u'frame_time': datetime.datetime(2016, 3, 31, 21, 53), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.4609375, 34.978794642857146, 34.7578125, 34.965401785714285, 35.306919642857146, 35.417410714285715, 35.42075892857143, 35.527901785714285, 35.4609375], u'x_verts': [-88.08709677419355, -88.09354838709677, -87.96451612903226, -87.35483870967742, -87.2741935483871, -87.59032258064516, -87.74516129032259, -87.89032258064516, -88.08709677419355], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 34, 274000), u'frame_id': 1313, u'frame_time': datetime.datetime(2016, 3, 31, 21, 53), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.47767857142857, 34.948660714285715, 34.875, 34.978794642857146, 35.387276785714285, 35.434151785714285, 35.504464285714285, 35.47767857142857], u'x_verts': [-88.1483870967742, -88.0967741935484, -87.71290322580646, -86.85161290322581, -87.02903225806452, -87.67096774193548, -88.01935483870969, -88.1483870967742], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 44, 20000), u'frame_id': 1314, u'frame_time': datetime.datetime(2016, 3, 31, 21, 54), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.47767857142857, 34.948660714285715, 34.875, 34.978794642857146, 35.387276785714285, 35.434151785714285, 35.504464285714285, 35.47767857142857], u'x_verts': [-88.1483870967742, -88.0967741935484, -87.71290322580646, -86.85161290322581, -87.02903225806452, -87.67096774193548, -88.01935483870969, -88.1483870967742], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 44, 20000), u'frame_id': 1314, u'frame_time': datetime.datetime(2016, 3, 31, 21, 54), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.50111607142857, 35.142857142857146, 34.941964285714285, 34.925223214285715, 35.38392857142857, 35.447544642857146, 35.504464285714285, 35.50111607142857], u'x_verts': [-88.07096774193549, -88.08064516129033, -88.01290322580645, -87.24193548387098, -87.17419354838711, -87.62903225806453, -87.95161290322581, -88.07096774193549], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 56, 243000), u'frame_id': 1316, u'frame_time': datetime.datetime(2016, 3, 31, 21, 56), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.50111607142857, 35.142857142857146, 34.941964285714285, 34.925223214285715, 35.38392857142857, 35.447544642857146, 35.504464285714285, 35.50111607142857], u'x_verts': [-88.07096774193549, -88.08064516129033, -88.01290322580645, -87.24193548387098, -87.17419354838711, -87.62903225806453, -87.95161290322581, -88.07096774193549], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 56, 243000), u'frame_id': 1316, u'frame_time': datetime.datetime(2016, 3, 31, 21, 56), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.497767857142854, 35.193080357142854, 34.988839285714285, 34.921875, 34.95200892857143, 35.300223214285715, 35.450892857142854, 35.544642857142854, 35.497767857142854], u'x_verts': [-88.01935483870969, -88.14193548387097, -88.02903225806452, -87.8967741935484, -87.25483870967743, -87.30967741935484, -87.66774193548387, -87.9, -88.01935483870969], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 7, 134000), u'frame_id': 1317, u'frame_time': datetime.datetime(2016, 3, 31, 21, 57), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.497767857142854, 35.193080357142854, 34.988839285714285, 34.921875, 34.95200892857143, 35.300223214285715, 35.450892857142854, 35.544642857142854, 35.497767857142854], u'x_verts': [-88.01935483870969, -88.14193548387097, -88.02903225806452, -87.8967741935484, -87.25483870967743, -87.30967741935484, -87.66774193548387, -87.9, -88.01935483870969], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 7, 134000), u'frame_id': 1317, u'frame_time': datetime.datetime(2016, 3, 31, 21, 57), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.4140625, 35.169642857142854, 34.901785714285715, 34.921875, 35.122767857142854, 35.323660714285715, 35.487723214285715, 35.4140625], u'x_verts': [-88.08387096774194, -88.06774193548388, -87.98387096774194, -87.47096774193548, -87.2516129032258, -87.55483870967743, -87.7483870967742, -88.08387096774194], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 16, 932000), u'frame_id': 1318, u'frame_time': datetime.datetime(2016, 3, 31, 21, 58), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.4140625, 35.169642857142854, 34.901785714285715, 34.921875, 35.122767857142854, 35.323660714285715, 35.487723214285715, 35.4140625], u'x_verts': [-88.08387096774194, -88.06774193548388, -87.98387096774194, -87.47096774193548, -87.2516129032258, -87.55483870967743, -87.7483870967742, -88.08387096774194], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 16, 932000), u'frame_id': 1318, u'frame_time': datetime.datetime(2016, 3, 31, 21, 58), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.37388392857143, 35.002232142857146, 34.88169642857143, 34.96205357142857, 35.347098214285715, 35.40736607142857, 35.37388392857143], u'x_verts': [-88.0, -88.04838709677419, -87.96451612903226, -87.11612903225807, -87.23548387096774, -87.9, -88.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 25), u'frame_id': 1319, u'frame_time': datetime.datetime(2016, 3, 31, 21, 59), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.37388392857143, 35.002232142857146, 34.88169642857143, 34.96205357142857, 35.347098214285715, 35.40736607142857, 35.37388392857143], u'x_verts': [-88.0, -88.04838709677419, -87.96451612903226, -87.11612903225807, -87.23548387096774, -87.9, -88.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 25), u'frame_id': 1319, u'frame_time': datetime.datetime(2016, 3, 31, 21, 59), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.457589285714285, 35.159598214285715, 35.018973214285715, 34.89174107142857, 34.93861607142857, 35.323660714285715, 35.4140625, 35.564732142857146, 35.457589285714285], u'x_verts': [-88.05806451612904, -88.06451612903226, -88.00967741935484, -87.88387096774194, -87.34193548387097, -87.3483870967742, -87.61612903225807, -87.73548387096774, -88.05806451612904], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 36, 979000), u'frame_id': 1320, u'frame_time': datetime.datetime(2016, 3, 31, 22, 0), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.457589285714285, 35.159598214285715, 35.018973214285715, 34.89174107142857, 34.93861607142857, 35.323660714285715, 35.4140625, 35.564732142857146, 35.457589285714285], u'x_verts': [-88.05806451612904, -88.06451612903226, -88.00967741935484, -87.88387096774194, -87.34193548387097, -87.3483870967742, -87.61612903225807, -87.73548387096774, -88.05806451612904], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 36, 979000), u'frame_id': 1320, u'frame_time': datetime.datetime(2016, 3, 31, 22, 0), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.404017857142854, 35.129464285714285, 34.875, 34.978794642857146, 35.16294642857143, 35.45424107142857, 35.59486607142857, 35.404017857142854], u'x_verts': [-88.09032258064516, -88.04838709677419, -87.90967741935485, -87.50645161290323, -87.18387096774194, -87.68709677419355, -87.87096774193549, -88.09032258064516], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 49, 422000), u'frame_id': 1321, u'frame_time': datetime.datetime(2016, 3, 31, 22, 1), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.404017857142854, 35.129464285714285, 34.875, 34.978794642857146, 35.16294642857143, 35.45424107142857, 35.59486607142857, 35.404017857142854], u'x_verts': [-88.09032258064516, -88.04838709677419, -87.90967741935485, -87.50645161290323, -87.18387096774194, -87.68709677419355, -87.87096774193549, -88.09032258064516], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 49, 422000), u'frame_id': 1321, u'frame_time': datetime.datetime(2016, 3, 31, 22, 1), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.39732142857143, 35.16294642857143, 34.99888392857143, 34.9453125, 34.972098214285715, 35.3203125, 35.504464285714285, 35.511160714285715, 35.39732142857143], u'x_verts': [-88.07096774193549, -87.99354838709678, -87.92258064516129, -87.70967741935485, -87.25483870967743, -87.25806451612904, -87.51612903225806, -87.92258064516129, -88.07096774193549], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 1, 920000), u'frame_id': 1322, u'frame_time': datetime.datetime(2016, 3, 31, 22, 2), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.39732142857143, 35.16294642857143, 34.99888392857143, 34.9453125, 34.972098214285715, 35.3203125, 35.504464285714285, 35.511160714285715, 35.39732142857143], u'x_verts': [-88.07096774193549, -87.99354838709678, -87.92258064516129, -87.70967741935485, -87.25483870967743, -87.25806451612904, -87.51612903225806, -87.92258064516129, -88.07096774193549], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 1, 920000), u'frame_id': 1322, u'frame_time': datetime.datetime(2016, 3, 31, 22, 2), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.377232142857146, 35.1796875, 34.935267857142854, 34.972098214285715, 35.263392857142854, 35.393973214285715, 35.558035714285715, 35.56138392857143, 35.377232142857146], u'x_verts': [-88.06774193548388, -88.05483870967743, -87.90967741935485, -87.48387096774194, -87.30000000000001, -87.45161290322581, -87.63870967741936, -87.8967741935484, -88.06774193548388], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 10, 216000), u'frame_id': 1323, u'frame_time': datetime.datetime(2016, 3, 31, 22, 3), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.377232142857146, 35.1796875, 34.935267857142854, 34.972098214285715, 35.263392857142854, 35.393973214285715, 35.558035714285715, 35.56138392857143, 35.377232142857146], u'x_verts': [-88.06774193548388, -88.05483870967743, -87.90967741935485, -87.48387096774194, -87.30000000000001, -87.45161290322581, -87.63870967741936, -87.8967741935484, -88.06774193548388], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 10, 216000), u'frame_id': 1323, u'frame_time': datetime.datetime(2016, 3, 31, 22, 3), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.527901785714285, 35.04575892857143, 34.801339285714285, 35.122767857142854, 35.450892857142854, 35.60825892857143, 35.527901785714285], u'x_verts': [-87.99032258064517, -87.96129032258065, -87.78064516129032, -87.4483870967742, -87.45161290322581, -87.63225806451614, -87.99032258064517], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 18, 860000), u'frame_id': 1324, u'frame_time': datetime.datetime(2016, 3, 31, 22, 4), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.527901785714285, 35.04575892857143, 34.801339285714285, 35.122767857142854, 35.450892857142854, 35.60825892857143, 35.527901785714285], u'x_verts': [-87.99032258064517, -87.96129032258065, -87.78064516129032, -87.4483870967742, -87.45161290322581, -87.63225806451614, -87.99032258064517], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 18, 860000), u'frame_id': 1324, u'frame_time': datetime.datetime(2016, 3, 31, 22, 4), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.333705357142854, 35.025669642857146, 34.911830357142854, 34.978794642857146, 35.112723214285715, 35.527901785714285, 35.67857142857143, 35.591517857142854, 35.333705357142854], u'x_verts': [-88.00645161290323, -87.92258064516129, -87.74516129032259, -87.3258064516129, -87.26451612903226, -87.56129032258065, -87.67741935483872, -87.81612903225808, -88.00645161290323], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 27, 89000), u'frame_id': 1325, u'frame_time': datetime.datetime(2016, 3, 31, 22, 5), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.333705357142854, 35.025669642857146, 34.911830357142854, 34.978794642857146, 35.112723214285715, 35.527901785714285, 35.67857142857143, 35.591517857142854, 35.333705357142854], u'x_verts': [-88.00645161290323, -87.92258064516129, -87.74516129032259, -87.3258064516129, -87.26451612903226, -87.56129032258065, -87.67741935483872, -87.81612903225808, -88.00645161290323], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 27, 89000), u'frame_id': 1325, u'frame_time': datetime.datetime(2016, 3, 31, 22, 5), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.404017857142854, 35.152901785714285, 34.978794642857146, 34.95200892857143, 35.07924107142857, 35.357142857142854, 35.50111607142857, 35.404017857142854], u'x_verts': [-87.97096774193548, -87.97096774193548, -87.9, -87.55483870967743, -87.10645161290323, -87.26451612903226, -87.7709677419355, -87.97096774193548], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 34, 490000), u'frame_id': 1326, u'frame_time': datetime.datetime(2016, 3, 31, 22, 6), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.404017857142854, 35.152901785714285, 34.978794642857146, 34.95200892857143, 35.07924107142857, 35.357142857142854, 35.50111607142857, 35.404017857142854], u'x_verts': [-87.97096774193548, -87.97096774193548, -87.9, -87.55483870967743, -87.10645161290323, -87.26451612903226, -87.7709677419355, -87.97096774193548], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 34, 490000), u'frame_id': 1326, u'frame_time': datetime.datetime(2016, 3, 31, 22, 6), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.390625, 35.049107142857146, 34.88169642857143, 35.015625, 35.37388392857143, 35.424107142857146, 35.390625], u'x_verts': [-87.90967741935485, -87.94193548387098, -87.67096774193548, -87.2741935483871, -87.23548387096774, -87.61612903225807, -87.90967741935485], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 43, 945000), u'frame_id': 1327, u'frame_time': datetime.datetime(2016, 3, 31, 22, 7), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.390625, 35.049107142857146, 34.88169642857143, 35.015625, 35.37388392857143, 35.424107142857146, 35.390625], u'x_verts': [-87.90967741935485, -87.94193548387098, -87.67096774193548, -87.2741935483871, -87.23548387096774, -87.61612903225807, -87.90967741935485], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 43, 945000), u'frame_id': 1327, u'frame_time': datetime.datetime(2016, 3, 31, 22, 7), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.410714285714285, 34.901785714285715, 34.901785714285715, 35.223214285714285, 35.393973214285715, 35.410714285714285], u'x_verts': [-87.96129032258065, -87.8967741935484, -87.41290322580646, -87.2483870967742, -87.41935483870968, -87.96129032258065], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 52, 82000), u'frame_id': 1328, u'frame_time': datetime.datetime(2016, 3, 31, 22, 8), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.410714285714285, 34.901785714285715, 34.901785714285715, 35.223214285714285, 35.393973214285715, 35.410714285714285], u'x_verts': [-87.96129032258065, -87.8967741935484, -87.41290322580646, -87.2483870967742, -87.41935483870968, -87.96129032258065], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 52, 82000), u'frame_id': 1328, u'frame_time': datetime.datetime(2016, 3, 31, 22, 8), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.5078125, 34.99888392857143, 34.86830357142857, 34.988839285714285, 35.33705357142857, 35.504464285714285, 35.5078125], u'x_verts': [-87.93225806451613, -87.90645161290323, -87.60967741935484, -86.90322580645162, -87.43870967741935, -87.73225806451613, -87.93225806451613], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 0, 702000), u'frame_id': 1329, u'frame_time': datetime.datetime(2016, 3, 31, 22, 9), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.5078125, 34.99888392857143, 34.86830357142857, 34.988839285714285, 35.33705357142857, 35.504464285714285, 35.5078125], u'x_verts': [-87.93225806451613, -87.90645161290323, -87.60967741935484, -86.90322580645162, -87.43870967741935, -87.73225806451613, -87.93225806451613], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 0, 702000), u'frame_id': 1329, u'frame_time': datetime.datetime(2016, 3, 31, 22, 9), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.390625, 34.91517857142857, 34.901785714285715, 35.30357142857143, 35.56138392857143, 35.59486607142857, 35.390625], u'x_verts': [-87.9741935483871, -87.87741935483872, -86.86129032258064, -87.09032258064516, -87.51935483870969, -87.8741935483871, -87.9741935483871], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 8, 374000), u'frame_id': 1330, u'frame_time': datetime.datetime(2016, 3, 31, 22, 10), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.390625, 34.91517857142857, 34.901785714285715, 35.30357142857143, 35.56138392857143, 35.59486607142857, 35.390625], u'x_verts': [-87.9741935483871, -87.87741935483872, -86.86129032258064, -87.09032258064516, -87.51935483870969, -87.8741935483871, -87.9741935483871], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 8, 374000), u'frame_id': 1330, u'frame_time': datetime.datetime(2016, 3, 31, 22, 10), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.393973214285715, 35.2265625, 35.029017857142854, 34.918526785714285, 35.2734375, 35.3671875, 35.440848214285715, 35.393973214285715], u'x_verts': [-87.95483870967742, -87.93870967741935, -87.87096774193549, -87.5741935483871, -87.28064516129032, -87.4741935483871, -87.80322580645162, -87.95483870967742], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 18, 326000), u'frame_id': 1331, u'frame_time': datetime.datetime(2016, 3, 31, 22, 11), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.393973214285715, 35.2265625, 35.029017857142854, 34.918526785714285, 35.2734375, 35.3671875, 35.440848214285715, 35.393973214285715], u'x_verts': [-87.95483870967742, -87.93870967741935, -87.87096774193549, -87.5741935483871, -87.28064516129032, -87.4741935483871, -87.80322580645162, -87.95483870967742], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 18, 326000), u'frame_id': 1331, u'frame_time': datetime.datetime(2016, 3, 31, 22, 11), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.4140625, 34.901785714285715, 34.8515625, 35.28013392857143, 35.434151785714285, 35.611607142857146, 35.58482142857143, 35.4140625], u'x_verts': [-87.94516129032259, -87.85161290322581, -87.42580645161291, -87.23548387096774, -87.49032258064517, -87.59354838709677, -87.80967741935484, -87.94516129032259], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 27, 972000), u'frame_id': 1332, u'frame_time': datetime.datetime(2016, 3, 31, 22, 12), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.4140625, 34.901785714285715, 34.8515625, 35.28013392857143, 35.434151785714285, 35.611607142857146, 35.58482142857143, 35.4140625], u'x_verts': [-87.94516129032259, -87.85161290322581, -87.42580645161291, -87.23548387096774, -87.49032258064517, -87.59354838709677, -87.80967741935484, -87.94516129032259], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 27, 972000), u'frame_id': 1332, u'frame_time': datetime.datetime(2016, 3, 31, 22, 12), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.691964285714285, 35.183035714285715, 34.958705357142854, 34.9453125, 35.47767857142857, 35.671875, 35.691964285714285], u'x_verts': [-87.72580645161291, -87.91935483870968, -87.90322580645162, -87.42258064516129, -87.40645161290323, -87.48387096774194, -87.72580645161291], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 35, 978000), u'frame_id': 1333, u'frame_time': datetime.datetime(2016, 3, 31, 22, 13), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.691964285714285, 35.183035714285715, 34.958705357142854, 34.9453125, 35.47767857142857, 35.671875, 35.691964285714285], u'x_verts': [-87.72580645161291, -87.91935483870968, -87.90322580645162, -87.42258064516129, -87.40645161290323, -87.48387096774194, -87.72580645161291], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 35, 978000), u'frame_id': 1333, u'frame_time': datetime.datetime(2016, 3, 31, 22, 13), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.564732142857146, 34.88169642857143, 34.93861607142857, 35.32700892857143, 35.434151785714285, 35.60825892857143, 35.7421875, 35.564732142857146], u'x_verts': [-87.84516129032258, -87.87741935483872, -87.20322580645161, -87.15806451612903, -87.4, -87.49032258064517, -87.63870967741936, -87.84516129032258], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 43, 938000), u'frame_id': 1334, u'frame_time': datetime.datetime(2016, 3, 31, 22, 14), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.564732142857146, 34.88169642857143, 34.93861607142857, 35.32700892857143, 35.434151785714285, 35.60825892857143, 35.7421875, 35.564732142857146], u'x_verts': [-87.84516129032258, -87.87741935483872, -87.20322580645161, -87.15806451612903, -87.4, -87.49032258064517, -87.63870967741936, -87.84516129032258], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 43, 938000), u'frame_id': 1334, u'frame_time': datetime.datetime(2016, 3, 31, 22, 14), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.51450892857143, 35.00892857142857, 34.838169642857146, 35.142857142857146, 35.38392857142857, 35.588169642857146, 35.51450892857143], u'x_verts': [-87.82903225806452, -87.88064516129033, -87.5741935483871, -87.04838709677419, -87.24516129032259, -87.66129032258065, -87.82903225806452], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 51, 372000), u'frame_id': 1335, u'frame_time': datetime.datetime(2016, 3, 31, 22, 15), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.51450892857143, 35.00892857142857, 34.838169642857146, 35.142857142857146, 35.38392857142857, 35.588169642857146, 35.51450892857143], u'x_verts': [-87.82903225806452, -87.88064516129033, -87.5741935483871, -87.04838709677419, -87.24516129032259, -87.66129032258065, -87.82903225806452], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 51, 372000), u'frame_id': 1335, u'frame_time': datetime.datetime(2016, 3, 31, 22, 15), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.417410714285715, 35.02232142857143, 34.818080357142854, 34.982142857142854, 35.333705357142854, 35.400669642857146, 35.46763392857143, 35.417410714285715], u'x_verts': [-87.81290322580645, -87.89032258064516, -87.70645161290324, -87.19032258064517, -87.22903225806452, -87.47096774193548, -87.67741935483872, -87.81290322580645], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 30, 37, 10000), u'frame_id': 1336, u'frame_time': datetime.datetime(2016, 3, 31, 22, 16), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.417410714285715, 35.02232142857143, 34.818080357142854, 34.982142857142854, 35.333705357142854, 35.400669642857146, 35.46763392857143, 35.417410714285715], u'x_verts': [-87.81290322580645, -87.89032258064516, -87.70645161290324, -87.19032258064517, -87.22903225806452, -87.47096774193548, -87.67741935483872, -87.81290322580645], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 30, 37, 10000), u'frame_id': 1336, u'frame_time': datetime.datetime(2016, 3, 31, 22, 16), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.504464285714285, 35.005580357142854, 34.82142857142857, 35.0625, 35.511160714285715, 35.681919642857146, 35.504464285714285], u'x_verts': [-87.75806451612904, -87.88064516129033, -87.74193548387098, -87.1483870967742, -87.41290322580646, -87.50967741935484, -87.75806451612904], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 30, 46, 916000), u'frame_id': 1337, u'frame_time': datetime.datetime(2016, 3, 31, 22, 17), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.504464285714285, 35.005580357142854, 34.82142857142857, 35.0625, 35.511160714285715, 35.681919642857146, 35.504464285714285], u'x_verts': [-87.75806451612904, -87.88064516129033, -87.74193548387098, -87.1483870967742, -87.41290322580646, -87.50967741935484, -87.75806451612904], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 30, 46, 916000), u'frame_id': 1337, u'frame_time': datetime.datetime(2016, 3, 31, 22, 17), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.46763392857143, 34.99888392857143, 34.918526785714285, 35.142857142857146, 35.31361607142857, 35.527901785714285, 35.46763392857143], u'x_verts': [-87.83225806451614, -87.83548387096775, -87.3483870967742, -87.20967741935485, -87.36451612903227, -87.62903225806453, -87.83225806451614], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 30, 53, 842000), u'frame_id': 1338, u'frame_time': datetime.datetime(2016, 3, 31, 22, 18), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.46763392857143, 34.99888392857143, 34.918526785714285, 35.142857142857146, 35.31361607142857, 35.527901785714285, 35.46763392857143], u'x_verts': [-87.83225806451614, -87.83548387096775, -87.3483870967742, -87.20967741935485, -87.36451612903227, -87.62903225806453, -87.83225806451614], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 30, 53, 842000), u'frame_id': 1338, u'frame_time': datetime.datetime(2016, 3, 31, 22, 18), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.440848214285715, 34.908482142857146, 34.831473214285715, 34.958705357142854, 35.39732142857143, 35.26674107142857, 35.35044642857143, 35.45424107142857, 35.440848214285715], u'x_verts': [-87.73225806451613, -87.83225806451614, -87.67096774193548, -86.99677419354839, -86.96129032258065, -87.3741935483871, -87.5, -87.58064516129033, -87.73225806451613], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 4, 990000), u'frame_id': 1339, u'frame_time': datetime.datetime(2016, 3, 31, 22, 19), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.440848214285715, 34.908482142857146, 34.831473214285715, 34.958705357142854, 35.39732142857143, 35.26674107142857, 35.35044642857143, 35.45424107142857, 35.440848214285715], u'x_verts': [-87.73225806451613, -87.83225806451614, -87.67096774193548, -86.99677419354839, -86.96129032258065, -87.3741935483871, -87.5, -87.58064516129033, -87.73225806451613], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 4, 990000), u'frame_id': 1339, u'frame_time': datetime.datetime(2016, 3, 31, 22, 19), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.410714285714285, 34.978794642857146, 34.8984375, 35.065848214285715, 35.353794642857146, 35.457589285714285, 35.410714285714285], u'x_verts': [-87.78709677419356, -87.83548387096775, -87.55483870967743, -87.31290322580645, -87.22580645161291, -87.48387096774194, -87.78709677419356], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 15, 186000), u'frame_id': 1340, u'frame_time': datetime.datetime(2016, 3, 31, 22, 20), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.410714285714285, 34.978794642857146, 34.8984375, 35.065848214285715, 35.353794642857146, 35.457589285714285, 35.410714285714285], u'x_verts': [-87.78709677419356, -87.83548387096775, -87.55483870967743, -87.31290322580645, -87.22580645161291, -87.48387096774194, -87.78709677419356], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 15, 186000), u'frame_id': 1340, u'frame_time': datetime.datetime(2016, 3, 31, 22, 20), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.47767857142857, 34.93861607142857, 34.85825892857143, 35.323660714285715, 35.44419642857143, 35.47767857142857], u'x_verts': [-87.82903225806452, -87.81290322580645, -87.41935483870968, -87.22580645161291, -87.49677419354839, -87.82903225806452], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 22, 434000), u'frame_id': 1341, u'frame_time': datetime.datetime(2016, 3, 31, 22, 21), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.47767857142857, 34.93861607142857, 34.85825892857143, 35.323660714285715, 35.44419642857143, 35.47767857142857], u'x_verts': [-87.82903225806452, -87.81290322580645, -87.41935483870968, -87.22580645161291, -87.49677419354839, -87.82903225806452], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 22, 434000), u'frame_id': 1341, u'frame_time': datetime.datetime(2016, 3, 31, 22, 21), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.40736607142857, 34.82142857142857, 34.911830357142854, 35.35044642857143, 35.470982142857146, 35.40736607142857], u'x_verts': [-87.80645161290323, -87.8258064516129, -87.22580645161291, -87.35806451612903, -87.5225806451613, -87.80645161290323], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 30, 31000), u'frame_id': 1342, u'frame_time': datetime.datetime(2016, 3, 31, 22, 22), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.40736607142857, 34.82142857142857, 34.911830357142854, 35.35044642857143, 35.470982142857146, 35.40736607142857], u'x_verts': [-87.80645161290323, -87.8258064516129, -87.22580645161291, -87.35806451612903, -87.5225806451613, -87.80645161290323], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 30, 31000), u'frame_id': 1342, u'frame_time': datetime.datetime(2016, 3, 31, 22, 22), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.370535714285715, 34.888392857142854, 34.838169642857146, 35.300223214285715, 35.638392857142854, 35.370535714285715], u'x_verts': [-87.79032258064517, -87.80967741935484, -87.2516129032258, -87.28709677419356, -87.3741935483871, -87.79032258064517], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 37, 765000), u'frame_id': 1343, u'frame_time': datetime.datetime(2016, 3, 31, 22, 23), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.370535714285715, 34.888392857142854, 34.838169642857146, 35.300223214285715, 35.638392857142854, 35.370535714285715], u'x_verts': [-87.79032258064517, -87.80967741935484, -87.2516129032258, -87.28709677419356, -87.3741935483871, -87.79032258064517], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 37, 765000), u'frame_id': 1343, u'frame_time': datetime.datetime(2016, 3, 31, 22, 23), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.47767857142857, 35.347098214285715, 35.193080357142854, 35.122767857142854, 34.982142857142854, 35.005580357142854, 35.316964285714285, 35.464285714285715, 35.51450892857143, 35.521205357142854, 35.47767857142857], u'x_verts': [-87.72580645161291, -87.85161290322581, -87.79354838709678, -87.76774193548387, -87.83548387096775, -87.30967741935484, -87.20967741935485, -87.26774193548387, -87.39354838709679, -87.63225806451614, -87.72580645161291], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 53, 903000), u'frame_id': 1344, u'frame_time': datetime.datetime(2016, 3, 31, 22, 24), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.47767857142857, 35.347098214285715, 35.193080357142854, 35.122767857142854, 34.982142857142854, 35.005580357142854, 35.316964285714285, 35.464285714285715, 35.51450892857143, 35.521205357142854, 35.47767857142857], u'x_verts': [-87.72580645161291, -87.85161290322581, -87.79354838709678, -87.76774193548387, -87.83548387096775, -87.30967741935484, -87.20967741935485, -87.26774193548387, -87.39354838709679, -87.63225806451614, -87.72580645161291], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 53, 903000), u'frame_id': 1344, u'frame_time': datetime.datetime(2016, 3, 31, 22, 24), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.390625, 35.176339285714285, 35.052455357142854, 34.978794642857146, 34.93861607142857, 35.37388392857143, 35.474330357142854, 35.58482142857143, 35.534598214285715, 35.390625], u'x_verts': [-87.7741935483871, -87.7516129032258, -87.76451612903226, -87.78387096774195, -87.36129032258064, -87.18387096774194, -87.48387096774194, -87.60000000000001, -87.67741935483872, -87.7741935483871], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 6, 583000), u'frame_id': 1345, u'frame_time': datetime.datetime(2016, 3, 31, 22, 25), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.390625, 35.176339285714285, 35.052455357142854, 34.978794642857146, 34.93861607142857, 35.37388392857143, 35.474330357142854, 35.58482142857143, 35.534598214285715, 35.390625], u'x_verts': [-87.7741935483871, -87.7516129032258, -87.76451612903226, -87.78387096774195, -87.36129032258064, -87.18387096774194, -87.48387096774194, -87.60000000000001, -87.67741935483872, -87.7741935483871], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 6, 583000), u'frame_id': 1345, u'frame_time': datetime.datetime(2016, 3, 31, 22, 25), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.347098214285715, 35.07924107142857, 34.9453125, 35.015625, 35.380580357142854, 35.464285714285715, 35.484375, 35.347098214285715], u'x_verts': [-87.80322580645162, -87.79354838709678, -87.69677419354839, -87.23225806451613, -87.30645161290323, -87.49354838709678, -87.67741935483872, -87.80322580645162], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 14, 452000), u'frame_id': 1346, u'frame_time': datetime.datetime(2016, 3, 31, 22, 26), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.347098214285715, 35.07924107142857, 34.9453125, 35.015625, 35.380580357142854, 35.464285714285715, 35.484375, 35.347098214285715], u'x_verts': [-87.80322580645162, -87.79354838709678, -87.69677419354839, -87.23225806451613, -87.30645161290323, -87.49354838709678, -87.67741935483872, -87.80322580645162], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 14, 452000), u'frame_id': 1346, u'frame_time': datetime.datetime(2016, 3, 31, 22, 26), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.6015625, 35.340401785714285, 35.24330357142857, 35.14955357142857, 35.075892857142854, 34.95200892857143, 34.965401785714285, 35.497767857142854, 35.588169642857146, 35.6015625], u'x_verts': [-87.44193548387098, -87.75806451612904, -87.75806451612904, -87.75483870967743, -87.79677419354839, -87.71290322580646, -87.3258064516129, -87.2709677419355, -87.29677419354839, -87.44193548387098], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 25, 741000), u'frame_id': 1347, u'frame_time': datetime.datetime(2016, 3, 31, 22, 27), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.6015625, 35.340401785714285, 35.24330357142857, 35.14955357142857, 35.075892857142854, 34.95200892857143, 34.965401785714285, 35.497767857142854, 35.588169642857146, 35.6015625], u'x_verts': [-87.44193548387098, -87.75806451612904, -87.75806451612904, -87.75483870967743, -87.79677419354839, -87.71290322580646, -87.3258064516129, -87.2709677419355, -87.29677419354839, -87.44193548387098], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 25, 741000), u'frame_id': 1347, u'frame_time': datetime.datetime(2016, 3, 31, 22, 27), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.46763392857143, 35.0625, 34.96875, 34.958705357142854, 35.223214285714285, 35.450892857142854, 35.521205357142854, 35.46763392857143], u'x_verts': [-87.58387096774194, -87.81612903225808, -87.69677419354839, -87.2709677419355, -86.83548387096775, -87.03548387096775, -87.43870967741935, -87.58387096774194], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 34, 33000), u'frame_id': 1348, u'frame_time': datetime.datetime(2016, 3, 31, 22, 28), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.46763392857143, 35.0625, 34.96875, 34.958705357142854, 35.223214285714285, 35.450892857142854, 35.521205357142854, 35.46763392857143], u'x_verts': [-87.58387096774194, -87.81612903225808, -87.69677419354839, -87.2709677419355, -86.83548387096775, -87.03548387096775, -87.43870967741935, -87.58387096774194], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 34, 33000), u'frame_id': 1348, u'frame_time': datetime.datetime(2016, 3, 31, 22, 28), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.551339285714285, 35.26674107142857, 35.166294642857146, 35.072544642857146, 35.00892857142857, 34.908482142857146, 35.122767857142854, 35.340401785714285, 35.5078125, 35.551339285714285], u'x_verts': [-87.5967741935484, -87.99354838709678, -87.93548387096774, -87.81935483870969, -87.71935483870968, -87.52903225806452, -86.98387096774194, -87.01935483870969, -87.28387096774195, -87.5967741935484], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 43, 417000), u'frame_id': 1349, u'frame_time': datetime.datetime(2016, 3, 31, 22, 29), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.551339285714285, 35.26674107142857, 35.166294642857146, 35.072544642857146, 35.00892857142857, 34.908482142857146, 35.122767857142854, 35.340401785714285, 35.5078125, 35.551339285714285], u'x_verts': [-87.5967741935484, -87.99354838709678, -87.93548387096774, -87.81935483870969, -87.71935483870968, -87.52903225806452, -86.98387096774194, -87.01935483870969, -87.28387096774195, -87.5967741935484], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 43, 417000), u'frame_id': 1349, u'frame_time': datetime.datetime(2016, 3, 31, 22, 29), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.39732142857143, 35.310267857142854, 35.106026785714285, 35.052455357142854, 34.98549107142857, 34.97544642857143, 35.3203125, 35.564732142857146, 35.856026785714285, 35.645089285714285, 35.39732142857143], u'x_verts': [-87.71935483870968, -87.99032258064517, -87.98064516129033, -87.84516129032258, -87.5741935483871, -87.4, -87.21290322580646, -87.29354838709678, -87.44193548387098, -87.53870967741936, -87.71935483870968], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 55, 455000), u'frame_id': 1350, u'frame_time': datetime.datetime(2016, 3, 31, 22, 30), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.39732142857143, 35.310267857142854, 35.106026785714285, 35.052455357142854, 34.98549107142857, 34.97544642857143, 35.3203125, 35.564732142857146, 35.856026785714285, 35.645089285714285, 35.39732142857143], u'x_verts': [-87.71935483870968, -87.99032258064517, -87.98064516129033, -87.84516129032258, -87.5741935483871, -87.4, -87.21290322580646, -87.29354838709678, -87.44193548387098, -87.53870967741936, -87.71935483870968], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 55, 455000), u'frame_id': 1350, u'frame_time': datetime.datetime(2016, 3, 31, 22, 30), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.393973214285715, 35.14955357142857, 35.052455357142854, 34.941964285714285, 35.082589285714285, 35.333705357142854, 35.393973214285715], u'x_verts': [-87.89354838709679, -87.95806451612904, -87.79677419354839, -87.49354838709678, -87.06451612903226, -87.33870967741936, -87.89354838709679], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 2, 625000), u'frame_id': 1351, u'frame_time': datetime.datetime(2016, 3, 31, 22, 31), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.393973214285715, 35.14955357142857, 35.052455357142854, 34.941964285714285, 35.082589285714285, 35.333705357142854, 35.393973214285715], u'x_verts': [-87.89354838709679, -87.95806451612904, -87.79677419354839, -87.49354838709678, -87.06451612903226, -87.33870967741936, -87.89354838709679], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 2, 625000), u'frame_id': 1351, u'frame_time': datetime.datetime(2016, 3, 31, 22, 31), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.340401785714285, 35.152901785714285, 35.05580357142857, 34.988839285714285, 34.931919642857146, 35.35044642857143, 35.450892857142854, 35.447544642857146, 35.340401785714285], u'x_verts': [-87.69677419354839, -87.67096774193548, -87.72580645161291, -87.66774193548387, -87.2483870967742, -87.20967741935485, -87.31612903225808, -87.51290322580645, -87.69677419354839], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 14, 697000), u'frame_id': 1352, u'frame_time': datetime.datetime(2016, 3, 31, 22, 32), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.340401785714285, 35.152901785714285, 35.05580357142857, 34.988839285714285, 34.931919642857146, 35.35044642857143, 35.450892857142854, 35.447544642857146, 35.340401785714285], u'x_verts': [-87.69677419354839, -87.67096774193548, -87.72580645161291, -87.66774193548387, -87.2483870967742, -87.20967741935485, -87.31612903225808, -87.51290322580645, -87.69677419354839], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 14, 697000), u'frame_id': 1352, u'frame_time': datetime.datetime(2016, 3, 31, 22, 32), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.50111607142857, 35.42075892857143, 34.97544642857143, 34.935267857142854, 35.112723214285715, 35.40736607142857, 35.50111607142857], u'x_verts': [-87.33548387096775, -87.73225806451613, -87.74516129032259, -87.66774193548387, -87.04516129032258, -87.18064516129033, -87.33548387096775], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 24, 48000), u'frame_id': 1353, u'frame_time': datetime.datetime(2016, 3, 31, 22, 33), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.50111607142857, 35.42075892857143, 34.97544642857143, 34.935267857142854, 35.112723214285715, 35.40736607142857, 35.50111607142857], u'x_verts': [-87.33548387096775, -87.73225806451613, -87.74516129032259, -87.66774193548387, -87.04516129032258, -87.18064516129033, -87.33548387096775], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 24, 48000), u'frame_id': 1353, u'frame_time': datetime.datetime(2016, 3, 31, 22, 33), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.447544642857146, 35.293526785714285, 35.203125, 34.995535714285715, 35.03236607142857, 35.37388392857143, 35.481026785714285, 35.447544642857146], u'x_verts': [-87.69354838709678, -87.96129032258065, -87.90645161290323, -87.61290322580646, -87.13548387096775, -87.2516129032258, -87.42903225806452, -87.69354838709678], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 32, 986000), u'frame_id': 1354, u'frame_time': datetime.datetime(2016, 3, 31, 22, 34), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.447544642857146, 35.293526785714285, 35.203125, 34.995535714285715, 35.03236607142857, 35.37388392857143, 35.481026785714285, 35.447544642857146], u'x_verts': [-87.69354838709678, -87.96129032258065, -87.90645161290323, -87.61290322580646, -87.13548387096775, -87.2516129032258, -87.42903225806452, -87.69354838709678], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 32, 986000), u'frame_id': 1354, u'frame_time': datetime.datetime(2016, 3, 31, 22, 34), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.434151785714285, 35.142857142857146, 35.005580357142854, 34.948660714285715, 35.310267857142854, 35.61830357142857, 35.434151785714285], u'x_verts': [-87.66774193548387, -87.80322580645162, -87.6258064516129, -87.28387096774195, -87.2, -87.25806451612904, -87.66774193548387], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 41, 463000), u'frame_id': 1355, u'frame_time': datetime.datetime(2016, 3, 31, 22, 35), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.434151785714285, 35.142857142857146, 35.005580357142854, 34.948660714285715, 35.310267857142854, 35.61830357142857, 35.434151785714285], u'x_verts': [-87.66774193548387, -87.80322580645162, -87.6258064516129, -87.28387096774195, -87.2, -87.25806451612904, -87.66774193548387], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 41, 463000), u'frame_id': 1355, u'frame_time': datetime.datetime(2016, 3, 31, 22, 35), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.213169642857146, 35.035714285714285, 34.982142857142854, 35.14955357142857, 35.38392857142857, 35.424107142857146, 35.213169642857146], u'x_verts': [-87.74516129032259, -87.66129032258065, -87.43548387096774, -87.22903225806452, -87.26451612903226, -87.42580645161291, -87.74516129032259], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 49, 798000), u'frame_id': 1356, u'frame_time': datetime.datetime(2016, 3, 31, 22, 36), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.213169642857146, 35.035714285714285, 34.982142857142854, 35.14955357142857, 35.38392857142857, 35.424107142857146, 35.213169642857146], u'x_verts': [-87.74516129032259, -87.66129032258065, -87.43548387096774, -87.22903225806452, -87.26451612903226, -87.42580645161291, -87.74516129032259], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 49, 798000), u'frame_id': 1356, u'frame_time': datetime.datetime(2016, 3, 31, 22, 36), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.34375, 35.17299107142857, 35.018973214285715, 34.925223214285715, 35.129464285714285, 35.598214285714285, 35.34375], u'x_verts': [-87.80967741935484, -87.7741935483871, -87.56774193548388, -87.20967741935485, -87.18387096774194, -87.25806451612904, -87.80967741935484], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 57, 65000), u'frame_id': 1357, u'frame_time': datetime.datetime(2016, 3, 31, 22, 37), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.34375, 35.17299107142857, 35.018973214285715, 34.925223214285715, 35.129464285714285, 35.598214285714285, 35.34375], u'x_verts': [-87.80967741935484, -87.7741935483871, -87.56774193548388, -87.20967741935485, -87.18387096774194, -87.25806451612904, -87.80967741935484], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 57, 65000), u'frame_id': 1357, u'frame_time': datetime.datetime(2016, 3, 31, 22, 37), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.53794642857143, 35.159598214285715, 35.002232142857146, 34.955357142857146, 35.390625, 35.60825892857143, 35.53794642857143], u'x_verts': [-87.50322580645162, -87.66774193548387, -87.56129032258065, -87.15806451612903, -87.18387096774194, -87.37096774193549, -87.50322580645162], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 3, 983000), u'frame_id': 1358, u'frame_time': datetime.datetime(2016, 3, 31, 22, 38), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.53794642857143, 35.159598214285715, 35.002232142857146, 34.955357142857146, 35.390625, 35.60825892857143, 35.53794642857143], u'x_verts': [-87.50322580645162, -87.66774193548387, -87.56129032258065, -87.15806451612903, -87.18387096774194, -87.37096774193549, -87.50322580645162], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 3, 983000), u'frame_id': 1358, u'frame_time': datetime.datetime(2016, 3, 31, 22, 38), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.427455357142854, 35.15625, 35.042410714285715, 34.955357142857146, 35.082589285714285, 35.333705357142854, 35.49107142857143, 35.427455357142854], u'x_verts': [-87.49677419354839, -87.65483870967742, -87.6258064516129, -87.49354838709678, -87.00967741935484, -87.1483870967742, -87.29354838709678, -87.49677419354839], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 11, 613000), u'frame_id': 1359, u'frame_time': datetime.datetime(2016, 3, 31, 22, 39), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.427455357142854, 35.15625, 35.042410714285715, 34.955357142857146, 35.082589285714285, 35.333705357142854, 35.49107142857143, 35.427455357142854], u'x_verts': [-87.49677419354839, -87.65483870967742, -87.6258064516129, -87.49354838709678, -87.00967741935484, -87.1483870967742, -87.29354838709678, -87.49677419354839], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 11, 613000), u'frame_id': 1359, u'frame_time': datetime.datetime(2016, 3, 31, 22, 39), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.46763392857143, 35.23325892857143, 35.129464285714285, 34.948660714285715, 34.972098214285715, 35.450892857142854, 35.46763392857143], u'x_verts': [-87.66451612903226, -87.78064516129032, -87.66129032258065, -87.53548387096775, -86.94193548387098, -87.12903225806453, -87.66451612903226], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 19, 115000), u'frame_id': 1360, u'frame_time': datetime.datetime(2016, 3, 31, 22, 40), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.46763392857143, 35.23325892857143, 35.129464285714285, 34.948660714285715, 34.972098214285715, 35.450892857142854, 35.46763392857143], u'x_verts': [-87.66451612903226, -87.78064516129032, -87.66129032258065, -87.53548387096775, -86.94193548387098, -87.12903225806453, -87.66451612903226], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 19, 115000), u'frame_id': 1360, u'frame_time': datetime.datetime(2016, 3, 31, 22, 40), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.56138392857143, 35.17299107142857, 34.988839285714285, 34.878348214285715, 35.47767857142857, 35.56138392857143], u'x_verts': [-87.5225806451613, -87.6483870967742, -87.55161290322582, -87.17419354838711, -87.18387096774194, -87.5225806451613], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 27, 22000), u'frame_id': 1361, u'frame_time': datetime.datetime(2016, 3, 31, 22, 41), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.56138392857143, 35.17299107142857, 34.988839285714285, 34.878348214285715, 35.47767857142857, 35.56138392857143], u'x_verts': [-87.5225806451613, -87.6483870967742, -87.55161290322582, -87.17419354838711, -87.18387096774194, -87.5225806451613], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 27, 22000), u'frame_id': 1361, u'frame_time': datetime.datetime(2016, 3, 31, 22, 41), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.51450892857143, 35.1328125, 35.04575892857143, 34.911830357142854, 34.955357142857146, 35.306919642857146, 35.53125, 35.51450892857143], u'x_verts': [-87.51290322580645, -87.60645161290323, -87.59032258064516, -87.3225806451613, -87.00322580645162, -87.19032258064517, -87.34193548387097, -87.51290322580645], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 35, 82000), u'frame_id': 1362, u'frame_time': datetime.datetime(2016, 3, 31, 22, 42), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.51450892857143, 35.1328125, 35.04575892857143, 34.911830357142854, 34.955357142857146, 35.306919642857146, 35.53125, 35.51450892857143], u'x_verts': [-87.51290322580645, -87.60645161290323, -87.59032258064516, -87.3225806451613, -87.00322580645162, -87.19032258064517, -87.34193548387097, -87.51290322580645], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 35, 82000), u'frame_id': 1362, u'frame_time': datetime.datetime(2016, 3, 31, 22, 42), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.357142857142854, 35.14955357142857, 35.025669642857146, 34.90513392857143, 35.176339285714285, 35.42075892857143, 35.357142857142854], u'x_verts': [-87.50967741935484, -87.59032258064516, -87.55161290322582, -87.3225806451613, -87.05483870967743, -87.19032258064517, -87.50967741935484], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 41, 721000), u'frame_id': 1363, u'frame_time': datetime.datetime(2016, 3, 31, 22, 43), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.357142857142854, 35.14955357142857, 35.025669642857146, 34.90513392857143, 35.176339285714285, 35.42075892857143, 35.357142857142854], u'x_verts': [-87.50967741935484, -87.59032258064516, -87.55161290322582, -87.3225806451613, -87.05483870967743, -87.19032258064517, -87.50967741935484], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 41, 721000), u'frame_id': 1363, u'frame_time': datetime.datetime(2016, 3, 31, 22, 43), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.521205357142854, 35.37388392857143, 35.286830357142854, 35.14955357142857, 35.035714285714285, 34.988839285714285, 35.025669642857146, 35.393973214285715, 35.534598214285715, 35.521205357142854], u'x_verts': [-87.38709677419355, -87.49677419354839, -87.47741935483872, -87.58387096774194, -87.53870967741936, -87.4, -87.1258064516129, -87.08387096774194, -87.21612903225807, -87.38709677419355], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 50, 490000), u'frame_id': 1364, u'frame_time': datetime.datetime(2016, 3, 31, 22, 44), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.521205357142854, 35.37388392857143, 35.286830357142854, 35.14955357142857, 35.035714285714285, 34.988839285714285, 35.025669642857146, 35.393973214285715, 35.534598214285715, 35.521205357142854], u'x_verts': [-87.38709677419355, -87.49677419354839, -87.47741935483872, -87.58387096774194, -87.53870967741936, -87.4, -87.1258064516129, -87.08387096774194, -87.21612903225807, -87.38709677419355], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 50, 490000), u'frame_id': 1364, u'frame_time': datetime.datetime(2016, 3, 31, 22, 44), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.57142857142857, 35.106026785714285, 34.911830357142854, 35.059151785714285, 35.3671875, 35.598214285714285, 35.57142857142857], u'x_verts': [-87.43225806451613, -87.56129032258065, -87.48387096774194, -87.11935483870968, -87.20967741935485, -87.31935483870969, -87.43225806451613], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 57, 549000), u'frame_id': 1365, u'frame_time': datetime.datetime(2016, 3, 31, 22, 45), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.57142857142857, 35.106026785714285, 34.911830357142854, 35.059151785714285, 35.3671875, 35.598214285714285, 35.57142857142857], u'x_verts': [-87.43225806451613, -87.56129032258065, -87.48387096774194, -87.11935483870968, -87.20967741935485, -87.31935483870969, -87.43225806451613], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 57, 549000), u'frame_id': 1365, u'frame_time': datetime.datetime(2016, 3, 31, 22, 45), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.3671875, 34.911830357142854, 34.988839285714285, 35.29017857142857, 35.534598214285715, 35.3671875], u'x_verts': [-87.56129032258065, -87.51935483870969, -86.78709677419356, -86.83225806451614, -87.19354838709678, -87.56129032258065], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 4, 855000), u'frame_id': 1366, u'frame_time': datetime.datetime(2016, 3, 31, 22, 46), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.3671875, 34.911830357142854, 34.988839285714285, 35.29017857142857, 35.534598214285715, 35.3671875], u'x_verts': [-87.56129032258065, -87.51935483870969, -86.78709677419356, -86.83225806451614, -87.19354838709678, -87.56129032258065], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 4, 855000), u'frame_id': 1366, u'frame_time': datetime.datetime(2016, 3, 31, 22, 46), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.306919642857146, 34.958705357142854, 34.908482142857146, 35.23325892857143, 35.551339285714285, 35.534598214285715, 35.306919642857146], u'x_verts': [-87.55161290322582, -87.50322580645162, -87.06774193548388, -87.01935483870969, -87.23225806451613, -87.5, -87.55161290322582], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 11, 699000), u'frame_id': 1367, u'frame_time': datetime.datetime(2016, 3, 31, 22, 47), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.306919642857146, 34.958705357142854, 34.908482142857146, 35.23325892857143, 35.551339285714285, 35.534598214285715, 35.306919642857146], u'x_verts': [-87.55161290322582, -87.50322580645162, -87.06774193548388, -87.01935483870969, -87.23225806451613, -87.5, -87.55161290322582], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 11, 699000), u'frame_id': 1367, u'frame_time': datetime.datetime(2016, 3, 31, 22, 47), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.4140625, 35.193080357142854, 34.97544642857143, 35.05580357142857, 35.353794642857146, 35.464285714285715, 35.4140625], u'x_verts': [-87.44193548387098, -87.50967741935484, -87.47741935483872, -86.93870967741935, -87.07096774193549, -87.24516129032259, -87.44193548387098], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 18, 322000), u'frame_id': 1368, u'frame_time': datetime.datetime(2016, 3, 31, 22, 48), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.4140625, 35.193080357142854, 34.97544642857143, 35.05580357142857, 35.353794642857146, 35.464285714285715, 35.4140625], u'x_verts': [-87.44193548387098, -87.50967741935484, -87.47741935483872, -86.93870967741935, -87.07096774193549, -87.24516129032259, -87.44193548387098], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 18, 322000), u'frame_id': 1368, u'frame_time': datetime.datetime(2016, 3, 31, 22, 48), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.474330357142854, 35.193080357142854, 35.025669642857146, 34.955357142857146, 35.504464285714285, 35.598214285714285, 35.474330357142854], u'x_verts': [-87.58709677419355, -87.61612903225807, -87.44516129032259, -87.18064516129033, -87.05483870967743, -87.32903225806452, -87.58709677419355], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 24, 479000), u'frame_id': 1369, u'frame_time': datetime.datetime(2016, 3, 31, 22, 49), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.474330357142854, 35.193080357142854, 35.025669642857146, 34.955357142857146, 35.504464285714285, 35.598214285714285, 35.474330357142854], u'x_verts': [-87.58709677419355, -87.61612903225807, -87.44516129032259, -87.18064516129033, -87.05483870967743, -87.32903225806452, -87.58709677419355], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 24, 479000), u'frame_id': 1369, u'frame_time': datetime.datetime(2016, 3, 31, 22, 49), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.521205357142854, 35.380580357142854, 35.122767857142854, 34.93861607142857, 35.082589285714285, 35.481026785714285, 35.521205357142854], u'x_verts': [-87.3258064516129, -87.53870967741936, -87.48387096774194, -87.41612903225807, -87.0967741935484, -87.09032258064516, -87.3258064516129], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 31, 129000), u'frame_id': 1370, u'frame_time': datetime.datetime(2016, 3, 31, 22, 50), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.521205357142854, 35.380580357142854, 35.122767857142854, 34.93861607142857, 35.082589285714285, 35.481026785714285, 35.521205357142854], u'x_verts': [-87.3258064516129, -87.53870967741936, -87.48387096774194, -87.41612903225807, -87.0967741935484, -87.09032258064516, -87.3258064516129], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 31, 129000), u'frame_id': 1370, u'frame_time': datetime.datetime(2016, 3, 31, 22, 50), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.32700892857143, 34.98549107142857, 34.871651785714285, 35.193080357142854, 35.32700892857143], u'x_verts': [-87.51290322580645, -87.46774193548387, -87.18064516129033, -87.13225806451614, -87.51290322580645], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 36, 222000), u'frame_id': 1371, u'frame_time': datetime.datetime(2016, 3, 31, 22, 51), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.32700892857143, 34.98549107142857, 34.871651785714285, 35.193080357142854, 35.32700892857143], u'x_verts': [-87.51290322580645, -87.46774193548387, -87.18064516129033, -87.13225806451614, -87.51290322580645], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 36, 222000), u'frame_id': 1371, u'frame_time': datetime.datetime(2016, 3, 31, 22, 51), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.447544642857146, 35.089285714285715, 35.015625, 35.035714285714285, 35.40736607142857, 35.470982142857146, 35.497767857142854, 35.447544642857146], u'x_verts': [-87.47741935483872, -87.44516129032259, -87.38709677419355, -87.10967741935484, -87.08709677419355, -87.2483870967742, -87.35806451612903, -87.47741935483872], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 45, 206000), u'frame_id': 1372, u'frame_time': datetime.datetime(2016, 3, 31, 22, 52), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.447544642857146, 35.089285714285715, 35.015625, 35.035714285714285, 35.40736607142857, 35.470982142857146, 35.497767857142854, 35.447544642857146], u'x_verts': [-87.47741935483872, -87.44516129032259, -87.38709677419355, -87.10967741935484, -87.08709677419355, -87.2483870967742, -87.35806451612903, -87.47741935483872], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 45, 206000), u'frame_id': 1372, u'frame_time': datetime.datetime(2016, 3, 31, 22, 52), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.504464285714285, 35.176339285714285, 35.082589285714285, 34.864955357142854, 35.25669642857143, 35.504464285714285, 35.504464285714285], u'x_verts': [-87.38064516129033, -87.50967741935484, -87.4741935483871, -87.17096774193548, -86.93548387096774, -87.08064516129033, -87.38064516129033], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 51, 481000), u'frame_id': 1373, u'frame_time': datetime.datetime(2016, 3, 31, 22, 53), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.504464285714285, 35.176339285714285, 35.082589285714285, 34.864955357142854, 35.25669642857143, 35.504464285714285, 35.504464285714285], u'x_verts': [-87.38064516129033, -87.50967741935484, -87.4741935483871, -87.17096774193548, -86.93548387096774, -87.08064516129033, -87.38064516129033], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 51, 481000), u'frame_id': 1373, u'frame_time': datetime.datetime(2016, 3, 31, 22, 53), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.581473214285715, 35.293526785714285, 35.152901785714285, 35.06919642857143, 34.93861607142857, 35.26674107142857, 35.581473214285715], u'x_verts': [-87.08709677419355, -87.46451612903226, -87.46774193548387, -87.40645161290323, -87.10645161290323, -87.03225806451613, -87.08709677419355], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 58, 343000), u'frame_id': 1374, u'frame_time': datetime.datetime(2016, 3, 31, 22, 54), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.581473214285715, 35.293526785714285, 35.152901785714285, 35.06919642857143, 34.93861607142857, 35.26674107142857, 35.581473214285715], u'x_verts': [-87.08709677419355, -87.46451612903226, -87.46774193548387, -87.40645161290323, -87.10645161290323, -87.03225806451613, -87.08709677419355], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 58, 343000), u'frame_id': 1374, u'frame_time': datetime.datetime(2016, 3, 31, 22, 54), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.534598214285715, 35.20982142857143, 35.112723214285715, 35.015625, 34.96205357142857, 35.54799107142857, 35.534598214285715], u'x_verts': [-87.33548387096775, -87.45806451612904, -87.48064516129033, -87.33870967741936, -87.00322580645162, -86.95161290322581, -87.33548387096775], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 4, 443000), u'frame_id': 1375, u'frame_time': datetime.datetime(2016, 3, 31, 22, 55), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.534598214285715, 35.20982142857143, 35.112723214285715, 35.015625, 34.96205357142857, 35.54799107142857, 35.534598214285715], u'x_verts': [-87.33548387096775, -87.45806451612904, -87.48064516129033, -87.33870967741936, -87.00322580645162, -86.95161290322581, -87.33548387096775], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 4, 443000), u'frame_id': 1375, u'frame_time': datetime.datetime(2016, 3, 31, 22, 55), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.4609375, 35.340401785714285, 35.16294642857143, 35.095982142857146, 35.042410714285715, 35.012276785714285, 35.37388392857143, 35.4609375], u'x_verts': [-87.30000000000001, -87.5, -87.48709677419356, -87.41935483870968, -87.2709677419355, -86.94193548387098, -87.0225806451613, -87.30000000000001], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 11, 523000), u'frame_id': 1376, u'frame_time': datetime.datetime(2016, 3, 31, 22, 56), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.4609375, 35.340401785714285, 35.16294642857143, 35.095982142857146, 35.042410714285715, 35.012276785714285, 35.37388392857143, 35.4609375], u'x_verts': [-87.30000000000001, -87.5, -87.48709677419356, -87.41935483870968, -87.2709677419355, -86.94193548387098, -87.0225806451613, -87.30000000000001], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 11, 523000), u'frame_id': 1376, u'frame_time': datetime.datetime(2016, 3, 31, 22, 56), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.54799107142857, 35.635044642857146, 35.10267857142857, 35.099330357142854, 35.1796875, 35.03236607142857, 34.948660714285715, 35.11607142857143, 35.497767857142854, 35.54799107142857], u'x_verts': [-87.13225806451614, -87.79354838709678, -87.86129032258064, -87.7225806451613, -87.5225806451613, -87.3967741935484, -87.23870967741937, -86.9741935483871, -86.98709677419356, -87.13225806451614], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 20, 149000), u'frame_id': 1377, u'frame_time': datetime.datetime(2016, 3, 31, 22, 57), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.54799107142857, 35.635044642857146, 35.10267857142857, 35.099330357142854, 35.1796875, 35.03236607142857, 34.948660714285715, 35.11607142857143, 35.497767857142854, 35.54799107142857], u'x_verts': [-87.13225806451614, -87.79354838709678, -87.86129032258064, -87.7225806451613, -87.5225806451613, -87.3967741935484, -87.23870967741937, -86.9741935483871, -86.98709677419356, -87.13225806451614], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 20, 149000), u'frame_id': 1377, u'frame_time': datetime.datetime(2016, 3, 31, 22, 57), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.517857142857146, 35.390625, 35.189732142857146, 35.095982142857146, 35.049107142857146, 34.9921875, 35.159598214285715, 35.517857142857146], u'x_verts': [-87.15806451612903, -87.43548387096774, -87.48064516129033, -87.41290322580646, -87.17096774193548, -86.9483870967742, -86.86774193548388, -87.15806451612903], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 28, 744000), u'frame_id': 1378, u'frame_time': datetime.datetime(2016, 3, 31, 22, 58), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.517857142857146, 35.390625, 35.189732142857146, 35.095982142857146, 35.049107142857146, 34.9921875, 35.159598214285715, 35.517857142857146], u'x_verts': [-87.15806451612903, -87.43548387096774, -87.48064516129033, -87.41290322580646, -87.17096774193548, -86.9483870967742, -86.86774193548388, -87.15806451612903], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 28, 744000), u'frame_id': 1378, u'frame_time': datetime.datetime(2016, 3, 31, 22, 58), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.26674107142857, 35.09263392857143, 34.97544642857143, 34.9921875, 35.38392857142857, 35.558035714285715, 35.598214285714285, 35.26674107142857], u'x_verts': [-87.44516129032259, -87.38064516129033, -87.33548387096775, -87.0225806451613, -86.89354838709679, -86.96129032258065, -87.2516129032258, -87.44516129032259], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 36, 349000), u'frame_id': 1379, u'frame_time': datetime.datetime(2016, 3, 31, 22, 59), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.26674107142857, 35.09263392857143, 34.97544642857143, 34.9921875, 35.38392857142857, 35.558035714285715, 35.598214285714285, 35.26674107142857], u'x_verts': [-87.44516129032259, -87.38064516129033, -87.33548387096775, -87.0225806451613, -86.89354838709679, -86.96129032258065, -87.2516129032258, -87.44516129032259], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 36, 349000), u'frame_id': 1379, u'frame_time': datetime.datetime(2016, 3, 31, 22, 59), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.58482142857143, 35.400669642857146, 35.1796875, 35.082589285714285, 34.96205357142857, 35.38392857142857, 35.675223214285715, 35.58482142857143], u'x_verts': [-87.22580645161291, -87.48064516129033, -87.38387096774194, -87.37096774193549, -87.10000000000001, -86.9483870967742, -87.04838709677419, -87.22580645161291], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 42, 774000), u'frame_id': 1380, u'frame_time': datetime.datetime(2016, 3, 31, 23, 0), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.58482142857143, 35.400669642857146, 35.1796875, 35.082589285714285, 34.96205357142857, 35.38392857142857, 35.675223214285715, 35.58482142857143], u'x_verts': [-87.22580645161291, -87.48064516129033, -87.38387096774194, -87.37096774193549, -87.10000000000001, -86.9483870967742, -87.04838709677419, -87.22580645161291], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 42, 774000), u'frame_id': 1380, u'frame_time': datetime.datetime(2016, 3, 31, 23, 0), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.511160714285715, 35.276785714285715, 35.213169642857146, 35.12611607142857, 35.02232142857143, 35.25, 35.56138392857143, 35.511160714285715], u'x_verts': [-87.15806451612903, -87.36451612903227, -87.51935483870969, -87.43548387096774, -87.13548387096775, -86.93548387096774, -86.94193548387098, -87.15806451612903], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 50, 226000), u'frame_id': 1381, u'frame_time': datetime.datetime(2016, 3, 31, 23, 1), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.511160714285715, 35.276785714285715, 35.213169642857146, 35.12611607142857, 35.02232142857143, 35.25, 35.56138392857143, 35.511160714285715], u'x_verts': [-87.15806451612903, -87.36451612903227, -87.51935483870969, -87.43548387096774, -87.13548387096775, -86.93548387096774, -86.94193548387098, -87.15806451612903], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 50, 226000), u'frame_id': 1381, u'frame_time': datetime.datetime(2016, 3, 31, 23, 1), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.5546875, 35.323660714285715, 35.169642857142854, 35.11607142857143, 35.0390625, 35.072544642857146, 35.591517857142854, 35.5546875], u'x_verts': [-87.14516129032259, -87.38709677419355, -87.46451612903226, -87.39032258064516, -87.18709677419355, -86.81935483870969, -86.91612903225807, -87.14516129032259], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 58, 665000), u'frame_id': 1382, u'frame_time': datetime.datetime(2016, 3, 31, 23, 2), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n{u'y_verts': [35.5546875, 35.323660714285715, 35.169642857142854, 35.11607142857143, 35.0390625, 35.072544642857146, 35.591517857142854, 35.5546875], u'x_verts': [-87.14516129032259, -87.38709677419355, -87.46451612903226, -87.39032258064516, -87.18709677419355, -86.81935483870969, -86.91612903225807, -87.14516129032259], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 58, 665000), u'frame_id': 1382, u'frame_time': datetime.datetime(2016, 3, 31, 23, 2), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n"
],
[
"# This prepares the polygon data for immedate use in the DC3 flash size statistics scripts\nflash_stat_polys = tuple(zip(p['x_verts'], p['y_verts']) for p in polys)\nflash_stat_left_time_edges = tuple(p['frame_time'] for p in polys)\ndt = flash_stat_left_time_edges[1] - flash_stat_left_time_edges[0]\nt_edge = flash_stat_left_time_edges + (flash_stat_left_time_edges[-1] + dt, )\n",
"_____no_output_____"
],
[
"# Set up a second, large-domain polygon with which to trim the polygons above.\nfilter_polys = [\n ( -88.2, 35.01),\n ( -87.5, 35.20),\n ( -87.0, 35.20),\n ( -87.0, 34.80),\n ( -88.2, 34.80),\n ( -88.2, 35.01),]\n",
"_____no_output_____"
],
[
"print polys[0]",
"{u'y_verts': [35.370535714285715, 35.450892857142854, 35.2734375, 34.941964285714285, 34.720982142857146, 35.018973214285715, 35.229910714285715, 35.370535714285715], u'x_verts': [-87.74516129032259, -88.03548387096775, -88.17741935483872, -88.1483870967742, -87.93870967741935, -87.73870967741937, -87.66774193548387, -87.74516129032259], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 25, 57, 189000), u'frame_id': 1307, u'frame_time': datetime.datetime(2016, 3, 31, 21, 47), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n"
],
[
"from shapely.geometry import Polygon\n\nfilter_geom = Polygon(filter_polys)\ntrimmed_flash_stat_polys = [Polygon(poly).intersection(filter_geom) \n for poly in flash_stat_polys]\n\n# sample_trimmed = trimmed_flash_stat_polys[0]\nupdated_coords = [{'x_verts':list(p.exterior.xy[0]), \n 'y_verts':list(p.exterior.xy[1])} \n for p in trimmed_flash_stat_polys ]\nassert len(polys) == len(updated_coords)\n# old_polys = copy.deepcopy(polys)\nfor poly, new_coords in zip(polys, updated_coords):\n poly.update(new_coords)\n \nprint polys",
"[{u'y_verts': [34.8, 34.941964285714285, 35.02210403697055, 35.1468885137057, 35.018973214285715, 34.8, 34.8], u'x_verts': [-88.01368523949169, -88.1483870967742, -88.15540617958217, -87.69567389687376, -87.73870967741937, -87.88567596955419, -88.01368523949169], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 25, 57, 189000), u'frame_id': 1307, u'frame_time': datetime.datetime(2016, 3, 31, 21, 47), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.8, 34.941964285714285, 35.02210403697055, 35.1468885137057, 35.018973214285715, 34.8, 34.8], u'x_verts': [-88.01368523949169, -88.1483870967742, -88.15540617958217, -87.69567389687376, -87.73870967741937, -87.88567596955419, -88.01368523949169], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 25, 57, 189000), u'frame_id': 1307, u'frame_time': datetime.datetime(2016, 3, 31, 21, 47), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.15948848151685, 35.10267857142857, 34.878348214285715, 34.871651785714285, 35.005580357142854, 35.03823012133358, 35.15948848151685], u'x_verts': [-87.64925296283265, -87.30645161290323, -87.30967741935484, -88.09032258064516, -88.0967741935484, -88.09599428982366, -87.64925296283265], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 22, 438000), u'frame_id': 1312, u'frame_time': datetime.datetime(2016, 3, 31, 21, 52), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.15948848151685, 35.10267857142857, 34.878348214285715, 34.871651785714285, 35.005580357142854, 35.03823012133358, 35.15948848151685], u'x_verts': [-87.64925296283265, -87.30645161290323, -87.30967741935484, -88.09032258064516, -88.0967741935484, -88.09599428982366, -87.64925296283265], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 22, 438000), u'frame_id': 1312, u'frame_time': datetime.datetime(2016, 3, 31, 21, 52), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.8, 34.978794642857146, 35.03911308695861, 35.2, 35.2, 34.965401785714285, 34.8, 34.8], u'x_verts': [-87.9891495601173, -88.09354838709677, -88.09274125857355, -87.5, -87.2994412818891, -87.35483870967742, -87.84061394380855, -87.9891495601173], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 34, 274000), u'frame_id': 1313, u'frame_time': datetime.datetime(2016, 3, 31, 21, 53), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.8, 34.978794642857146, 35.03911308695861, 35.2, 35.2, 34.965401785714285, 34.8, 34.8], u'x_verts': [-87.9891495601173, -88.09354838709677, -88.09274125857355, -87.5, -87.2994412818891, -87.35483870967742, -87.84061394380855, -87.9891495601173], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 34, 274000), u'frame_id': 1313, u'frame_time': datetime.datetime(2016, 3, 31, 21, 53), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.96091241974318, 34.875, 34.948660714285715, 35.03571314915519, 35.2, 35.2, 34.96091241974318], u'x_verts': [-87.0, -87.71290322580646, -88.0967741935484, -88.10526734521771, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 44, 20000), u'frame_id': 1314, u'frame_time': datetime.datetime(2016, 3, 31, 21, 54), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.96091241974318, 34.875, 34.948660714285715, 35.03571314915519, 35.2, 35.2, 34.96091241974318], u'x_verts': [-87.0, -87.71290322580646, -88.0967741935484, -88.10526734521771, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 44, 20000), u'frame_id': 1314, u'frame_time': datetime.datetime(2016, 3, 31, 21, 54), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.925223214285715, 34.941964285714285, 35.050820170451345, 35.2, 35.2], u'x_verts': [-87.20135625147164, -87.24193548387098, -88.01290322580645, -88.04960989833715, -87.5, -87.20135625147164], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 56, 243000), u'frame_id': 1316, u'frame_time': datetime.datetime(2016, 3, 31, 21, 56), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.925223214285715, 34.941964285714285, 35.050820170451345, 35.2, 35.2], u'x_verts': [-87.20135625147164, -87.24193548387098, -88.01290322580645, -88.04960989833715, -87.5, -87.20135625147164], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 26, 56, 243000), u'frame_id': 1316, u'frame_time': datetime.datetime(2016, 3, 31, 21, 56), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.95200892857143, 34.921875, 34.988839285714285, 35.047590290216206, 35.2, 35.2], u'x_verts': [-87.29389371381308, -87.25483870967743, -87.8967741935484, -88.02903225806452, -88.0615094570982, -87.5, -87.29389371381308], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 7, 134000), u'frame_id': 1317, u'frame_time': datetime.datetime(2016, 3, 31, 21, 57), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.95200892857143, 34.921875, 34.988839285714285, 35.047590290216206, 35.2, 35.2], u'x_verts': [-87.29389371381308, -87.25483870967743, -87.8967741935484, -88.02903225806452, -88.0615094570982, -87.5, -87.29389371381308], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 7, 134000), u'frame_id': 1317, u'frame_time': datetime.datetime(2016, 3, 31, 21, 57), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.122767857142854, 34.921875, 34.901785714285715, 35.05559173641707, 35.2, 35.2], u'x_verts': [-87.36818637992832, -87.2516129032258, -87.47096774193548, -87.98387096774194, -88.0320304447792, -87.5, -87.36818637992832], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 16, 932000), u'frame_id': 1318, u'frame_time': datetime.datetime(2016, 3, 31, 21, 58), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.122767857142854, 34.921875, 34.901785714285715, 35.05559173641707, 35.2, 35.2], u'x_verts': [-87.36818637992832, -87.2516129032258, -87.47096774193548, -87.98387096774194, -88.0320304447792, -87.5, -87.36818637992832], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 16, 932000), u'frame_id': 1318, u'frame_time': datetime.datetime(2016, 3, 31, 21, 58), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.96205357142857, 34.88169642857143, 35.002232142857146, 35.05294416374732, 35.2, 35.2], u'x_verts': [-87.1898868630201, -87.11612903225807, -87.96451612903226, -88.04838709677419, -88.04178465987829, -87.5, -87.1898868630201], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 25), u'frame_id': 1319, u'frame_time': datetime.datetime(2016, 3, 31, 21, 59), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.96205357142857, 34.88169642857143, 35.002232142857146, 35.05294416374732, 35.2, 35.2], u'x_verts': [-87.1898868630201, -87.11612903225807, -87.96451612903226, -88.04838709677419, -88.04178465987829, -87.5, -87.1898868630201], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 25), u'frame_id': 1319, u'frame_time': datetime.datetime(2016, 3, 31, 21, 59), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.93861607142857, 34.89174107142857, 35.018973214285715, 35.057573270079985, 35.2, 35.2], u'x_verts': [-87.34631510051426, -87.34193548387097, -87.88387096774194, -88.00967741935484, -88.02473005760007, -87.5, -87.34631510051426], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 36, 979000), u'frame_id': 1320, u'frame_time': datetime.datetime(2016, 3, 31, 22, 0), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.93861607142857, 34.89174107142857, 35.018973214285715, 35.057573270079985, 35.2, 35.2], u'x_verts': [-87.34631510051426, -87.34193548387097, -87.88387096774194, -88.00967741935484, -88.02473005760007, -87.5, -87.34631510051426], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 36, 979000), u'frame_id': 1320, u'frame_time': datetime.datetime(2016, 3, 31, 22, 0), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.16294642857143, 34.978794642857146, 34.875, 35.06124551731521, 35.2, 35.2], u'x_verts': [-87.24788283277717, -87.18387096774194, -87.50645161290323, -87.90967741935485, -88.01120072568082, -87.5, -87.24788283277717], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 49, 422000), u'frame_id': 1321, u'frame_time': datetime.datetime(2016, 3, 31, 22, 1), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.16294642857143, 34.978794642857146, 34.875, 35.06124551731521, 35.2, 35.2], u'x_verts': [-87.24788283277717, -87.18387096774194, -87.50645161290323, -87.90967741935485, -88.01120072568082, -87.5, -87.24788283277717], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 27, 49, 422000), u'frame_id': 1321, u'frame_time': datetime.datetime(2016, 3, 31, 22, 1), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.972098214285715, 34.9453125, 34.99888392857143, 35.07621952245914, 35.2, 35.2], u'x_verts': [-87.25694995864352, -87.25483870967743, -87.70967741935485, -87.92258064516129, -87.95603333830842, -87.5, -87.25694995864352], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 1, 920000), u'frame_id': 1322, u'frame_time': datetime.datetime(2016, 3, 31, 22, 2), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.972098214285715, 34.9453125, 34.99888392857143, 35.07621952245914, 35.2, 35.2], u'x_verts': [-87.25694995864352, -87.25483870967743, -87.70967741935485, -87.92258064516129, -87.95603333830842, -87.5, -87.25694995864352], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 1, 920000), u'frame_id': 1322, u'frame_time': datetime.datetime(2016, 3, 31, 22, 2), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.972098214285715, 34.935267857142854, 35.06748774096746, 35.2, 35.2], u'x_verts': [-87.34001483129404, -87.48387096774194, -87.90967741935485, -87.98820305959359, -87.5, -87.34001483129404], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 10, 216000), u'frame_id': 1323, u'frame_time': datetime.datetime(2016, 3, 31, 22, 3), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.972098214285715, 34.935267857142854, 35.06748774096746, 35.2, 35.2], u'x_verts': [-87.34001483129404, -87.48387096774194, -87.90967741935485, -87.98820305959359, -87.5, -87.34001483129404], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 10, 216000), u'frame_id': 1323, u'frame_time': datetime.datetime(2016, 3, 31, 22, 3), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.122767857142854, 34.801339285714285, 35.04575892857143, 35.07432572849284, 35.2, 35.2], u'x_verts': [-87.44914636822472, -87.4483870967742, -87.78064516129032, -87.96129032258065, -87.96301047397377, -87.5, -87.44914636822472], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 18, 860000), u'frame_id': 1324, u'frame_time': datetime.datetime(2016, 3, 31, 22, 4), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.122767857142854, 34.801339285714285, 35.04575892857143, 35.07432572849284, 35.2, 35.2], u'x_verts': [-87.44914636822472, -87.4483870967742, -87.78064516129032, -87.96129032258065, -87.96301047397377, -87.5, -87.44914636822472], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 18, 860000), u'frame_id': 1324, u'frame_time': datetime.datetime(2016, 3, 31, 22, 4), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.112723214285715, 34.978794642857146, 34.911830357142854, 35.025669642857146, 35.08119594068494, 35.2, 35.2], u'x_verts': [-87.32690253208463, -87.26451612903226, -87.3258064516129, -87.74516129032259, -87.92258064516129, -87.93769916589757, -87.5, -87.32690253208463], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 27, 89000), u'frame_id': 1325, u'frame_time': datetime.datetime(2016, 3, 31, 22, 5), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.112723214285715, 34.978794642857146, 34.911830357142854, 35.025669642857146, 35.08119594068494, 35.2, 35.2], u'x_verts': [-87.32690253208463, -87.26451612903226, -87.3258064516129, -87.74516129032259, -87.92258064516129, -87.93769916589757, -87.5, -87.32690253208463], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 27, 89000), u'frame_id': 1325, u'frame_time': datetime.datetime(2016, 3, 31, 22, 5), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.07924107142857, 34.95200892857143, 34.978794642857146, 35.08020846188873, 35.2, 35.2], u'x_verts': [-87.1751366757352, -87.10645161290323, -87.55483870967743, -87.9, -87.9413372456731, -87.5, -87.1751366757352], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 34, 490000), u'frame_id': 1326, u'frame_time': datetime.datetime(2016, 3, 31, 22, 6), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.07924107142857, 34.95200892857143, 34.978794642857146, 35.08020846188873, 35.2, 35.2], u'x_verts': [-87.1751366757352, -87.10645161290323, -87.55483870967743, -87.9, -87.9413372456731, -87.5, -87.1751366757352], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 34, 490000), u'frame_id': 1326, u'frame_time': datetime.datetime(2016, 3, 31, 22, 6), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.015625, 34.88169642857143, 35.049107142857146, 35.08086015987734, 35.2, 35.2], u'x_verts': [-87.2542719324691, -87.2741935483871, -87.67096774193548, -87.94193548387098, -87.9389362530835, -87.5, -87.2542719324691], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 43, 945000), u'frame_id': 1327, u'frame_time': datetime.datetime(2016, 3, 31, 22, 7), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.015625, 34.88169642857143, 35.049107142857146, 35.08086015987734, 35.2, 35.2], u'x_verts': [-87.2542719324691, -87.2741935483871, -87.67096774193548, -87.94193548387098, -87.9389362530835, -87.5, -87.2542719324691], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 43, 945000), u'frame_id': 1327, u'frame_time': datetime.datetime(2016, 3, 31, 22, 7), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.901785714285715, 34.901785714285715, 35.085966735966736, 35.2, 35.2], u'x_verts': [-87.2602688172043, -87.41290322580646, -87.8967741935484, -87.92012255170151, -87.5, -87.2602688172043], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 52, 82000), u'frame_id': 1328, u'frame_time': datetime.datetime(2016, 3, 31, 22, 8), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.901785714285715, 34.901785714285715, 35.085966735966736, 35.2, 35.2], u'x_verts': [-87.2602688172043, -87.41290322580646, -87.8967741935484, -87.92012255170151, -87.5, -87.2602688172043], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 28, 52, 82000), u'frame_id': 1328, u'frame_time': datetime.datetime(2016, 3, 31, 22, 8), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.97232754403131, 34.86830357142857, 34.99888392857143, 35.08844475422753, 35.2, 35.2, 35.05176957831325, 34.97232754403131], u'x_verts': [-87.0, -87.60967741935484, -87.90645161290323, -87.91099301074068, -87.5, -87.22794871794872, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 0, 702000), u'frame_id': 1329, u'frame_time': datetime.datetime(2016, 3, 31, 22, 9), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.97232754403131, 34.86830357142857, 34.99888392857143, 35.08844475422753, 35.2, 35.2, 35.05176957831325, 34.97232754403131], u'x_verts': [-87.0, -87.60967741935484, -87.90645161290323, -87.91099301074068, -87.5, -87.22794871794872, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 0, 702000), u'frame_id': 1329, u'frame_time': datetime.datetime(2016, 3, 31, 22, 9), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.90361394557823, 34.91517857142857, 35.08800912770171, 35.2, 35.2, 35.14512072434608, 34.90361394557823], u'x_verts': [-87.0, -87.87741935483872, -87.91259795057265, -87.5, -87.03128315412187, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 8, 374000), u'frame_id': 1330, u'frame_time': datetime.datetime(2016, 3, 31, 22, 10), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.90361394557823, 34.91517857142857, 35.08800912770171, 35.2, 35.2, 35.14512072434608, 34.90361394557823], u'x_verts': [-87.0, -87.87741935483872, -87.91259795057265, -87.5, -87.03128315412187, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 8, 374000), u'frame_id': 1330, u'frame_time': datetime.datetime(2016, 3, 31, 22, 10), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.918526785714285, 35.029017857142854, 35.09332332000446, 35.2, 35.2], u'x_verts': [-87.34138567660783, -87.5741935483871, -87.87096774193549, -87.893019347352, -87.5, -87.34138567660783], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 18, 326000), u'frame_id': 1331, u'frame_time': datetime.datetime(2016, 3, 31, 22, 11), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.918526785714285, 35.029017857142854, 35.09332332000446, 35.2, 35.2], u'x_verts': [-87.34138567660783, -87.5741935483871, -87.87096774193549, -87.893019347352, -87.5, -87.34138567660783], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 18, 326000), u'frame_id': 1331, u'frame_time': datetime.datetime(2016, 3, 31, 22, 11), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.8515625, 34.901785714285715, 35.09498597474114, 35.2, 35.2], u'x_verts': [-87.27107022849462, -87.42580645161291, -87.85161290322581, -87.88689377726948, -87.5, -87.27107022849462], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 27, 972000), u'frame_id': 1332, u'frame_time': datetime.datetime(2016, 3, 31, 22, 12), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.8515625, 34.901785714285715, 35.09498597474114, 35.2, 35.2], u'x_verts': [-87.27107022849462, -87.42580645161291, -87.85161290322581, -87.88689377726948, -87.5, -87.27107022849462], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 27, 972000), u'frame_id': 1332, u'frame_time': datetime.datetime(2016, 3, 31, 22, 12), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.9453125, 34.958705357142854, 35.08802919839346, 35.2, 35.2], u'x_verts': [-87.41486440792588, -87.42258064516129, -87.90322580645162, -87.91252400591884, -87.5, -87.41486440792588], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 35, 978000), u'frame_id': 1333, u'frame_time': datetime.datetime(2016, 3, 31, 22, 13), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.9453125, 34.958705357142854, 35.08802919839346, 35.2, 35.2], u'x_verts': [-87.41486440792588, -87.42258064516129, -87.90322580645162, -87.91252400591884, -87.5, -87.41486440792588], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 35, 978000), u'frame_id': 1333, u'frame_time': datetime.datetime(2016, 3, 31, 22, 13), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.93861607142857, 34.88169642857143, 35.100360636330905, 35.2, 35.2], u'x_verts': [-87.17283277715981, -87.20322580645161, -87.87741935483872, -87.86709239246508, -87.5, -87.17283277715981], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 43, 938000), u'frame_id': 1334, u'frame_time': datetime.datetime(2016, 3, 31, 22, 14), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.93861607142857, 34.88169642857143, 35.100360636330905, 35.2, 35.2], u'x_verts': [-87.17283277715981, -87.20322580645161, -87.87741935483872, -87.86709239246508, -87.5, -87.17283277715981], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 43, 938000), u'frame_id': 1334, u'frame_time': datetime.datetime(2016, 3, 31, 22, 14), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.142857142857146, 34.838169642857146, 35.00892857142857, 35.09918290101945, 35.2, 35.2], u'x_verts': [-87.09502986857825, -87.04838709677419, -87.5741935483871, -87.88064516129033, -87.87143141729678, -87.5, -87.09502986857825], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 51, 372000), u'frame_id': 1335, u'frame_time': datetime.datetime(2016, 3, 31, 22, 15), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.142857142857146, 34.838169642857146, 35.00892857142857, 35.09918290101945, 35.2, 35.2], u'x_verts': [-87.09502986857825, -87.04838709677419, -87.5741935483871, -87.88064516129033, -87.87143141729678, -87.5, -87.09502986857825], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 29, 51, 372000), u'frame_id': 1335, u'frame_time': datetime.datetime(2016, 3, 31, 22, 15), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.982142857142854, 34.818080357142854, 35.02232142857143, 35.098084975796155, 35.2, 35.2], u'x_verts': [-87.21431029185868, -87.19032258064517, -87.70645161290324, -87.89032258064516, -87.87547640496155, -87.5, -87.21431029185868], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 30, 37, 10000), u'frame_id': 1336, u'frame_time': datetime.datetime(2016, 3, 31, 22, 16), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.982142857142854, 34.818080357142854, 35.02232142857143, 35.098084975796155, 35.2, 35.2], u'x_verts': [-87.21431029185868, -87.19032258064517, -87.70645161290324, -87.89032258064516, -87.87547640496155, -87.5, -87.21431029185868], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 30, 37, 10000), u'frame_id': 1336, u'frame_time': datetime.datetime(2016, 3, 31, 22, 16), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.0625, 34.82142857142857, 35.005580357142854, 35.103192006882146, 35.2, 35.2], u'x_verts': [-87.22945273631842, -87.1483870967742, -87.74193548387098, -87.88064516129033, -87.8566610272763, -87.5, -87.22945273631842], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 30, 46, 916000), u'frame_id': 1337, u'frame_time': datetime.datetime(2016, 3, 31, 22, 17), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.0625, 34.82142857142857, 35.005580357142854, 35.103192006882146, 35.2, 35.2], u'x_verts': [-87.22945273631842, -87.1483870967742, -87.74193548387098, -87.88064516129033, -87.8566610272763, -87.5, -87.22945273631842], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 30, 46, 916000), u'frame_id': 1337, u'frame_time': datetime.datetime(2016, 3, 31, 22, 17), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.142857142857146, 34.918526785714285, 34.99888392857143, 35.109146050291876, 35.2, 35.2], u'x_verts': [-87.26149272612271, -87.20967741935485, -87.3483870967742, -87.83548387096775, -87.83472507787204, -87.5, -87.26149272612271], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 30, 53, 842000), u'frame_id': 1338, u'frame_time': datetime.datetime(2016, 3, 31, 22, 18), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.142857142857146, 34.918526785714285, 34.99888392857143, 35.109146050291876, 35.2, 35.2], u'x_verts': [-87.26149272612271, -87.20967741935485, -87.3483870967742, -87.83548387096775, -87.83472507787204, -87.5, -87.26149272612271], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 30, 53, 842000), u'frame_id': 1338, u'frame_time': datetime.datetime(2016, 3, 31, 22, 18), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.958096590909086, 34.831473214285715, 34.908482142857146, 35.1206322082231, 35.2, 35.2, 34.958096590909086], u'x_verts': [-87.0, -87.67096774193548, -87.83225806451614, -87.7924076539149, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 4, 990000), u'frame_id': 1339, u'frame_time': datetime.datetime(2016, 3, 31, 22, 19), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.958096590909086, 34.831473214285715, 34.908482142857146, 35.1206322082231, 35.2, 35.2, 34.958096590909086], u'x_verts': [-87.0, -87.67096774193548, -87.83225806451614, -87.7924076539149, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 4, 990000), u'frame_id': 1339, u'frame_time': datetime.datetime(2016, 3, 31, 22, 19), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.065848214285715, 34.8984375, 34.978794642857146, 35.113021612420695, 35.2, 35.2], u'x_verts': [-87.27232558139535, -87.31290322580645, -87.55483870967743, -87.83548387096775, -87.82044669108166, -87.5, -87.27232558139535], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 15, 186000), u'frame_id': 1340, u'frame_time': datetime.datetime(2016, 3, 31, 22, 20), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.065848214285715, 34.8984375, 34.978794642857146, 35.113021612420695, 35.2, 35.2], u'x_verts': [-87.27232558139535, -87.31290322580645, -87.55483870967743, -87.83548387096775, -87.82044669108166, -87.5, -87.27232558139535], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 15, 186000), u'frame_id': 1340, u'frame_time': datetime.datetime(2016, 3, 31, 22, 20), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.85825892857143, 34.93861607142857, 35.113647643149584, 35.2, 35.2], u'x_verts': [-87.27723369691344, -87.41935483870968, -87.81290322580645, -87.81814026208048, -87.5, -87.27723369691344], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 22, 434000), u'frame_id': 1341, u'frame_time': datetime.datetime(2016, 3, 31, 22, 21), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.85825892857143, 34.93861607142857, 35.113647643149584, 35.2, 35.2], u'x_verts': [-87.27723369691344, -87.41935483870968, -87.81290322580645, -87.81814026208048, -87.5, -87.27723369691344], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 22, 434000), u'frame_id': 1341, u'frame_time': datetime.datetime(2016, 3, 31, 22, 21), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.911830357142854, 34.82142857142857, 35.114191704849695, 35.2, 35.2], u'x_verts': [-87.3126996634655, -87.22580645161291, -87.8258064516129, -87.81613582423796, -87.5, -87.3126996634655], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 30, 31000), u'frame_id': 1342, u'frame_time': datetime.datetime(2016, 3, 31, 22, 22), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.911830357142854, 34.82142857142857, 35.114191704849695, 35.2, 35.2], u'x_verts': [-87.3126996634655, -87.22580645161291, -87.8258064516129, -87.81613582423796, -87.5, -87.3126996634655], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 30, 31000), u'frame_id': 1342, u'frame_time': datetime.datetime(2016, 3, 31, 22, 22), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.838169642857146, 34.888392857142854, 35.11845143188454, 35.2, 35.2], u'x_verts': [-87.27940003116721, -87.2516129032258, -87.80967741935484, -87.80044209305697, -87.5, -87.27940003116721], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 37, 765000), u'frame_id': 1343, u'frame_time': datetime.datetime(2016, 3, 31, 22, 23), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.838169642857146, 34.888392857142854, 35.11845143188454, 35.2, 35.2], u'x_verts': [-87.27940003116721, -87.2516129032258, -87.80967741935484, -87.80044209305697, -87.5, -87.27940003116721], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 37, 765000), u'frame_id': 1343, u'frame_time': datetime.datetime(2016, 3, 31, 22, 23), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.005580357142854, 34.982142857142854, 35.122767857142854, 35.12691413245065, 35.2, 35.2], u'x_verts': [-87.24724014336918, -87.30967741935484, -87.83548387096775, -87.76774193548387, -87.76926372255025, -87.5, -87.24724014336918], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 53, 903000), u'frame_id': 1344, u'frame_time': datetime.datetime(2016, 3, 31, 22, 24), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.005580357142854, 34.982142857142854, 35.122767857142854, 35.12691413245065, 35.2, 35.2], u'x_verts': [-87.24724014336918, -87.30967741935484, -87.83548387096775, -87.76774193548387, -87.76926372255025, -87.5, -87.24724014336918], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 31, 53, 903000), u'frame_id': 1344, u'frame_time': datetime.datetime(2016, 3, 31, 22, 24), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.93861607142857, 34.978794642857146, 35.052455357142854, 35.130406510456275, 35.2, 35.2], u'x_verts': [-87.25474772539289, -87.36129032258064, -87.78387096774195, -87.76451612903226, -87.75639706674004, -87.5, -87.25474772539289], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 6, 583000), u'frame_id': 1345, u'frame_time': datetime.datetime(2016, 3, 31, 22, 25), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.93861607142857, 34.978794642857146, 35.052455357142854, 35.130406510456275, 35.2, 35.2], u'x_verts': [-87.25474772539289, -87.36129032258064, -87.78387096774195, -87.76451612903226, -87.75639706674004, -87.5, -87.25474772539289], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 6, 583000), u'frame_id': 1345, u'frame_time': datetime.datetime(2016, 3, 31, 22, 25), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.015625, 34.9453125, 35.07924107142857, 35.11992362911175, 35.2, 35.2], u'x_verts': [-87.26974055440466, -87.23225806451613, -87.69677419354839, -87.79354838709678, -87.79501820853565, -87.5, -87.26974055440466], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 14, 452000), u'frame_id': 1346, u'frame_time': datetime.datetime(2016, 3, 31, 22, 26), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.015625, 34.9453125, 35.07924107142857, 35.11992362911175, 35.2, 35.2], u'x_verts': [-87.26974055440466, -87.23225806451613, -87.69677419354839, -87.79354838709678, -87.79501820853565, -87.5, -87.26974055440466], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 14, 452000), u'frame_id': 1346, u'frame_time': datetime.datetime(2016, 3, 31, 22, 26), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.965401785714285, 34.95200892857143, 35.075892857142854, 35.12740732421165, 35.2, 35.2], u'x_verts': [-87.30164063028336, -87.3258064516129, -87.71290322580646, -87.79677419354839, -87.76744670027286, -87.5, -87.30164063028336], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 25, 741000), u'frame_id': 1347, u'frame_time': datetime.datetime(2016, 3, 31, 22, 27), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.965401785714285, 34.95200892857143, 35.075892857142854, 35.12740732421165, 35.2, 35.2], u'x_verts': [-87.30164063028336, -87.3258064516129, -87.71290322580646, -87.79677419354839, -87.76744670027286, -87.5, -87.30164063028336], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 25, 741000), u'frame_id': 1347, u'frame_time': datetime.datetime(2016, 3, 31, 22, 27), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.123288690476194, 34.958705357142854, 34.96875, 35.0625, 35.12371973782251, 35.2, 35.2, 35.123288690476194], u'x_verts': [-87.0, -87.2709677419355, -87.69677419354839, -87.81612903225808, -87.78103254486444, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 34, 33000), u'frame_id': 1348, u'frame_time': datetime.datetime(2016, 3, 31, 22, 28), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.123288690476194, 34.958705357142854, 34.96875, 35.0625, 35.12371973782251, 35.2, 35.2, 35.123288690476194], u'x_verts': [-87.0, -87.2709677419355, -87.69677419354839, -87.81612903225808, -87.78103254486444, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 34, 33000), u'frame_id': 1348, u'frame_time': datetime.datetime(2016, 3, 31, 22, 28), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.11642804311073, 34.908482142857146, 35.00892857142857, 35.072544642857146, 35.103058549947775, 35.2, 35.2, 35.11642804311073], u'x_verts': [-87.0, -87.52903225806452, -87.71935483870968, -87.81935483870969, -87.85715271071872, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 43, 417000), u'frame_id': 1349, u'frame_time': datetime.datetime(2016, 3, 31, 22, 29), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.11642804311073, 34.908482142857146, 35.00892857142857, 35.072544642857146, 35.103058549947775, 35.2, 35.2, 35.11642804311073], u'x_verts': [-87.0, -87.52903225806452, -87.71935483870968, -87.81935483870969, -87.85715271071872, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 43, 417000), u'frame_id': 1349, u'frame_time': datetime.datetime(2016, 3, 31, 22, 29), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.97544642857143, 34.98549107142857, 35.052455357142854, 35.08439105366707, 35.2, 35.2], u'x_verts': [-87.27817517486169, -87.4, -87.5741935483871, -87.84516129032258, -87.92592769701608, -87.5, -87.27817517486169], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 55, 455000), u'frame_id': 1350, u'frame_time': datetime.datetime(2016, 3, 31, 22, 30), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.97544642857143, 34.98549107142857, 35.052455357142854, 35.08439105366707, 35.2, 35.2], u'x_verts': [-87.27817517486169, -87.4, -87.5741935483871, -87.84516129032258, -87.92592769701608, -87.5, -87.27817517486169], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 32, 55, 455000), u'frame_id': 1350, u'frame_time': datetime.datetime(2016, 3, 31, 22, 30), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.082589285714285, 34.941964285714285, 35.052455357142854, 35.09862874666861, 35.2, 35.2], u'x_verts': [-87.19271684587814, -87.06451612903226, -87.49354838709678, -87.79677419354839, -87.87347303858932, -87.5, -87.19271684587814], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 2, 625000), u'frame_id': 1351, u'frame_time': datetime.datetime(2016, 3, 31, 22, 31), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.082589285714285, 34.941964285714285, 35.052455357142854, 35.09862874666861, 35.2, 35.2], u'x_verts': [-87.19271684587814, -87.06451612903226, -87.49354838709678, -87.79677419354839, -87.87347303858932, -87.5, -87.19271684587814], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 2, 625000), u'frame_id': 1351, u'frame_time': datetime.datetime(2016, 3, 31, 22, 31), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.931919642857146, 34.988839285714285, 35.05580357142857, 35.152901785714285, 35.1535695247121, 35.2, 35.2], u'x_verts': [-87.22359225806453, -87.2483870967742, -87.66774193548387, -87.72580645161291, -87.67096774193548, -87.67105964579756, -87.5, -87.22359225806453], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 14, 697000), u'frame_id': 1352, u'frame_time': datetime.datetime(2016, 3, 31, 22, 32), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.931919642857146, 34.988839285714285, 35.05580357142857, 35.152901785714285, 35.1535695247121, 35.2, 35.2], u'x_verts': [-87.22359225806453, -87.2483870967742, -87.66774193548387, -87.72580645161291, -87.67096774193548, -87.67105964579756, -87.5, -87.22359225806453], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 14, 697000), u'frame_id': 1352, u'frame_time': datetime.datetime(2016, 3, 31, 22, 32), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.112723214285715, 34.935267857142854, 34.97544642857143, 35.13470879154907, 35.2, 35.2], u'x_verts': [-87.08529325513197, -87.04516129032258, -87.66774193548387, -87.74516129032259, -87.7405465574508, -87.5, -87.08529325513197], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 24, 48000), u'frame_id': 1353, u'frame_time': datetime.datetime(2016, 3, 31, 22, 33), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.112723214285715, 34.935267857142854, 34.97544642857143, 35.13470879154907, 35.2, 35.2], u'x_verts': [-87.08529325513197, -87.04516129032258, -87.66774193548387, -87.74516129032259, -87.7405465574508, -87.5, -87.08529325513197], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 24, 48000), u'frame_id': 1353, u'frame_time': datetime.datetime(2016, 3, 31, 22, 33), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.03236607142857, 34.995535714285715, 35.1211436850179, 35.2, 35.2], u'x_verts': [-87.19248576850096, -87.13548387096775, -87.61290322580646, -87.79052326572354, -87.5, -87.19248576850096], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 32, 986000), u'frame_id': 1354, u'frame_time': datetime.datetime(2016, 3, 31, 22, 34), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.03236607142857, 34.995535714285715, 35.1211436850179, 35.2, 35.2], u'x_verts': [-87.19248576850096, -87.13548387096775, -87.61290322580646, -87.79052326572354, -87.5, -87.19248576850096], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 32, 986000), u'frame_id': 1354, u'frame_time': datetime.datetime(2016, 3, 31, 22, 34), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.948660714285715, 35.005580357142854, 35.124230186774355, 35.2, 35.2], u'x_verts': [-87.22557546794107, -87.28387096774195, -87.6258064516129, -87.7791519434629, -87.5, -87.22557546794107], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 41, 463000), u'frame_id': 1355, u'frame_time': datetime.datetime(2016, 3, 31, 22, 35), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.948660714285715, 35.005580357142854, 35.124230186774355, 35.2, 35.2], u'x_verts': [-87.22557546794107, -87.28387096774195, -87.6258064516129, -87.7791519434629, -87.5, -87.22557546794107], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 41, 463000), u'frame_id': 1355, u'frame_time': datetime.datetime(2016, 3, 31, 22, 35), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.14955357142857, 34.982142857142854, 35.035714285714285, 35.14251960736968, 35.2, 35.2], u'x_verts': [-87.2366697388633, -87.22903225806452, -87.43548387096774, -87.66129032258065, -87.7117698675854, -87.5, -87.2366697388633], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 49, 798000), u'frame_id': 1356, u'frame_time': datetime.datetime(2016, 3, 31, 22, 36), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.14955357142857, 34.982142857142854, 35.035714285714285, 35.14251960736968, 35.2, 35.2], u'x_verts': [-87.2366697388633, -87.22903225806452, -87.43548387096774, -87.66129032258065, -87.7117698675854, -87.5, -87.2366697388633], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 49, 798000), u'frame_id': 1356, u'frame_time': datetime.datetime(2016, 3, 31, 22, 36), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.129464285714285, 34.925223214285715, 35.018973214285715, 35.138225073797734, 35.2, 35.2], u'x_verts': [-87.19503533026113, -87.18387096774194, -87.20967741935485, -87.56774193548388, -87.72759183337676, -87.5, -87.19503533026113], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 57, 65000), u'frame_id': 1357, u'frame_time': datetime.datetime(2016, 3, 31, 22, 37), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.129464285714285, 34.925223214285715, 35.018973214285715, 35.138225073797734, 35.2, 35.2], u'x_verts': [-87.19503533026113, -87.18387096774194, -87.20967741935485, -87.56774193548388, -87.72759183337676, -87.5, -87.19503533026113], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 33, 57, 65000), u'frame_id': 1357, u'frame_time': datetime.datetime(2016, 3, 31, 22, 37), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.955357142857146, 35.002232142857146, 35.15526556457946, 35.2, 35.2], u'x_verts': [-87.17256906534325, -87.15806451612903, -87.56129032258065, -87.66481107786515, -87.5, -87.17256906534325], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 3, 983000), u'frame_id': 1358, u'frame_time': datetime.datetime(2016, 3, 31, 22, 38), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.955357142857146, 35.002232142857146, 35.15526556457946, 35.2, 35.2], u'x_verts': [-87.17256906534325, -87.15806451612903, -87.56129032258065, -87.66481107786515, -87.5, -87.17256906534325], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 3, 983000), u'frame_id': 1358, u'frame_time': datetime.datetime(2016, 3, 31, 22, 38), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.082589285714285, 34.955357142857146, 35.042410714285715, 35.15625, 35.1582960194858, 35.2, 35.2], u'x_verts': [-87.07453189964158, -87.00967741935484, -87.49354838709678, -87.6258064516129, -87.65483870967742, -87.65364624399967, -87.5, -87.07453189964158], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 11, 613000), u'frame_id': 1359, u'frame_time': datetime.datetime(2016, 3, 31, 22, 39), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.082589285714285, 34.955357142857146, 35.042410714285715, 35.15625, 35.1582960194858, 35.2, 35.2], u'x_verts': [-87.07453189964158, -87.00967741935484, -87.49354838709678, -87.6258064516129, -87.65483870967742, -87.65364624399967, -87.5, -87.07453189964158], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 11, 613000), u'frame_id': 1359, u'frame_time': datetime.datetime(2016, 3, 31, 22, 39), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.96980541537267, 34.948660714285715, 35.129464285714285, 35.14985641928891, 35.2, 35.2, 35.120689655172384, 34.96980541537267], u'x_verts': [-87.0, -87.53548387096775, -87.66129032258065, -87.68473950788298, -87.5, -87.03099180389505, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 19, 115000), u'frame_id': 1360, u'frame_time': datetime.datetime(2016, 3, 31, 22, 40), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.96980541537267, 34.948660714285715, 35.129464285714285, 35.14985641928891, 35.2, 35.2, 35.120689655172384, 34.96980541537267], u'x_verts': [-87.0, -87.53548387096775, -87.66129032258065, -87.68473950788298, -87.5, -87.03099180389505, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 19, 115000), u'frame_id': 1360, u'frame_time': datetime.datetime(2016, 3, 31, 22, 40), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.878348214285715, 34.988839285714285, 35.16137973514013, 35.2, 35.2], u'x_verts': [-87.17938727698686, -87.17419354838711, -87.55161290322582, -87.64228518632585, -87.5, -87.17938727698686], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 27, 22000), u'frame_id': 1361, u'frame_time': datetime.datetime(2016, 3, 31, 22, 41), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.878348214285715, 34.988839285714285, 35.16137973514013, 35.2, 35.2], u'x_verts': [-87.17938727698686, -87.17419354838711, -87.55161290322582, -87.64228518632585, -87.5, -87.17938727698686], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 27, 22000), u'frame_id': 1361, u'frame_time': datetime.datetime(2016, 3, 31, 22, 41), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.955357142857146, 34.911830357142854, 35.04575892857143, 35.1328125, 35.17383493867521, 35.2, 35.2], u'x_verts': [-87.1334214029698, -87.00322580645162, -87.3225806451613, -87.59032258064516, -87.60645161290323, -87.5963975943545, -87.5, -87.1334214029698], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 35, 82000), u'frame_id': 1362, u'frame_time': datetime.datetime(2016, 3, 31, 22, 42), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.955357142857146, 34.911830357142854, 35.04575892857143, 35.1328125, 35.17383493867521, 35.2, 35.2], u'x_verts': [-87.1334214029698, -87.00322580645162, -87.3225806451613, -87.59032258064516, -87.60645161290323, -87.5963975943545, -87.5, -87.1334214029698], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 35, 82000), u'frame_id': 1362, u'frame_time': datetime.datetime(2016, 3, 31, 22, 42), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.176339285714285, 34.90513392857143, 35.025669642857146, 35.14955357142857, 35.17854040879632, 35.2, 35.2], u'x_verts': [-87.06795404330536, -87.05483870967743, -87.3225806451613, -87.55161290322582, -87.59032258064516, -87.57906165180303, -87.5, -87.06795404330536], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 41, 721000), u'frame_id': 1363, u'frame_time': datetime.datetime(2016, 3, 31, 22, 43), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.176339285714285, 34.90513392857143, 35.025669642857146, 35.14955357142857, 35.17854040879632, 35.2, 35.2], u'x_verts': [-87.06795404330536, -87.05483870967743, -87.3225806451613, -87.55161290322582, -87.59032258064516, -87.57906165180303, -87.5, -87.06795404330536], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 41, 721000), u'frame_id': 1363, u'frame_time': datetime.datetime(2016, 3, 31, 22, 43), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.025669642857146, 34.988839285714285, 35.035714285714285, 35.14955357142857, 35.184614683757665, 35.2, 35.2], u'x_verts': [-87.10595698924732, -87.1258064516129, -87.4, -87.53870967741936, -87.58387096774194, -87.5566827440507, -87.5, -87.10595698924732], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 50, 490000), u'frame_id': 1364, u'frame_time': datetime.datetime(2016, 3, 31, 22, 44), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.025669642857146, 34.988839285714285, 35.035714285714285, 35.14955357142857, 35.184614683757665, 35.2, 35.2], u'x_verts': [-87.10595698924732, -87.1258064516129, -87.4, -87.53870967741936, -87.58387096774194, -87.5566827440507, -87.5, -87.10595698924732], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 50, 490000), u'frame_id': 1364, u'frame_time': datetime.datetime(2016, 3, 31, 22, 44), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.059151785714285, 34.911830357142854, 35.106026785714285, 35.18965755012584, 35.2, 35.2], u'x_verts': [-87.16065451145396, -87.11935483870968, -87.48387096774194, -87.56129032258065, -87.53810376269428, -87.5, -87.16065451145396], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 57, 549000), u'frame_id': 1365, u'frame_time': datetime.datetime(2016, 3, 31, 22, 45), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.059151785714285, 34.911830357142854, 35.106026785714285, 35.18965755012584, 35.2, 35.2], u'x_verts': [-87.16065451145396, -87.11935483870968, -87.48387096774194, -87.56129032258065, -87.53810376269428, -87.5, -87.16065451145396], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 34, 57, 549000), u'frame_id': 1365, u'frame_time': datetime.datetime(2016, 3, 31, 22, 45), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.966449024543735, 34.911830357142854, 35.187847000610034, 35.2, 35.2, 34.966449024543735], u'x_verts': [-87.0, -87.51935483870969, -87.54477420827882, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 4, 855000), u'frame_id': 1366, u'frame_time': datetime.datetime(2016, 3, 31, 22, 46), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.966449024543735, 34.911830357142854, 35.187847000610034, 35.2, 35.2, 34.966449024543735], u'x_verts': [-87.0, -87.51935483870969, -87.54477420827882, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 4, 855000), u'frame_id': 1366, u'frame_time': datetime.datetime(2016, 3, 31, 22, 46), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.908482142857146, 34.958705357142854, 35.190386093461775, 35.2, 35.2], u'x_verts': [-87.02430994346525, -87.06774193548388, -87.50322580645162, -87.53541965566716, -87.5, -87.02430994346525], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 11, 699000), u'frame_id': 1367, u'frame_time': datetime.datetime(2016, 3, 31, 22, 47), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.908482142857146, 34.958705357142854, 35.190386093461775, 35.2, 35.2], u'x_verts': [-87.02430994346525, -87.06774193548388, -87.50322580645162, -87.53541965566716, -87.5, -87.02430994346525], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 11, 699000), u'frame_id': 1367, u'frame_time': datetime.datetime(2016, 3, 31, 22, 47), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.04666114200171, 34.97544642857143, 35.193080357142854, 35.19776288772856, 35.2, 35.2, 35.19389699477352, 35.04666114200171], u'x_verts': [-87.0, -87.47741935483872, -87.50967741935484, -87.50824199257902, -87.5, -87.00270871088559, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 18, 322000), u'frame_id': 1368, u'frame_time': datetime.datetime(2016, 3, 31, 22, 48), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.04666114200171, 34.97544642857143, 35.193080357142854, 35.19776288772856, 35.2, 35.2, 35.19389699477352, 35.04666114200171], u'x_verts': [-87.0, -87.47741935483872, -87.50967741935484, -87.50824199257902, -87.5, -87.00270871088559, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 18, 322000), u'frame_id': 1368, u'frame_time': datetime.datetime(2016, 3, 31, 22, 48), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.955357142857146, 35.025669642857146, 35.17381855216594, 35.2, 35.2], u'x_verts': [-87.1245948072384, -87.18064516129033, -87.44516129032259, -87.59645796570445, -87.5, -87.1245948072384], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 24, 479000), u'frame_id': 1369, u'frame_time': datetime.datetime(2016, 3, 31, 22, 49), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.955357142857146, 35.025669642857146, 35.17381855216594, 35.2, 35.2], u'x_verts': [-87.1245948072384, -87.18064516129033, -87.44516129032259, -87.59645796570445, -87.5, -87.1245948072384], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 24, 479000), u'frame_id': 1369, u'frame_time': datetime.datetime(2016, 3, 31, 22, 49), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.082589285714285, 34.93861607142857, 35.122767857142854, 35.19992331351983, 35.2, 35.2], u'x_verts': [-87.0948730459926, -87.0967741935484, -87.41612903225807, -87.48387096774194, -87.50028252913746, -87.5, -87.0948730459926], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 31, 129000), u'frame_id': 1370, u'frame_time': datetime.datetime(2016, 3, 31, 22, 50), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.082589285714285, 34.93861607142857, 35.122767857142854, 35.19992331351983, 35.2, 35.2], u'x_verts': [-87.0948730459926, -87.0967741935484, -87.41612903225807, -87.48387096774194, -87.50028252913746, -87.5, -87.0948730459926], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 31, 129000), u'frame_id': 1370, u'frame_time': datetime.datetime(2016, 3, 31, 22, 50), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.193080357142854, 34.871651785714285, 34.98549107142857, 35.2, 35.2], u'x_verts': [-87.15192473118282, -87.13225806451614, -87.18064516129033, -87.46774193548387, -87.49610794855577, -87.15192473118282], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 36, 222000), u'frame_id': 1371, u'frame_time': datetime.datetime(2016, 3, 31, 22, 51), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.193080357142854, 34.871651785714285, 34.98549107142857, 35.2, 35.2], u'x_verts': [-87.15192473118282, -87.13225806451614, -87.18064516129033, -87.46774193548387, -87.49610794855577, -87.15192473118282], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 36, 222000), u'frame_id': 1371, u'frame_time': datetime.datetime(2016, 3, 31, 22, 51), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.035714285714285, 35.015625, 35.089285714285715, 35.2, 35.2], u'x_verts': [-87.09969582485712, -87.10967741935484, -87.38709677419355, -87.44516129032259, -87.45513013767462, -87.09969582485712], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 45, 206000), u'frame_id': 1372, u'frame_time': datetime.datetime(2016, 3, 31, 22, 52), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 35.035714285714285, 35.015625, 35.089285714285715, 35.2, 35.2], u'x_verts': [-87.09969582485712, -87.10967741935484, -87.38709677419355, -87.44516129032259, -87.45513013767462, -87.09969582485712], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 45, 206000), u'frame_id': 1372, u'frame_time': datetime.datetime(2016, 3, 31, 22, 52), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.149370107632095, 34.864955357142854, 35.082589285714285, 35.176339285714285, 35.199886643597644, 35.2, 35.2, 35.149370107632095], u'x_verts': [-87.0, -87.17096774193548, -87.4741935483871, -87.50967741935484, -87.50041762885078, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 51, 481000), u'frame_id': 1373, u'frame_time': datetime.datetime(2016, 3, 31, 22, 53), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.149370107632095, 34.864955357142854, 35.082589285714285, 35.176339285714285, 35.199886643597644, 35.2, 35.2, 35.149370107632095], u'x_verts': [-87.0, -87.17096774193548, -87.4741935483871, -87.50967741935484, -87.50041762885078, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 51, 481000), u'frame_id': 1373, u'frame_time': datetime.datetime(2016, 3, 31, 22, 53), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.93861607142857, 35.06919642857143, 35.152901785714285, 35.2, 35.2], u'x_verts': [-87.04734913320166, -87.10645161290323, -87.40645161290323, -87.46774193548387, -87.46666154633897, -87.04734913320166], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 58, 343000), u'frame_id': 1374, u'frame_time': datetime.datetime(2016, 3, 31, 22, 54), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.93861607142857, 35.06919642857143, 35.152901785714285, 35.2, 35.2], u'x_verts': [-87.04734913320166, -87.10645161290323, -87.40645161290323, -87.46774193548387, -87.46666154633897, -87.04734913320166], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 35, 58, 343000), u'frame_id': 1374, u'frame_time': datetime.datetime(2016, 3, 31, 22, 54), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.99867466517869, 34.96205357142857, 35.015625, 35.112723214285715, 35.2, 35.2, 34.99867466517869], u'x_verts': [-87.0, -87.00322580645162, -87.33870967741936, -87.48064516129033, -87.46034853540972, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 4, 443000), u'frame_id': 1375, u'frame_time': datetime.datetime(2016, 3, 31, 22, 55), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [34.99867466517869, 34.96205357142857, 35.015625, 35.112723214285715, 35.2, 35.2, 34.99867466517869], u'x_verts': [-87.0, -87.00322580645162, -87.33870967741936, -87.48064516129033, -87.46034853540972, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 4, 443000), u'frame_id': 1375, u'frame_time': datetime.datetime(2016, 3, 31, 22, 55), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.01759453781512, 35.042410714285715, 35.095982142857146, 35.16294642857143, 35.2, 35.2, 35.01759453781512], u'x_verts': [-87.0, -87.2709677419355, -87.41935483870968, -87.48709677419356, -87.48979103266383, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 11, 523000), u'frame_id': 1376, u'frame_time': datetime.datetime(2016, 3, 31, 22, 56), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.01759453781512, 35.042410714285715, 35.095982142857146, 35.16294642857143, 35.2, 35.2, 35.01759453781512], u'x_verts': [-87.0, -87.2709677419355, -87.41935483870968, -87.48709677419356, -87.48979103266383, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 11, 523000), u'frame_id': 1376, u'frame_time': datetime.datetime(2016, 3, 31, 22, 56), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.09973867595819, 34.948660714285715, 35.03236607142857, 35.1796875, 35.099330357142854, 35.10261788511815, 35.2, 35.2, 35.09973867595819], u'x_verts': [-87.0, -87.23870967741937, -87.3967741935484, -87.5225806451613, -87.7225806451613, -87.85877621272262, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 20, 149000), u'frame_id': 1377, u'frame_time': datetime.datetime(2016, 3, 31, 22, 57), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.09973867595819, 34.948660714285715, 35.03236607142857, 35.1796875, 35.099330357142854, 35.10261788511815, 35.2, 35.2, 35.09973867595819], u'x_verts': [-87.0, -87.23870967741937, -87.3967741935484, -87.5225806451613, -87.7225806451613, -87.85877621272262, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 20, 149000), u'frame_id': 1377, u'frame_time': datetime.datetime(2016, 3, 31, 22, 57), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.00538625776397, 35.049107142857146, 35.095982142857146, 35.189732142857146, 35.2, 35.2, 35.00538625776397], u'x_verts': [-87.0, -87.17096774193548, -87.41290322580646, -87.48064516129033, -87.47833691756273, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 28, 744000), u'frame_id': 1378, u'frame_time': datetime.datetime(2016, 3, 31, 22, 58), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.00538625776397, 35.049107142857146, 35.095982142857146, 35.189732142857146, 35.2, 35.2, 35.00538625776397], u'x_verts': [-87.0, -87.17096774193548, -87.41290322580646, -87.48064516129033, -87.47833691756273, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 28, 744000), u'frame_id': 1378, u'frame_time': datetime.datetime(2016, 3, 31, 22, 58), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.060742187500026, 34.9921875, 34.97544642857143, 35.09263392857143, 35.2, 35.2, 35.060742187500026], u'x_verts': [-87.0, -87.0225806451613, -87.33548387096775, -87.38064516129033, -87.4204301075269, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 36, 349000), u'frame_id': 1379, u'frame_time': datetime.datetime(2016, 3, 31, 22, 59), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.060742187500026, 34.9921875, 34.97544642857143, 35.09263392857143, 35.2, 35.2, 35.060742187500026], u'x_verts': [-87.0, -87.0225806451613, -87.33548387096775, -87.38064516129033, -87.4204301075269, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 36, 349000), u'frame_id': 1379, u'frame_time': datetime.datetime(2016, 3, 31, 22, 59), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.96205357142857, 35.082589285714285, 35.1796875, 35.2, 35.2], u'x_verts': [-87.01448711384195, -87.10000000000001, -87.37096774193549, -87.38387096774194, -87.39276637341155, -87.01448711384195], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 42, 774000), u'frame_id': 1380, u'frame_time': datetime.datetime(2016, 3, 31, 23, 0), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.2, 34.96205357142857, 35.082589285714285, 35.1796875, 35.2, 35.2], u'x_verts': [-87.01448711384195, -87.10000000000001, -87.37096774193549, -87.38387096774194, -87.39276637341155, -87.01448711384195], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 42, 774000), u'frame_id': 1380, u'frame_time': datetime.datetime(2016, 3, 31, 23, 0), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.176555299539174, 35.02232142857143, 35.12611607142857, 35.1985655837514, 35.2, 35.2, 35.176555299539174], u'x_verts': [-87.0, -87.13548387096775, -87.43548387096774, -87.50528469144221, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 50, 226000), u'frame_id': 1381, u'frame_time': datetime.datetime(2016, 3, 31, 23, 1), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.176555299539174, 35.02232142857143, 35.12611607142857, 35.1985655837514, 35.2, 35.2, 35.176555299539174], u'x_verts': [-87.0, -87.13548387096775, -87.43548387096774, -87.50528469144221, -87.5, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 50, 226000), u'frame_id': 1381, u'frame_time': datetime.datetime(2016, 3, 31, 23, 1), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.05609727443609, 35.0390625, 35.11607142857143, 35.169642857142854, 35.2, 35.2, 35.05609727443609], u'x_verts': [-87.0, -87.18709677419355, -87.39032258064516, -87.46451612903226, -87.44925666199158, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 58, 665000), u'frame_id': 1382, u'frame_time': datetime.datetime(2016, 3, 31, 23, 2), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}, {u'y_verts': [35.05609727443609, 35.0390625, 35.11607142857143, 35.169642857142854, 35.2, 35.2, 35.05609727443609], u'x_verts': [-87.0, -87.18709677419355, -87.39032258064516, -87.46451612903226, -87.44925666199158, -87.0, -87.0], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 36, 58, 665000), u'frame_id': 1382, u'frame_time': datetime.datetime(2016, 3, 31, 23, 2), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}]\n"
],
[
"print polys[0]",
"{u'y_verts': [34.8, 34.941964285714285, 35.02210403697055, 35.1468885137057, 35.018973214285715, 34.8, 34.8], u'x_verts': [-88.01368523949169, -88.1483870967742, -88.15540617958217, -87.69567389687376, -87.73870967741937, -87.88567596955419, -88.01368523949169], u'title': u'Lasso Verts', 'created': datetime.datetime(2016, 4, 20, 22, 25, 57, 189000), u'frame_id': 1307, u'frame_time': datetime.datetime(2016, 3, 31, 21, 47), u'field': u'flash_extent', u'lon_verts': None, u'filename': u'/data/VORTEX-SE/NALMA/realtime/flashsort/results/grid_files/2016/Mar/31/NALMA_20160331_000000_86400_10src_0.0109deg-dx_flash_extent.nc', u'lat_verts': None}\n"
]
],
[
[
"## Further usage\nThe updated polygon dictionary above can be used anywhere read_polys had previously provided a dictionary of time-stamped polygons.",
"_____no_output_____"
]
]
] |
[
"code",
"markdown"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
4ac2d8c3f8263f14891374ab20af58400fe7b81f
| 252,408 |
ipynb
|
Jupyter Notebook
|
WebSci19-P2P-Lending/Notebooks/prosper_all.ipynb
|
LINK-NU/CRII-1755873
|
6da63966550c2d04f71f9d85c8e93dc8cb16e34d
|
[
"MIT"
] | null | null | null |
WebSci19-P2P-Lending/Notebooks/prosper_all.ipynb
|
LINK-NU/CRII-1755873
|
6da63966550c2d04f71f9d85c8e93dc8cb16e34d
|
[
"MIT"
] | null | null | null |
WebSci19-P2P-Lending/Notebooks/prosper_all.ipynb
|
LINK-NU/CRII-1755873
|
6da63966550c2d04f71f9d85c8e93dc8cb16e34d
|
[
"MIT"
] | null | null | null | 129.90633 | 116,272 | 0.805822 |
[
[
[
"import ml\nreload(ml)\nfrom ml import *\nimport timeit\nimport scipy\nimport operator\nimport collections\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\nimport seaborn as sns\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nfrom __future__ import division\nfrom matplotlib.colors import ListedColormap\nimport statsmodels.api as sm\nfrom sklearn import metrics\nfrom sklearn.svm import SVC\nfrom sklearn.feature_selection import RFE\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import GaussianNB as GNB\nfrom sklearn.ensemble import AdaBoostClassifier as ADB\nfrom sklearn.neural_network import MLPClassifier as MLP\nfrom sklearn.tree import DecisionTreeClassifier as CART\nfrom sklearn.ensemble import RandomForestClassifier as RF\nfrom sklearn.neighbors import KNeighborsClassifier as KNN\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA\nfrom sklearn.model_selection import train_test_split, KFold\nfrom sklearn.metrics import classification_report\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.manifold.t_sne import TSNE\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import roc_curve\nfrom collections import OrderedDict\nimport warnings\nwarnings.filterwarnings('ignore')\npd.set_option('display.max_colwidth', -1)\npd.set_option('display.float_format', lambda x: '%.3f' % x)\nsns.set_style('whitegrid')\nplt.style.use('seaborn-whitegrid')\n%matplotlib inline\n\n__author__ = 'HK Dambanemuya'\n__version__ = 'Python 2'\n\n'''\n Analysis originaly performed in Python 2 (deprecated)\n Seaborn, Statsmodel, and * imports broken in Python 3\n'''",
"_____no_output_____"
],
[
"# Lender Experience\n# Borrower Experience\n\nborrower_features = [\"DebtToIncomeRatio\", \"BorrowerAge\", \"BorrowerSuccessRate\", \"AvailableBankcardCredit\", \n \"BankDraftFeeAnnualRate\", \"BorrowerMaximumRate\", \"CreditGrade\",\n \"CreditScoreRangeLower\", \"CreditScoreRangeUpper\", \"DebtToIncomeRatio\", \"EffectiveYield\", \n \"IsBorrowerHomeowner\", \"OnTimeProsperPayments\", \"ProsperPaymentsLessThanOneMonthLate\",\n \"ProsperPaymentsOneMonthPlusLate\", \"ProsperScore\", \"TotalInquiries\", \"TotalProsperLoans\",\n \"TotalProsperPaymentsBilled\", \"TradesOpenedLast6Months\", ]\n\nlender_features = [\"NoLenders\", \"MedianLenderAge\", \"MedianLenderSuccessRate\"]\n\nloan_features = [\"MedianEstimatedLoss\", \"MedianEstimatedReturn\", \"MedianLenderRate\", \"MedianLenderYield\", \n \"MedianMonthlyLoanPayment\", \"TotalMonthlyLoanPayment\",\n \"MedianTerm\", \"MedianAgeInMonths\", \"TotalAmountBorrowed\", \"MedianBorrowerRate\", ]\n\nlisting_features = [\"ListingKey\", \"Category\", \"AmountRequested\", \"BidCount\",\n \"BidMaximumRate\", \n \"ProsperPrincipalBorrowed\", \"ProsperPrincipalOutstanding\",\n \"TimeToFirstBid\", \"AvgInterBidTime\", \"TimeToCompletion\",\n \"Gini\", \"DescriptionLength\", \"FundedOrNot\", \"RepaidOrNot\"]",
"_____no_output_____"
]
],
[
[
"## Bid Data",
"_____no_output_____"
]
],
[
[
"bid_data = pd.read_csv('../Data/bid_notick.txt', sep=\"|\")\nbid_data = bid_data[[\"Bid_Key\", \"Amount\",\"CreationDate\",\"ListingKey\",\"ListingStatus\"]]\nbid_data= bid_data.rename(index=str, columns={\"Bid_Key\": \"BidKey\", \"Amount\": \"BidAmount\", \"CreationDate\": \"BidCreationDate\", \"ListingKey\": \"ListingKey\", \"ListingStatus\": \"ListingStatus\"})\nbid_data = bid_data.loc[(bid_data[\"ListingStatus\"]==\"Cancelled\") | (bid_data[\"ListingStatus\"]==\"Expired\") | (bid_data[\"ListingStatus\"]==\"Withdrawn\") | (bid_data[\"ListingStatus\"]==\"Completed\")]\nbid_data = bid_data.loc[bid_data[\"BidAmount\"]>0]\nbid_data[\"FundedOrNot\"] = bid_data[\"ListingStatus\"]==\"Completed\"\nbid_data.sample(10)",
"_____no_output_____"
]
],
[
[
"## Listing Data",
"_____no_output_____"
]
],
[
[
"listing_data = pd.read_csv('../Data/listing.txt', sep=\"|\")\nlisting_data = listing_data[[\"Lst_Key\", \"ActiveProsperLoans\", \"BidCount\", \"BidMaximumRate\", \"AmountRequested\",\"CreationDate\", \n \"BorrowerRate\", \"BorrowerMaximumRate\", \"EffectiveYield\", \"BorrowerState\",\"CreditGrade\",\n \"DebtToIncomeRatio\", \"EstimatedReturn\", \"EstimatedLoss\", \"IsBorrowerHomeowner\", \"Category\",\n \"LenderRate\", \"LenderYield\", \"TotalProsperLoans\", \"MonthlyLoanPayment\", \"OnTimeProsperPayments\",\n \"ProsperScore\"]]\nlisting_data = listing_data.rename(index=str, columns={\"Lst_Key\": \"ListingKey\", \"AmountRequested\": \"AmountRequested\", \"CreationDate\": \"ListingStartDate\"})\nlisting_data.sample(5)",
"_____no_output_____"
]
],
[
[
"## Loan Data",
"_____no_output_____"
]
],
[
[
"loan_data = pd.read_csv('../Data/loan.txt', sep=\"|\")\nloan_data = loan_data[[\"Status\",\"ListingKey\",\"CreationDate\"]]\nloan_data = loan_data.rename(index=str, columns={\"Status\": \"LoanStatus\", \"ListingKey\": \"ListingKey\", \"CreationDate\": \"LoanCreationDate\"})\nloan_data = loan_data.loc[(loan_data[\"LoanStatus\"]==\"Paid\") | \n (loan_data[\"LoanStatus\"]==\"Defaulted (Bankruptcy)\") |\n (loan_data[\"LoanStatus\"]==\"Defaulted (Delinquency)\") |\n (loan_data[\"LoanStatus\"]==\"Defaulted (PaidInFull)\") |\n (loan_data[\"LoanStatus\"]==\"Defaulted (SettledInFull)\")]\nloan_data['RepaidOrNot'] = loan_data[\"LoanStatus\"]==\"Paid\"\nloan_data.sample(10)",
"_____no_output_____"
]
],
[
[
"## Merge Data",
"_____no_output_____"
]
],
[
[
"data = bid_data.merge(listing_data, on=\"ListingKey\")\ndata = data.merge(loan_data, on=\"ListingKey\", how=\"outer\")\ndata = data[data.FundedOrNot == True]\n\ndel bid_data\ndel listing_data\ndel loan_data\n\ndata.sample(10)",
"_____no_output_____"
],
[
"print (\"Dataset dimension: {0}\".format(data.shape))\nprint (\"\\nDataset contains {0} features: {1}.\".format(len(data.columns), data.columns))\nprint \"\\nTotal Listings: \", len(set(data.ListingKey))\nprint \"\\nTotal Bids: \", len(set(data.BidKey))\nprint (\"\\nListing Status:\")\nprint Counter(data.ListingStatus)\nprint (\"\\nFunding Status:\")\nprint Counter(data.FundedOrNot)\nprint (\"\\nPercentage Funded: \")\nprint (dict(Counter(data.FundedOrNot))[True] / len(data)) * 100\nprint (\"\\nRepayment Status:\")\nprint Counter(data.loc[data['FundedOrNot']==True]['RepaidOrNot'])\nprint (\"\\nPercentage Repaid:\")\nprint (dict(Counter(data.loc[data['FundedOrNot']==True]['RepaidOrNot']))[True] / len(data.loc[data['FundedOrNot']==True])) * 100",
"Dataset dimension: (9702715, 30)\n\nDataset contains 30 features: Index([u'BidKey', u'BidAmount', u'BidCreationDate', u'ListingKey',\n u'ListingStatus', u'FundedOrNot', u'ActiveProsperLoans', u'BidCount',\n u'BidMaximumRate', u'AmountRequested', u'ListingStartDate',\n u'BorrowerRate', u'BorrowerMaximumRate', u'EffectiveYield',\n u'BorrowerState', u'CreditGrade', u'DebtToIncomeRatio',\n u'EstimatedReturn', u'EstimatedLoss', u'IsBorrowerHomeowner',\n u'Category', u'LenderRate', u'LenderYield', u'TotalProsperLoans',\n u'MonthlyLoanPayment', u'OnTimeProsperPayments', u'ProsperScore',\n u'LoanStatus', u'LoanCreationDate', u'RepaidOrNot'],\n dtype='object').\n\nTotal Listings: 235753\n\nTotal Bids: 9702715\n\nListing Status:\nCounter({'Completed': 6300999, 'Cancelled': 1332168, 'Expired': 1297213, 'Withdrawn': 772335})\n\nFunding Status:\nCounter({True: 6300999, False: 3401716})\n\nPercentage Funded: \n64.940575911\n\nRepayment Status:\nCounter({True: 3090657, nan: 2775487, False: 434855})\n\nPercentage Repaid:\n49.0502696477\n"
]
],
[
[
"## Summary Statistics",
"_____no_output_____"
]
],
[
[
"data.describe()",
"_____no_output_____"
]
],
[
[
"## Correlation Matrix",
"_____no_output_____"
]
],
[
[
"corr = data.corr(method='pearson')\nmask = np.zeros_like(corr, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\nplt.figure(figsize=(12,8))\nsns.heatmap(corr, \n xticklabels=corr.columns,\n yticklabels=corr.columns,\n cmap=sns.color_palette(\"coolwarm_r\"),\n mask = mask,\n linewidths=.5,\n annot=True)\nplt.title(\"Variable Correlation Heatmap\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Listing Status",
"_____no_output_____"
]
],
[
[
"print data.groupby('ListingStatus').size()\nlisting_labels = sorted(data.groupby('ListingStatus').groups.keys())\nplt.bar(listing_labels, \n data.groupby('ListingStatus').size())\nplt.yscale('log')\nplt.xticks(range(4), listing_labels, rotation='vertical')\nplt.title('Listing Status')\nplt.show()",
"ListingStatus\nCancelled 1332168\nCompleted 6300999\nExpired 1297213\nWithdrawn 772335 \ndtype: int64\n"
],
[
"data.hist(figsize=(12,12), layout=(5,4), log=True)\nplt.grid()\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
],
[
"funding_features = ['AmountRequested', 'BidCount', 'BidMaximumRate', 'BorrowerRate', \n'BorrowerMaximumRate', 'EffectiveYield', 'DebtToIncomeRatio', 'IsBorrowerHomeowner', 'Category', \n'OnTimeProsperPayments', 'ActiveProsperLoans', 'TotalProsperLoans', 'ProsperScore']\ny_funding = data['FundedOrNot']\ny_funding = np.array(y_funding)\nfunding_class_names = np.unique(y_funding)\nprint \"Class Names: %s\" % funding_class_names\n",
"Class Names: [False True]\n"
],
[
"print \"\\nFunding target labels:\", Counter(data.FundedOrNot)",
"\nFunding target labels: Counter({True: 6300999, False: 3401716})\n"
],
[
"# data.loc[data['FundedOrNot']==True].fillna(False)",
"_____no_output_____"
],
[
"repayment_features = funding_features\ny_repayment =data.loc[data['FundedOrNot']==True]['RepaidOrNot'].fillna(False)\ny_repayment = np.array(y_repayment)\nrepayment_class_names = np.unique(y_repayment)\nprint \"Class Names: %s\" % repayment_class_names",
"_____no_output_____"
],
[
"print \"Classification Features: %s\" % funding_features",
"Classification Features: ['AmountRequested', 'BidCount', 'BidMaximumRate', 'BorrowerRate', 'BorrowerMaximumRate', 'EffectiveYield', 'DebtToIncomeRatio', 'IsBorrowerHomeowner', 'Category', 'OnTimeProsperPayments', 'ActiveProsperLoans', 'TotalProsperLoans', 'ProsperScore']\n"
],
[
"print \"Repayment target labels:\", Counter(data.loc[data['FundedOrNot']==True]['RepaidOrNot'])",
"Repayment target labels: Counter({nan: 6177203, True: 3090657, False: 434855})\n"
],
[
"names = ['RBF SVM', 'Naive Bayes', 'AdaBoost', 'Neural Net', \n 'Decision Tree', 'Random Forest', 'K-Nearest Neighbors', 'QDA']\nprint \"\\nClassifiers: %s\" % names",
"\nClassifiers: ['RBF SVM', 'Naive Bayes', 'AdaBoost', 'Neural Net', 'Decision Tree', 'Random Forest', 'K-Nearest Neighbors', 'QDA']\n"
],
[
"# Construct Feature Space\nfunding_feature_space = data[funding_features].fillna(0)\nX_funding = funding_feature_space.as_matrix().astype(np.float)\n# This is Important!\nscaler = StandardScaler()\nX_funding = scaler.fit_transform(X_funding)\nprint \"Feature space holds %d observations and %d features\" % X_funding.shape",
"Feature space holds 9702715 observations and 13 features\n"
],
[
"# # T-Stochastic Neighborhood Embedding\n# start = timeit.default_timer()\n# Y = TSNE(n_components=2).fit_transform(X)\n# stop = timeit.default_timer()\n# print \"\\nEmbedded Feature space holds %d observations and %d features\" % Y.shape\n# print \"Feature Embedding completed in %s seconds\" % (stop - start)",
"_____no_output_____"
],
[
"# Filter important features\n#filtered_features = [u'customer_autoship_active_flag', u'total_autoships', u'autoship_active', u'autoship_cancel', u'pets', u'brands']\n# print \"\\nFiltered Features:\"\n# print filtered_features",
"_____no_output_____"
],
[
"frank_summary(X_funding, y_funding, funding_features)",
"_____no_output_____"
],
[
"logit = sm.Logit(data['FundedOrNot'], \n scaler.fit_transform(data[funding_features].fillna(0)))\nresult = logit.fit()\nprint result.summary()",
"Optimization terminated successfully.\n Current function value: 0.563821\n Iterations 6\n Logit Regression Results \n==============================================================================\nDep. Variable: FundedOrNot No. Observations: 9702715\nModel: Logit Df Residuals: 9702702\nMethod: MLE Df Model: 12\nDate: Sun, 05 Aug 2018 Pseudo R-squ.: 0.1297\nTime: 12:21:21 Log-Likelihood: -5.4706e+06\nconverged: True LL-Null: -6.2856e+06\n LLR p-value: 0.000\n==============================================================================\n coef std err z P>|z| [0.025 0.975]\n------------------------------------------------------------------------------\nx1 -0.8033 0.001 -621.446 0.000 -0.806 -0.801\nx2 0.7738 0.001 553.450 0.000 0.771 0.777\nx3 -3.9240 0.015 -259.783 0.000 -3.954 -3.894\nx4 3.3482 0.015 219.990 0.000 3.318 3.378\nx5 0.6067 0.002 302.369 0.000 0.603 0.611\nx6 0.0297 0.001 42.939 0.000 0.028 0.031\nx7 0.0836 0.001 106.588 0.000 0.082 0.085\nx8 0.0551 0.001 71.988 0.000 0.054 0.057\nx9 -0.3319 0.001 -403.581 0.000 -0.334 -0.330\nx10 0.0466 0.002 28.515 0.000 0.043 0.050\nx11 0.1393 0.001 123.110 0.000 0.137 0.141\nx12 0.1831 0.002 97.743 0.000 0.179 0.187\nx13 0.7396 0.001 817.185 0.000 0.738 0.741\n==============================================================================\n"
],
[
"# prob_plot(X_funding, y_funding) #Inspect probability distribution",
"_____no_output_____"
],
[
"# plot_accuracy(X, y_funding, names)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac2dd0931c60f2315284c9c183c2ecb546c0e59
| 737,844 |
ipynb
|
Jupyter Notebook
|
Practise_realdata/Heart_disease.ipynb
|
yokesh492/Ml_class_ineuron
|
b40346705711298f87218eb3cf2bff0d31801525
|
[
"MIT"
] | null | null | null |
Practise_realdata/Heart_disease.ipynb
|
yokesh492/Ml_class_ineuron
|
b40346705711298f87218eb3cf2bff0d31801525
|
[
"MIT"
] | null | null | null |
Practise_realdata/Heart_disease.ipynb
|
yokesh492/Ml_class_ineuron
|
b40346705711298f87218eb3cf2bff0d31801525
|
[
"MIT"
] | null | null | null | 641.046047 | 323,274 | 0.94274 |
[
[
[
"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n",
"_____no_output_____"
],
[
"df = pd.read_csv(r'D:\\ml_ineuron\\modular\\Ml_class_ineuron\\data\\heart.csv')\ndf.head()",
"_____no_output_____"
],
[
"df['target'].value_counts()",
"_____no_output_____"
],
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 303 entries, 0 to 302\nData columns (total 14 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 age 303 non-null int64 \n 1 sex 303 non-null int64 \n 2 cp 303 non-null int64 \n 3 trestbps 303 non-null int64 \n 4 chol 303 non-null int64 \n 5 fbs 303 non-null int64 \n 6 restecg 303 non-null int64 \n 7 thalach 303 non-null int64 \n 8 exang 303 non-null int64 \n 9 oldpeak 303 non-null float64\n 10 slope 303 non-null int64 \n 11 ca 303 non-null int64 \n 12 thal 303 non-null int64 \n 13 target 303 non-null int64 \ndtypes: float64(1), int64(13)\nmemory usage: 33.3 KB\n"
],
[
"df.describe()",
"_____no_output_____"
],
[
"df.isnull().sum()",
"_____no_output_____"
],
[
"sns.countplot(x = 'target', data = df)",
"_____no_output_____"
],
[
"df.columns",
"_____no_output_____"
],
[
"sns.pairplot(df[['age', 'trestbps', 'chol', 'thalach', 'target']], hue = 'target', plot_kws={'alpha':0.6})",
"_____no_output_____"
],
[
"plt.figure(figsize=(12,8), dpi = 150)\nsns.heatmap(df.corr(), annot = True, cmap = 'viridis')",
"_____no_output_____"
],
[
"X = df.drop('target', axis = 1)\ny = df['target']\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=101)\n\nscaler = StandardScaler()\n\nscaled_X_train = scaler.fit_transform(X_train)\nscaled_X_test = scaler.transform(X_test)\n\nfrom sklearn.linear_model import LogisticRegressionCV\n\nlog_model = LogisticRegressionCV()\nlog_model.fit(scaled_X_train, y_train)\n ",
"_____no_output_____"
],
[
"log_model.Cs_ #best C values after cross validation",
"_____no_output_____"
],
[
"log_model.C_ #actual C value which the model decided",
"_____no_output_____"
],
[
"log_model.get_params() #These parameters were passed to cross validation for fitting ",
"_____no_output_____"
],
[
"log_model.coef_",
"_____no_output_____"
],
[
"coefs = pd.Series(index = X.columns, data = log_model.coef_[0])\ncoefs",
"_____no_output_____"
],
[
"plt.figure(dpi = 150)\nsns.barplot(x = coefs.index, y= coefs.values)\nplt.xticks(rotation=90)",
"_____no_output_____"
],
[
"plt.figure(figsize=(10,6), dpi = 150)\ncoefs = coefs.sort_values()\nsns.barplot(x = coefs.index, y= coefs.values)\nplt.xticks(rotation=90)",
"_____no_output_____"
],
[
"from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, plot_confusion_matrix\ny_pred = log_model.predict(scaled_X_test)\nconfusion_matrix(y_test, y_pred)",
"_____no_output_____"
],
[
"plot_confusion_matrix(log_model, scaled_X_test, y_test) # Total 5 mistakes based on this data",
"C:\\Users\\yoke pc\\anaconda3\\envs\\yoke01\\lib\\site-packages\\sklearn\\utils\\deprecation.py:87: FutureWarning: Function plot_confusion_matrix is deprecated; Function `plot_confusion_matrix` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: ConfusionMatrixDisplay.from_predictions or ConfusionMatrixDisplay.from_estimator.\n warnings.warn(msg, category=FutureWarning)\n"
],
[
"print(classification_report(y_test, y_pred))",
" precision recall f1-score support\n\n 0 0.86 0.80 0.83 15\n 1 0.82 0.88 0.85 16\n\n accuracy 0.84 31\n macro avg 0.84 0.84 0.84 31\nweighted avg 0.84 0.84 0.84 31\n\n"
],
[
"from sklearn.metrics import plot_precision_recall_curve, plot_roc_curve\nplot_precision_recall_curve(log_model, scaled_X_test, y_test)",
"C:\\Users\\yoke pc\\anaconda3\\envs\\yoke01\\lib\\site-packages\\sklearn\\utils\\deprecation.py:87: FutureWarning: Function plot_precision_recall_curve is deprecated; Function `plot_precision_recall_curve` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: PrecisionRecallDisplay.from_predictions or PrecisionRecallDisplay.from_estimator.\n warnings.warn(msg, category=FutureWarning)\n"
],
[
"plot_roc_curve(log_model, scaled_X_test, y_test)",
"C:\\Users\\yoke pc\\anaconda3\\envs\\yoke01\\lib\\site-packages\\sklearn\\utils\\deprecation.py:87: FutureWarning: Function plot_roc_curve is deprecated; Function :func:`plot_roc_curve` is deprecated in 1.0 and will be removed in 1.2. Use one of the class methods: :meth:`sklearn.metric.RocCurveDisplay.from_predictions` or :meth:`sklearn.metric.RocCurveDisplay.from_estimator`.\n warnings.warn(msg, category=FutureWarning)\n"
],
[
"patient = [[ 54. , 1. , 0. , 122. , 286. , 0. , 0. , 116. , 1. ,\n 3.2, 1. , 2. , 2. ]] #double bracket denotes your 2 dimensional data",
"_____no_output_____"
],
[
"log_model.predict(patient)",
"_____no_output_____"
],
[
"log_model.predict_proba(patient) #More probability of belonging to the 0 class",
"_____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"
]
] |
4ac2dd62f95c11f9375993924e817208f558b54b
| 39,898 |
ipynb
|
Jupyter Notebook
|
Python-and-Spark-for-Big-Data-master/Spark_DataFrame_Project_Exercise/Spark DataFrames Project Exercise.ipynb
|
ivy-Ruxin-Tong/Spark-and-Python-for-Big-Data-with-PySpark
|
ccbbdf106be00d059dc1f14a3783fd79b1f8a3b6
|
[
"MIT"
] | null | null | null |
Python-and-Spark-for-Big-Data-master/Spark_DataFrame_Project_Exercise/Spark DataFrames Project Exercise.ipynb
|
ivy-Ruxin-Tong/Spark-and-Python-for-Big-Data-with-PySpark
|
ccbbdf106be00d059dc1f14a3783fd79b1f8a3b6
|
[
"MIT"
] | null | null | null |
Python-and-Spark-for-Big-Data-master/Spark_DataFrame_Project_Exercise/Spark DataFrames Project Exercise.ipynb
|
ivy-Ruxin-Tong/Spark-and-Python-for-Big-Data-with-PySpark
|
ccbbdf106be00d059dc1f14a3783fd79b1f8a3b6
|
[
"MIT"
] | null | null | null | 19,949 | 39,897 | 0.629305 |
[
[
[
"# Spark DataFrames Project Exercise",
"_____no_output_____"
],
[
"Let's get some quick practice with your new Spark DataFrame skills, you will be asked some basic questions about some stock market data, in this case Walmart Stock from the years 2012-2017. This exercise will just ask a bunch of questions, unlike the future machine learning exercises, which will be a little looser and be in the form of \"Consulting Projects\", but more on that later!\n\nFor now, just answer the questions and complete the tasks below.",
"_____no_output_____"
],
[
"#### Use the walmart_stock.csv file to Answer and complete the tasks below!",
"_____no_output_____"
],
[
"#### Load the Walmart Stock CSV File, have Spark infer the data types.",
"_____no_output_____"
]
],
[
[
"walmart = spark.read.csv(\"/FileStore/tables/walmart_stock.csv\", inferSchema = True, header = True)",
"_____no_output_____"
]
],
[
[
"#### What are the column names?",
"_____no_output_____"
]
],
[
[
"walmart.columns\n",
"_____no_output_____"
]
],
[
[
"#### What does the Schema look like?",
"_____no_output_____"
]
],
[
[
"walmart.printSchema()",
"_____no_output_____"
],
[
"from pyspark.sql import functions as F\nwalmart = walmart.withColumn('Date', F.to_timestamp('Date'))",
"_____no_output_____"
],
[
"walmart.printSchema()",
"_____no_output_____"
]
],
[
[
"#### Print out the first 5 columns.",
"_____no_output_____"
]
],
[
[
"for row in walmart.head(5):\n print(row)",
"_____no_output_____"
]
],
[
[
"#### Use describe() to learn about the DataFrame.",
"_____no_output_____"
]
],
[
[
"walmart.describe().show()",
"_____no_output_____"
]
],
[
[
"## Bonus Question!\n#### There are too many decimal places for mean and stddev in the describe() dataframe. Format the numbers to just show up to two decimal places. Pay careful attention to the datatypes that .describe() returns, we didn't cover how to do this exact formatting, but we covered something very similar. [Check this link for a hint](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.Column.cast)\n\nIf you get stuck on this, don't worry, just view the solutions.",
"_____no_output_____"
]
],
[
[
"walmart.describe().printSchema()",
"_____no_output_____"
],
[
"from pyspark.sql.functions import format_number\nresult = walmart.describe()",
"_____no_output_____"
],
[
"result.select(result['summary'], \n format_number(result['Open'].cast('float'),2).alias('Open'),\n format_number(result['High'].cast('float'),2).alias('High'),\n format_number(result['Low'].cast('float'),2).alias('Low'),\n format_number(result['Close'].cast('float'),2).alias('Close'),\n result['Volume'].cast('int').alias('Volume'),\n format_number(result['Adj Close'].cast('float'),2).alias('Adj Close')).show()",
"_____no_output_____"
]
],
[
[
"#### Create a new dataframe with a column called HV Ratio that is the ratio of the High Price versus volume of stock traded for a day.",
"_____no_output_____"
]
],
[
[
"walmart.withColumn('HV Ratio', walmart[\"High\"]/walmart[\"Low\"]).select('HV Ratio').show()",
"_____no_output_____"
]
],
[
[
"#### What day had the Peak High in Price?",
"_____no_output_____"
]
],
[
[
"walmart.orderBy('High').select('Date').show() # ascending",
"_____no_output_____"
],
[
"walmart.orderBy(walmart['High'].desc()).select('Date').show() # desc",
"_____no_output_____"
]
],
[
[
"#### What is the mean of the Close column?",
"_____no_output_____"
]
],
[
[
"from pyspark.sql.functions import mean\nwalmart.select(mean('Close')).show()",
"_____no_output_____"
]
],
[
[
"#### What is the max and min of the Volume column?",
"_____no_output_____"
]
],
[
[
"from pyspark.sql.functions import max, min",
"_____no_output_____"
],
[
"walmart.select(max(\"Volume\"), min(\"Volume\")).show()",
"_____no_output_____"
]
],
[
[
"#### How many days was the Close lower than 60 dollars?",
"_____no_output_____"
]
],
[
[
"walmart.filter('Close < 60').count()",
"_____no_output_____"
],
[
"walmart.filter(walmart['Close'] < 60).count()",
"_____no_output_____"
],
[
"from pyspark.sql.functions import count\nresult = walmart.filter(walmart['Close'] < 60)\nresult.select(count('Close')).show()",
"_____no_output_____"
]
],
[
[
"#### What percentage of the time was the High greater than 80 dollars ?\n#### In other words, (Number of Days High>80)/(Total Days in the dataset)",
"_____no_output_____"
]
],
[
[
"100*walmart.filter(walmart['High'] > 80).count()*1.0 / walmart.count()",
"_____no_output_____"
]
],
[
[
"#### What is the Pearson correlation between High and Volume?\n#### [Hint](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrameStatFunctions.corr)",
"_____no_output_____"
]
],
[
[
"from pyspark.sql.functions import corr\nwalmart.select(corr('High', 'Volume')).show()",
"_____no_output_____"
]
],
[
[
"#### What is the max High per year?",
"_____no_output_____"
]
],
[
[
"from pyspark.sql.functions import year\nyeardf = walmart.withColumn('Year', year('Date'))\nyeardf.groupby('year').max('High').show()",
"_____no_output_____"
]
],
[
[
"#### What is the average Close for each Calendar Month?\n#### In other words, across all the years, what is the average Close price for Jan,Feb, Mar, etc... Your result will have a value for each of these months.",
"_____no_output_____"
]
],
[
[
"from pyspark.sql.functions import month\nmonthdf = walmart.withColumn('month', month('Date'))\nmonthdf.groupby('month').avg('Close').orderBy('month').show()",
"_____no_output_____"
]
],
[
[
"# Great Job!",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4ac2e619ba639bbf3d65f8100d15ce88409068ea
| 14,015 |
ipynb
|
Jupyter Notebook
|
HubSpot/HubSpot_Get_closed_deals_weekly.ipynb
|
srini047/awesome-notebooks
|
2a5b771b37b62090de5311d61dce8495fae7b59f
|
[
"BSD-3-Clause"
] | null | null | null |
HubSpot/HubSpot_Get_closed_deals_weekly.ipynb
|
srini047/awesome-notebooks
|
2a5b771b37b62090de5311d61dce8495fae7b59f
|
[
"BSD-3-Clause"
] | null | null | null |
HubSpot/HubSpot_Get_closed_deals_weekly.ipynb
|
srini047/awesome-notebooks
|
2a5b771b37b62090de5311d61dce8495fae7b59f
|
[
"BSD-3-Clause"
] | null | null | null | 28.602041 | 293 | 0.494113 |
[
[
[
"<img width=\"10%\" alt=\"Naas\" src=\"https://landen.imgix.net/jtci2pxwjczr/assets/5ice39g4.png?w=160\"/>",
"_____no_output_____"
],
[
"# HubSpot - Get closed deals weekly\n<a href=\"https://app.naas.ai/user-redirect/naas/downloader?url=https://raw.githubusercontent.com/jupyter-naas/awesome-notebooks/master/HubSpot/HubSpot_Get_closed_deals_weekly.ipynb\" target=\"_parent\"><img src=\"https://naasai-public.s3.eu-west-3.amazonaws.com/open_in_naas.svg\"/></a>",
"_____no_output_____"
],
[
"**Tags:** #hubspot #crm #sales #deal #scheduler #asset #html #png #csv #naas_drivers #naas",
"_____no_output_____"
],
[
"**Author:** [Florent Ravenel](https://www.linkedin.com/in/florent-ravenel/)",
"_____no_output_____"
],
[
"## Input",
"_____no_output_____"
]
],
[
[
"#-> Uncomment the 2 lines below (by removing the hashtag) to schedule your job everyday at 8:00 AM (NB: you can choose the time of your scheduling bot)\n# import naas\n# naas.scheduler.add(cron=\"0 8 * * *\")\n\n#-> Uncomment the line below (by removing the hashtag) to remove your scheduler\n# naas.scheduler.delete()",
"_____no_output_____"
]
],
[
[
"### Import libraries",
"_____no_output_____"
]
],
[
[
"from naas_drivers import hubspot\nfrom datetime import timedelta\nimport pandas as pd\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots",
"_____no_output_____"
]
],
[
[
"### Setup your HubSpot\n👉 Access your [HubSpot API key](https://knowledge.hubspot.com/integrations/how-do-i-get-my-hubspot-api-key)",
"_____no_output_____"
]
],
[
[
"HS_API_KEY = 'YOUR_HUBSPOT_API_KEY'",
"_____no_output_____"
]
],
[
[
"### Select your pipeline ID\nHere below you can select your pipeline.<br>\nIf not, all deals will be taken for the analysis",
"_____no_output_____"
]
],
[
[
"df_pipelines = hubspot.connect(HS_API_KEY).pipelines.get_all()\ndf_pipelines",
"_____no_output_____"
],
[
"pipeline_id = None",
"_____no_output_____"
]
],
[
[
"### Setup Outputs",
"_____no_output_____"
]
],
[
[
"csv_output = \"HubSpot_closed_weekly.csv\"\nimage_output = \"HubSpot_closed_weekly.html\"\nhtml_output = \"HubSpot_closed_weekly.png\"",
"_____no_output_____"
]
],
[
[
"## Model",
"_____no_output_____"
],
[
"### Get all deals",
"_____no_output_____"
]
],
[
[
"df_deals = hubspot.connect(HS_API_KEY).deals.get_all()\ndf_deals",
"_____no_output_____"
]
],
[
[
"### Create trend data",
"_____no_output_____"
]
],
[
[
"def get_trend(df_deals, pipeline):\n df = df_deals.copy()\n # Filter data\n df = df[df[\"pipeline\"].astype(str) == str(pipeline)]\n \n # Prep data\n df[\"closedate\"] = pd.to_datetime(df[\"closedate\"])\n df[\"amount\"] = df.apply(lambda row: float(row[\"amount\"]) if str(row[\"amount\"]) not in [\"None\", \"\"] else 0, axis=1)\n \n # Calc by week\n df = df.groupby(pd.Grouper(freq='W', key='closedate')).agg({\"hs_object_id\": \"count\", \"amount\": \"sum\"}).reset_index()\n df[\"closedate\"] = df[\"closedate\"] + timedelta(days=-1)\n df = pd.melt(df, id_vars=\"closedate\")\n \n # Rename col\n to_rename = {\n \"closedate\": \"LABEL_ORDER\",\n \"variable\": \"GROUP\",\n \"value\": \"VALUE\"\n }\n df = df.rename(columns=to_rename).replace(\"hs_object_id\", \"No of deals\").replace(\"amount\", \"Amount\")\n df[\"YEAR\"] = df[\"LABEL_ORDER\"].dt.strftime(\"%Y\")\n df = df[df[\"YEAR\"] == datetime.now().strftime(\"%Y\")]\n df[\"LABEL\"] = df[\"LABEL_ORDER\"].dt.strftime(\"%Y-W%U\")\n df[\"LABEL_ORDER\"] = df[\"LABEL_ORDER\"].dt.strftime(\"%Y%U\")\n df = df[df[\"LABEL_ORDER\"].astype(int) <= int(datetime.now().strftime(\"%Y%U\"))]\n \n # Calc variation\n df_var = pd.DataFrame()\n groups = df.GROUP.unique()\n for group in groups:\n tmp = df[df.GROUP == group].reset_index(drop=True)\n for idx, row in tmp.iterrows():\n if idx == 0:\n value_n1 = 0\n else:\n value_n1 = tmp.loc[tmp.index[idx-1], \"VALUE\"]\n tmp.loc[tmp.index[idx], \"VALUE_COMP\"] = value_n1\n df_var = pd.concat([df_var, tmp]).fillna(0).reset_index(drop=True)\n df_var[\"VARV\"] = df_var[\"VALUE\"] - df_var[\"VALUE_COMP\"]\n df_var[\"VARP\"] = df_var[\"VARV\"] / abs(df_var[\"VALUE_COMP\"])\n \n # Prep data\n df_var[\"VALUE_D\"] = df_var[\"VALUE\"].map(\"{:,.0f}\".format).str.replace(\",\", \" \")\n df_var[\"VARV_D\"] = df_var[\"VARV\"].map(\"{:,.0f}\".format).str.replace(\",\", \" \")\n df_var.loc[df_var[\"VARV\"] > 0, \"VARV_D\"] = \"+\" + df_var[\"VARV_D\"]\n df_var[\"VARP_D\"] = df_var[\"VARP\"].map(\"{:,.0%}\".format).str.replace(\",\", \" \")\n df_var.loc[df_var[\"VARP\"] > 0, \"VARP_D\"] = \"+\" + df_var[\"VARP_D\"]\n \n # Create hovertext\n df_var[\"TEXT\"] = (\"<b>Deal closed as of \" + df_var[\"LABEL\"] + \" : </b>\" + \n df_var[\"VALUE_D\"] + \"<br>\" + \n df_var[\"VARP_D\"] + \" vs last week (\" + df_var[\"VARV_D\"] + \")\")\n return df_var\n\ndf_trend = get_trend(df_deals, pipeline_id)\ndf_trend",
"_____no_output_____"
]
],
[
[
"## Output",
"_____no_output_____"
],
[
"### Plotting a barchart with filters",
"_____no_output_____"
]
],
[
[
"def create_barchart(df, label, group, value, varv, varp): \n # Create figure with secondary y-axis\n fig = make_subplots(specs=[[{\"secondary_y\": True}]])\n\n # Add traces\n df1 = df[df[group] == \"No of deals\"].reset_index(drop=True)[:]\n total_volume = \"{:,.0f}\".format(df1[value].sum()).replace(\",\", \" \")\n var_volume = df1.loc[df1.index[-1], varv]\n positive = False\n if var_volume > 0:\n positive = True\n var_volume = \"{:,.0f}\".format(var_volume).replace(\",\", \" \")\n if positive:\n var_volume = f\"+{var_volume}\"\n fig.add_trace(\n go.Bar(\n name=\"No of deals\",\n x=df1[label],\n y=df1[value],\n offsetgroup=0,\n hoverinfo=\"text\",\n text=df1[\"VALUE_D\"],\n hovertext=df1[\"TEXT\"],\n marker=dict(color=\"#33475b\")\n ),\n secondary_y=False,\n )\n \n df2 = df[df[group] == \"Amount\"].reset_index(drop=True)[:]\n total_value = \"{:,.0f}\".format(df2[value].sum()).replace(\",\", \" \")\n var_value = df2.loc[df2.index[-1], varv]\n positive = False\n if var_value > 0:\n positive = True\n var_value = \"{:,.0f}\".format(var_value).replace(\",\", \" \")\n if positive:\n var_value = f\"+{var_value}\"\n fig.add_trace(\n go.Bar(\n name=\"Amount\",\n x=df2[label],\n y=df2[value],\n text=df2[\"VALUE_D\"] + \" K€\",\n offsetgroup=1,\n hoverinfo=\"text\",\n hovertext=df2[\"TEXT\"],\n marker=dict(color=\"#ff7a59\")\n ),\n secondary_y=True,\n )\n\n # Add figure title\n fig.update_layout(\n title=f\"<b>Hubspot - Closed deals this year</b><br><span style='font-size: 14px;'>Total deals: {total_volume} ({total_value} K€) | This week: {var_volume} ({var_value} K€) vs last week</span>\",\n title_font=dict(family=\"Arial\", size=20, color=\"black\"),\n legend=None,\n plot_bgcolor=\"#ffffff\",\n width=1200,\n height=800,\n paper_bgcolor=\"white\",\n xaxis_title=\"Weeks\",\n xaxis_title_font=dict(family=\"Arial\", size=11, color=\"black\"),\n )\n\n # Set y-axes titles\n fig.update_yaxes(\n title_text=\"No of deals\",\n title_font=dict(family=\"Arial\", size=11, color=\"black\"),\n secondary_y=False\n )\n fig.update_yaxes(\n title_text=\"Amount in K€\",\n title_font=dict(family=\"Arial\", size=11, color=\"black\"),\n secondary_y=True\n )\n fig.show()\n return fig\n\nfig = create_barchart(df_trend, \"LABEL\", \"GROUP\", \"VALUE\", \"VARV\", \"VARP\")",
"_____no_output_____"
]
],
[
[
"### Export and share graph",
"_____no_output_____"
]
],
[
[
"# Export in HTML\ndf_trend.to_csv(csv_output, index=False)\nfig.write_image(image_output)\nfig.write_html(html_output)\n\n# Shave with naas\nnaas.asset.add(csv_output)\nnaas.asset.add(image_output)\nnaas.asset.add(html_output, params={\"inline\": True})\n\n#-> Uncomment the line below (by removing the hashtag) to delete your asset\n# naas.asset.delete(csv_output)\n# naas.asset.delete(image_output)\n# naas.asset.delete(html_output)",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac2ecc8ed6b74680972668f2513be3cae174880
| 64,213 |
ipynb
|
Jupyter Notebook
|
2021dataPyMarzo22porHoraCorrecto.ipynb
|
diegostaPy/escaramujo
|
8d01e087b115c8669bead2af2a335ed47c933285
|
[
"MIT"
] | null | null | null |
2021dataPyMarzo22porHoraCorrecto.ipynb
|
diegostaPy/escaramujo
|
8d01e087b115c8669bead2af2a335ed47c933285
|
[
"MIT"
] | null | null | null |
2021dataPyMarzo22porHoraCorrecto.ipynb
|
diegostaPy/escaramujo
|
8d01e087b115c8669bead2af2a335ed47c933285
|
[
"MIT"
] | null | null | null | 191.110119 | 44,132 | 0.892436 |
[
[
[
"import pandas as pd\nimport pytz, datetime\nimport pytz\nfrom pytz import timezone\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n",
"_____no_output_____"
],
[
"path='datos2021/'\nfilenamePy=path+'flux.json'\n",
"_____no_output_____"
],
[
"py = pd.read_json (filenamePy, lines=True)\npy['datetime']=pd.to_datetime(py.hora, unit='s',utc=True)\npy.set_index(['datetime'],drop=True, inplace=True)\npy= py.iloc[1:]\n#py.tail()",
"_____no_output_____"
],
[
"py = pd.read_json (filenamePy, lines=True)\npy['datetime']=pd.to_datetime(py.hora, unit='s',utc=True)\npy['datetime'] = py['datetime'].dt.tz_convert('America/Sao_Paulo')\npy.set_index(['datetime'],drop=True, inplace=True)\n#py.tail()",
"_____no_output_____"
],
[
"py=py.resample('H').sum()",
"_____no_output_____"
],
[
"py['conteo']=py['conteo'].values/0.0512\npy['canal_a']=py['canal_a'].values/1.364\npy['canal_b']=py['canal_b'].values/0.0512\npy['ratio']=py['canal_a'].values - py['conteo'].values\n",
"_____no_output_____"
],
[
"py.tail()",
"_____no_output_____"
],
[
"flagPy1=np.logical_and(py.index>\"2021-04-01\",py.index<\"2021-04-08\")\nflagPy2=np.logical_and(py.index>\"2021-03-18\",py.index<\"2021-04-08\")",
"_____no_output_____"
],
[
"fig, axes = plt.subplots(3,1, figsize=(15,10), sharex=True)\nplt.subplot(311)\n\naxes =py['canal_a'][flagPy1].plot(marker='.',markersize=3.5, linestyle='None',legend=True, alpha=1,color='r', subplots=True)\nax = plt.gca()\nax.set_ylabel('Total de muones')\nax.set_ylim(9000, 13000)\n\nplt.subplot(312)\naxes =py['conteo'][flagPy1].plot(marker='.',markersize=3.5, linestyle='None',legend=True, alpha=1,color='r', subplots=True)\nax = plt.gca()\nax.set_ylim(5000, 10000)\nax.set_ylabel('Counts Cosmic')\n\nplt.subplot(313)\naxes =py['ratio'][flagPy1].plot(marker='.',markersize=3.5, linestyle='None',legend=True, label='Paraguay Marzo 2021',alpha=1,color='r', subplots=True)\nax = plt.gca()\nax.set_ylabel('Precipitados')\n\n#plt.subplot(313)\n#axes =mex['Coincidencias'][flagMex].plot(marker='.',markersize=2.5,linestyle='None', label='México Marzo 2020',alpha=1,color='b', subplots=True)\n#ax = plt.gca()\n#ax.set_ylabel('Counts')\n#ax.set_xlabel('Date')\nplt.xticks(rotation = 45)\nplt.savefig('EscaramujovsParaguay.png')",
"_____no_output_____"
],
[
"import seaborn as sns\nfig, axes = plt.subplots(1,2, figsize=(10,5), sharex=True)\nplt.subplot(121)\nsns.set(style=\"whitegrid\")\nax = sns.boxplot(data=py['conteo'][flagPy1])\nplt.subplot(122)\nsns.set(style=\"whitegrid\")\nax = sns.boxplot(data=py['canal_a'][flagPy1])\nplt.savefig(\"boxplot.png\", bbox_inches='tight')",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac2eea099a2070b9c0e148cb1875d64d0b918a4
| 96,151 |
ipynb
|
Jupyter Notebook
|
SRAL/03_L2P along-track.ipynb
|
EUMETSAT-Training/python-examples
|
d85800518898130a3ab803745933753eed0c83b1
|
[
"MIT"
] | 4 |
2019-04-09T07:11:04.000Z
|
2021-04-14T13:09:47.000Z
|
SRAL/03_L2P along-track.ipynb
|
eumetsat-training/python-examples
|
d85800518898130a3ab803745933753eed0c83b1
|
[
"MIT"
] | null | null | null |
SRAL/03_L2P along-track.ipynb
|
eumetsat-training/python-examples
|
d85800518898130a3ab803745933753eed0c83b1
|
[
"MIT"
] | null | null | null | 466.752427 | 47,236 | 0.940864 |
[
[
[
"# A look at \"level 2 plus\" data #\n\nDatasets with a number of pre-processings done are available. Some corrections are provided for applications which may need alternate models or datasets. ",
"_____no_output_____"
],
[
"** Import libraries **",
"_____no_output_____"
]
],
[
[
"import os\nimport numpy as np\nfrom netCDF4 import Dataset\nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom mpl_toolkits.basemap import Basemap\n\nplt.rcParams[\"figure.figsize\"] = (16,10)\nplt.ioff()",
"_____no_output_____"
]
],
[
[
"** Along-track \"level2P\" data ** (i.e. data pre-computed over ocean for SLA)\n\nnote that the track is the same than in previous exercise. ",
"_____no_output_____"
]
],
[
[
"# look at the data (e.g. a Saral file, during drifting phase)\ninput_root = '../data/'\ninput_path = ''\ninput_file = 'global_sla_l2p_ntc_s3a_C0021_P0050_20170809T144624_20170809T153306_20171005T180516.nc'\nmy_file = os.path.join(input_root,input_path,input_file)\nnc = Dataset(my_file, 'r')\n\nfor variable in nc.variables:\n print(variable)",
"time\nlatitude\nlongitude\naltitude\nrange\nwet_tropospheric_correction\nwet_tropospheric_correction_model\ndry_tropospheric_correction_model\ndynamic_atmospheric_correction\nocean_tide_height\nsolid_earth_tide\npole_tide\nsea_state_bias\nionospheric_correction\nmean_sea_surface\nsea_level_anomaly\ninter_mission_bias\nvalidation_flag\n"
],
[
"# map the data\nlat = nc.variables['latitude'][:]\nlon = nc.variables['longitude'][:]\nsla = nc.variables['sea_level_anomaly'][:]\n\nm = Basemap(projection='kav7',lon_0=0,resolution='c')\nm.drawcoastlines()\nm.fillcontinents(color='#636363')\nx, y = m(lon, lat)\nscatter = m.scatter(x, y, c=sla, cmap='RdYlBu_r', vmin=-0.25, vmax=0.25, marker='o', edgecolors='black', linewidth=0.01)\ncb = m.colorbar(scatter, pad=1, size='2.5%', extend='both')\nplt.title('sea level anomaly [m]', size=18)\nplt.show()",
"_____no_output_____"
]
],
[
[
"** Use of the \"validation\" flag **\n\nA flag is provided within the variables of the file which can be used to remove e.g. spurious data.\nNote that this track crosses the Gulf Stream, so high variability is to be expected. ",
"_____no_output_____"
]
],
[
[
"validation_flag = nc.variables['validation_flag'][:]\nfig1 = plt.figure()\nplt.title('SLA rough', size=18);\nplt.plot(lat, sla)\n\nfig2 = plt.figure()\nplt.title('validation flag', size=18);\nplt.plot(lat, validation_flag)\n\ntime_index = np.where(validation_flag == 0 )\nfig3 = plt.figure()\nplt.title('valid SLAs', size=18);\nplt.plot(lat[time_index], sla[time_index])\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac2f6f8191031cd309237043ebef16ce43987b9
| 87,539 |
ipynb
|
Jupyter Notebook
|
Code/Excel Handling.ipynb
|
FlorianYANG/PAiF
|
8b244c66fbc1084cba4d4db9015238ef9f41b8e8
|
[
"MIT"
] | 1 |
2021-06-06T06:18:35.000Z
|
2021-06-06T06:18:35.000Z
|
Code/Excel Handling.ipynb
|
FlorianYANG/PAiF
|
8b244c66fbc1084cba4d4db9015238ef9f41b8e8
|
[
"MIT"
] | null | null | null |
Code/Excel Handling.ipynb
|
FlorianYANG/PAiF
|
8b244c66fbc1084cba4d4db9015238ef9f41b8e8
|
[
"MIT"
] | null | null | null | 64.272394 | 24,252 | 0.664298 |
[
[
[
"import numpy as np, pandas as pd, matplotlib.pyplot as plt\nimport os\nimport seaborn as sns\nsns.set()",
"_____no_output_____"
],
[
"root_path = r'C:\\Users\\54638\\Desktop\\Cannelle\\Excel handling'\ninput_path = os.path.join(root_path, \"input\")\noutput_path = os.path.join(root_path, \"output\")",
"_____no_output_____"
],
[
"%%time \n# this line magic function should always be put on first line of the cell, and without comments followed after in the same line\n\n# Read all Excel file\nall_deals = pd.DataFrame()\n\nfor file in os.listdir(input_path):\n # can add other criteria as you want\n if file[-4:] == 'xlsx': \n tmp = pd.read_excel(os.path.join(input_path,file), index_col = 'order_no')\n all_deals = pd.concat([all_deals, tmp])\n\n# reindex, otherwise you may have many lines with same index\n# all_deals = all_deals.reset_index() # this method is not recommended here, as it will pop out the original index 'order_no'\nall_deals.index = range(len(all_deals))",
"Wall time: 3.32 s\n"
],
[
"all_deals.head()\n# all_deals.tail()\n# all_deals.shape\n# all_deals.describe()",
"_____no_output_____"
],
[
"# overview\nall_deals['counterparty'].value_counts().sort_values(ascending = False)\n# all_deals['counterparty'].unique()",
"_____no_output_____"
],
[
"all_deals['deal'].value_counts().sort_values(ascending = False)",
"_____no_output_____"
],
[
"deal_vol = all_deals['deal'].value_counts().sort_values()\ndeal_vol.plot(figsize = (10,6), kind = 'bar');",
"_____no_output_____"
],
[
"# Some slicing\nall_deals[all_deals['deal'] == 'Accumulator']",
"_____no_output_____"
],
[
"all_deals[(all_deals['deal'] == 'Variance Swap') \n & (all_deals['counterparty'].isin(['Citi','HSBC']))]",
"_____no_output_____"
],
[
"all_deals.groupby('currency').sum()\n# all_deals.groupby('currency')[['nominal']].sum()",
"_____no_output_____"
],
[
"ccy_way = all_deals.groupby(['way','currency']).sum().unstack('currency')\nccy_way",
"_____no_output_____"
],
[
"ccy_way.plot(figsize = (10,6), kind ='bar')\nplt.legend(loc='upper left', bbox_to_anchor=(1,1), ncol=1)",
"_____no_output_____"
],
[
"# pivot_table\nall_deals.pivot_table(values = 'nominal', \n index='counterparty', columns='deal', aggfunc='count')",
"_____no_output_____"
],
[
"# save data\n# ccy_way.to_excel(os.path.join(output_path,\"Extract.xlsx\"))\n\nfile_name = \"Extract\" + \".xlsx\"\nsheet_name = \"Extract\"\nwriter = pd.ExcelWriter(os.path.join(output_path, file_name), engine = 'xlsxwriter')\nccy_way.to_excel(writer, sheet_name=sheet_name)\n\n# adjust the column width\nworksheet = writer.sheets[sheet_name]\nfor id, col in enumerate(ccy_way):\n series = ccy_way[col]\n max_len = max(\n series.astype(str).map(len).max(), # len of largest item\n len(str(series.name)) # len of column name\n ) + 3 # a little extra space\n max_len = min(max_len, 30) # set a cap, dont be too long\n worksheet.set_column(id+1, id+1, max_len)\nwriter.save()",
"_____no_output_____"
],
[
"# Deleting all the file\ndel_path = input_path\nfor file in os.listdir(del_path):\n os.remove(os.path.join(del_path, file))",
"_____no_output_____"
],
[
"# Generating file, all the data you see is just randomly created\nimport calendar\n\n# Transaction generator\ndef generate_data(year, month):\n \n order_amount = max(int(np.random.randn()*200)+500,0) + np.random.randint(2000)\n start_loc = 1\n\n order_no = np.arange(start_loc,order_amount+start_loc)\n\n countparty_list = ['JPMorgan', 'Credit Suisse', 'Deutsche Bank', 'BNP Paribas', 'Credit Agricole', 'SinoPac', 'Goldman Sachs', 'Citi',\n 'Blackstone', 'HSBC', 'Natixis', 'BOCI', 'UBS', 'CLSA', 'CICC', 'Fidelity', 'Jefferies']\n countparty_prob = [0.04, 0.07, 0.06, 0.1, 0.09, 0.02, 0.1, 0.08, 0.025, 0.13, 0.065, 0.05, 0.01, 0.08, 0.01, 0.04, 0.03]\n countparty = np.random.choice(countparty_list, size=order_amount, p=countparty_prob)\n\n deal_list = ['Autocall', 'Accumulator', 'Range Accrual', 'Variance Swap', 'Vanilla', 'Digital', 'Twinwin', 'ForwardStart',\n 'ForwardBasket', 'Cross Currency Swap', 'Hybrid']\n deal_prob = [0.16, 0.2, 0.11, 0.05, 0.11, 0.09, 0.08, 0.04, 0.04, 0.03, 0.09]\n deal = np.random.choice(deal_list, size=order_amount, p=deal_prob)\n\n way = np.random.choice(['buy','sell'], size=order_amount)\n\n nominal = [(int(np.random.randn()*10) + np.random.randint(200)+ 50)*1000 for _ in range(order_amount)]\n \n currency_list = ['USD', 'CNY', 'EUR', 'SGP', 'JPY', 'KRW', 'AUD', 'GBP']\n currency_prob = [0.185, 0.195, 0.14, 0.08, 0.135, 0.125, 0.06, 0.08]\n currency = np.random.choice(currency_list, size=order_amount, p=currency_prob)\n \n datelist = list(date for date in calendar.Calendar().itermonthdates(year, month) if date.month == month)\n trade_date = np.random.choice(datelist, size=order_amount)\n \n data = {'order_no': order_no, 'counterparty': countparty, 'deal':deal, 'way': way, 'nominal': nominal, \n 'currency':currency, 'trade_date': trade_date}\n \n \n return pd.DataFrame(data)",
"_____no_output_____"
],
[
"save_path = input_path\ncur_month = 4\ncur_year = 2018\nfor i in range(24):\n if cur_month == 12:\n cur_month = 1\n cur_year +=1\n else:\n cur_month += 1\n \n df = generate_data(cur_year, cur_month)\n df_name = 'Derivatives Transaction '+calendar.month_abbr[cur_month]+' '+str(cur_year)+'.xlsx'\n df.to_excel(os.path.join(save_path, df_name), index = False)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac302c7949353e62904fd1b0e4bb172e2f27c92
| 58,667 |
ipynb
|
Jupyter Notebook
|
examples/fuzzy_pandas examples.ipynb
|
Aniket-Sharma/fuzzy_pandas
|
96782b5b45806a9c8f68ae9dbcee90beeb40594b
|
[
"MIT"
] | 52 |
2019-08-05T20:49:57.000Z
|
2022-03-28T10:15:05.000Z
|
examples/fuzzy_pandas examples.ipynb
|
Aniket-Sharma/fuzzy_pandas
|
96782b5b45806a9c8f68ae9dbcee90beeb40594b
|
[
"MIT"
] | 4 |
2020-01-15T12:59:30.000Z
|
2020-09-12T11:53:50.000Z
|
examples/fuzzy_pandas examples.ipynb
|
Aniket-Sharma/fuzzy_pandas
|
96782b5b45806a9c8f68ae9dbcee90beeb40594b
|
[
"MIT"
] | 19 |
2019-10-29T11:22:58.000Z
|
2022-03-13T19:15:51.000Z
| 29.689777 | 304 | 0.410231 |
[
[
[
"# fuzzy_pandas examples\n\nThese are almost all from [Max Harlow](https://twitter.com/maxharlow)'s [awesome NICAR2019 presentation](https://docs.google.com/presentation/d/1djKgqFbkYDM8fdczFhnEJLwapzmt4RLuEjXkJZpKves/) where he demonstrated [csvmatch](https://github.com/maxharlow/csvmatch), which fuzzy_pandas is based on.\n\n**SCROLL DOWN DOWN DOWN TO GET TO THE FUZZY MATCHING PARTS.**",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport fuzzy_pandas as fpd",
"_____no_output_____"
],
[
"df1 = pd.read_csv(\"data/data1.csv\")\ndf2 = pd.read_csv(\"data/data2.csv\")",
"_____no_output_____"
],
[
"df1",
"_____no_output_____"
],
[
"df2",
"_____no_output_____"
]
],
[
[
"# Exact matches\n\nBy default, all columns from both dataframes are returned.",
"_____no_output_____"
]
],
[
[
"# csvmatch \\\n# forbes-billionaires.csv \\\n# bloomberg-billionaires.csv \\\n# --fields1 name \\\n# --fields2 Name\n\ndf1 = pd.read_csv(\"data/forbes-billionaires.csv\")\ndf2 = pd.read_csv(\"data/bloomberg-billionaires.csv\")\n\nresults = fpd.fuzzy_merge(df1, df2, left_on='name', right_on='Name')\n\nprint(\"Found\", results.shape)\nresults.head(5)",
"Found (354, 19)\n"
]
],
[
[
"### Only keeping matching columns\n\nThe csvmatch default only gives you the shared columns, which you can reproduce with `keep='match'`",
"_____no_output_____"
]
],
[
[
"df1 = pd.read_csv(\"data/forbes-billionaires.csv\")\ndf2 = pd.read_csv(\"data/bloomberg-billionaires.csv\")\n\nresults = fpd.fuzzy_merge(df1, df2, left_on='name', right_on='Name', keep='match')\n\nprint(\"Found\", results.shape)\nresults.head(5)",
"Found (354, 2)\n"
]
],
[
[
"### Only keeping specified columns",
"_____no_output_____"
]
],
[
[
"df1 = pd.read_csv(\"data/forbes-billionaires.csv\")\ndf2 = pd.read_csv(\"data/bloomberg-billionaires.csv\")\n\nresults = fpd.fuzzy_merge(df1, df2,\n left_on='name',\n right_on='Name',\n keep_left=['name', 'realTimeRank'],\n keep_right=['Rank'])\n\nprint(\"Found\", results.shape)\nresults.head(5)",
"Found (354, 3)\n"
]
],
[
[
"## Case sensitivity\n\nThis one doesn't give us any results!",
"_____no_output_____"
]
],
[
[
"# csvmatch \\\n# cia-world-leaders.csv \\\n# davos-attendees-2019.csv \\\n# --fields1 name \\\n# --fields2 full_name\n\ndf1 = pd.read_csv(\"data/cia-world-leaders.csv\")\ndf2 = pd.read_csv(\"data/davos-attendees-2019.csv\")\n\nresults = fpd.fuzzy_merge(df1, df2,\n left_on='name',\n right_on='full_name',\n keep='match')\n\nprint(\"Found\", results.shape)\nresults.head(10)",
"Found (0, 2)\n"
]
],
[
[
"But if we add **ignore_case** we are good to go.",
"_____no_output_____"
]
],
[
[
"# csvmatch \\\n# cia-world-leaders.csv \\\n# davos-attendees-2019.csv \\\n# --fields1 name \\\n# --fields2 full_name \\\n# --ignore-case \\\n\ndf1 = pd.read_csv(\"data/cia-world-leaders.csv\")\ndf2 = pd.read_csv(\"data/davos-attendees-2019.csv\")\n\nresults = fpd.fuzzy_merge(df1, df2,\n left_on='name',\n right_on='full_name',\n ignore_case=True,\n keep='match')\n\nprint(\"Found\", results.shape)\nresults.head(5)",
"Found (119, 2)\n"
]
],
[
[
"### Ignoring case, non-latin characters, word ordering\n\nYou should really be reading [the presentation](https://docs.google.com/presentation/d/1djKgqFbkYDM8fdczFhnEJLwapzmt4RLuEjXkJZpKves/edit)!",
"_____no_output_____"
]
],
[
[
"# $ csvmatch \\\n# cia-world-leaders.csv \\\n# davos-attendees-2019.csv \\\n# --fields1 name \\\n# --fields2 full_name \\\n# -i -a -n -s \\\n\ndf1 = pd.read_csv(\"data/cia-world-leaders.csv\")\ndf2 = pd.read_csv(\"data/davos-attendees-2019.csv\")\n\nresults = fpd.fuzzy_merge(df1, df2,\n left_on=['name'],\n right_on=['full_name'],\n ignore_case=True,\n ignore_nonalpha=True,\n ignore_nonlatin=True,\n ignore_order_words=True,\n keep='match')\n\nprint(\"Found\", results.shape)\nresults.head(5)",
"Found (138, 2)\n"
]
],
[
[
"# Fuzzy matching\n\n## Levenshtein: Edit distance",
"_____no_output_____"
]
],
[
[
"# csvmatch \\\n# cia-world-leaders.csv \\\n# forbes-billionaires.csv \\\n# --fields1 name \\\n# --fields2 name \\\n# --fuzzy levenshtein \\\n\ndf1 = pd.read_csv(\"data/cia-world-leaders.csv\")\ndf2 = pd.read_csv(\"data/forbes-billionaires.csv\")\n\nresults = fpd.fuzzy_merge(df1, df2,\n left_on='name',\n right_on='name',\n method='levenshtein',\n keep='match')\n\nprint(\"Found\", results.shape)\nresults.head(10)",
"Found (323, 2)\n"
]
],
[
[
"### Setting a threshold with Levenshtein",
"_____no_output_____"
]
],
[
[
"# csvmatch \\\n# cia-world-leaders.csv \\\n# forbes-billionaires.csv \\\n# --fields1 name \\\n# --fields2 name \\\n# --fuzzy levenshtein \\\n\ndf1 = pd.read_csv(\"data/cia-world-leaders.csv\")\ndf2 = pd.read_csv(\"data/forbes-billionaires.csv\")\n\nresults = fpd.fuzzy_merge(df1, df2,\n left_on='name',\n right_on='name',\n method='levenshtein',\n threshold=0.85,\n keep='match')\n\nprint(\"Found\", results.shape)\nresults.head(10)",
"Found (0, 2)\n"
]
],
[
[
"## Jaro: Edit distance",
"_____no_output_____"
]
],
[
[
"# csvmatch \\\n# cia-world-leaders.csv \\\n# forbes-billionaires.csv \\\n# --fields1 name \\\n# --fields2 name \\\n# --fuzzy levenshtein \\\n\ndf1 = pd.read_csv(\"data/cia-world-leaders.csv\")\ndf2 = pd.read_csv(\"data/forbes-billionaires.csv\")\n\nresults = fpd.fuzzy_merge(df1, df2,\n left_on='name',\n right_on='name',\n method='jaro',\n keep='match')\n\nprint(\"Found\", results.shape)\nresults.head(10)",
"Found (77842, 2)\n"
]
],
[
[
"## Metaphone: Phonetic match",
"_____no_output_____"
]
],
[
[
"# csvmatch \\\n# cia-world-leaders.csv \\\n# un-sanctions.csv \\\n# --fields1 name \\\n# --fields2 name \\\n# --fuzzy metaphone \\\n\ndf1 = pd.read_csv(\"data/cia-world-leaders.csv\")\ndf2 = pd.read_csv(\"data/un-sanctions.csv\")\n\nresults = fpd.fuzzy_merge(df1, df2,\n left_on='name',\n right_on='name',\n method='metaphone',\n keep='match')\n\nprint(\"Found\", results.shape)\nresults.head(10)",
"Found (18, 2)\n"
]
],
[
[
"## Bilenko\n\nYou'll need to respond to the prompts when you run the code. 10-15 is best, but send `f` when you've decided you're finished.",
"_____no_output_____"
]
],
[
[
"# $ csvmatch \\\n# cia-world-leaders.csv \\\n# davos-attendees-2019.csv \\\n# --fields1 name \\\n# --fields2 full_name \\\n# --fuzzy bilenko \\\n\ndf1 = pd.read_csv(\"data/cia-world-leaders.csv\")\ndf2 = pd.read_csv(\"data/davos-attendees-2019.csv\")\n\nresults = fpd.fuzzy_merge(df1, df2,\n left_on='name',\n right_on='full_name',\n method='bilenko',\n keep='match')\n\nprint(\"Found\", results.shape)\nresults.head(10)",
"\nAnswer questions as follows:\n y - yes\n n - no\n s - skip\n f - finished\n\nname: Antonio Eduardo BECALI Garrido\n\nname: Antonio Neri\n\nDo these records refer to the same thing? [y/n/s/f] "
]
]
] |
[
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac309dcffa6409ed4f856fae74ba8766505633e
| 122,556 |
ipynb
|
Jupyter Notebook
|
CPB100/lab4a/demandforecast.ipynb
|
bjoernrost/training-data-analyst
|
1335591d9381e93ec2ade0d943fb46ad5020aba4
|
[
"Apache-2.0"
] | 7 |
2019-05-10T14:13:40.000Z
|
2022-01-19T16:59:04.000Z
|
CPB100/lab4a/demandforecast.ipynb
|
bjoernrost/training-data-analyst
|
1335591d9381e93ec2ade0d943fb46ad5020aba4
|
[
"Apache-2.0"
] | 11 |
2020-01-28T22:33:18.000Z
|
2022-03-11T23:36:42.000Z
|
CPB100/lab4a/demandforecast.ipynb
|
bjoernrost/training-data-analyst
|
1335591d9381e93ec2ade0d943fb46ad5020aba4
|
[
"Apache-2.0"
] | 8 |
2020-02-03T18:31:37.000Z
|
2021-08-13T13:58:54.000Z
| 84.288858 | 22,008 | 0.750759 |
[
[
[
"<h1>Demand forecasting with BigQuery and TensorFlow</h1>\n\nIn this notebook, we will develop a machine learning model to predict the demand for taxi cabs in New York.\n\nTo develop the model, we will need to get historical data of taxicab usage. This data exists in BigQuery. Let's start by looking at the schema.",
"_____no_output_____"
]
],
[
[
"import google.datalab.bigquery as bq\nimport pandas as pd\nimport numpy as np\nimport shutil",
"_____no_output_____"
],
[
"%bq tables describe --name bigquery-public-data.new_york.tlc_yellow_trips_2015",
"_____no_output_____"
]
],
[
[
"<h2> Analyzing taxicab demand </h2>\n\nLet's pull the number of trips for each day in the 2015 dataset using Standard SQL.",
"_____no_output_____"
]
],
[
[
"%bq query\nSELECT \n EXTRACT (DAYOFYEAR from pickup_datetime) AS daynumber\nFROM `bigquery-public-data.new_york.tlc_yellow_trips_2015` \nLIMIT 5",
"_____no_output_____"
]
],
[
[
"<h3> Modular queries and Pandas dataframe </h3>\n\nLet's use the total number of trips as our proxy for taxicab demand (other reasonable alternatives are total trip_distance or total fare_amount). It is possible to predict multiple variables using Tensorflow, but for simplicity, we will stick to just predicting the number of trips.\n\nWe will give our query a name 'taxiquery' and have it use an input variable '$YEAR'. We can then invoke the 'taxiquery' by giving it a YEAR. The to_dataframe() converts the BigQuery result into a <a href='http://pandas.pydata.org/'>Pandas</a> dataframe.",
"_____no_output_____"
]
],
[
[
"%bq query -n taxiquery\nWITH trips AS (\n SELECT EXTRACT (DAYOFYEAR from pickup_datetime) AS daynumber \n FROM `bigquery-public-data.new_york.tlc_yellow_trips_*`\n where _TABLE_SUFFIX = @YEAR\n)\nSELECT daynumber, COUNT(1) AS numtrips FROM trips\nGROUP BY daynumber ORDER BY daynumber",
"_____no_output_____"
],
[
"query_parameters = [\n {\n 'name': 'YEAR',\n 'parameterType': {'type': 'STRING'},\n 'parameterValue': {'value': 2015}\n }\n]\ntrips = taxiquery.execute(query_params=query_parameters).result().to_dataframe()\ntrips[:5]",
"_____no_output_____"
]
],
[
[
"<h3> Benchmark </h3>\n\nOften, a reasonable estimate of something is its historical average. We can therefore benchmark our machine learning model against the historical average.",
"_____no_output_____"
]
],
[
[
"avg = np.mean(trips['numtrips'])\nprint('Just using average={0} has RMSE of {1}'.format(avg, np.sqrt(np.mean((trips['numtrips'] - avg)**2))))",
"Just using average=400309.5589041096 has RMSE of 51613.65169049127\n"
]
],
[
[
"The mean here is about 400,000 and the root-mean-square-error (RMSE) in this case is about 52,000. In other words, if we were to estimate that there are 400,000 taxi trips on any given day, that estimate is will be off on average by about 52,000 in either direction.\n \nLet's see if we can do better than this -- our goal is to make predictions of taxicab demand whose RMSE is lower than 52,000.\n\nWhat kinds of things affect people's use of taxicabs?",
"_____no_output_____"
],
[
"<h2> Weather data </h2>\n\nWe suspect that weather influences how often people use a taxi. Perhaps someone who'd normally walk to work would take a taxi if it is very cold or rainy.\n\nOne of the advantages of using a global data warehouse like BigQuery is that you get to mash up unrelated datasets quite easily.",
"_____no_output_____"
]
],
[
[
"%bq query\nSELECT * FROM `bigquery-public-data.noaa_gsod.stations`\nWHERE state = 'NY' AND wban != '99999' AND name LIKE '%LA GUARDIA%'",
"_____no_output_____"
]
],
[
[
"<h3> Variables </h3>\n\nLet's pull out the minimum and maximum daily temperature (in Fahrenheit) as well as the amount of rain (in inches) for La Guardia airport.",
"_____no_output_____"
]
],
[
[
"%bq query -n wxquery\nSELECT EXTRACT (DAYOFYEAR FROM CAST(CONCAT(@YEAR,'-',mo,'-',da) AS TIMESTAMP)) AS daynumber,\n MIN(EXTRACT (DAYOFWEEK FROM CAST(CONCAT(@YEAR,'-',mo,'-',da) AS TIMESTAMP))) dayofweek,\n MIN(min) mintemp, MAX(max) maxtemp, MAX(IF(prcp=99.99,0,prcp)) rain\nFROM `bigquery-public-data.noaa_gsod.gsod*`\nWHERE stn='725030' AND _TABLE_SUFFIX = @YEAR\nGROUP BY 1 ORDER BY daynumber DESC",
"_____no_output_____"
],
[
"query_parameters = [\n {\n 'name': 'YEAR',\n 'parameterType': {'type': 'STRING'},\n 'parameterValue': {'value': 2015}\n }\n]\nweather = wxquery.execute(query_params=query_parameters).result().to_dataframe()\nweather[:5]",
"_____no_output_____"
]
],
[
[
"<h3> Merge datasets </h3>\n\nLet's use Pandas to merge (combine) the taxi cab and weather datasets day-by-day.",
"_____no_output_____"
]
],
[
[
"data = pd.merge(weather, trips, on='daynumber')\ndata[:5]",
"_____no_output_____"
]
],
[
[
"<h3> Exploratory analysis </h3>\n\nIs there a relationship between maximum temperature and the number of trips?",
"_____no_output_____"
]
],
[
[
"j = data.plot(kind='scatter', x='maxtemp', y='numtrips')",
"/usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans\n (prop.get_family(), self.defaultFamily[fontext]))\n"
]
],
[
[
"The scatterplot above doesn't look very promising. There appears to be a weak downward trend, but it's also quite noisy.\n\nIs there a relationship between the day of the week and the number of trips?",
"_____no_output_____"
]
],
[
[
"j = data.plot(kind='scatter', x='dayofweek', y='numtrips')",
"/usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans\n (prop.get_family(), self.defaultFamily[fontext]))\n"
]
],
[
[
"Hurrah, we seem to have found a predictor. It appears that people use taxis more later in the week. Perhaps New Yorkers make weekly resolutions to walk more and then lose their determination later in the week, or maybe it reflects tourism dynamics in New York City.\n\nPerhaps if we took out the <em>confounding</em> effect of the day of the week, maximum temperature will start to have an effect. Let's see if that's the case:",
"_____no_output_____"
]
],
[
[
"j = data[data['dayofweek'] == 7].plot(kind='scatter', x='maxtemp', y='numtrips')",
"/usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans\n (prop.get_family(), self.defaultFamily[fontext]))\n"
]
],
[
[
"Removing the confounding factor does seem to reflect an underlying trend around temperature. But ... the data are a little sparse, don't you think? This is something that you have to keep in mind -- the more predictors you start to consider (here we are using two: day of week and maximum temperature), the more rows you will need so as to avoid <em> overfitting </em> the model.",
"_____no_output_____"
],
[
"<h3> Adding 2014 and 2016 data </h3>\n\nLet's add in 2014 and 2016 data to the Pandas dataframe. Note how useful it was for us to modularize our queries around the YEAR.",
"_____no_output_____"
]
],
[
[
"data2 = data # 2015 data\nfor year in [2014, 2016]:\n query_parameters = [\n {\n 'name': 'YEAR',\n 'parameterType': {'type': 'STRING'},\n 'parameterValue': {'value': year}\n }\n ]\n weather = wxquery.execute(query_params=query_parameters).result().to_dataframe()\n trips = taxiquery.execute(query_params=query_parameters).result().to_dataframe()\n data_for_year = pd.merge(weather, trips, on='daynumber')\n data2 = pd.concat([data2, data_for_year])\ndata2.describe()",
"_____no_output_____"
],
[
"j = data2[data2['dayofweek'] == 7].plot(kind='scatter', x='maxtemp', y='numtrips')",
"/usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans\n (prop.get_family(), self.defaultFamily[fontext]))\n"
]
],
[
[
"The data do seem a bit more robust. If we had even more data, it would be better of course. But in this case, we only have 2014-2016 data for taxi trips, so that's what we will go with.",
"_____no_output_____"
],
[
"<h2> Machine Learning with Tensorflow </h2>\n\nWe'll use 80% of our dataset for training and 20% of the data for testing the model we have trained. Let's shuffle the rows of the Pandas dataframe so that this division is random. The predictor (or input) columns will be every column in the database other than the number-of-trips (which is our target, or what we want to predict).\n\nThe machine learning models that we will use -- linear regression and neural networks -- both require that the input variables are numeric in nature.\n\nThe day of the week, however, is a categorical variable (i.e. Tuesday is not really greater than Monday). So, we should create separate columns for whether it is a Monday (with values 0 or 1), Tuesday, etc.\n\nAgainst that, we do have limited data (remember: the more columns you use as input features, the more rows you need to have in your training dataset), and it appears that there is a clear linear trend by day of the week. So, we will opt for simplicity here and use the data as-is. Try uncommenting the code that creates separate columns for the days of the week and re-run the notebook if you are curious about the impact of this simplification.",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nshuffled = data2.sample(frac=1, random_state=13)\n# It would be a good idea, if we had more data, to treat the days as categorical variables\n# with the small amount of data, we have though, the model tends to overfit\n#predictors = shuffled.iloc[:,2:5]\n#for day in range(1,8):\n# matching = shuffled['dayofweek'] == day\n# key = 'day_' + str(day)\n# predictors[key] = pd.Series(matching, index=predictors.index, dtype=float)\npredictors = shuffled.iloc[:,1:5]\npredictors[:5]",
"/usr/local/envs/py3env/lib/python3.5/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n from ._conv import register_converters as _register_converters\n"
],
[
"shuffled[:5]",
"_____no_output_____"
],
[
"targets = shuffled.iloc[:,5]\ntargets[:5]",
"_____no_output_____"
]
],
[
[
"Let's update our benchmark based on the 80-20 split and the larger dataset.",
"_____no_output_____"
]
],
[
[
"trainsize = int(len(shuffled['numtrips']) * 0.8)\navg = np.mean(shuffled['numtrips'][:trainsize])\nrmse = np.sqrt(np.mean((targets[trainsize:] - avg)**2))\nprint('Just using average={0} has RMSE of {1}'.format(avg, rmse))",
"Just using average=402667.6826484018 has RMSE of 62394.11232075195\n"
]
],
[
[
"<h2> Linear regression with tf.contrib.learn </h2>\n\nWe scale the number of taxicab rides by 400,000 so that the model can keep its predicted values in the [0-1] range. The optimization goes a lot faster when the weights are small numbers. We save the weights into ./trained_model_linear and display the root mean square error on the test dataset.",
"_____no_output_____"
]
],
[
[
"SCALE_NUM_TRIPS = 600000.0\ntrainsize = int(len(shuffled['numtrips']) * 0.8)\ntestsize = len(shuffled['numtrips']) - trainsize\nnpredictors = len(predictors.columns)\nnoutputs = 1\ntf.logging.set_verbosity(tf.logging.WARN) # change to INFO to get output every 100 steps ...\nshutil.rmtree('./trained_model_linear', ignore_errors=True) # so that we don't load weights from previous runs\nestimator = tf.contrib.learn.LinearRegressor(model_dir='./trained_model_linear',\n feature_columns=tf.contrib.learn.infer_real_valued_columns_from_input(predictors.values))\n\nprint(\"starting to train ... this will take a while ... use verbosity=INFO to get more verbose output\")\ndef input_fn(features, targets):\n return tf.constant(features.values), tf.constant(targets.values.reshape(len(targets), noutputs)/SCALE_NUM_TRIPS)\nestimator.fit(input_fn=lambda: input_fn(predictors[:trainsize], targets[:trainsize]), steps=10000)\n\npred = np.multiply(list(estimator.predict(predictors[trainsize:].values)), SCALE_NUM_TRIPS )\nrmse = np.sqrt(np.mean(np.power((targets[trainsize:].values - pred), 2)))\nprint('LinearRegression has RMSE of {0}'.format(rmse))\n",
"WARNING:tensorflow:From <ipython-input-21-3865241c1b45>:9: infer_real_valued_columns_from_input (from tensorflow.contrib.learn.python.learn.estimators.estimator) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease specify feature columns explicitly.\nWARNING:tensorflow:From /usr/local/envs/py3env/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py:142: setup_train_data_feeder (from tensorflow.contrib.learn.python.learn.learn_io.data_feeder) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use tensorflow/transform or tf.data.\nWARNING:tensorflow:From /usr/local/envs/py3env/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py:96: extract_dask_data (from tensorflow.contrib.learn.python.learn.learn_io.dask_io) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease feed input to tf.data to support dask.\nWARNING:tensorflow:From /usr/local/envs/py3env/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py:100: extract_pandas_data (from tensorflow.contrib.learn.python.learn.learn_io.pandas_io) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease access pandas data directly.\nWARNING:tensorflow:From /usr/local/envs/py3env/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py:159: DataFeeder.__init__ (from tensorflow.contrib.learn.python.learn.learn_io.data_feeder) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use tensorflow/transform or tf.data.\nWARNING:tensorflow:From /usr/local/envs/py3env/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py:340: check_array (from tensorflow.contrib.learn.python.learn.learn_io.data_feeder) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease convert numpy dtypes explicitly.\nWARNING:tensorflow:float64 is not supported by many models, consider casting to float32.\nWARNING:tensorflow:From /usr/local/envs/py3env/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py:182: infer_real_valued_columns_from_input_fn (from tensorflow.contrib.learn.python.learn.estimators.estimator) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease specify feature columns explicitly.\nWARNING:tensorflow:From /usr/local/envs/py3env/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/linear.py:738: regression_head (from tensorflow.contrib.learn.python.learn.estimators.head) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease switch to tf.contrib.estimator.*_head.\nWARNING:tensorflow:From /usr/local/envs/py3env/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py:1179: BaseEstimator.__init__ (from tensorflow.contrib.learn.python.learn.estimators.estimator) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease replace uses of any Estimator from tf.contrib.learn with an Estimator from tf.estimator.*\nWARNING:tensorflow:From /usr/local/envs/py3env/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py:427: RunConfig.__init__ (from tensorflow.contrib.learn.python.learn.estimators.run_config) is deprecated and will be removed in a future version.\nInstructions for updating:\nWhen switching to tf.estimator.Estimator, use tf.estimator.RunConfig instead.\nstarting to train ... this will take a while ... use verbosity=INFO to get more verbose output\nWARNING:tensorflow:From /usr/local/envs/py3env/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/head.py:678: ModelFnOps.__new__ (from tensorflow.contrib.learn.python.learn.estimators.model_fn) is deprecated and will be removed in a future version.\nInstructions for updating:\nWhen switching to tf.estimator.Estimator, use tf.estimator.EstimatorSpec. You can use the `estimator_spec` method to create an equivalent one.\nWARNING:tensorflow:From /usr/local/envs/py3env/lib/python3.5/site-packages/tensorflow/python/util/deprecation.py:497: calling LinearRegressor.predict (from tensorflow.contrib.learn.python.learn.estimators.linear) with outputs=None is deprecated and will be removed after 2017-03-01.\nInstructions for updating:\nPlease switch to predict_scores, or set `outputs` argument.\nWARNING:tensorflow:From /usr/local/envs/py3env/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/linear.py:843: calling BaseEstimator.predict (from tensorflow.contrib.learn.python.learn.estimators.estimator) with x is deprecated and will be removed after 2016-12-01.\nInstructions for updating:\nEstimator is decoupled from Scikit Learn interface by moving into\nseparate class SKCompat. Arguments x, y and batch_size are only\navailable in the SKCompat class, Estimator will only accept input_fn.\nExample conversion:\n est = Estimator(...) -> est = SKCompat(Estimator(...))\nWARNING:tensorflow:float64 is not supported by many models, consider casting to float32.\nLinearRegression has RMSE of 56643.95363906046\n"
]
],
[
[
"The RMSE here (57K) is lower than the benchmark (62K) indicates that we are doing about 10% better with the machine learning model than we would be if we were to just use the historical average (our benchmark).",
"_____no_output_____"
],
[
"<h2> Neural network with tf.contrib.learn </h2>\n\nLet's make a more complex model with a few hidden nodes.",
"_____no_output_____"
]
],
[
[
"SCALE_NUM_TRIPS = 600000.0\ntrainsize = int(len(shuffled['numtrips']) * 0.8)\ntestsize = len(shuffled['numtrips']) - trainsize\nnpredictors = len(predictors.columns)\nnoutputs = 1\ntf.logging.set_verbosity(tf.logging.WARN) # change to INFO to get output every 100 steps ...\nshutil.rmtree('./trained_model', ignore_errors=True) # so that we don't load weights from previous runs\nestimator = tf.contrib.learn.DNNRegressor(model_dir='./trained_model',\n hidden_units=[5, 5], \n feature_columns=tf.contrib.learn.infer_real_valued_columns_from_input(predictors.values))\n\nprint(\"starting to train ... this will take a while ... use verbosity=INFO to get more verbose output\")\ndef input_fn(features, targets):\n return tf.constant(features.values), tf.constant(targets.values.reshape(len(targets), noutputs)/SCALE_NUM_TRIPS)\nestimator.fit(input_fn=lambda: input_fn(predictors[:trainsize], targets[:trainsize]), steps=10000)\n\npred = np.multiply(list(estimator.predict(predictors[trainsize:].values)), SCALE_NUM_TRIPS )\nrmse = np.sqrt(np.mean((targets[trainsize:].values - pred)**2))\nprint('Neural Network Regression has RMSE of {0}'.format(rmse))",
"WARNING:tensorflow:float64 is not supported by many models, consider casting to float32.\nstarting to train ... this will take a while ... use verbosity=INFO to get more verbose output\nWARNING:tensorflow:From /usr/local/envs/py3env/lib/python3.5/site-packages/tensorflow/python/util/deprecation.py:497: calling DNNRegressor.predict (from tensorflow.contrib.learn.python.learn.estimators.dnn) with outputs=None is deprecated and will be removed after 2017-03-01.\nInstructions for updating:\nPlease switch to predict_scores, or set `outputs` argument.\nWARNING:tensorflow:float64 is not supported by many models, consider casting to float32.\n"
]
],
[
[
"Using a neural network results in similar performance to the linear model when I ran it -- it might be because there isn't enough data for the NN to do much better. (NN training is a non-convex optimization, and you will get different results each time you run the above code).",
"_____no_output_____"
],
[
"<h2> Running a trained model </h2>\n\nSo, we have trained a model, and saved it to a file. Let's use this model to predict taxicab demand given the expected weather for three days.\n\nHere we make a Dataframe out of those inputs, load up the saved model (note that we have to know the model equation -- it's not saved in the model file) and use it to predict the taxicab demand.",
"_____no_output_____"
]
],
[
[
"input = pd.DataFrame.from_dict(data = \n {'dayofweek' : [4, 5, 6],\n 'mintemp' : [60, 40, 50],\n 'maxtemp' : [70, 90, 60],\n 'rain' : [0, 0.5, 0]})\n# read trained model from ./trained_model\nestimator = tf.contrib.learn.LinearRegressor(model_dir='./trained_model_linear',\n feature_columns=tf.contrib.learn.infer_real_valued_columns_from_input(input.values))\n\npred = np.multiply(list(estimator.predict(input.values)), SCALE_NUM_TRIPS )\nprint(pred)",
"WARNING:tensorflow:float64 is not supported by many models, consider casting to float32.\nWARNING:tensorflow:float64 is not supported by many models, consider casting to float32.\n[354762.78 306764.7 387226.62]\n"
]
],
[
[
"Looks like we should tell some of our taxi drivers to take the day off on Thursday (day=5). No wonder -- the forecast calls for extreme weather fluctuations on Thursday.",
"_____no_output_____"
],
[
"Copyright 2017 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",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
4ac30e62728f0012aa1d93439f2392ba89d973e0
| 1,014,278 |
ipynb
|
Jupyter Notebook
|
jupyterNotebooks/clustering/clustering.ipynb
|
grehujt/SmallPythonProjects
|
5e6ca01935a0f209330bf0a92d4c053465dd8d9d
|
[
"MIT"
] | null | null | null |
jupyterNotebooks/clustering/clustering.ipynb
|
grehujt/SmallPythonProjects
|
5e6ca01935a0f209330bf0a92d4c053465dd8d9d
|
[
"MIT"
] | null | null | null |
jupyterNotebooks/clustering/clustering.ipynb
|
grehujt/SmallPythonProjects
|
5e6ca01935a0f209330bf0a92d4c053465dd8d9d
|
[
"MIT"
] | null | null | null | 726.560172 | 162,132 | 0.932931 |
[
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy.linalg import norm\nimport pandas as pd\nplt.style.use('ggplot')",
"_____no_output_____"
],
[
"deaths = pd.read_csv('deaths.txt')\npumps = pd.read_csv('pumps.txt')\nprint deaths.head()\nprint pumps.head()",
" X Y\n0 13.588010 11.095600\n1 9.878124 12.559180\n2 14.653980 10.180440\n3 15.220570 9.993003\n4 13.162650 12.963190\n X Y\n0 8.651201 17.891600\n1 10.984780 18.517851\n2 13.378190 17.394541\n3 14.879830 17.809919\n4 8.694768 14.905470\n"
],
[
"plt.plot(deaths['X'], deaths['Y'], 'o', lw=0, mew=1, mec='0.9', ms=6) # marker edge color/width, marker size\nplt.plot(pumps['X'], pumps['Y'], 'ks', lw=0, mew=1, mec='0.9', ms=6)\nplt.axis('equal')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.title('Jhon Snow\\'s Cholera')",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(4, 3.5))\nax = fig.add_subplot(111)\nplt.plot(deaths['X'], deaths['Y'], 'bo', lw=0, mew=1, mec='0.9', ms=6, alpha=0.6) # marker edge color/width, marker size\nplt.plot(pumps['X'], pumps['Y'], 'ks', lw=0, mew=1, mec='0.9', ms=6)\nplt.axis('equal')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.title('Jhon Snow\\'s Cholera')\nfrom matplotlib.patches import Ellipse\ne = Ellipse(xy=(deaths['X'].mean(), deaths['Y'].mean()), \n width=deaths.X.std(), height=deaths.Y.std(), lw=2, fc='None', ec='r', zorder=10)\nax.add_artist(e)\nplt.plot(deaths['X'].mean(), deaths['Y'].mean(), 'r.', lw=2)\nfor i in pumps.index:\n plt.annotate(s='%d'%i, xy=(pumps[['X', 'Y']].loc[i]), xytext=(-15, 6), textcoords='offset points', color='k')\n",
"_____no_output_____"
],
[
"# calculate the nearing pump for each death\ndeaths['C'] = [np.argmin(norm(pumps - deaths.iloc[i,:2], axis=1)) for i in xrange(len(deaths))]\ndeaths.head()",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(4, 3.5))\nax = fig.add_subplot(111)\nplt.scatter(deaths['X'], deaths['Y'], marker='o', lw=0.5, color=plt.cm.jet(deaths.C/12), edgecolors='0.5')\nplt.plot(pumps['X'], pumps['Y'], 'ks', lw=0, mew=1, mec='0.9', ms=6)\nplt.axis('equal')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.title('Jhon Snow\\'s Cholera')\nfrom matplotlib.patches import Ellipse\ne = Ellipse(xy=(deaths['X'].mean(), deaths['Y'].mean()), \n width=deaths.X.std(), height=deaths.Y.std(), lw=2, fc='None', ec='r', zorder=10)\nax.add_artist(e)\nplt.plot(deaths['X'].mean(), deaths['Y'].mean(), 'r.', lw=2)\nfor i in pumps.index:\n plt.annotate(s='%d'%i, xy=(pumps[['X', 'Y']].loc[i]), xytext=(-15, 6), textcoords='offset points', color='k')",
"_____no_output_____"
],
[
"#################\nd2 = pd.read_hdf('../LinearRegression/ch4data.h5').dropna()\nrates = d2[['dfe', 'gdp', 'both']].as_matrix().astype('float')\nprint rates.shape",
"(141, 3)\n"
],
[
"plt.figure(figsize=(8, 3.5))\nplt.subplot(121)\n_ = plt.hist(rates[:, 1], bins=20, color='steelblue')\nplt.xticks(rotation=45, ha='right')\nplt.yscale('log')\nplt.xlabel('GDP')\nplt.ylabel('count')\nplt.subplot(122)\nplt.scatter(rates[:, 0], rates[:, 2], s=141*4*rates[:, 1] / rates[:, 1].max(), edgecolor='0.3', color='steelblue')\nplt.xlabel('dfe')\nplt.ylabel('suicide rate (both)')\nplt.subplots_adjust(wspace=0.3)",
"_____no_output_____"
],
[
"from scipy.cluster.vq import whiten\nw = whiten(rates) # convert to unit variance, k-means prerequisite\nplt.figure(figsize=(8, 3.5))\nplt.subplot(121)\n_ = plt.hist(w[:, 1], bins=20, color='steelblue')\nplt.xticks(rotation=45, ha='right')\nplt.yscale('log')\nplt.xlabel('GDP')\nplt.ylabel('count')\nplt.subplot(122)\nplt.scatter(w[:, 0], w[:, 2], s=141*4*w[:, 1] / w[:, 1].max(), edgecolor='0.3', color='steelblue')\nplt.xlabel('dfe')\nplt.ylabel('suicide rate (both)')\nplt.subplots_adjust(wspace=0.3)",
"_____no_output_____"
],
[
"from sklearn.cluster import KMeans\nk = 2\nmodel = KMeans(n_clusters=k).fit(w[:, [0, 2]])\n\nplt.scatter(w[:, 0], w[:, 2], s=141*4*w[:, 1] / w[:, 1].max(), edgecolor='0.3',\n color=plt.cm.get_cmap(\"hsv\", k+1)(model.labels_), alpha=0.5)\nplt.xlabel('dfe')\nplt.ylabel('suicide rate (both)')\n\nplt.scatter(model.cluster_centers_[:, 0], model.cluster_centers_[:, 1], marker='+',\n color='k', s=141, lw=3)",
"_____no_output_____"
],
[
"x, y = np.meshgrid(np.linspace(0, 4, 100), np.linspace(0, 7, 100))\nx, y = x.reshape((-1, 1)), y.reshape((-1, 1))\np = model.predict(np.hstack((x, y)))\nplt.scatter(x, y, color=plt.cm.get_cmap(\"hsv\", k+1)(p), alpha=0.3)\nplt.scatter(model.cluster_centers_[:, 0], model.cluster_centers_[:, 1], marker='+',\n color='k', s=141, lw=3)\nplt.xlim((0, 4))\nplt.ylim((0, 7))",
"_____no_output_____"
],
[
"############\nimport astropy.coordinates as coord\nimport astropy.units as u\nimport astropy.constants as c",
"_____no_output_____"
],
[
"uzcat = pd.read_table('uzcJ2000.tab', sep='\\t', dtype='str', header=16, \n names=['ra', 'dec', 'Zmag', 'cz', 'cze', 'T', 'U',\n 'Ne', 'Zname', 'C', 'Ref', 'Oname', 'M', 'N'], skiprows=[17])\nuzcat.head()",
"_____no_output_____"
],
[
"uzcat['ra'] = uzcat['ra'].apply(lambda x: '%sh%sm%ss' % (x[:2], x[2:4], x[4:]))\nuzcat['dec'] = uzcat['dec'].apply(lambda x: '%sd%sm%ss' % (x[:3], x[3:5], x[5:]))\nuzcat.head()",
"_____no_output_____"
],
[
"uzcat2 = uzcat.applymap(lambda x: np.nan if x.isspace() else x.strip())\nuzcat2['cz'] = uzcat2['cz'].astype('float')\nuzcat2['Zmag'] = uzcat2['Zmag'].astype('float')\nuzcat2.head()",
"_____no_output_____"
],
[
"coords_uzc = coord.SkyCoord(uzcat2['ra'], uzcat2['dec'], frame='fk5', equinox='J2000')\ncolor_czs = (uzcat2['cz'] + abs(uzcat2['cz'].min())) / (uzcat2['cz'].max() + abs(uzcat2['cz'].min())) ",
"_____no_output_____"
],
[
"from matplotlib.patheffects import withStroke\nwhitebg = withStroke(foreground='w', linewidth=2.5)\nfig = plt.figure(figsize=(8, 3.5), facecolor='w')\nax = fig.add_subplot(111, projection='mollweide')\nax.scatter(coords_uzc.ra.radian - np.pi, coords_uzc.dec.radian, c=plt.cm.Blues_r(color_czs),\n s=4, marker='.', zorder=-1)\n#plt.grid()\nfor label in ax.get_xticklabels():\n label.set_path_effects([whitebg])",
"_____no_output_____"
],
[
"uzcat2.cz.hist(bins=50)\nplt.yscale('log')\nplt.xlabel('cz distance')\nplt.ylabel('count')\n_ = plt.xticks(rotation=45, ha='right')",
"_____no_output_____"
],
[
"uzc_czs = uzcat2['cz'].as_matrix() \nuzcat2['Zmag'] = uzcat2['Zmag'].astype('float') \ndecmin = 15 \ndecmax = 30 \nramin = 90 \nramax = 295 \nczmin = 0 \nczmax = 12500 \nselection_dec = (coords_uzc.dec.deg > decmin) * (coords_uzc.dec.deg < decmax) \nselection_ra = (coords_uzc.ra.deg > ramin) * (coords_uzc.ra.deg < ramax) \nselection_czs = (uzc_czs > czmin) * (uzc_czs < czmax) \nselection= selection_dec * selection_ra * selection_czs ",
"_____no_output_____"
],
[
"fig = plt.figure( figsize=(6,6)) \nax = fig.add_subplot(111, projection='polar') \nsct = ax.scatter(coords_uzc.ra.radian[selection_dec], uzc_czs[selection_dec],\n color='SteelBlue', s=uzcat2['Zmag'][selection_dec * selection_czs],\n edgecolors=\"none\", alpha=0.7, zorder=0) \nax.set_rlim(0,20000) \nax.set_theta_offset(np.pi/-2) \nax.set_rlabel_position(65) \nax.set_rticks(range(2500, 20001, 5000)); \nax.plot([(ramin * u.deg).to(u.radian).value, (ramin * u.deg).to(u.radian).value], [0, 12500],\n color='IndianRed', alpha=0.8, dashes=(10,4)) \nax.plot([ramax*np.pi/180., ramax*np.pi/180.], [0,12500], color='IndianRed', alpha=0.8, dashes=(10, 4)) \ntheta = np.arange(ramin, ramax, 1) \nax.plot(theta*np.pi/180., np.ones_like(theta)*12500, color='IndianRed', alpha=0.8, dashes=(10, 4)) ",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(6,6)) \nax = fig.add_subplot(111, polar=True) \nsct = ax.scatter(coords_uzc.ra.radian[selection], uzc_czs[selection], color='SteelBlue', \n s=uzcat2['Zmag'][selection], edgecolors=\"none\", alpha=0.7, zorder=0) \nax.set_rlim(0,12500) \nax.set_theta_offset(np.pi/-2) \nax.set_rlabel_position(65) \nax.set_rticks(range(2500,12501,2500)); ",
"_____no_output_____"
],
[
"mycat = uzcat2.copy(deep=True).loc[selection] \nmycat['ra_deg'] = coords_uzc.ra.deg[selection] \nmycat['dec_deg'] = coords_uzc.dec.deg[selection] \nzs = (((mycat['cz'].as_matrix() * u.km / u.s) / c.c).decompose()) \ndist = coord.Distance(z=zs) \nprint(dist) \nmycat['dist'] = dist \ncoords_xyz = coord.SkyCoord(ra=mycat['ra_deg'] * u.deg,\n dec=mycat['dec_deg'] * u.deg,\n distance=dist * u.Mpc,\n frame='fk5',\n equinox='J2000')\nmycat['X'] = coords_xyz.cartesian.x.value \nmycat['Y'] = coords_xyz.cartesian.y.value \nmycat['Z'] = coords_xyz.cartesian.z.value\nmycat.head()",
"[ 62.79998101 172.23410971 145.40065934 ..., 64.30473839 61.81198342\n 57.46582197] Mpc\n"
],
[
"fig, axs = plt.subplots(1, 2, figsize=(14,6))\n\nplt.subplot(121) \nplt.scatter(mycat['Y'], -1*mycat['X'], s=8,\n color=plt.cm.OrRd_r(10**(mycat.Zmag - mycat.Zmag.max())),\n edgecolor='None') \nplt.xlabel('Y (Mpc)')\nplt.ylabel('X (Mpc)') \nplt.axis('equal')\n\nplt.subplot(122) \nplt.scatter(-1*mycat['X'], mycat['Z'], s=8,\n color=plt.cm.OrRd_r(10**(mycat.Zmag - mycat.Zmag.max())),\n edgecolor='None') \nlstyle = dict(lw=1.5, color='k', dashes=(6, 4)) \nplt.plot([0, 150], [0, 80], **lstyle) \nplt.plot([0, 150], [0, 45], **lstyle) \nplt.plot([0, -25], [0, 80], **lstyle) \nplt.plot([0, -25], [0, 45], **lstyle) \nplt.xlabel('X (Mpc)')\nplt.ylabel('Z (Mpc)') \nplt.axis('equal') \nplt.subplots_adjust(wspace=0.25)",
"_____no_output_____"
],
[
"#mycat.to_pickle('data_ch5_clustering.pick')",
"_____no_output_____"
],
[
"import scipy.cluster.hierarchy as hac\nX = mycat.X.reshape(-1, 1)\nY = mycat.Y.reshape(-1, 1)\ngalpos = np.hstack((X, Y))\nZ = hac.linkage(galpos, metric='euclidean', method='centroid')",
"_____no_output_____"
],
[
"plt.figure(figsize=(10, 8))\nhac.dendrogram(Z, p=6, truncate_mode='level', orientation='right');",
"_____no_output_____"
],
[
"k = 10\nclusters = hac.fcluster(Z, k, criterion='maxclust')\nplt.scatter(Y, -X, c=clusters, cmap='rainbow')\nfor i in range(k):\n plt.plot(Y[clusters==i+1].mean(), -X[clusters==i+1].mean(), \n 'o', c='0.7', mec='k', mew=1.5, alpha=0.7)",
"_____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"
]
] |
4ac311c73b397b63cb8be040be4fc65de23f6af2
| 10,712 |
ipynb
|
Jupyter Notebook
|
read_&_write_to_txt.ipynb
|
becliu/Python-practice
|
aa2a8e1d6026991af2f86fd3595775011ef3e7e7
|
[
"MIT"
] | null | null | null |
read_&_write_to_txt.ipynb
|
becliu/Python-practice
|
aa2a8e1d6026991af2f86fd3595775011ef3e7e7
|
[
"MIT"
] | null | null | null |
read_&_write_to_txt.ipynb
|
becliu/Python-practice
|
aa2a8e1d6026991af2f86fd3595775011ef3e7e7
|
[
"MIT"
] | null | null | null | 20.365019 | 377 | 0.492718 |
[
[
[
"# I/O",
"_____no_output_____"
]
],
[
[
"%%writefile myfile.txt \nHello this is a text file\nthis is the second line\nthis is the third line",
"Overwriting myfile.txt\n"
],
[
"myfile = open('myfile.txt')",
"_____no_output_____"
],
[
"myfile = open('whoops_wrong.txt') # there's no such file",
"_____no_output_____"
],
[
"pwd # know where this jupyter notebook is ",
"_____no_output_____"
],
[
"myfile = open('myfile.txt')",
"_____no_output_____"
],
[
"myfile.read()",
"_____no_output_____"
],
[
"myfile.read() # when you try to read it again, the cursor is already at the end of the file",
"_____no_output_____"
],
[
"myfile.seek(0) # move the curser back to position 0",
"_____no_output_____"
],
[
"myfile.read()",
"_____no_output_____"
],
[
"myfile.seek(0)",
"_____no_output_____"
],
[
"myfile.readlines() # this is better way of reading a txt file line by line in a list",
"_____no_output_____"
]
],
[
[
"## file location",
"_____no_output_____"
]
],
[
[
"pwd",
"_____no_output_____"
],
[
"myfile = open('/Users/Crystal/src/Python-practice/myfile.txt')",
"_____no_output_____"
],
[
"myfile.close() # close your file",
"_____no_output_____"
],
[
"with open('myfile.txt') as my_new_file: # by this way, you don't worry about closing the file like above\n contents = my_new_file.read()",
"_____no_output_____"
],
[
"contents",
"_____no_output_____"
]
],
[
[
"## write & overwrite to a file",
"_____no_output_____"
]
],
[
[
"with open('myfile.txt', mode='r') as myfile: # shift + tab, then you'll see doc of this open() function\n contents = myfile.read() ",
"_____no_output_____"
],
[
"contents",
"_____no_output_____"
],
[
"%%writefile my_new_file.txt\nONE ON FIRST\nTWO ON SECOND\nTHREE ON THIRD",
"Overwriting my_new_file.txt\n"
],
[
"with open('my_new_file.txt', mode = 'r') as f:\n print(f.read())",
"ONE ON FIRST\nTWO ON SECOND\nTHREE ON THIRD\n\n"
],
[
"with open('my_new_file.txt', mode = 'a') as f: # 'a' means append\n f.write('FOUR ON FOURTH') # \\n is initiate a new line",
"_____no_output_____"
],
[
"with open('my_new_file.txt', mode = 'r') as f:\n print(f.read())",
"ONE ON FIRST\nTWO ON SECOND\nTHREE ON THIRD\nFOUR ON FOURTH\n"
],
[
"with open('my_new_file.txt', mode = 'a') as f: # 'a' means append\n f.write('TTTTest') # \\n is initiate a new line",
"_____no_output_____"
],
[
"with open('my_new_file.txt', mode = 'r') as f:\n print(f.read())",
"ONE ON FIRST\nTWO ON SECOND\nTHREE ON THIRD\nFOUR ON FOURTHTTTTest\n"
],
[
"with open('sgadgfdg.txt', mode = 'w') as f: # 'w' means overwrite an existing file or create a new file if not exists\n f.write('I CREATED THIS FILE!')",
"_____no_output_____"
],
[
"with open('sgadgfdg.txt', mode = 'r') as f:\n print(f.read())",
"I CREATED THIS FILE!\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac320c301707e2a6b5e3504a103dce861c89570
| 13,839 |
ipynb
|
Jupyter Notebook
|
book-d2l-en/chapter_linear-networks/linear-regression-gluon.ipynb
|
linked0/dlnd-deep-learning
|
f67a5be7a700c1a30fde71ebbb6a72c3bdd09fb7
|
[
"MIT"
] | null | null | null |
book-d2l-en/chapter_linear-networks/linear-regression-gluon.ipynb
|
linked0/dlnd-deep-learning
|
f67a5be7a700c1a30fde71ebbb6a72c3bdd09fb7
|
[
"MIT"
] | 115 |
2020-01-28T22:21:35.000Z
|
2022-03-11T23:42:46.000Z
|
book-d2l-en/chapter_linear-networks/linear-regression-gluon.ipynb
|
linked0/deep-learning
|
f67a5be7a700c1a30fde71ebbb6a72c3bdd09fb7
|
[
"MIT"
] | null | null | null | 37.201613 | 677 | 0.620637 |
[
[
[
"# Concise Implementation of Linear Regression\n\nWith the development of deep learning frameworks, it has become increasingly easy to develop deep learning applications. In practice, we can usually implement the same model, but much more concisely than how we introduce it in the previous section. In this section, we will introduce how to use the Gluon interface provided by MXNet.\n\n## Generating Data Sets\n\nWe will generate the same data set as that used in the previous section.",
"_____no_output_____"
]
],
[
[
"from mxnet import autograd, nd\n\nnum_inputs = 2\nnum_examples = 1000\ntrue_w = nd.array([2, -3.4])\ntrue_b = 4.2\nfeatures = nd.random.normal(scale=1, shape=(num_examples, num_inputs))\nlabels = nd.dot(features, true_w) + true_b\nlabels += nd.random.normal(scale=0.01, shape=labels.shape)",
"_____no_output_____"
]
],
[
[
"## Reading Data\n\nGluon provides the `data` module to read data. Since `data` is often used as a variable name, we will replace it with the pseudonym `gdata` (adding the first letter of Gluon) when referring to the imported `data` module. In each iteration, we will randomly read a mini-batch containing 10 data instances.",
"_____no_output_____"
]
],
[
[
"from mxnet.gluon import data as gdata\n\nbatch_size = 10\n# Combine the features and labels of the training data\ndataset = gdata.ArrayDataset(features, labels)\n# Randomly reading mini-batches\ndata_iter = gdata.DataLoader(dataset, batch_size, shuffle=True)",
"_____no_output_____"
]
],
[
[
"The use of `data_iter` here is the same as in the previous section. Now, we can read and print the first mini-batch of instances.",
"_____no_output_____"
]
],
[
[
"for X, y in data_iter:\n print(X, y)\n break",
"\n[[ 1.9782461 -2.0905404 ]\n [ 1.7928383 -0.09992757]\n [-0.8624608 -0.4348689 ]\n [-0.27312678 0.45424792]\n [-0.46069986 0.8082894 ]\n [-0.8634535 -0.97035617]\n [ 0.01487677 -0.12173855]\n [-1.2860336 -1.6586353 ]\n [ 0.52979773 -2.436552 ]\n [ 0.44809967 0.00624379]]\n<NDArray 10x2 @cpu(0)> \n[15.254026 8.135473 3.9542496 2.1196961 0.51967335 5.750222\n 4.648376 7.265286 13.54595 5.088348 ]\n<NDArray 10 @cpu(0)>\n"
]
],
[
[
"## Define the Model\n\nWhen we implemented the linear regression model from scratch in the previous section, we needed to define the model parameters and use them to describe step by step how the model is evaluated. This can become complicated as we build complex models. Gluon provides a large number of predefined layers, which allow us to focus especially on the layers used to construct the model rather than having to focus on the implementation.\n\nTo define a linear model, first import the module `nn`. `nn` is an abbreviation for neural networks. As the name implies, this module defines a large number of neural network layers. We will first define a model variable `net`, which is a `Sequential` instance. In Gluon, a `Sequential` instance can be regarded as a container that concatenates the various layers in sequence. When constructing the model, we will add the layers in their order of occurrence in the container. When input data is given, each layer in the container will be calculated in order, and the output of one layer will be the input of the next layer.",
"_____no_output_____"
]
],
[
[
"from mxnet.gluon import nn\nnet = nn.Sequential()",
"_____no_output_____"
]
],
[
[
"Recall the architecture of a single layer network. The layer is fully connected since it connects all inputs with all outputs by means of a matrix-vector multiplication. In Gluon, the fully connected layer is referred to as a `Dense` instance. Since we only want to generate a single scalar output, we set that number to $1$.\n\n",
"_____no_output_____"
]
],
[
[
"net.add(nn.Dense(1))",
"_____no_output_____"
]
],
[
[
"It is worth noting that, in Gluon, we do not need to specify the input shape for each layer, such as the number of linear regression inputs. When the model sees the data, for example, when the `net(X)` is executed later, the model will automatically infer the number of inputs in each layer. We will describe this mechanism in detail in the chapter \"Deep Learning Computation\". Gluon introduces this design to make model development more convenient.\n\n\n## Initialize Model Parameters\n\nBefore using `net`, we need to initialize the model parameters, such as the weights and biases in the linear regression model. We will import the `initializer` module from MXNet. This module provides various methods for model parameter initialization. The `init` here is the abbreviation of `initializer`. By`init.Normal(sigma=0.01)` we specify that each weight parameter element is to be randomly sampled at initialization with a normal distribution with a mean of 0 and standard deviation of 0.01. The bias parameter will be initialized to zero by default.",
"_____no_output_____"
]
],
[
[
"from mxnet import init\nnet.initialize(init.Normal(sigma=0.01))",
"_____no_output_____"
]
],
[
[
"The code above looks pretty straightforward but in reality something quite strange is happening here. We are initializing parameters for a networks where we haven't told Gluon yet how many dimensions the input will have. It might be 2 as in our example or 2,000, so we couldn't just preallocate enough space to make it work. What happens behind the scenes is that the updates are deferred until the first time that data is sent through the networks. In doing so, we prime all settings (and the user doesn't even need to worry about it). The only cautionary notice is that since the parameters have not been initialized yet, we would not be able to manipulate them yet.\n\n\n## Define the Loss Function\n\nIn Gluon, the module `loss` defines various loss functions. We will replace the imported module `loss` with the pseudonym `gloss`, and directly use the squared loss it provides as a loss function for the model.",
"_____no_output_____"
]
],
[
[
"from mxnet.gluon import loss as gloss\nloss = gloss.L2Loss() # The squared loss is also known as the L2 norm loss",
"_____no_output_____"
]
],
[
[
"## Define the Optimization Algorithm\n\nAgain, we do not need to implement mini-batch stochastic gradient descent. After importing Gluon, we now create a `Trainer` instance and specify a mini-batch stochastic gradient descent with a learning rate of 0.03 (`sgd`) as the optimization algorithm. This optimization algorithm will be used to iterate through all the parameters contained in the `net` instance's nested layers through the `add` function. These parameters can be obtained by the `collect_params` function.",
"_____no_output_____"
]
],
[
[
"from mxnet import gluon\ntrainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.03})",
"_____no_output_____"
]
],
[
[
"## Training\n\nYou might have noticed that it was a bit more concise to express our model in Gluon. For example, we didn't have to individually allocate parameters, define our loss function, or implement stochastic gradient descent. The benefits of relying on Gluon's abstractions will grow substantially once we start working with much more complex models. But once we have all the basic pieces in place, the training loop itself is quite similar to what we would do if implementing everything from scratch.\n\nTo refresh your memory. For some number of epochs, we'll make a complete pass over the dataset (train_data), grabbing one mini-batch of inputs and the corresponding ground-truth labels at a time. Then, for each batch, we'll go through the following ritual.\n\n* Generate predictions `net(X)` and the loss `l` by executing a forward pass through the network.\n* Calculate gradients by making a backwards pass through the network via `l.backward()`.\n* Update the model parameters by invoking our SGD optimizer (note that we need not tell trainer.step about which parameters but rather just the amount of data, since we already performed that in the initialization of trainer).\n\nFor good measure we compute the loss on the features after each epoch and print it to monitor progress.",
"_____no_output_____"
]
],
[
[
"num_epochs = 3\nfor epoch in range(1, num_epochs + 1):\n for X, y in data_iter:\n with autograd.record():\n l = loss(net(X), y)\n l.backward()\n trainer.step(batch_size)\n l = loss(net(features), labels)\n print('epoch %d, loss: %f' % (epoch, l.mean().asnumpy()))",
"epoch 1, loss: 0.040886\nepoch 2, loss: 0.000161\n"
]
],
[
[
"The model parameters we have learned and the actual model parameters are compared as below. We get the layer we need from the `net` and access its weight (`weight`) and bias (`bias`). The parameters we have learned and the actual parameters are very close.",
"_____no_output_____"
]
],
[
[
"w = net[0].weight.data()\nprint('Error in estimating w', true_w.reshape(w.shape) - w)\nb = net[0].bias.data()\nprint('Error in estimating b', true_b - b)",
"Error in estimating w \n[[ 0.00027549 -0.00047135]]\n<NDArray 1x2 @cpu(0)>\nError in estimating b \n[0.00035286]\n<NDArray 1 @cpu(0)>\n"
]
],
[
[
"## Summary\n\n* Using Gluon, we can implement the model more succinctly.\n* In Gluon, the module `data` provides tools for data processing, the module `nn` defines a large number of neural network layers, and the module `loss` defines various loss functions.\n* MXNet's module `initializer` provides various methods for model parameter initialization.\n* Dimensionality and storage are automagically inferred (but caution if you want to access parameters before they've been initialized).\n\n\n## Exercises\n\n1. If we replace `l = loss(output, y)` with `l = loss(output, y).mean()`, we need to change `trainer.step(batch_size)` to `trainer.step(1)` accordingly. Why?\n1. Review the MXNet documentation to see what loss functions and initialization methods are provided in the modules `gluon.loss` and `init`. Replace the loss by Huber's loss.\n1. How do you access the gradient of `dense.weight`?\n\n## Scan the QR Code to [Discuss](https://discuss.mxnet.io/t/2333)\n\n",
"_____no_output_____"
]
]
] |
[
"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"
]
] |
4ac32b70707588d5ad0661ddd4da668c5f13967a
| 461,274 |
ipynb
|
Jupyter Notebook
|
notebooks/team_model.ipynb
|
tallamjr/AIrsenal
|
48f223407d806a9a374a406d6fe1289e5a36e48f
|
[
"MIT"
] | null | null | null |
notebooks/team_model.ipynb
|
tallamjr/AIrsenal
|
48f223407d806a9a374a406d6fe1289e5a36e48f
|
[
"MIT"
] | null | null | null |
notebooks/team_model.ipynb
|
tallamjr/AIrsenal
|
48f223407d806a9a374a406d6fe1289e5a36e48f
|
[
"MIT"
] | null | null | null | 629.296044 | 143,508 | 0.950229 |
[
[
[
"\nfrom airsenal.framework.utils import *\nfrom airsenal.framework.bpl_interface import get_fitted_team_model\nfrom airsenal.framework.season import get_current_season, CURRENT_TEAMS\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport numpy as np\n\n%matplotlib inline",
"_____no_output_____"
],
[
"model_team = get_fitted_team_model(get_current_season(), NEXT_GAMEWEEK, session)",
"Fitting team model...\n"
],
[
"# extract indices of current premier league teams\n# val-1 because 1-indexed in model but 0-indexed in python\ncurrent_idx = {key: val-1 for key, val in model_team.team_indices.items()\n if key in CURRENT_TEAMS}\n\ntop6 = ['MCI', 'LIV', 'TOT', 'CHE', 'MUN', 'ARS']",
"_____no_output_____"
],
[
"ax = plt.figure(figsize=(15, 5)).gca()\nfor team, idx in current_idx.items():\n sns.kdeplot(model_team.a[:, idx], label=team)\nplt.title('a')\nplt.legend()\n\nax = plt.figure(figsize=(15, 5)).gca()\nfor team, idx in current_idx.items():\n sns.kdeplot(model_team.b[:, idx], label=team)\nplt.title('b')\nplt.legend()",
"_____no_output_____"
],
[
"a_mean = model_team.a.mean(axis=0)\nb_mean = model_team.b.mean(axis=0)\n\na_conf95 = np.abs(np.quantile(model_team.a,[0.025, 0.975], axis=0) - a_mean)\nb_conf95 = np.abs(np.quantile(model_team.b, [0.025, 0.975], axis=0) - b_mean)\na_conf80 = np.abs(np.quantile(model_team.a,[0.1, 0.9], axis=0) - a_mean)\nb_conf80 = np.abs(np.quantile(model_team.b, [0.1, 0.9], axis=0) - b_mean)\n\nfig = plt.figure(figsize=(10,10))\nax = fig.gca(aspect='equal')\nplt.errorbar(a_mean[list(current_idx.values())],\n b_mean[list(current_idx.values())],\n xerr=a_conf80[:, list(current_idx.values())],\n yerr=b_conf80[:, list(current_idx.values())],\n marker='o', markersize=10,\n linestyle='', linewidth=0.5)\nplt.xlabel('a', fontsize=14)\nplt.ylabel('b', fontsize=14)\n\nfor team, idx in current_idx.items():\n ax.annotate(team,\n (a_mean[idx]-0.03, b_mean[idx]+0.02), \n fontsize=12)\n \nplt.plot([0.6, 1.6], [0.6, 1.6], \"k--\")\n",
"_____no_output_____"
],
[
"# team features (excluding first column which is team name)\nfeats = model_team.X.columns[1:]\n\nfor idx in range(model_team.beta_a.shape[1]):\n sns.kdeplot(model_team.beta_a[:,idx], \n label=feats[idx])\n\nplt.legend()\nplt.title('beta_a')\n\nplt.figure()\nfor idx in range(model_team.beta_b.shape[1]):\n sns.kdeplot(model_team.beta_b[:,idx],\n label=feats[idx])\nplt.legend()\nplt.title('beta_b')",
"_____no_output_____"
],
[
"beta_a_mean = model_team.beta_a.mean(axis=0)\nbeta_b_mean = model_team.beta_b.mean(axis=0)\n\nbeta_a_conf95 = np.abs(np.quantile(model_team.beta_a,[0.025, 0.975], axis=0) - beta_a_mean)\nbeta_b_conf95 = np.abs(np.quantile(model_team.beta_b, [0.025, 0.975], axis=0) - beta_b_mean)\nbeta_a_conf80 = np.abs(np.quantile(model_team.beta_a,[0.1, 0.9], axis=0) - beta_a_mean)\nbeta_b_conf80 = np.abs(np.quantile(model_team.beta_b, [0.1, 0.9], axis=0) - beta_b_mean)\n\nfig = plt.figure(figsize=(10,10))\nax = fig.gca(aspect='equal')\nplt.errorbar(beta_a_mean,\n beta_b_mean,\n xerr=beta_a_conf80,\n yerr=beta_b_conf80,\n marker='o', markersize=10,\n linestyle='', linewidth=0.5)\nplt.xlabel('beta_a', fontsize=14)\nplt.ylabel('beta_b', fontsize=14)\nplt.title('FIFA Ratings')\n\nfor idx, feat in enumerate(feats):\n ax.annotate(feat,\n (beta_a_mean[idx]-0.03, beta_b_mean[idx]+0.02), \n fontsize=12)\n \nxlim = ax.get_xlim()\nylim = ax.get_ylim()\nplt.plot([0, 0], ylim, color='k', linewidth=0.75)\nplt.plot(xlim, [0, 0], color='k', linewidth=0.75)\nplt.xlim(xlim)\nplt.ylim(ylim)",
"_____no_output_____"
],
[
"sns.kdeplot(model_team.beta_b_0)",
"_____no_output_____"
],
[
"sns.kdeplot(model_team.sigma_a)",
"_____no_output_____"
],
[
"sns.kdeplot(model_team.sigma_b)",
"_____no_output_____"
],
[
"sns.kdeplot(model_team.gamma)",
"_____no_output_____"
],
[
"model_team.log_score()",
"_____no_output_____"
],
[
"team_h = \"MCI\"\nteam_a = \"MUN\"",
"_____no_output_____"
],
[
"model_team.plot_score_probabilities(team_h, team_a);",
"_____no_output_____"
],
[
"model_team.concede_n_probability(2, team_h, team_a)",
"_____no_output_____"
],
[
"model_team.score_n_probability(2, team_h, team_a)",
"_____no_output_____"
],
[
"model_team.overall_probabilities(team_h, team_a)",
"_____no_output_____"
],
[
"model_team.score_probability(team_h, team_a, 2, 2)",
"_____no_output_____"
],
[
"sim = model_team.simulate_match(team_h, team_a)\nsim[team_h].value_counts(normalize=True).sort_index().plot.bar()\nplt.title(team_h)\nplt.ylim([0, 0.4])\nplt.xlim([-1, 8])\n\nplt.figure()\nsim[team_a].value_counts(normalize=True).sort_index().plot.bar()\nplt.title(team_a)\nplt.ylim([0, 0.4])\nplt.xlim([-1, 8])",
"_____no_output_____"
],
[
"max_goals = 10\n\nprob_score_h = [model_team.score_n_probability(n, team_h, team_a) for n in range(max_goals)]\nprint(team_h, \"exp goals\", sum([n*prob_score_h[n] for n in range(max_goals)])/sum(prob_score_h))\n\nprob_score_a = [model_team.score_n_probability(n, team_a, team_h, home=False) for n in range(max_goals)]\nprint(team_a, \"exp goals\", sum([n*prob_score_a[n] for n in range(max_goals)])/sum(prob_score_a))\n\nmax_prob = 1.1*max(prob_score_h + prob_score_a)\n\nplt.figure(figsize=(15,5))\nplt.subplot(1,2,1)\nplt.bar(range(max_goals), prob_score_h)\nplt.ylim([0, max_prob])\nplt.xlim([-1, max_goals])\nplt.title(team_h)\n\nplt.subplot(1,2,2)\nplt.bar(range(max_goals), prob_score_a)\nplt.ylim([0, max_prob])\nplt.xlim([-1, max_goals])\nplt.title(team_a);",
"MCI exp goals 2.2045828567041346\nMUN exp goals 1.0397137935432637\n"
],
[
"df = model_team.simulate_match(team_h, team_a)\nprint(df.quantile(0.25))\nprint(df.median())\nprint(df.quantile(0.75))",
"MCI 1.0\nMUN 0.0\nName: 0.25, dtype: float64\nMCI 2.0\nMUN 1.0\ndtype: float64\nMCI 3.0\nMUN 2.0\nName: 0.75, dtype: float64\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac3380d03ad524463cc521de3e854e82c85078e
| 55,156 |
ipynb
|
Jupyter Notebook
|
Day 56/dlnd_tv_script_generation.ipynb
|
vgaurav3011/100-Days-of-ML
|
ec302b03fd492c459cff2592b3a4f5e38f9c9d72
|
[
"MIT"
] | 12 |
2020-03-30T15:10:48.000Z
|
2021-11-08T06:04:01.000Z
|
Day 56/dlnd_tv_script_generation.ipynb
|
vgaurav3011/100-Days-of-ML
|
ec302b03fd492c459cff2592b3a4f5e38f9c9d72
|
[
"MIT"
] | 3 |
2021-06-08T22:34:58.000Z
|
2022-01-13T03:25:23.000Z
|
Day 55/dlnd_tv_script_generation.ipynb
|
vgaurav3011/100-Days-of-ML
|
ec302b03fd492c459cff2592b3a4f5e38f9c9d72
|
[
"MIT"
] | 3 |
2020-04-13T09:51:28.000Z
|
2021-04-28T07:37:36.000Z
| 38.760365 | 995 | 0.564925 |
[
[
[
"# TV Script Generation\n\nIn this project, you'll generate your own [Seinfeld](https://en.wikipedia.org/wiki/Seinfeld) TV scripts using RNNs. You'll be using part of the [Seinfeld dataset](https://www.kaggle.com/thec03u5/seinfeld-chronicles#scripts.csv) of scripts from 9 seasons. The Neural Network you'll build will generate a new ,\"fake\" TV script, based on patterns it recognizes in this training data.\n\n## Get the Data\n\nThe data is already provided for you in `./data/Seinfeld_Scripts.txt` and you're encouraged to open that file and look at the text. \n>* As a first step, we'll load in this data and look at some samples. \n* Then, you'll be tasked with defining and training an RNN to generate a new script!",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# load in data\nimport helper\ndata_dir = './data/Seinfeld_Scripts.txt'\ntext = helper.load_data(data_dir)",
"_____no_output_____"
]
],
[
[
"## Explore the Data\nPlay around with `view_line_range` to view different parts of the data. This will give you a sense of the data you'll be working with. You can see, for example, that it is all lowercase text, and each new line of dialogue is separated by a newline character `\\n`.",
"_____no_output_____"
]
],
[
[
"view_line_range = (0, 10)\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nimport numpy as np\n\nprint('Dataset Stats')\nprint('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))\n\nlines = text.split('\\n')\nprint('Number of lines: {}'.format(len(lines)))\nword_count_line = [len(line.split()) for line in lines]\nprint('Average number of words in each line: {}'.format(np.average(word_count_line)))\n\nprint()\nprint('The lines {} to {}:'.format(*view_line_range))\nprint('\\n'.join(text.split('\\n')[view_line_range[0]:view_line_range[1]]))",
"Dataset Stats\nRoughly the number of unique words: 46367\nNumber of lines: 109233\nAverage number of words in each line: 5.544240293684143\n\nThe lines 0 to 10:\njerry: do you know what this is all about? do you know, why were here? to be out, this is out...and out is one of the single most enjoyable experiences of life. people...did you ever hear people talking about we should go out? this is what theyre talking about...this whole thing, were all out now, no one is home. not one person here is home, were all out! there are people trying to find us, they dont know where we are. (on an imaginary phone) did you ring?, i cant find him. where did he go? he didnt tell me where he was going. he must have gone out. you wanna go out you get ready, you pick out the clothes, right? you take the shower, you get all ready, get the cash, get your friends, the car, the spot, the reservation...then youre standing around, what do you do? you go we gotta be getting back. once youre out, you wanna get back! you wanna go to sleep, you wanna get up, you wanna go out again tomorrow, right? where ever you are in life, its my feeling, youve gotta go. \n\njerry: (pointing at georges shirt) see, to me, that button is in the worst possible spot. the second button literally makes or breaks the shirt, look at it. its too high! its in no-mans-land. you look like you live with your mother. \n\ngeorge: are you through? \n\njerry: you do of course try on, when you buy? \n\ngeorge: yes, it was purple, i liked it, i dont actually recall considering the buttons. \n\n"
]
],
[
[
"---\n## Implement Pre-processing Functions\nThe first thing to do to any dataset is pre-processing. Implement the following pre-processing functions below:\n- Lookup Table\n- Tokenize Punctuation\n\n### Lookup Table\nTo create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:\n- Dictionary to go from the words to an id, we'll call `vocab_to_int`\n- Dictionary to go from the id to word, we'll call `int_to_vocab`\n\nReturn these dictionaries in the following **tuple** `(vocab_to_int, int_to_vocab)`",
"_____no_output_____"
]
],
[
[
"import problem_unittests as tests\nfrom collections import Counter\ndef create_lookup_tables(text):\n \"\"\"\n Create lookup tables for vocabulary\n :param text: The text of tv scripts split into words\n :return: A tuple of dicts (vocab_to_int, int_to_vocab)\n \"\"\"\n # TODO: Implement Function\n count = Counter(text)\n vocabulary = sorted(count, key=count.get, reverse=True)\n \n int_vocabulary = {i: word for i, word in enumerate(vocabulary)}\n vocabulary_int = {word: i for i, word in int_vocabulary.items()}\n # return tuple\n return (vocabulary_int, int_vocabulary)\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_create_lookup_tables(create_lookup_tables)",
"Tests Passed\n"
]
],
[
[
"### Tokenize Punctuation\nWe'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks can create multiple ids for the same word. For example, \"bye\" and \"bye!\" would generate two different word ids.\n\nImplement the function `token_lookup` to return a dict that will be used to tokenize symbols like \"!\" into \"||Exclamation_Mark||\". Create a dictionary for the following symbols where the symbol is the key and value is the token:\n- Period ( **.** )\n- Comma ( **,** )\n- Quotation Mark ( **\"** )\n- Semicolon ( **;** )\n- Exclamation mark ( **!** )\n- Question mark ( **?** )\n- Left Parentheses ( **(** )\n- Right Parentheses ( **)** )\n- Dash ( **-** )\n- Return ( **\\n** )\n\nThis dictionary will be used to tokenize the symbols and add the delimiter (space) around it. This separates each symbols as its own word, making it easier for the neural network to predict the next word. Make sure you don't use a value that could be confused as a word; for example, instead of using the value \"dash\", try using something like \"||dash||\".",
"_____no_output_____"
]
],
[
[
"def token_lookup():\n \"\"\"\n Generate a dict to turn punctuation into a token.\n :return: Tokenized dictionary where the key is the punctuation and the value is the token\n \"\"\"\n # TODO: Implement Function\n tokenfinder = dict()\n tokenfinder['.'] = '<PERIOD>'\n tokenfinder[','] = '<COMMA>'\n tokenfinder['\"'] = '<QUOTATION_MARK>'\n tokenfinder[';'] = '<SEMICOLON>'\n tokenfinder['!'] = '<EXCLAMATION_MARK>'\n tokenfinder['?'] = '<QUESTION_MARK>'\n tokenfinder['('] = '<LEFT_PAREN>'\n tokenfinder[')'] = '<RIGHT_PAREN>'\n tokenfinder['?'] = '<QUESTION_MARK>'\n tokenfinder['-'] = '<DASH>'\n tokenfinder['\\n'] = '<NEW_LINE>'\n return tokenfinder \n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_tokenize(token_lookup)",
"Tests Passed\n"
]
],
[
[
"## Pre-process all the data and save it\n\nRunning the code cell below will pre-process all the data and save it to file. You're encouraged to lok at the code for `preprocess_and_save_data` in the `helpers.py` file to see what it's doing in detail, but you do not need to change this code.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# pre-process training data\nhelper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)",
"_____no_output_____"
]
],
[
[
"# Check Point\nThis is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport helper\nimport problem_unittests as tests\n\nint_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()",
"_____no_output_____"
]
],
[
[
"## Build the Neural Network\nIn this section, you'll build the components necessary to build an RNN by implementing the RNN Module and forward and backpropagation functions.\n\n### Check Access to GPU",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport torch\n\n# Check for a GPU\ntrain_on_gpu = torch.cuda.is_available()\nif not train_on_gpu:\n print('No GPU found. Please use a GPU to train your neural network.')",
"_____no_output_____"
]
],
[
[
"## Input\nLet's start with the preprocessed input data. We'll use [TensorDataset](http://pytorch.org/docs/master/data.html#torch.utils.data.TensorDataset) to provide a known format to our dataset; in combination with [DataLoader](http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader), it will handle batching, shuffling, and other dataset iteration functions.\n\nYou can create data with TensorDataset by passing in feature and target tensors. Then create a DataLoader as usual.\n```\ndata = TensorDataset(feature_tensors, target_tensors)\ndata_loader = torch.utils.data.DataLoader(data, \n batch_size=batch_size)\n```\n\n### Batching\nImplement the `batch_data` function to batch `words` data into chunks of size `batch_size` using the `TensorDataset` and `DataLoader` classes.\n\n>You can batch words using the DataLoader, but it will be up to you to create `feature_tensors` and `target_tensors` of the correct size and content for a given `sequence_length`.\n\nFor example, say we have these as input:\n```\nwords = [1, 2, 3, 4, 5, 6, 7]\nsequence_length = 4\n```\n\nYour first `feature_tensor` should contain the values:\n```\n[1, 2, 3, 4]\n```\nAnd the corresponding `target_tensor` should just be the next \"word\"/tokenized word value:\n```\n5\n```\nThis should continue with the second `feature_tensor`, `target_tensor` being:\n```\n[2, 3, 4, 5] # features\n6 # target\n```",
"_____no_output_____"
]
],
[
[
"from torch.utils.data import TensorDataset, DataLoader\n\n\ndef batch_data(words, sequence_length, batch_size):\n \"\"\"\n Batch the neural network data using DataLoader\n :param words: The word ids of the TV scripts\n :param sequence_length: The sequence length of each batch\n :param batch_size: The size of each batch; the number of sequences in a batch\n :return: DataLoader with batched data\n \"\"\"\n # TODO: Implement function\n \n n_batches = len(words)//batch_size\n # number of words in a batch\n words = words[:n_batches*batch_size]\n # length of output\n y_len = len(words) - sequence_length\n # empty lists for sequences\n x, y = [], []\n for i in range(0, y_len):\n i_end = sequence_length + i\n x_batch = words[i:i_end]\n x.append(x_batch)\n batch_y = words[i_end] \n y.append(batch_y) \n\n data = TensorDataset(torch.from_numpy(np.asarray(x)), torch.from_numpy(np.asarray(y)))\n data_loader = DataLoader(data, shuffle=False, batch_size=batch_size)\n # return a dataloader\n return data_loader \n\n# there is no test for this function, but you are encouraged to create\n# print statements and tests of your own\n",
"_____no_output_____"
]
],
[
[
"### Test your dataloader \n\nYou'll have to modify this code to test a batching function, but it should look fairly similar.\n\nBelow, we're generating some test text data and defining a dataloader using the function you defined, above. Then, we are getting some sample batch of inputs `sample_x` and targets `sample_y` from our dataloader.\n\nYour code should return something like the following (likely in a different order, if you shuffled your data):\n\n```\ntorch.Size([10, 5])\ntensor([[ 28, 29, 30, 31, 32],\n [ 21, 22, 23, 24, 25],\n [ 17, 18, 19, 20, 21],\n [ 34, 35, 36, 37, 38],\n [ 11, 12, 13, 14, 15],\n [ 23, 24, 25, 26, 27],\n [ 6, 7, 8, 9, 10],\n [ 38, 39, 40, 41, 42],\n [ 25, 26, 27, 28, 29],\n [ 7, 8, 9, 10, 11]])\n\ntorch.Size([10])\ntensor([ 33, 26, 22, 39, 16, 28, 11, 43, 30, 12])\n```\n\n### Sizes\nYour sample_x should be of size `(batch_size, sequence_length)` or (10, 5) in this case and sample_y should just have one dimension: batch_size (10). \n\n### Values\n\nYou should also notice that the targets, sample_y, are the *next* value in the ordered test_text data. So, for an input sequence `[ 28, 29, 30, 31, 32]` that ends with the value `32`, the corresponding output should be `33`.",
"_____no_output_____"
]
],
[
[
"# test dataloader\n\ntest_text = range(50)\nt_loader = batch_data(test_text, sequence_length=5, batch_size=10)\n\ndata_iter = iter(t_loader)\nsample_x, sample_y = data_iter.next()\n\nprint(sample_x.shape)\nprint(sample_x)\nprint()\nprint(sample_y.shape)\nprint(sample_y)",
"torch.Size([10, 5])\ntensor([[ 0, 1, 2, 3, 4],\n [ 1, 2, 3, 4, 5],\n [ 2, 3, 4, 5, 6],\n [ 3, 4, 5, 6, 7],\n [ 4, 5, 6, 7, 8],\n [ 5, 6, 7, 8, 9],\n [ 6, 7, 8, 9, 10],\n [ 7, 8, 9, 10, 11],\n [ 8, 9, 10, 11, 12],\n [ 9, 10, 11, 12, 13]])\n\ntorch.Size([10])\ntensor([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])\n"
]
],
[
[
"---\n## Build the Neural Network\nImplement an RNN using PyTorch's [Module class](http://pytorch.org/docs/master/nn.html#torch.nn.Module). You may choose to use a GRU or an LSTM. To complete the RNN, you'll have to implement the following functions for the class:\n - `__init__` - The initialize function. \n - `init_hidden` - The initialization function for an LSTM/GRU hidden state\n - `forward` - Forward propagation function.\n \nThe initialize function should create the layers of the neural network and save them to the class. The forward propagation function will use these layers to run forward propagation and generate an output and a hidden state.\n\n**The output of this model should be the *last* batch of word scores** after a complete sequence has been processed. That is, for each input sequence of words, we only want to output the word scores for a single, most likely, next word.\n\n### Hints\n\n1. Make sure to stack the outputs of the lstm to pass to your fully-connected layer, you can do this with `lstm_output = lstm_output.contiguous().view(-1, self.hidden_dim)`\n2. You can get the last batch of word scores by shaping the output of the final, fully-connected layer like so:\n\n```\n# reshape into (batch_size, seq_length, output_size)\noutput = output.view(batch_size, -1, self.output_size)\n# get last batch\nout = output[:, -1]\n```",
"_____no_output_____"
]
],
[
[
"import torch.nn as nn\n\nclass RNN(nn.Module):\n \n def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):\n \"\"\"\n Initialize the PyTorch RNN Module\n :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary)\n :param output_size: The number of output dimensions of the neural network\n :param embedding_dim: The size of embeddings, should you choose to use them \n :param hidden_dim: The size of the hidden layer outputs\n :param dropout: dropout to add in between LSTM/GRU layers\n \"\"\"\n super(RNN, self).__init__()\n # TODO: Implement function\n self.embed = nn.Embedding(vocab_size, embedding_dim)\n # set class variables\n self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=dropout, batch_first=True)\n self.output_size = output_size\n self.n_layers = n_layers\n self.hidden_dim = hidden_dim\n # define model layers\n self.fc = nn.Linear(hidden_dim, output_size)\n \n def forward(self, nn_input, hidden):\n \"\"\"\n Forward propagation of the neural network\n :param nn_input: The input to the neural network\n :param hidden: The hidden state \n :return: Two Tensors, the output of the neural network and the latest hidden state\n \"\"\"\n # TODO: Implement function \n batch_size = nn_input.size(0)\n \n embedding = self.embed(nn_input)\n lstm_output, hidden = self.lstm(embedding, hidden)\n # return one batch of output word scores and the hidden state\n out = self.fc(lstm_output)\n out = out.view(batch_size, -1, self.output_size)\n out = out[:, -1]\n return out, hidden\n \n \n def init_hidden(self, batch_size):\n '''\n Initialize the hidden state of an LSTM/GRU\n :param batch_size: The batch_size of the hidden state\n :return: hidden state of dims (n_layers, batch_size, hidden_dim)\n '''\n # Implement function\n weight = next(self.parameters()).data\n \n \n if (train_on_gpu):\n hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda(),\n weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda())\n else:\n hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_(),\n weight.new(self.n_layers, batch_size, self.hidden_dim).zero_())\n \n return hidden\n # initialize hidden state with zero weights, and move to GPU if available\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_rnn(RNN, train_on_gpu)",
"Tests Passed\n"
]
],
[
[
"### Define forward and backpropagation\n\nUse the RNN class you implemented to apply forward and back propagation. This function will be called, iteratively, in the training loop as follows:\n```\nloss = forward_back_prop(decoder, decoder_optimizer, criterion, inp, target)\n```\n\nAnd it should return the average loss over a batch and the hidden state returned by a call to `RNN(inp, hidden)`. Recall that you can get this loss by computing it, as usual, and calling `loss.item()`.\n\n**If a GPU is available, you should move your data to that GPU device, here.**",
"_____no_output_____"
]
],
[
[
"def forward_back_prop(rnn, optimizer, criterion, inp, target, hidden):\n \"\"\"\n Forward and backward propagation on the neural network\n :param decoder: The PyTorch Module that holds the neural network\n :param decoder_optimizer: The PyTorch optimizer for the neural network\n :param criterion: The PyTorch loss function\n :param inp: A batch of input to the neural network\n :param target: The target output for the batch of input\n :return: The loss and the latest hidden state Tensor\n \"\"\"\n \n # TODO: Implement Function\n if(train_on_gpu):\n rnn.cuda()\n # move data to GPU, if available\n h1 = tuple([each.data for each in hidden])\n rnn.zero_grad()\n # perform backpropagation and optimization\n if(train_on_gpu):\n inputs, target = inp.cuda(), target.cuda()\n \n output, h = rnn(inputs, h1)\n loss = criterion(output, target)\n loss.backward()\n nn.utils.clip_grad_norm(rnn.parameters(), 5)\n optimizer.step()\n # return the loss over a batch and the hidden state produced by our model\n return loss.item(), h1\n\n# Note that these tests aren't completely extensive.\n# they are here to act as general checks on the expected outputs of your functions\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_forward_back_prop(RNN, forward_back_prop, train_on_gpu)",
"Tests Passed\n"
]
],
[
[
"## Neural Network Training\n\nWith the structure of the network complete and data ready to be fed in the neural network, it's time to train it.\n\n### Train Loop\n\nThe training loop is implemented for you in the `train_decoder` function. This function will train the network over all the batches for the number of epochs given. The model progress will be shown every number of batches. This number is set with the `show_every_n_batches` parameter. You'll set this parameter along with other parameters in the next section.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n\ndef train_rnn(rnn, batch_size, optimizer, criterion, n_epochs, show_every_n_batches=100):\n batch_losses = []\n \n rnn.train()\n\n print(\"Training for %d epoch(s)...\" % n_epochs)\n for epoch_i in range(1, n_epochs + 1):\n \n # initialize hidden state\n hidden = rnn.init_hidden(batch_size)\n \n for batch_i, (inputs, labels) in enumerate(train_loader, 1):\n \n # make sure you iterate over completely full batches, only\n n_batches = len(train_loader.dataset)//batch_size\n if(batch_i > n_batches):\n break\n \n # forward, back prop\n loss, hidden = forward_back_prop(rnn, optimizer, criterion, inputs, labels, hidden) \n # record loss\n batch_losses.append(loss)\n\n # printing loss stats\n if batch_i % show_every_n_batches == 0:\n print('Epoch: {:>4}/{:<4} Loss: {}\\n'.format(\n epoch_i, n_epochs, np.average(batch_losses)))\n batch_losses = []\n\n # returns a trained rnn\n return rnn",
"_____no_output_____"
]
],
[
[
"### Hyperparameters\n\nSet and train the neural network with the following parameters:\n- Set `sequence_length` to the length of a sequence.\n- Set `batch_size` to the batch size.\n- Set `num_epochs` to the number of epochs to train for.\n- Set `learning_rate` to the learning rate for an Adam optimizer.\n- Set `vocab_size` to the number of uniqe tokens in our vocabulary.\n- Set `output_size` to the desired size of the output.\n- Set `embedding_dim` to the embedding dimension; smaller than the vocab_size.\n- Set `hidden_dim` to the hidden dimension of your RNN.\n- Set `n_layers` to the number of layers/cells in your RNN.\n- Set `show_every_n_batches` to the number of batches at which the neural network should print progress.\n\nIf the network isn't getting the desired results, tweak these parameters and/or the layers in the `RNN` class.",
"_____no_output_____"
]
],
[
[
"# Data params\n# Sequence Length\nsequence_length = 5 # of words in a sequence\n# Batch Size\nbatch_size = 128\n\n# data loader - do not change\ntrain_loader = batch_data(int_text, sequence_length, batch_size)",
"_____no_output_____"
],
[
"# Training parameters\n# Number of Epochs\nnum_epochs = 10\n# Learning Rate\nlearning_rate = 0.001 \n\n# Model parameters\n# Vocab size\nvocab_size = len(vocab_to_int)\n# Output size\noutput_size = vocab_size\n# Embedding Dimension\nembedding_dim = 200\n# Hidden Dimension\nhidden_dim = 250\n# Number of RNN Layers\nn_layers = 2\n\n# Show stats for every n number of batches\nshow_every_n_batches = 500",
"_____no_output_____"
]
],
[
[
"### Train\nIn the next cell, you'll train the neural network on the pre-processed data. If you have a hard time getting a good loss, you may consider changing your hyperparameters. In general, you may get better results with larger hidden and n_layer dimensions, but larger models take a longer time to train. \n> **You should aim for a loss less than 3.5.** \n\nYou should also experiment with different sequence lengths, which determine the size of the long range dependencies that a model can learn.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n\n# create model and move to gpu if available\nrnn = RNN(vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5)\nif train_on_gpu:\n rnn.cuda()\n\n# defining loss and optimization functions for training\noptimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate)\ncriterion = nn.CrossEntropyLoss()\n\n# training the model\ntrained_rnn = train_rnn(rnn, batch_size, optimizer, criterion, num_epochs, show_every_n_batches)\n\n# saving the trained model\nhelper.save_model('./save/trained_rnn', trained_rnn)\nprint('Model Trained and Saved')",
"Training for 10 epoch(s)...\n"
]
],
[
[
"### Question: How did you decide on your model hyperparameters? \nFor example, did you try different sequence_lengths and find that one size made the model converge faster? What about your hidden_dim and n_layers; how did you decide on those?",
"_____no_output_____"
],
[
"**Answer:** \n- I experimented with the hyperparameters and observed different scenarios. Learning from the content, the dimensions for the typical layers were given from 100-300. For exact tuning, I referred to the blog:\nhttps://towardsdatascience.com/choosing-the-right-hyperparameters-for-a-simple-lstm-using-keras-f8e9ed76f046\n\n- I particularly loved this post: https://blog.floydhub.com/guide-to-hyperparameters-search-for-deep-learning-models/\n\n- It was about hyperparameter in general but its emphasis on preventing any overfitting or underfitting in the model was great. I tried a learning rate of 0.01 initially however turned out the loss saturated just after 4 epochs and my best understanding of the situation was that the model was jumping quite quickly in the gradient descent and thus these large jumps were at cost of missing many features that hold significance for predicting patterns.\n- A learning rate of 0.0001 became too low and the model was converging slowly but provided that we had to wait more patiently for the loss to minimize. I tried with sequence length of 25 initially and the loss was high nearly starting from 11 and coming towars 7 to maximum of 6.2. So, my understanding was that we need to have lesser number of sequences to identify patterns more accurately as the model seemed in a hurry to predict it and led to huge loss values.\n\n- So, I tried with 15, 20 and 10 sequence lengths and everytime the loss decreased so finally I decided to keep it minimal enough and took 5 so that atleast we can identify patterns more correctly than rushing to a large value and spoiling the aim of the training. The sequence length of 10 noted good patterns too with loss minimizing upto 3.7. \n\n- With 250 hidden layers, I do not think that there was a problem in minimizing loss due to less number of layers for processing the sequence. Ofcourse, the idea of a cyclic learning rate can be used to further minimize the loss by making use of optimized learning rate at the correct timing.\n\n- Finally with a learning rate of 0.001 and 5 sequences with batch size of 128 I was able to minimize the loss below 3.5! Also, batch size also affects the training process with larger batch sizes accelerating the time of training but at the cost of loss and too small batch size took huge training time! If used less than 128, the model was converging at only a little better loss and hence, as a tradeoff 128 did not seem to be a bad batch size for training but I do recommend 64 too!",
"_____no_output_____"
],
[
"---\n# Checkpoint\n\nAfter running the above training cell, your model will be saved by name, `trained_rnn`, and if you save your notebook progress, **you can pause here and come back to this code at another time**. You can resume your progress by running the next cell, which will load in our word:id dictionaries _and_ load in your saved model by name!",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport torch\nimport helper\nimport problem_unittests as tests\n\n_, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()\ntrained_rnn = helper.load_model('./save/trained_rnn')",
"_____no_output_____"
]
],
[
[
"## Generate TV Script\nWith the network trained and saved, you'll use it to generate a new, \"fake\" Seinfeld TV script in this section.\n\n### Generate Text\nTo generate the text, the network needs to start with a single word and repeat its predictions until it reaches a set length. You'll be using the `generate` function to do this. It takes a word id to start with, `prime_id`, and generates a set length of text, `predict_len`. Also note that it uses topk sampling to introduce some randomness in choosing the most likely next word, given an output set of word scores!",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nimport torch.nn.functional as F\n\ndef generate(rnn, prime_id, int_to_vocab, token_dict, pad_value, predict_len=100):\n \"\"\"\n Generate text using the neural network\n :param decoder: The PyTorch Module that holds the trained neural network\n :param prime_id: The word id to start the first prediction\n :param int_to_vocab: Dict of word id keys to word values\n :param token_dict: Dict of puncuation tokens keys to puncuation values\n :param pad_value: The value used to pad a sequence\n :param predict_len: The length of text to generate\n :return: The generated text\n \"\"\"\n rnn.eval()\n \n # create a sequence (batch_size=1) with the prime_id\n current_seq = np.full((1, sequence_length), pad_value)\n current_seq[-1][-1] = prime_id\n predicted = [int_to_vocab[prime_id]]\n \n for _ in range(predict_len):\n if train_on_gpu:\n current_seq = torch.LongTensor(current_seq).cuda()\n else:\n current_seq = torch.LongTensor(current_seq)\n \n # initialize the hidden state\n hidden = rnn.init_hidden(current_seq.size(0))\n \n # get the output of the rnn\n output, _ = rnn(current_seq, hidden)\n \n # get the next word probabilities\n p = F.softmax(output, dim=1).data\n if(train_on_gpu):\n p = p.cpu() # move to cpu\n \n # use top_k sampling to get the index of the next word\n top_k = 5\n p, top_i = p.topk(top_k)\n top_i = top_i.numpy().squeeze()\n \n # select the likely next word index with some element of randomness\n p = p.numpy().squeeze()\n word_i = np.random.choice(top_i, p=p/p.sum())\n \n # retrieve that word from the dictionary\n word = int_to_vocab[word_i]\n predicted.append(word) \n \n # the generated word becomes the next \"current sequence\" and the cycle can continue\n current_seq = np.roll(current_seq, -1, 1)\n current_seq[-1][-1] = word_i\n \n gen_sentences = ' '.join(predicted)\n \n # Replace punctuation tokens\n for key, token in token_dict.items():\n ending = ' ' if key in ['\\n', '(', '\"'] else ''\n gen_sentences = gen_sentences.replace(' ' + token.lower(), key)\n gen_sentences = gen_sentences.replace('\\n ', '\\n')\n gen_sentences = gen_sentences.replace('( ', '(')\n \n # return all the sentences\n return gen_sentences",
"_____no_output_____"
]
],
[
[
"### Generate a New Script\nIt's time to generate the text. Set `gen_length` to the length of TV script you want to generate and set `prime_word` to one of the following to start the prediction:\n- \"jerry\"\n- \"elaine\"\n- \"george\"\n- \"kramer\"\n\nYou can set the prime word to _any word_ in our dictionary, but it's best to start with a name for generating a TV script. (You can also start with any other names you find in the original text file!)",
"_____no_output_____"
]
],
[
[
"# run the cell multiple times to get different results!\ngen_length = 400 # modify the length to your preference\nprime_word = 'jerry' # name for starting the script\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\npad_word = helper.SPECIAL_WORDS['PADDING']\ngenerated_script = generate(trained_rnn, vocab_to_int[prime_word + ':'], int_to_vocab, token_dict, vocab_to_int[pad_word], gen_length)\nprint(generated_script)",
"/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:36: UserWarning: RNN module weights are not part of single contiguous chunk of memory. This means they need to be compacted at every call, possibly greatly increasing memory usage. To compact weights again call flatten_parameters().\n"
]
],
[
[
"#### Save your favorite scripts\n\nOnce you have a script that you like (or find interesting), save it to a text file!",
"_____no_output_____"
]
],
[
[
"# save script to a text file\nf = open(\"generated_script_1.txt\",\"w\")\nf.write(generated_script)\nf.close()",
"_____no_output_____"
]
],
[
[
"# The TV Script is Not Perfect\nIt's ok if the TV script doesn't make perfect sense. It should look like alternating lines of dialogue, here is one such example of a few generated lines.\n\n### Example generated script\n\n>jerry: what about me?\n>\n>jerry: i don't have to wait.\n>\n>kramer:(to the sales table)\n>\n>elaine:(to jerry) hey, look at this, i'm a good doctor.\n>\n>newman:(to elaine) you think i have no idea of this...\n>\n>elaine: oh, you better take the phone, and he was a little nervous.\n>\n>kramer:(to the phone) hey, hey, jerry, i don't want to be a little bit.(to kramer and jerry) you can't.\n>\n>jerry: oh, yeah. i don't even know, i know.\n>\n>jerry:(to the phone) oh, i know.\n>\n>kramer:(laughing) you know...(to jerry) you don't know.\n\nYou can see that there are multiple characters that say (somewhat) complete sentences, but it doesn't have to be perfect! It takes quite a while to get good results, and often, you'll have to use a smaller vocabulary (and discard uncommon words), or get more data. The Seinfeld dataset is about 3.4 MB, which is big enough for our purposes; for script generation you'll want more than 1 MB of text, generally. \n\n# Submitting This Project\nWhen submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as \"dlnd_tv_script_generation.ipynb\" and save another copy as an HTML file by clicking \"File\" -> \"Download as..\"->\"html\". Include the \"helper.py\" and \"problem_unittests.py\" files in your submission. Once you download these files, compress them into one zip file for submission.",
"_____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"
],
[
"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"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4ac344afa1ac52393883384c2a04d0c8638b7d62
| 28,197 |
ipynb
|
Jupyter Notebook
|
validate/pointjet/pointjet.ipynb
|
gvn22/ZonalFlow.jl
|
3ebfdd1d172f97321df13781239da28597137361
|
[
"MIT"
] | 3 |
2021-03-26T10:51:38.000Z
|
2022-02-10T03:36:34.000Z
|
validate/pointjet/pointjet.ipynb
|
gvn22/ZonalFlow.jl
|
3ebfdd1d172f97321df13781239da28597137361
|
[
"MIT"
] | 17 |
2020-10-27T12:11:31.000Z
|
2021-10-19T14:54:44.000Z
|
validate/pointjet/pointjet.ipynb
|
gvn22/ZonalFlow.jl
|
3ebfdd1d172f97321df13781239da28597137361
|
[
"MIT"
] | 1 |
2021-04-10T12:18:54.000Z
|
2021-04-10T12:18:54.000Z
| 30.715686 | 188 | 0.488137 |
[
[
[
"# Deterministic point jet",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport pandas as pd\n\nimport numpy as np\nimport matplotlib.pylab as pl",
"_____no_output_____"
]
],
[
[
"\\begin{equation}\n \\partial_t \\zeta = \\frac{\\zeta_{jet}}{\\tau} - \\mu \\zeta + \\nu_\\alpha \\nabla^{2\\alpha} - \\beta \\partial_x \\psi - J(\\psi, \\zeta) \\zeta\n\\end{equation}",
"_____no_output_____"
],
[
"Here $\\zeta_{jet}$ is the profile of a prescribed jet and $\\tau = 1/\\mu$ is the relaxation time. Also $\\beta = 2\\Omega cos \\theta$ and $\\theta = 0$ corresponds to the equator.",
"_____no_output_____"
],
[
"Parameters\n\n> $\\Omega = 2\\pi$\n\n> $\\mu = 0.05$\n\n> $\\nu = 0$\n\n> $\\nu_4 = 0$\n\n> $\\Xi = 1.0$\n\n> $\\Delta \\theta = 0.1$\n\n> $\\tau$ = 20 days",
"_____no_output_____"
]
],
[
[
"dn = \"pointjet/8x8/\"",
"_____no_output_____"
],
[
"# Parameters: μ = 0.05, τ = 20.0, Ξ = 1.0*Ω and Δθ = 0.1\nM = 8\nN = 8\n\ncolors = pl.cm.nipy_spectral(np.linspace(0,1,M))",
"_____no_output_____"
]
],
[
[
"## NL v GQL v GCE2",
"_____no_output_____"
]
],
[
[
"nl = np.load(dn+\"nl.npz\",allow_pickle=True) \ngql = np.load(dn+\"gql.npz\",allow_pickle=True) \ngce2 = np.load(dn+\"gce2.npz\",allow_pickle=True) ",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,2,figsize=(14,5))\n \n# # Energy\n# ax[0].plot(nl['t'],nl['Etav'],label=r'$\\langle NL \\rangle$')\n# ax[0].plot(gql['t'],gql['Etav'],label=r'$\\langle GQL(M) \\rangle$')\n# ax[0].plot(gce2['t'],gce2['Etav'],label=r'$\\langle GCE2(M) \\rangle$')\n\n# ax[0].set_xlabel(r'$t$',fontsize=14)\n# ax[0].set_ylabel(r'$E$',fontsize=14)\n# # ax[0].legend(bbox_to_anchor=(1.01,0.85),fontsize=14)\n\n# # Enstrophy\n# ax[1].plot(nl['t'],nl['Ztav'],label=r'$\\langle NL \\rangle$')\n# ax[1].plot(gql['t'],gql['Ztav'],label=r'$\\langle GQL(M) \\rangle$')\n# ax[1].plot(gce2['t'],gce2['Ztav'],label=r'$\\langle GCE2(M) \\rangle$')\n\n\n# ax[1].set_xlabel(r'$t$',fontsize=14)\n# ax[1].set_ylabel(r'$Z$',fontsize=14)\n# ax[1].legend(loc=4,fontsize=14)\n\n# plt.show()",
"_____no_output_____"
],
[
"fig,ax = plt.subplots(1,3,figsize=(14,5))\n\nax[0].set_title(f'NL')\nfor i,x in enumerate(nl['Emt'].T): \n ax[0].plot(nl['t'],x,label=i,c=colors[i])\n\nax[1].set_title(f'GQL(M)')\nfor i,x in enumerate(gql['Emt'].T):\n ax[1].plot(gql['t'],x,label=i,c=colors[i])\n\nax[2].set_title(f'GCE2(M)')\nfor i,x in enumerate(gce2['Emt'].T):\n ax[2].plot(gce2['t'],x,label=i,c=colors[i])\n\nfor a in ax:\n \n a.set_xlabel(r'$t$',fontsize=14)\n a.set_yscale('log')\n a.set_ylim(1e-12,1e2)\n\nax[0].set_ylabel(r'$E(m)$',fontsize=14)\nax[2].legend(bbox_to_anchor=(1.01,0.85),ncol=1)\n\nplt.show()",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,3,figsize=(16,4))\n\n# im = ax[0].imshow((nl['Vxy'][:,:,0]),interpolation=\"bicubic\",cmap=\"RdBu_r\",origin=\"lower\")\n# fig.colorbar(im, ax=ax[0])\n# ax[0].set_title(r'NL: $\\zeta(x,y,t = 0 )$',fontsize=14)\n\n# im = ax[1].imshow((gql['Vxy'][:,:,0]),interpolation=\"bicubic\",cmap=\"RdBu_r\",origin=\"lower\")\n# fig.colorbar(im, ax=ax[1])\n# ax[1].set_title(r'GQL: $\\zeta(x,y,t = 0 )$',fontsize=14)\n\n# im = ax[2].imshow((gce2['Vxy'][:,:,0]),interpolation=\"bicubic\",cmap=\"RdBu_r\",origin=\"lower\")\n# fig.colorbar(im, ax=ax[2])\n# ax[2].set_title(r'GCE2:$\\zeta(x,y,t = 0 )$',fontsize=14)\n\n# for a in ax:\n# a.set_xticks([0,M-1,2*M-2])\n# a.set_xticklabels([r'$0$',r'$\\pi$',r'$2\\pi$'],fontsize=14)\n# a.set_yticks([0,M-1,2*M-2])\n# a.set_yticklabels([r'$0$',r'$\\pi$',r'$2\\pi$'],fontsize=14)\n\n\n# plt.show()",
"_____no_output_____"
],
[
"fig,ax = plt.subplots(1,3,figsize=(16,4))\n\nim = ax[0].imshow((nl['Vxy'][:,:,-1]),interpolation=\"bicubic\",cmap=\"RdBu_r\",origin=\"lower\")\nfig.colorbar(im, ax=ax[0])\nax[0].set_title(r'NL: $\\zeta(x,y,t = 0 )$',fontsize=14)\n\nim = ax[1].imshow((gql['Vxy'][:,:,-1]),interpolation=\"bicubic\",cmap=\"RdBu_r\",origin=\"lower\")\nfig.colorbar(im, ax=ax[1])\nax[1].set_title(r'GQL: $\\zeta(x,y,t = 0 )$',fontsize=14)\n\nim = ax[2].imshow((gce2['Vxy'][:,:,-1]),interpolation=\"bicubic\",cmap=\"RdBu_r\",origin=\"lower\")\nfig.colorbar(im, ax=ax[2])\nax[2].set_title(r'GCE2:$\\zeta(x,y,t = 0 )$',fontsize=14)\n\nfor a in ax:\n \n a.set_xticks([0,M-1,2*M-2])\n a.set_xticklabels([r'$0$',r'$\\pi$',r'$2\\pi$'],fontsize=14)\n a.set_yticks([0,M-1,2*M-2])\n a.set_yticklabels([r'$0$',r'$\\pi$',r'$2\\pi$'],fontsize=14)\n\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"## QL v CE2 v GCE2(0)",
"_____no_output_____"
]
],
[
[
"ql = np.load(dn+\"ql.npz\",allow_pickle=True) \nce2 = np.load(dn+\"ce2.npz\",allow_pickle=True)\ngce2 = np.load(dn+\"gce2_0.npz\",allow_pickle=True)",
"_____no_output_____"
],
[
"fig,ax = plt.subplots(1,3,figsize=(18,5))\n \n# Energy\nax[0].set_title(f'QL',fontsize=14)\nfor i,x in enumerate(ql['Emtav'].T):\n ax[0].plot(ql['t'],x,label=i,c=colors[i])\n\nax[1].set_title(f'CE2',fontsize=14)\nfor i,x in enumerate(ce2['Emtav'].T):\n ax[1].plot(ce2['t'],x,label=i,c=colors[i])\n\nax[2].set_title(f'GCE2(0)',fontsize=14)\nfor i,x in enumerate(gce2['Emtav'].T):\n ax[2].plot(gce2['t'],x,label=i,c=colors[i])\n\nax[2].legend(bbox_to_anchor=(1.01,0.5),ncol=1)\n\n\nfor a in ax:\n a.set_xlabel(r'$t$',fontsize=14)\n a.set_ylabel(r'$E$',fontsize=14)\n a.set_yscale('log')\n a.set_ylim(1e-12,1e2)\n \n\n# plt.show()\n# plt.savefig(dn+\"ze_tau20_qlce2gce2_0.png\",bbox_inches='tight',)",
"_____no_output_____"
]
],
[
[
"## GQL(1) v GCE2(1)",
"_____no_output_____"
]
],
[
[
"gql = np.load(dn+\"gql_1.npz\",allow_pickle=True) \ngce2 = np.load(dn+\"gce2_1.npz\",allow_pickle=True) ",
"_____no_output_____"
],
[
"fig,ax = plt.subplots(1,2,figsize=(14,5))\n \n# Energy\nax[0].set_title(f'GQL(1)',fontsize=14)\nfor i,x in enumerate(gql['Emtav'].T):\n ax[0].plot(gql['t'],x,label=i,c=colors[i])\n\nax[1].set_title(f'GCE2(1)',fontsize=14)\nfor i,x in enumerate(gce2['Emtav'].T):\n ax[1].plot(gce2['t'],x,label=i,c=colors[i])\n\nfor a in ax:\n a.set_xlabel(r'$t$',fontsize=14)\n a.set_ylabel(r'$E$',fontsize=14)\n a.set_yscale('log')\n# a.set_ylim(1e-1,1e0)\nax[1].legend(bbox_to_anchor=(1.01,0.85),fontsize=14)\n\nplt.show()",
"_____no_output_____"
],
[
"fig,ax = plt.subplots(1,2,figsize=(15,6))\n\nax[0].set_title(f'GQL(1)',fontsize=14)\nim = ax[0].imshow((gql['Vxy'][:,:,-1]),cmap=\"RdBu_r\",origin=\"lower\",interpolation=\"bicubic\")\nfig.colorbar(im,ax=ax[0])\n\nax[1].set_title(f'GCE2(1)',fontsize=14)\nim = ax[1].imshow((gce2['Vxy'][:,:,-1]),cmap=\"RdBu_r\",origin=\"lower\",interpolation=\"bicubic\")\nfig.colorbar(im,ax=ax[1])\n\nfor a in ax:\n a.set_xticks([0,M-1,2*M-2])\n a.set_xticklabels([r'$0$',r'$\\pi$',r'$2\\pi$'],fontsize=14)\n a.set_yticks([0,M-1,2*M-2])\n a.set_yticklabels([r'$0$',r'$\\pi$',r'$2\\pi$'],fontsize=14)\n\nplt.show()",
"_____no_output_____"
],
[
"fig,ax = plt.subplots(1,2,figsize=(12,6))\n\nax[0].set_title('GQL(1)')\nim = ax[0].imshow((gql['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im)\n\nax[1].set_title('GCE2(1)')\nim = ax[1].imshow((gce2['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im)\n\nfor a in ax:\n a.set_xticks([0,M-1,2*M-2])\n a.set_xticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)\n a.set_yticks([0,M-1,2*M-2])\n a.set_yticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)\n\nplt.show()",
"_____no_output_____"
],
[
"gql = np.load(dn+\"gql_3.npz\",allow_pickle=True) \ngce2 = np.load(dn+\"gce2_3.npz\",allow_pickle=True) ",
"_____no_output_____"
],
[
"fig,ax = plt.subplots(1,2,figsize=(14,5))\n \n# Energy\nax[0].set_title(f'GQL(3)',fontsize=14)\nfor i,x in enumerate(gql['Emtav'].T):\n ax[0].plot(gql['t'],x,label=i,c=colors[i])\n\nax[1].set_title(f'GCE2(3)',fontsize=14)\nfor i,x in enumerate(gce2['Emtav'].T):\n ax[1].plot(gce2['t'],x,label=i,c=colors[i])\n\nfor a in ax:\n a.set_xlabel(r'$t$',fontsize=14)\n a.set_ylabel(r'$E$',fontsize=14)\n a.set_yscale('log')\n# a.set_ylim(1e-1,1e0)\n\nax[1].legend(bbox_to_anchor=(1.01,0.85),fontsize=14)\n\nplt.show()",
"_____no_output_____"
],
[
"fig,ax = plt.subplots(1,2,figsize=(15,6))\n\nax[0].set_title(f'GQL(3)',fontsize=14)\nim = ax[0].imshow((gql['Vxy'][:,:,-1]),cmap=\"RdBu_r\",origin=\"lower\",interpolation=\"bicubic\")\nfig.colorbar(im,ax=ax[0])\n\nax[1].set_title(f'GCE2(3)',fontsize=14)\nim = ax[1].imshow((gce2['Vxy'][:,:,-1]),cmap=\"RdBu_r\",origin=\"lower\",interpolation=\"bicubic\")\nfig.colorbar(im,ax=ax[1])\n\nfor a in ax:\n a.set_xticks([0,M-1,2*M-2])\n a.set_xticklabels([r'$0$',r'$\\pi$',r'$2\\pi$'],fontsize=14)\n a.set_yticks([0,M-1,2*M-2])\n a.set_yticklabels([r'$0$',r'$\\pi$',r'$2\\pi$'],fontsize=14)\n\nplt.show()",
"_____no_output_____"
],
[
"fig,ax = plt.subplots(1,2,figsize=(12,6))\n\nax[0].set_title('GQL(3)')\nim = ax[0].imshow((gql['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im)\n\nax[1].set_title('GCE2(3)')\nim = ax[1].imshow((gce2['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im)\n\nfor a in ax:\n a.set_xticks([0,M-1,2*M-2])\n a.set_xticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)\n a.set_yticks([0,M-1,2*M-2])\n a.set_yticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)\n\nplt.show()",
"_____no_output_____"
],
[
"# gql = np.load(dn+\"gql_5.npz\",allow_pickle=True) \n# gce2 = np.load(dn+\"gce2_5.npz\",allow_pickle=True) ",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,2,figsize=(14,5))\n \n# # Energy\n# ax[0].set_title(f'GQL(5)',fontsize=14)\n# for i,x in enumerate(gql['Emtav'].T):\n# ax[0].plot(gql['t'],x,label=i,c=colors[i])\n\n# ax[1].set_title(f'GCE2(5)',fontsize=14)\n# for i,x in enumerate(gce2['Emtav'].T):\n# ax[1].plot(gce2['t'],x,c=colors[i])\n\n# for a in ax:\n# a.set_xlabel(r'$t$',fontsize=14)\n# a.set_ylabel(r'$E$',fontsize=14)\n# a.set_yscale('log')\n# # a.set_ylim(1e-1,1e0)\n# # ax[1].legend(bbox_to_anchor=(1.01,0.85),fontsize=14)\n\n# plt.show()",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,2,figsize=(12,6))\n\n# ax[0].set_title('GQL(5)')\n# im = ax[0].imshow((gql['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# # fig.colorbar(im)\n\n# ax[1].set_title('GCE2(5)')\n# im = ax[1].imshow((gce2['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# # fig.colorbar(im)\n\n# for a in ax:\n# a.set_xticks([0,M-1,2*M-2])\n# a.set_xticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)\n# a.set_yticks([0,M-1,2*M-2])\n# a.set_yticklabels([r'$-M$',r'$0$',r'$M$'],fontsize=14)\n\n# plt.show()",
"_____no_output_____"
],
[
"# dn = \"pointjet/12x12/\"",
"_____no_output_____"
],
[
"# Parameters: μ = 0.05, τ = 20.0, Ξ = 1.0*Ω and Δθ = 0.1\nNx = 12\nNy = 12",
"_____no_output_____"
],
[
"nl = np.load(dn+\"nl.npz\",allow_pickle=True) \ngql = np.load(dn+\"gql.npz\",allow_pickle=True) \ngce2 = np.load(dn+\"gce2.npz\",allow_pickle=True) ",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,2,figsize=(14,5))\n \n# # Energy\n# ax[0].plot(nl['t'],nl['Etav'],label=r'$\\langle NL \\rangle$')\n# ax[0].plot(gql['t'],gql['Etav'],label=r'$\\langle GQL(M) \\rangle$')\n# ax[0].plot(gce2['t'],gce2['Etav'],label=r'$\\langle GCE2(M) \\rangle$')\n\n# ax[0].set_xlabel(r'$t$',fontsize=14)\n# ax[0].set_ylabel(r'$E$',fontsize=14)\n# # ax[0].legend(bbox_to_anchor=(1.01,0.85),fontsize=14)\n\n# # Enstrophy\n# ax[1].plot(nl['t'],nl['Ztav'],label=r'$\\langle NL \\rangle$')\n# ax[1].plot(gql['t'],gql['Ztav'],label=r'$\\langle GQL(M) \\rangle$')\n# ax[1].plot(gce2['t'],gce2['Ztav'],label=r'$\\langle GCE2(M) \\rangle$')\n\n\n# ax[1].set_xlabel(r'$t$',fontsize=14)\n# ax[1].set_ylabel(r'$Z$',fontsize=14)\n# ax[1].legend(loc=4,fontsize=14)\n\n# plt.show()",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,3,figsize=(14,5))\n\n# ax[0].set_title(f'NL')\n# for i,x in enumerate(nl['Emt'].T): \n# ax[0].plot(nl['t'],x,label=i,c=colors[i])\n\n# ax[1].set_title(f'GQL(M)')\n# for i,x in enumerate(gql['Emt'].T):\n# ax[1].plot(gql['t'],x,label=i,c=colors[i])\n\n# ax[2].set_title(f'GCE2(M)')\n# for i,x in enumerate(gce2['Emt'].T):\n# ax[2].plot(gce2['t'],x,label=i,c=colors[i])\n\n# for a in ax:\n \n# a.set_xlabel(r'$t$',fontsize=14)\n# a.set_yscale('log')\n# # a.set_ylim(1e-10,1e1)\n\n# ax[0].set_ylabel(r'$E(m)$',fontsize=14)\n# ax[2].legend(bbox_to_anchor=(1.01,0.85),ncol=1)\n\n# plt.show()",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,3,figsize=(24,6))\n\n# ax[0].set_title(f'NL',fontsize=14)\n# im = ax[0].imshow((nl['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[0])\n\n# ax[1].set_title(f'GQL(M)',fontsize=14)\n# im = ax[1].imshow((gql['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[1])\n\n# ax[2].set_title(f'GCE2(M)',fontsize=14)\n# im = ax[2].imshow((gce2['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[2])\n\n# for a in ax:\n# a.set_xticks([0,Nx-1,2*Nx-2])\n# a.set_xticklabels([r'$-N_x$',r'$0$',r'$N_x$'],fontsize=14)\n# a.set_yticks([0,Ny-1,2*Ny-2])\n# a.set_yticklabels([r'$-N_y$',r'$0$',r'$N_y$'],fontsize=14)\n\n# plt.show()",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,3,figsize=(24,6))\n\n# ax[0].set_title(f'NL',fontsize=14)\n# im = ax[0].imshow((nl['Vxy'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[0])\n\n# ax[1].set_title(f'GQL(M)',fontsize=14)\n# im = ax[1].imshow((gql['Vxy'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[1])\n\n# ax[2].set_title(f'GCE2(M)',fontsize=14)\n# im = ax[2].imshow((gce2['Vxy'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[2])\n\n# for a in ax:\n# a.set_xticks([0,Nx-1,2*Nx-2])\n# a.set_xticklabels([r'$-N_x$',r'$0$',r'$N_x$'],fontsize=14)\n# a.set_yticks([0,Ny-1,2*Ny-2])\n# a.set_yticklabels([r'$-N_y$',r'$0$',r'$N_y$'],fontsize=14)\n\n# plt.show()",
"_____no_output_____"
],
[
"ql = np.load(dn+\"ql.npz\",allow_pickle=True) \nce2 = np.load(dn+\"ce2.npz\",allow_pickle=True)\ngce2 = np.load(dn+\"gce2_0.npz\",allow_pickle=True)",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,3,figsize=(14,5))\n \n# # Energy\n# ax[0].set_title(f'QL',fontsize=14)\n# for i,x in enumerate(ql['Emtav'].T):\n# ax[0].plot(ql['t'],x,label=i,c=colors[i])\n\n# ax[1].set_title(f'CE2',fontsize=14)\n# for i,x in enumerate(ce2['Emtav'].T):\n# ax[1].plot(ce2['t'],x,c=colors[i])\n\n# ax[2].set_title(f'GCE2(0)',fontsize=14)\n# for i,x in enumerate(gce2['Emtav'].T):\n# ax[2].plot(gce2['t'],x,c=colors[i])\n\n\n# for a in ax:\n# a.set_xlabel(r'$t$',fontsize=14)\n# a.set_ylabel(r'$E$',fontsize=14)\n# a.set_yscale('log')\n# # a.set_ylim(1e-1,1e0)\n# # ax[1].legend(bbox_to_anchor=(1.01,0.85),fontsize=14)\n\n# plt.show()",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,3,figsize=(24,6))\n\n# ax[0].set_title(f'QL',fontsize=14)\n# im = ax[0].imshow((ql['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[0])\n\n# ax[1].set_title(f'CE2',fontsize=14)\n# im = ax[1].imshow((ce2['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[1])\n\n# ax[2].set_title(f'GCE2(0)',fontsize=14)\n# im = ax[2].imshow((gce2['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[2])\n\n# for a in ax:\n# a.set_xticks([0,Nx-1,2*Nx-2])\n# a.set_xticklabels([r'$-N_x$',r'$0$',r'$N_x$'],fontsize=14)\n# a.set_yticks([0,Ny-1,2*Ny-2])\n# a.set_yticklabels([r'$-N_y$',r'$0$',r'$N_y$'],fontsize=14)\n\n# plt.show()",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,3,figsize=(24,6))\n\n# ax[0].set_title(f'QL',fontsize=14)\n# im = ax[0].imshow((ql['Vxy'][:,:,-1]),cmap=\"RdBu_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[0])\n\n# ax[1].set_title(f'CE2',fontsize=14)\n# im = ax[1].imshow((ce2['Vxy'][:,:,-1]),cmap=\"RdBu_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[1])\n\n# ax[2].set_title(f'GCE2(0)',fontsize=14)\n# im = ax[2].imshow((gce2['Vxy'][:,:,-1]),cmap=\"RdBu_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[2])\n\n# for a in ax:\n# a.set_xticks([0,Nx-1,2*Nx-2])\n# a.set_xticklabels([r'$-N_x$',r'$0$',r'$N_x$'],fontsize=14)\n# a.set_yticks([0,Ny-1,2*Ny-2])\n# a.set_yticklabels([r'$-N_y$',r'$0$',r'$N_y$'],fontsize=14)\n\n# plt.show()",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,3,figsize=(24,6))\n\n# ax[0].set_title(f'QL',fontsize=14)\n# im = ax[0].imshow((ql['Uxy'][:,:,-1]),cmap=\"RdBu_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[0])\n\n# ax[1].set_title(f'CE2',fontsize=14)\n# im = ax[1].imshow((ce2['Uxy'][:,:,-1]),cmap=\"RdBu_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[1])\n\n# ax[2].set_title(f'GCE2(0)',fontsize=14)\n# im = ax[2].imshow((gce2['Uxy'][:,:,-1]),cmap=\"RdBu_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[2])\n\n# for a in ax:\n# a.set_xticks([0,Nx-1,2*Nx-2])\n# a.set_xticklabels([r'$-N_x$',r'$0$',r'$N_x$'],fontsize=14)\n# a.set_yticks([0,Ny-1,2*Ny-2])\n# a.set_yticklabels([r'$-N_y$',r'$0$',r'$N_y$'],fontsize=14)\n\n# plt.show()",
"_____no_output_____"
],
[
"gql = np.load(dn+\"gql_3.npz\",allow_pickle=True) \ngce2 = np.load(dn+\"gce2_3.npz\",allow_pickle=True) ",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,2,figsize=(14,5))\n \n# # Energy\n# ax[0].set_title(f'GQL',fontsize=14)\n# for i,x in enumerate(gql['Emtav'].T):\n# ax[0].plot(gql['t'],x,label=i,c=colors[i])\n\n# ax[1].set_title(f'GCE2',fontsize=14)\n# for i,x in enumerate(gce2['Emtav'].T):\n# ax[1].plot(gce2['t'],x,c=colors[i])\n\n# for a in ax:\n# a.set_xlabel(r'$t$',fontsize=14)\n# a.set_ylabel(r'$E$',fontsize=14)\n# a.set_yscale('log')\n# # a.set_ylim(1e-1,1e0)\n# # ax[1].legend(bbox_to_anchor=(1.01,0.85),fontsize=14)\n\n# plt.show()",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,2,figsize=(15,6))\n\n# ax[0].set_title(f'GQL(1)',fontsize=14)\n# im = ax[0].imshow((gql['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[0])\n\n# ax[1].set_title(f'GCE2(1)',fontsize=14)\n# im = ax[1].imshow((gce2['Emn'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[1])\n\n# for a in ax:\n# a.set_xticks([0,Nx-1,2*Nx-2])\n# a.set_xticklabels([r'$-N_x$',r'$0$',r'$N_x$'],fontsize=14)\n# a.set_yticks([0,Ny-1,2*Ny-2])\n# a.set_yticklabels([r'$-N_y$',r'$0$',r'$N_y$'],fontsize=14)\n\n# plt.show()",
"_____no_output_____"
],
[
"# fig,ax = plt.subplots(1,2,figsize=(15,6))\n\n# ax[0].set_title(f'GQL(1)',fontsize=14)\n# im = ax[0].imshow((gql['Vxy'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[0])\n\n# ax[1].set_title(f'GCE2(1)',fontsize=14)\n# im = ax[1].imshow((gce2['Vxy'][:,:,-1]),cmap=\"nipy_spectral_r\",origin=\"lower\",interpolation=\"bicubic\")\n# fig.colorbar(im,ax=ax[1])\n\n# for a in ax:\n# a.set_xticks([0,Nx-1,2*Nx-2])\n# a.set_xticklabels([r'$-N_x$',r'$0$',r'$N_x$'],fontsize=14)\n# a.set_yticks([0,Ny-1,2*Ny-2])\n# a.set_yticklabels([r'$-N_y$',r'$0$',r'$N_y$'],fontsize=14)\n\n# plt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"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"
]
] |
4ac3505f2653dbc650c8da52f9213aefe13ad3f2
| 51,864 |
ipynb
|
Jupyter Notebook
|
ipynb/Intro_autonomous_Traders_mt5se.ipynb
|
paulo-al-castro/mt5se
|
51ae88c8a09ba7ff2a4f0a5d5fa6f4bb42dcc04b
|
[
"MIT"
] | 2 |
2021-06-04T23:43:57.000Z
|
2022-02-22T06:44:00.000Z
|
ipynb/Intro_autonomous_Traders_mt5se.ipynb
|
paulo-al-castro/mt5se
|
51ae88c8a09ba7ff2a4f0a5d5fa6f4bb42dcc04b
|
[
"MIT"
] | 1 |
2021-06-05T02:11:04.000Z
|
2022-02-24T01:35:30.000Z
|
ipynb/Intro_autonomous_Traders_mt5se.ipynb
|
paulo-al-castro/mt5se
|
51ae88c8a09ba7ff2a4f0a5d5fa6f4bb42dcc04b
|
[
"MIT"
] | 2 |
2021-06-04T03:37:02.000Z
|
2022-01-14T11:45:24.000Z
| 58.936364 | 18,422 | 0.612448 |
[
[
[
"# Building Autonomous Trader using mt5se",
"_____no_output_____"
],
[
"## How to setup and use mt5se\n### 1. Install Metatrader 5 (https://www.metatrader5.com/)\n### 2. Install python package Metatrader5 using pip\n#### Use: pip install MetaTrader5 ... or Use sys package\n### 3. Install python package mt5se using pip\n#### Use: pip install mt5se ... or Use sys package\n#### For documentation, check : https://paulo-al-castro.github.io/mt5se/\n\n",
"_____no_output_____"
]
],
[
[
"# installing Metatrader5 using sys\nimport sys\n# python MetaTrader5\n#!{sys.executable} -m pip install MetaTrader5\n#mt5se \n!{sys.executable} -m pip install mt5se --upgrade\n\n",
"_____no_output_____"
]
],
[
[
"\n<hr>\n\n## Connecting and getting account information\n",
"_____no_output_____"
]
],
[
[
"import mt5se as se\n\nconnected=se.connect()\nif connected:\n print('Ok!! It is connected to the Stock exchange!!')\nelse:\n print('Something went wrong! It is NOT connected to se!!')\n\n\n",
"Ok!! It is connected to the Stock exchange!!\n"
],
[
"ti=se.terminal_info()\nprint('Metatrader program file path: ', ti.path) \nprint('Metatrader path to data folder: ', ti.data_path )\nprint('Metatrader common data path: ',ti.commondata_path)",
"Metatrader program file path: C:\\Program Files\\MetaTrader 5 Terminal\nMetatrader path to data folder: C:\\Users\\PauloAndre\\AppData\\Roaming\\MetaQuotes\\Terminal\\FB9A56D617EDDDFE29EE54EBEFFE96C1\nMetatrader common data path: C:\\Users\\PauloAndre\\AppData\\Roaming\\MetaQuotes\\Terminal\\Common\n"
]
],
[
[
"<hr>\n\n### Getting information about the account",
"_____no_output_____"
]
],
[
[
"acc=se.account_info() # it returns account's information \nprint('login=',acc.login) # Account id\nprint('balance=',acc.balance) # Account balance in the deposit currency using buy price of assets (margin_free+margin)\nprint('equity=',acc.equity) # Account equity in the deposit currency using current price of assets (capital liquido) (margin_free+margin+profit)\nprint('free margin=',acc.margin_free) # Free margin ( balance in cash ) of an account in the deposit currency(BRL)\nprint('margin=',acc.margin) #Account margin used in the deposit currency (equity-margin_free-profit )\nprint('client name=',acc.name) #Client name\nprint('Server =',acc.server) # Trade server name\nprint('Currency =',acc.currency) # Account currency, BRL for Brazilian Real\n",
"login= 20604\nbalance= 100001.1\nequity= 100022.8\nfree margin= 97538.1\nmargin= 2484.7\nclient name= paulo castro\nServer = Tradeview-Demo\nCurrency = USD\n"
]
],
[
[
"<hr>\n\n### Getting info about asset's prices quotes (a.k.a bars)\n\n",
"_____no_output_____"
]
],
[
[
"import pandas as pd\n\n# Some example of Assets in Nasdaq\nassets=[\n'AAL', #\tAmerican Airlines Group, Inc.\t\n'GOOG', #\t\tApple Inc.\t\t\n'UAL', #\t\tUnited Airlines Holdings, Inc.\t\n'AMD', #\t\tAdvanced Micro Devices, Inc.\t\n'MSFT' #\t\tMICROSOFT\n]\nasset=assets[0]\n\ndf=se.get_bars(asset,10) # it returns the last 10 days\nprint(df)",
" time open high low close tick_volume spread real_volume\n0 2021-04-15 22.65 22.65 21.69 22.13 68339 0 3004358\n1 2021-04-16 22.01 22.35 21.87 22.01 64555 0 2957521\n2 2021-04-19 21.96 21.98 21.37 21.55 79229 0 3297570\n3 2021-04-20 21.02 21.02 19.96 20.36 83509 0 3496234\n4 2021-04-21 20.00 21.02 19.64 20.99 81736 0 3501087\n5 2021-04-22 21.57 21.59 20.04 20.07 87741 0 4550065\n6 2021-04-23 20.26 21.19 20.18 21.10 74520 0 3555802\n7 2021-04-26 21.52 22.04 21.47 22.03 79937 0 3904580\n8 2021-04-27 22.00 22.06 21.60 21.75 76687 0 4069314\n9 2021-04-28 21.62 21.88 21.48 21.69 72387 0 3368493\n"
]
],
[
[
"<hr>\n\n### Getting information about current position\n",
"_____no_output_____"
]
],
[
[
"print('Position=',se.get_positions()) # return the current value of assets (not include balance or margin)\nsymbol_id='MSFT'\nprint('Position on paper ',symbol_id,' =',se.get_position_value(symbol_id)) # return the current position in a given asset (symbol_id)\n\npos=se.get_position_value(symbol_id)\nprint(pos)\n\n",
"Position= symbol type volume price_open price_current\n0 MSFT 0 10.0 248.47 250.68\nPosition on paper MSFT = 2506.8\n2506.9\n"
]
],
[
[
"<hr>\n\n### Creating, checking and sending orders\n",
"_____no_output_____"
]
],
[
[
"###Buying three hundred shares of AAPL !!\nsymbol_id='AAPL'\nbars=se.get_bars(symbol_id,2)\nprice=se.get_last(bars)\nvolume=300\n\n\nb=se.buyOrder(symbol_id,volume, price ) # price, sl and tp are optional\n\nif se.is_market_open(symbol_id):\n print('Market is Open!!')\nelse:\n print('Market is closed! Orders will not be accepted!!')\n\nif se.checkOrder(b):\n print('Buy order seems ok!')\nelse:\n print('Error : ',se.getLastError())\n\n\n# if se.sendOrder(b):\n# print('Order executed!)\n",
"Market is Open!!\nBuy order seems ok!\n"
]
],
[
[
"### Direct Control Robots using mt5se",
"_____no_output_____"
]
],
[
[
"\n\nimport mt5se as se\nimport pandas as pd\nimport time\nasset='AAPL'\n\ndef run(asset):\n if se.is_market_open(asset): # change 'if' for 'while' for running until the end of the market session \n print(\"getting information\")\n bars=se.get_bars(asset,14)\n curr_shares=se.get_shares(asset)\n # number of shares that you can buy\n price=se.get_last(bars)\n free_shares=se.get_affor_shares(asset,price)\n rsi=se.tech.rsi(bars)\n print(\"deliberating\") \n if rsi>=70 and free_shares>0: \n order=se.buyOrder(asset,free_shares)\n elif rsi<70 and curr_shares>0:\n order=se.sellOrder(asset,curr_shares)\n else:\n order=None\n print(\"sending order\")\n # check and send (it is sent only if check is ok!)\n if order!=None:\n if se.checkOrder(order) and se.sendOrder(order): \n print('order sent to se')\n else:\n print('Error : ',se.getLastError())\n else:\n print(\"No order at the moment for asset=\",asset )\n time.sleep(1) # waits one second \t\t\n print('Trader ended operation!')\n\nif se.connect()==False:\n print('Error when trying to connect to se')\n exit()\nelse:\n run(asset) # trade asset PETR4",
"getting information\ndeliberating\nsending order\nNo order at the moment for asset= AAPL\nTrader ended operation!\n"
]
],
[
[
"### Multiple asset Trading Robot",
"_____no_output_____"
]
],
[
[
"#Multiple asset Robot (Example), single strategy for multiple assets, where the resources are equally shared among the assets\nimport time\n\ndef runMultiAsset(assets):\n if se.is_market_open(assets[0]): # change 'if' for 'while' for running until the end of the market session \n for asset in assets:\n bars=se.get_bars(asset,14) #get information\n curr_shares=se.get_shares(asset)\n money=se.account_info().margin_free/len(assets) # number of shares that you can buy\n price=se.get_last(bars)\n free_shares=se.get_affor_shares(asset,price,money)\n rsi=se.tech.rsi(bars)\n if rsi>=70 and free_shares>0: \n order=se.buyOrder(asset,free_shares)\n elif rsi<70 and curr_shares>0:\n order=se.sellOrder(asset,curr_shares)\n else:\n order=None\n if order!=None: # check and send if it is Ok\n if se.checkOrder(order) and se.sendOrder(order): \n print('order sent to se')\n else:\n print('Error : ',se.getLastError())\n else:\n print(\"No order at the moment for asset=\",asset)\n time.sleep(1) \n print('Trader ended operation!')\n\t\t\n\n",
"_____no_output_____"
]
],
[
[
"## Running multiple asset direct control code!\n\n",
"_____no_output_____"
]
],
[
[
"\nassets=['GOOG','AAPL']\n\nrunMultiAsset(assets) # trade asset ",
"No order at the moment for asset= GOOG\nNo order at the moment for asset= AAPL\nTrader ended operation!\n"
]
],
[
[
"### Processing Financial Data - Return Histogram Example ",
"_____no_output_____"
]
],
[
[
"import mt5se as se\nfrom datetime import datetime\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nasset='MSFT'\nse.connect()\nbars=se.get_bars(asset,252) # 252 business days (basically one year)\nx=se.get_returns(bars) # calculate daily returns given the bars\n#With a small change we can see the historgram of weekly returns\n#x=se.getReturns(bars,offset=5)\nplt.hist(x,bins=16) # creates a histogram graph with 16 bins\nplt.grid()\nplt.show()\n",
"_____no_output_____"
]
],
[
[
"### Robots based on Inversion of control \n\nYou may use an alternative method to build your robots, that may reduce your workload. It is called inverse control robots. You receive the most common information requrired by robots and returns your orders\n\nLet's some examples of Robots based on Inversion of Control including the multiasset strategy presented before in a inverse control implementation",
"_____no_output_____"
],
[
"### Trader class\nInversion of control Traders are classes that inherint from se.Trader and they have to implement just one function:\ntrade: It is called at each moment, with dbars. It should returns the list of orders to be executed or None if there is no order at the moment\n\nYour trader may also implement two other function if required:\nsetup: It is called once when the operation starts. It receives dbars ('mem' bars from each asset) . See the operation setup, for more information\n\nending: It is called one when the sheculed operation reaches its end time.\n\nYour Trader class may also implement a constructor function\n\nLet's see an Example!",
"_____no_output_____"
],
[
"### A Random Trader",
"_____no_output_____"
]
],
[
[
"import numpy.random as rand\n\nclass RandomTrader(se.Trader):\n def __init__(self):\n pass\n\n def setup(self,dbars):\n print('just getting started!')\n\n def trade(self,dbars):\n orders=[] \n assets=ops['assets']\n for asset in assets:\n if rand.randint(2)==1: \n order=se.buyOrder(asset,100)\n else:\n \torder=se.sellOrder(asset,100)\n orders.append(order)\n return orders\n \n def ending(self,dbars):\n print('Ending stuff')\n\n\nif issubclass(RandomTrader,se.Trader):\n print('Your trader class seems Ok!')\nelse:\n print('Your trader class should a subclass of se.Trader')\n\ntrader=RandomTrader() # DummyTrader class also available in se.sampleTraders.DummyTrader()\n",
"Your trader class seems Ok!\n"
]
],
[
[
"### Another Example of Trader class",
"_____no_output_____"
]
],
[
[
"class MultiAssetTrader(se.Trader):\n def trade(self,dbars):\n assets=dbars.keys()\n orders=[]\n for asset in assets:\n bars=dbars[asset]\n curr_shares=se.get_shares(asset)\n money=se.get_balance()/len(assets) # divide o saldo em dinheiro igualmente entre os ativos\n # number of shares that you can buy of asset \n price=se.get_last(bars)\n free_shares=se.get_affor_shares(asset,price,money)\n rsi=se.tech.rsi(bars)\n if rsi>=70 and free_shares>0: \n order=se.buyOrder(asset,free_shares)\n elif rsi<70 and curr_shares>0:\n order=se.sellOrder(asset,curr_shares)\n else:\n order=None\n if order!=None:\n orders.append(order)\n return orders \n\nif issubclass(MultiAssetTrader,se.Trader):\n print('Your trader class seems Ok!')\nelse:\n print('Your trader class should a subclass of se.Trader')\n\ntrader=MultiAssetTrader() ",
"_____no_output_____"
]
],
[
[
"### Testing your Trader!!!\n\nThe evaluation for trading robots is usually called backtesting. That means that a trading robot executes with historical price series , and its performance is computed\n\nIn backtesting, time is discretized according with bars and the package mt5se controls the information access to the Trader according with the simulated time.\n\nTo backtest one strategy, you just need to create a subclass of Trader and implement one function:\ntrade\n\nYou may implement function setup, to prepare the Trader Strategy if it is required and a function ending to clean up after the backtest is done\n\nThe simulation time advances and in function 'trade' the Trader class receives the new bar info and decides wich orders to send\n\n\n",
"_____no_output_____"
],
[
"## Let's create a Simple Algorithmic Trader and Backtest it",
"_____no_output_____"
]
],
[
[
"## Defines the Trader\n\nclass MonoAssetTrader(se.Trader):\n def trade(self,dbars):\n assets=dbars.keys()\n asset=list(assets)[0]\n orders=[]\n bars=dbars[asset]\n curr_shares=se.get_shares(asset)\n # number of shares that you can buy\n price=se.get_last(bars)\n free_shares=se.get_affor_shares(asset,price)\n rsi=se.tech.rsi(bars)\n if rsi>=70: \n order=se.buyOrder(asset,free_shares)\n else:\n order=se.sellOrder(asset,curr_shares)\n if rsi>=70 and free_shares>0: \n order=se.buyOrder(asset,free_shares)\n elif rsi<70 and curr_shares>0:\n order=se.sellOrder(asset,curr_shares)\n if order!=None:\n orders.append(order)\n return orders \n\ntrader=MonoAssetTrader() # also available in se.sampleTraders.MonoAssetTrader()\nprint(trader)\n",
"_____no_output_____"
]
],
[
[
"## Setup and check a backtest!",
"_____no_output_____"
]
],
[
[
"# sets Backtest options \nprestart=se.date(2018,12,10)\nstart=se.date(2019,1,10)\nend=se.date(2019,2,27)\ncapital=1000000\nresults_file='data_equity_file.csv'\nverbose=False \nassets=['AAPL']\n# Use True if you want debug information for your Trader \n#sets the backtest setup\nperiod=se.DAILY \n # it may be se.INTRADAY (one minute interval)\nbts=se.backtest.set(assets,prestart,start,end,period,capital,results_file,verbose)\n\n# check if the backtest setup is ok!\nif se.backtest.checkBTS(bts): \n print('Backtest Setup is Ok!')\nelse:\n print('Backtest Setup is NOT Ok!')\n\n",
"_____no_output_____"
]
],
[
[
"## Run the Backtest",
"_____no_output_____"
]
],
[
[
"\n# Running the backtest\ndf= se.backtest.run(trader,bts) \n# run calls the Trader. setup and trade (once for each bar)\n\n",
"_____no_output_____"
]
],
[
[
"## Evaluate the Backtest result",
"_____no_output_____"
]
],
[
[
"#print the results\nprint(df)\n\n# evaluates the backtest results\nse.backtest.evaluate(df)\n",
"_____no_output_____"
]
],
[
[
"## Evaluating Backtesting results\n\nThe method backtest.run creates a data file with the name given in the backtest setup (bts) \n\nThis will give you a report about the trader performance\n\nWe need ot note that it is hard to perform meaningful evaluations using backtest. There are many pitfalls to avoid and it may be easier to get trading robots with great performance in backtest, but that perform really badly in real operations. \n\nMore about that in mt5se backtest evaluation chapter.\n\nFor a deeper discussion, we suggest:\nIs it a great Autonomous Trading Strategy or you are just fooling yourself Bernardini,M. and Castro, P.A.L\n\nIn order to analyze the trader's backtest, you may use :\n\nse.backtest.evaluateFile(fileName) #fileName is the name of file generated by the backtest\nor\nse.bactest.evaluate(df) # df is the dataframe returned by se.backtest.run\n",
"_____no_output_____"
],
[
"# Another Example: Multiasset Trader",
"_____no_output_____"
]
],
[
[
"import mt5se as se\n\nclass MultiAssetTrader(se.Trader):\n def trade(self,dbars):\n assets=dbars.keys()\n orders=[]\n for asset in assets:\n bars=dbars[asset]\n curr_shares=se.get_shares(asset)\n money=se.get_balance()/len(assets) # divide o saldo em dinheiro igualmente entre os ativos\n # number of shares that you can buy of asset \n price=se.get_last(bars)\n free_shares=se.get_affor_shares(asset,price,money)\n rsi=se.tech.rsi(bars)\n if rsi>=70 and free_shares>0: \n order=se.buyOrder(asset,free_shares)\n elif rsi<70 and curr_shares>0:\n order=se.sellOrder(asset,curr_shares)\n else:\n order=None\n if order!=None:\n orders.append(order)\n return orders \n\n\ntrader=MultiAssetTrader() # also available in se.sampleTraders.MultiAssetTrader()\nprint(trader)\n ",
"_____no_output_____"
]
],
[
[
"## Setuping Backtest for Multiple Assets",
"_____no_output_____"
]
],
[
[
"\n# sets Backtest options \nprestart=se.date(2020,5,4)\nstart=se.date(2020,5,6)\nend=se.date(2020,6,21)\ncapital=10000000\nresults_file='data_equity_file.csv'\nverbose=False \nassets=[\n'AAL', #\tAmerican Airlines Group, Inc.\t\n'GOOG', #\t\tApple Inc.\t\t\n'UAL', #\t\tUnited Airlines Holdings, Inc.\t\n'AMD', #\t\tAdvanced Micro Devices, Inc.\t\n'MSFT' #\t\tMICROSOFT\n]\n# Use True if you want debug information for your Trader \n#sets the backtest setup\nperiod=se.DAILY \n\nbts=se.backtest.set(assets,prestart,start,end,period,capital,results_file,verbose)\nif se.backtest.checkBTS(bts): # check if the backtest setup is ok!\n print('Backtest Setup is Ok!')\nelse:\n print('Backtest Setup is NOT Ok!')",
"_____no_output_____"
]
],
[
[
"## Run and evaluate the backtest",
"_____no_output_____"
]
],
[
[
"se.connect()\n\n# Running the backtest\ndf= se.backtest.run(trader,bts) \n# run calls the Trader. setup and trade (once for each bar)\n\n# evaluates the backtest results\nse.backtest.evaluate(df)",
"_____no_output_____"
]
],
[
[
"## Next Deploying Autonomous Trader powered by mt5se\n\n### You have seen how to:\n install and import mt5se and MetaTrader5\n get financial data\n create direct control trading robots\n create [Simple] Trader classes based on inversion of control\n backtest Autonomous Traders\n### Next, We are going to show how to:\n\n deploy autonomous trader to run on simulated or real Stock Exchange accounts\n create Autonomous Traders based on Artifical Intelligence and Machine Learning \n\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"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4ac358234872fef9e9cd44e192d044c5f9ea1bf4
| 2,410 |
ipynb
|
Jupyter Notebook
|
0.17/_downloads/01fb0f5b44af7b68840573c40d1eec05/plot_read_and_write_raw_data.ipynb
|
drammock/mne-tools.github.io
|
5d3a104d174255644d8d5335f58036e32695e85d
|
[
"BSD-3-Clause"
] | null | null | null |
0.17/_downloads/01fb0f5b44af7b68840573c40d1eec05/plot_read_and_write_raw_data.ipynb
|
drammock/mne-tools.github.io
|
5d3a104d174255644d8d5335f58036e32695e85d
|
[
"BSD-3-Clause"
] | null | null | null |
0.17/_downloads/01fb0f5b44af7b68840573c40d1eec05/plot_read_and_write_raw_data.ipynb
|
drammock/mne-tools.github.io
|
5d3a104d174255644d8d5335f58036e32695e85d
|
[
"BSD-3-Clause"
] | null | null | null | 33.472222 | 944 | 0.552697 |
[
[
[
"%matplotlib inline",
"_____no_output_____"
]
],
[
[
"\n# Reading and writing raw files\n\n\nIn this example, we read a raw file. Plot a segment of MEG data\nrestricted to MEG channels. And save these data in a new\nraw file.\n\n",
"_____no_output_____"
]
],
[
[
"# Author: Alexandre Gramfort <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport mne\nfrom mne.datasets import sample\n\nprint(__doc__)\n\ndata_path = sample.data_path()\n\nfname = data_path + '/MEG/sample/sample_audvis_raw.fif'\n\nraw = mne.io.read_raw_fif(fname)\n\n# Set up pick list: MEG + STI 014 - bad channels\nwant_meg = True\nwant_eeg = False\nwant_stim = False\ninclude = ['STI 014']\nraw.info['bads'] += ['MEG 2443', 'EEG 053'] # bad channels + 2 more\n\npicks = mne.pick_types(raw.info, meg=want_meg, eeg=want_eeg, stim=want_stim,\n include=include, exclude='bads')\n\nsome_picks = picks[:5] # take 5 first\nstart, stop = raw.time_as_index([0, 15]) # read the first 15s of data\ndata, times = raw[some_picks, start:(stop + 1)]\n\n# save 150s of MEG data in FIF file\nraw.save('sample_audvis_meg_trunc_raw.fif', tmin=0, tmax=150, picks=picks,\n overwrite=True)",
"_____no_output_____"
]
],
[
[
"Show MEG data\n\n",
"_____no_output_____"
]
],
[
[
"raw.plot()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac362b94f757ed49b6e548d1e19b817490c8b08
| 4,041 |
ipynb
|
Jupyter Notebook
|
touchtypingfun/01.preface.ipynb
|
hawken-im/ProgramingNomad
|
10bd2ce06fc4b7575fcd9b4545a85f793c6819ff
|
[
"CC0-1.0"
] | null | null | null |
touchtypingfun/01.preface.ipynb
|
hawken-im/ProgramingNomad
|
10bd2ce06fc4b7575fcd9b4545a85f793c6819ff
|
[
"CC0-1.0"
] | null | null | null |
touchtypingfun/01.preface.ipynb
|
hawken-im/ProgramingNomad
|
10bd2ce06fc4b7575fcd9b4545a85f793c6819ff
|
[
"CC0-1.0"
] | null | null | null | 25.099379 | 257 | 0.582034 |
[
[
[
"# 前言 这个教程的特点?一共就五个,但核心思想是:及时获得学习结果正反馈",
"_____no_output_____"
],
[
"#### 特点一 从第一章开始,就能做出可以运行的真东西",
"_____no_output_____"
],
[
"> 而不是外面那些平淡无奇的编程教学:先教“Hello World”,然后好几个章节都在教基础知识而出不来成果,劝退多少新人;",
"_____no_output_____"
],
[
"### 如果非要“Hello World”一次才算编程教学的开始,行啊,我们现在就完成这个仪式,一个不够,我们来三个:",
"_____no_output_____"
]
],
[
[
"<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<meta charset=\"utf-8\">\n\t\t<title>Hello World 1</title>\n\t</head>\n\t<body>\n\t\t<p>Hello World 2</p>\n\t\t<script>\n\t\talert('Hello World 3');\n\t\t</script>\n\t</body>\n</html>",
"_____no_output_____"
]
],
[
[
"请复制上面这段代码,桌面或随便哪里新建一个文本文件,粘贴这段代码。保存。关闭。\n然后将这个文本文件的后缀名\".txt\",更改为\".html\"。双击打开或右键-在浏览器打开。\n到这里应该成功运行了刚刚的网页,恭喜,礼成!\n\n刚刚的文件是不是叫做“新建文本文件.html\",请改名叫“index.html“,这个以后还能用。\n\n如果是苹果电脑请打开苹果自带的“文本编辑“软件,在顶部菜单栏点击“格式”展开菜单,再点击“制作纯文本”。这个时候“文本编辑”会切换到纯文本编辑模式,然后将代码粘贴进去。保存到桌面或者你喜欢的文件夹里。苹果电脑保存的时候就可以要取名字,取名为:",
"_____no_output_____"
],
[
"> index.html\n\n接下来,去你保存了这个文件的文件夹里双击打开,运行成功,恭喜,礼成!\n\n刚刚的文件先留着,我们以后还用得到。",
"_____no_output_____"
],
[
"继续说这个教程的特点",
"_____no_output_____"
],
[
"#### 特点二 每一个小节学一个编程知识点,并且立刻运用这个知识点来做有用的小玩意,不会因为学到基础知识无法得到应用,感到枯燥。即是说,本教程正反馈及时,学起来有成就感。\n\n#### 特点三 本教程完全针对计算机小白读者,甚至会假设读者连键盘上的一些符号在哪都找不到,因此特别在此推出打字练习小游戏:\n\n> <a>https://play.hawken.im/typing</a>\n\n这个小游戏会最终会教会读者怎么不看键盘打字,我们称为“盲打”,这个技能对编程或者写文章或者操作其他软件(因为会用到快捷键)都很有帮助。",
"_____no_output_____"
],
[
"#### 特点四 学完本教程,就会完成第3点中分享的打字练习小游戏。本书最后一章我会提供英语词库,把这个打字小游戏转变成背单词小游戏。所以学完本教程你甚至可以用你自己的学习成果来背英语单词!\n\n#### 特点五 有没有发现,到现在本教程都没有提到我们是要学 JavaScript(JS) 这种编程语言?我这样处理,是想让读者大人们理解:重要的是编程这门技能,编程语言并不重要。选择 JS 这门语言的唯一理由就是,这个语言写出来的程序能够被各种流行的浏览器直接解读,写出来的东西能够直接呈现出结果。非常有快速正反馈作用,我认为这是非常适合初学者的一门语言。",
"_____no_output_____"
],
[
"### 让我们开始",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4ac363599889670b1ac4616377a6e58b78dec377
| 17,956 |
ipynb
|
Jupyter Notebook
|
intro-to-pytorch/Part 1 - Tensors in PyTorch (Exercises).ipynb
|
pasbury/udacity-deep-learning-v2-pytorch
|
a30f40d15f99a327c0ce0f356d7670724f89cdaa
|
[
"MIT"
] | null | null | null |
intro-to-pytorch/Part 1 - Tensors in PyTorch (Exercises).ipynb
|
pasbury/udacity-deep-learning-v2-pytorch
|
a30f40d15f99a327c0ce0f356d7670724f89cdaa
|
[
"MIT"
] | 5 |
2020-09-26T01:10:18.000Z
|
2022-02-10T01:43:51.000Z
|
intro-to-pytorch/Part 1 - Tensors in PyTorch (Exercises).ipynb
|
pasbury/udacity-deep-learning-v2-pytorch
|
a30f40d15f99a327c0ce0f356d7670724f89cdaa
|
[
"MIT"
] | null | null | null | 49.877778 | 1,203 | 0.635665 |
[
[
[
"# Introduction to Deep Learning with PyTorch\n\nIn this notebook, you'll get introduced to [PyTorch](http://pytorch.org/), a framework for building and training neural networks. PyTorch in a lot of ways behaves like the arrays you love from Numpy. These Numpy arrays, after all, are just tensors. PyTorch takes these tensors and makes it simple to move them to GPUs for the faster processing needed when training neural networks. It also provides a module that automatically calculates gradients (for backpropagation!) and another module specifically for building neural networks. All together, PyTorch ends up being more coherent with Python and the Numpy/Scipy stack compared to TensorFlow and other frameworks.\n\n",
"_____no_output_____"
],
[
"## Neural Networks\n\nDeep Learning is based on artificial neural networks which have been around in some form since the late 1950s. The networks are built from individual parts approximating neurons, typically called units or simply \"neurons.\" Each unit has some number of weighted inputs. These weighted inputs are summed together (a linear combination) then passed through an activation function to get the unit's output.\n\n<img src=\"assets/simple_neuron.png\" width=400px>\n\nMathematically this looks like: \n\n$$\n\\begin{align}\ny &= f(w_1 x_1 + w_2 x_2 + b) \\\\\ny &= f\\left(\\sum_i w_i x_i +b \\right)\n\\end{align}\n$$\n\nWith vectors this is the dot/inner product of two vectors:\n\n$$\nh = \\begin{bmatrix}\nx_1 \\, x_2 \\cdots x_n\n\\end{bmatrix}\n\\cdot \n\\begin{bmatrix}\n w_1 \\\\\n w_2 \\\\\n \\vdots \\\\\n w_n\n\\end{bmatrix}\n$$",
"_____no_output_____"
],
[
"## Tensors\n\nIt turns out neural network computations are just a bunch of linear algebra operations on *tensors*, a generalization of matrices. A vector is a 1-dimensional tensor, a matrix is a 2-dimensional tensor, an array with three indices is a 3-dimensional tensor (RGB color images for example). The fundamental data structure for neural networks are tensors and PyTorch (as well as pretty much every other deep learning framework) is built around tensors.\n\n<img src=\"assets/tensor_examples.svg\" width=600px>\n\nWith the basics covered, it's time to explore how we can use PyTorch to build a simple neural network.",
"_____no_output_____"
]
],
[
[
"# First, import PyTorch\nimport torch",
"_____no_output_____"
],
[
"def activation(x):\n \"\"\" Sigmoid activation function \n \n Arguments\n ---------\n x: torch.Tensor\n \"\"\"\n return 1/(1+torch.exp(-x))",
"_____no_output_____"
],
[
"### Generate some data\ntorch.manual_seed(7) # Set the random seed so things are predictable\n\n# Features are 5 random normal variables\nfeatures = torch.randn((1, 5))\n# True weights for our data, random normal variables again\nweights = torch.randn_like(features)\n# and a true bias term\nbias = torch.randn((1, 1))",
"_____no_output_____"
]
],
[
[
"Above I generated data we can use to get the output of our simple network. This is all just random for now, going forward we'll start using normal data. Going through each relevant line:\n\n`features = torch.randn((1, 5))` creates a tensor with shape `(1, 5)`, one row and five columns, that contains values randomly distributed according to the normal distribution with a mean of zero and standard deviation of one. \n\n`weights = torch.randn_like(features)` creates another tensor with the same shape as `features`, again containing values from a normal distribution.\n\nFinally, `bias = torch.randn((1, 1))` creates a single value from a normal distribution.\n\nPyTorch tensors can be added, multiplied, subtracted, etc, just like Numpy arrays. In general, you'll use PyTorch tensors pretty much the same way you'd use Numpy arrays. They come with some nice benefits though such as GPU acceleration which we'll get to later. For now, use the generated data to calculate the output of this simple single layer network. \n> **Exercise**: Calculate the output of the network with input features `features`, weights `weights`, and bias `bias`. Similar to Numpy, PyTorch has a [`torch.sum()`](https://pytorch.org/docs/stable/torch.html#torch.sum) function, as well as a `.sum()` method on tensors, for taking sums. Use the function `activation` defined above as the activation function.",
"_____no_output_____"
]
],
[
[
"## Calculate the output of this network using the weights and bias tensors",
"_____no_output_____"
]
],
[
[
"You can do the multiplication and sum in the same operation using a matrix multiplication. In general, you'll want to use matrix multiplications since they are more efficient and accelerated using modern libraries and high-performance computing on GPUs.\n\nHere, we want to do a matrix multiplication of the features and the weights. For this we can use [`torch.mm()`](https://pytorch.org/docs/stable/torch.html#torch.mm) or [`torch.matmul()`](https://pytorch.org/docs/stable/torch.html#torch.matmul) which is somewhat more complicated and supports broadcasting. If we try to do it with `features` and `weights` as they are, we'll get an error\n\n```python\n>> torch.mm(features, weights)\n\n---------------------------------------------------------------------------\nRuntimeError Traceback (most recent call last)\n<ipython-input-13-15d592eb5279> in <module>()\n----> 1 torch.mm(features, weights)\n\nRuntimeError: size mismatch, m1: [1 x 5], m2: [1 x 5] at /Users/soumith/minicondabuild3/conda-bld/pytorch_1524590658547/work/aten/src/TH/generic/THTensorMath.c:2033\n```\n\nAs you're building neural networks in any framework, you'll see this often. Really often. What's happening here is our tensors aren't the correct shapes to perform a matrix multiplication. Remember that for matrix multiplications, the number of columns in the first tensor must equal to the number of rows in the second column. Both `features` and `weights` have the same shape, `(1, 5)`. This means we need to change the shape of `weights` to get the matrix multiplication to work.\n\n**Note:** To see the shape of a tensor called `tensor`, use `tensor.shape`. If you're building neural networks, you'll be using this method often.\n\nThere are a few options here: [`weights.reshape()`](https://pytorch.org/docs/stable/tensors.html#torch.Tensor.reshape), [`weights.resize_()`](https://pytorch.org/docs/stable/tensors.html#torch.Tensor.resize_), and [`weights.view()`](https://pytorch.org/docs/stable/tensors.html#torch.Tensor.view).\n\n* `weights.reshape(a, b)` will return a new tensor with the same data as `weights` with size `(a, b)` sometimes, and sometimes a clone, as in it copies the data to another part of memory.\n* `weights.resize_(a, b)` returns the same tensor with a different shape. However, if the new shape results in fewer elements than the original tensor, some elements will be removed from the tensor (but not from memory). If the new shape results in more elements than the original tensor, new elements will be uninitialized in memory. Here I should note that the underscore at the end of the method denotes that this method is performed **in-place**. Here is a great forum thread to [read more about in-place operations](https://discuss.pytorch.org/t/what-is-in-place-operation/16244) in PyTorch.\n* `weights.view(a, b)` will return a new tensor with the same data as `weights` with size `(a, b)`.\n\nI usually use `.view()`, but any of the three methods will work for this. So, now we can reshape `weights` to have five rows and one column with something like `weights.view(5, 1)`.\n\n> **Exercise**: Calculate the output of our little network using matrix multiplication.",
"_____no_output_____"
]
],
[
[
"## Calculate the output of this network using matrix multiplication",
"_____no_output_____"
]
],
[
[
"### Stack them up!\n\nThat's how you can calculate the output for a single neuron. The real power of this algorithm happens when you start stacking these individual units into layers and stacks of layers, into a network of neurons. The output of one layer of neurons becomes the input for the next layer. With multiple input units and output units, we now need to express the weights as a matrix.\n\n<img src='assets/multilayer_diagram_weights.png' width=450px>\n\nThe first layer shown on the bottom here are the inputs, understandably called the **input layer**. The middle layer is called the **hidden layer**, and the final layer (on the right) is the **output layer**. We can express this network mathematically with matrices again and use matrix multiplication to get linear combinations for each unit in one operation. For example, the hidden layer ($h_1$ and $h_2$ here) can be calculated \n\n$$\n\\vec{h} = [h_1 \\, h_2] = \n\\begin{bmatrix}\nx_1 \\, x_2 \\cdots \\, x_n\n\\end{bmatrix}\n\\cdot \n\\begin{bmatrix}\n w_{11} & w_{12} \\\\\n w_{21} &w_{22} \\\\\n \\vdots &\\vdots \\\\\n w_{n1} &w_{n2}\n\\end{bmatrix}\n$$\n\nThe output for this small network is found by treating the hidden layer as inputs for the output unit. The network output is expressed simply\n\n$$\ny = f_2 \\! \\left(\\, f_1 \\! \\left(\\vec{x} \\, \\mathbf{W_1}\\right) \\mathbf{W_2} \\right)\n$$",
"_____no_output_____"
]
],
[
[
"### Generate some data\ntorch.manual_seed(7) # Set the random seed so things are predictable\n\n# Features are 3 random normal variables\nfeatures = torch.randn((1, 3))\n\n# Define the size of each layer in our network\nn_input = features.shape[1] # Number of input units, must match number of input features\nn_hidden = 2 # Number of hidden units \nn_output = 1 # Number of output units\n\n# Weights for inputs to hidden layer\nW1 = torch.randn(n_input, n_hidden)\n# Weights for hidden layer to output layer\nW2 = torch.randn(n_hidden, n_output)\n\n# and bias terms for hidden and output layers\nB1 = torch.randn((1, n_hidden))\nB2 = torch.randn((1, n_output))",
"_____no_output_____"
]
],
[
[
"> **Exercise:** Calculate the output for this multi-layer network using the weights `W1` & `W2`, and the biases, `B1` & `B2`. ",
"_____no_output_____"
]
],
[
[
"## Your solution here",
"_____no_output_____"
]
],
[
[
"If you did this correctly, you should see the output `tensor([[ 0.3171]])`.\n\nThe number of hidden units a parameter of the network, often called a **hyperparameter** to differentiate it from the weights and biases parameters. As you'll see later when we discuss training a neural network, the more hidden units a network has, and the more layers, the better able it is to learn from data and make accurate predictions.",
"_____no_output_____"
],
[
"## Numpy to Torch and back\n\nSpecial bonus section! PyTorch has a great feature for converting between Numpy arrays and Torch tensors. To create a tensor from a Numpy array, use `torch.from_numpy()`. To convert a tensor to a Numpy array, use the `.numpy()` method.",
"_____no_output_____"
]
],
[
[
"import numpy as np\na = np.random.rand(4,3)\na",
"_____no_output_____"
],
[
"b = torch.from_numpy(a)\nb",
"_____no_output_____"
],
[
"b.numpy()",
"_____no_output_____"
]
],
[
[
"The memory is shared between the Numpy array and Torch tensor, so if you change the values in-place of one object, the other will change as well.",
"_____no_output_____"
]
],
[
[
"# Multiply PyTorch Tensor by 2, in place\nb.mul_(2)",
"_____no_output_____"
],
[
"# Numpy array matches new values from Tensor\na",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4ac3719bf9d74c208ca1d6fd590fb30089a191c9
| 64,183 |
ipynb
|
Jupyter Notebook
|
Bayes_expansion_formula.ipynb
|
taishi107/Bayesian_theory
|
2c94e328926fb8035ca7f4b838e6f258bfb0c736
|
[
"MIT"
] | null | null | null |
Bayes_expansion_formula.ipynb
|
taishi107/Bayesian_theory
|
2c94e328926fb8035ca7f4b838e6f258bfb0c736
|
[
"MIT"
] | null | null | null |
Bayes_expansion_formula.ipynb
|
taishi107/Bayesian_theory
|
2c94e328926fb8035ca7f4b838e6f258bfb0c736
|
[
"MIT"
] | null | null | null | 213.943333 | 20,932 | 0.897496 |
[
[
[
"## ベイズの展開公式(Ⅰ)\n",
"_____no_output_____"
],
[
"### ベイズの基本公式\n$$\n\\begin{align}\nP(H|D) &= \\frac{P(D|H)P(H)}{P(D)}\n\\end{align}\n$$",
"_____no_output_____"
],
[
"\n$H$を原因、$D$を結果とする \n$ P(H|D) $ : 事後確率 (結果$D$が原因$H$より得られる確率) \n$ P(D|H) $ : 尤度 (原因$H$のもとで結果$D$が得られる確率) \n$ P(H) $ : 事前確率 (結果$D$を得る前の原因$H$が起こる確率)",
"_____no_output_____"
],
[
"### ベイズの展開公式\n原因$H$が$n$個ある場合\n$$\n\\begin{align}\nP(D) &= P(D \\cap H_{1}) + P(D \\cap H_{2}) + ... + P(D \\cap H_{n})\\\\\n&= \\sum _{k=1} ^{n}{P(D \\cap H_{k})}\n\\end{align}\n$$\n\n$\n\\begin{align}\nP(D \\cap H) &= P(H|D)P(D)\\\\\n\\end{align}\n$\nにより、\n\n$$\n\\begin{align}\nP(D) &= P(H_{1}|D)P(D) + P(H_{2}|D)P(D) + ... + P(H_{n}|D)P(D)\\\\\n&= \\sum _{k=1} ^{n}{ P(H_{k}|D)P(D)}\n\\end{align}\n$$\n\nしたがって、結果$D$が原因$H_{i}$より得られる確率は \n$$\n\\begin{align}\nP(H_{i}|D) &= \\frac{P(D|H_{i})P(H_{i})}{P(D|H_{1})P(H_{1}) + P(D|H_{2})P(H_{2}) + ... + P(D|H_{n})P(H_{n})}\\\\ \n&= \\frac{P(D|H_{i})P(H_{i})}{\\sum _{k=1} ^{n}{P(D|H_{k})P(H_{k})}}\n\\end{align}\n$$",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"# 初期設定\nstats = [\"R\",\"G\",\"B\"]\nbox = [[2,8,3],[8,3,6],[3,6,4]]\nd_n = len(stats) # 結果の数\nh_n = len(box) # 原因の数",
"_____no_output_____"
],
[
"def Likelihood(H):\n prob2 = []\n for i in range(d_n):\n prob = []\n for j in range(h_n):\n prob.append(box[j][i]/sum(box[j]))\n prob2.append(prob)\n return prob2",
"_____no_output_____"
],
[
"def calc(X,H):\n a_prob = []\n k = stats.index(X)\n prob2 =Likelihood(H)\n prob3 = []\n for i in range(h_n):\n prob3.append(prob2[k][i]*H[i])\n sum_prob = sum(prob3)\n for j in range(h_n):\n a_prob.append((prob2[k][j]*H[j])/(sum_prob))\n \n return a_prob",
"_____no_output_____"
],
[
"def draw(Y):\n x=[]\n y=[]\n x = [i for i in range(len(select))]\n for i in range(h_n):\n y = [Y[j][i] for j in range(len(select))]\n plt.plot(x,y,linewidth=2, color=\"red\")\n plt.title(\"box{}\".format(i+1))\n plt.xlabel(\"Number of trials\")\n plt.ylabel(\"probability\")\n plt.grid(True)\n plt.figure()",
"_____no_output_____"
],
[
"select = [\"R\",\"R\",\"R\",\"G\",\"R\",\"R\",\"G\"]",
"_____no_output_____"
],
[
"H = [1.0/h_n for i in range(h_n)]\nchange = []\nfor i in range(len(select)):\n ans = calc(select[i],H)\n change.append(ans)\n H = ans \n print(\"{}回目:{}を取る\".format(i+1,select[i]))\n for j in range(h_n):\n print(\"箱{}:\".format(j+1),ans[j])\n print(\"------------------------------------------------\")",
"1回目:Rを取る\n箱1: 0.17989417989417988\n箱2: 0.5502645502645502\n箱3: 0.2698412698412699\n------------------------------------------------\n2回目:Rを取る\n箱1: 0.07932477870033625\n箱2: 0.7421944692239072\n箱3: 0.1784807520757566\n------------------------------------------------\n3回目:Rを取る\n箱1: 0.03030800751685471\n箱2: 0.8674024671137607\n箱3: 0.10228952536938467\n------------------------------------------------\n4回目:Gを取る\n箱1: 0.08519095299384458\n箱2: 0.6991694472404864\n箱3: 0.21563959976566913\n------------------------------------------------\n5回目:Rを取る\n箱1: 0.03344380751231158\n箱2: 0.8395742358393803\n箱3: 0.12698195664830805\n------------------------------------------------\n6回目:Rを取る\n箱1: 0.011978328811727534\n箱2: 0.9198013453777305\n箱3: 0.06822032581054198\n------------------------------------------------\n7回目:Gを取る\n箱1: 0.03664104447341887\n箱2: 0.8068473065746923\n箱3: 0.15651164895188885\n------------------------------------------------\n"
],
[
"draw(change)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac37cb7db7ff0e9a65644bd51c4c5cd8a066433
| 182,485 |
ipynb
|
Jupyter Notebook
|
notebooks/Modeling_off_original_data_smote_gridsearchcv.ipynb
|
JonRivera/bridges-to-prosperity-ds-d
|
ccfba16629524f94d4734f0238f92564932c8c77
|
[
"MIT"
] | 2 |
2020-11-05T22:24:13.000Z
|
2021-05-24T07:51:11.000Z
|
notebooks/Modeling_off_original_data_smote_gridsearchcv.ipynb
|
JonRivera/bridges-to-prosperity-ds-d
|
ccfba16629524f94d4734f0238f92564932c8c77
|
[
"MIT"
] | 6 |
2020-11-05T21:53:27.000Z
|
2020-11-18T18:26:40.000Z
|
notebooks/Modeling_off_original_data_smote_gridsearchcv.ipynb
|
JonRivera/bridges-to-prosperity-ds-d
|
ccfba16629524f94d4734f0238f92564932c8c77
|
[
"MIT"
] | 8 |
2020-10-27T15:49:55.000Z
|
2020-11-20T22:43:54.000Z
| 99.392702 | 25,138 | 0.680763 |
[
[
[
"<a href=\"https://colab.research.google.com/github/Lambda-School-Labs/bridges-to-prosperity-ds-d/blob/SMOTE_model_building%2Ftrevor/notebooks/Modeling_off_original_data_smote_gridsearchcv.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"This notebook is for problem 2 as described in `B2P Dataset_2020.10.xlsx` Contextual Summary tab:\n\n## Problem 2: Predicting which sites will be technically rejected in future engineering reviews\n\n> Any sites with a \"Yes\" in the column AQ (`Senior Engineering Review Conducted`) have undergone a full technical review, and of those, the Stage (column L) can be considered to be correct. (`Bridge Opportunity: Stage`)\n\n> Any sites without a \"Yes\" in Column AQ (`Senior Engineering Review Conducted`) have not undergone a full technical review, and the Stage is based on the assessor's initial estimate as to whether the site was technically feasible or not. \n\n> We want to know if we can use the sites that have been reviewed to understand which of the sites that haven't yet been reviewed are likely to be rejected by the senior engineering team. \n\n> Any of the data can be used, but our guess is that Estimated Span, Height Differential Between Banks, Created By, and Flag for Rejection are likely to be the most reliable predictors.\n",
"_____no_output_____"
],
[
"### Load the data",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nurl = 'https://github.com/Lambda-School-Labs/bridges-to-prosperity-ds-d/blob/main/Data/B2P%20Dataset_2020.10.xlsx?raw=true'\ndf = pd.read_excel(url, sheet_name='Data')",
"_____no_output_____"
]
],
[
[
"### Define the target",
"_____no_output_____"
]
],
[
[
"# Any sites with a \"Yes\" in the column \"Senior Engineering Review Conducted\"\n# have undergone a full technical review, and of those, the \n# \"Bridge Opportunity: Stage\" column can be considered to be correct.\npositive = (\n (df['Senior Engineering Review Conducted']=='Yes') & \n (df['Bridge Opportunity: Stage'].isin(['Complete', 'Prospecting', 'Confirmed']))\n)\n\nnegative = (\n (df['Senior Engineering Review Conducted']=='Yes') & \n (df['Bridge Opportunity: Stage'].isin(['Rejected', 'Cancelled']))\n)\n\n# Any sites without a \"Yes\" in column Senior Engineering Review Conducted\" \n# have not undergone a full technical review ...\n# So these sites are unknown and unlabeled\nunknown = df['Senior Engineering Review Conducted'].isna()\n\n# Create a new column named \"Good Site.\" This is the target to predict.\n# Assign a 1 for the positive class and 0 for the negative class.\ndf.loc[positive, 'Good Site'] = 1\ndf.loc[negative, 'Good Site'] = 0\n\n# Assign -1 for unknown/unlabled observations. \n# Scikit-learn's documentation for \"Semi-Supervised Learning\" says, \n# \"It is important to assign an identifier to unlabeled points ...\n# The identifier that this implementation uses is the integer value -1.\"\n# We'll explain this soon!\ndf.loc[unknown, 'Good Site'] = -1",
"_____no_output_____"
]
],
[
[
"### Drop columns used to derive the target",
"_____no_output_____"
]
],
[
[
"# Because these columns were used to derive the target, \n# We can't use them as features, or it would be leakage.\ndf = df.drop(columns=['Senior Engineering Review Conducted', 'Bridge Opportunity: Stage'])",
"_____no_output_____"
]
],
[
[
"### Look at target's distribution",
"_____no_output_____"
]
],
[
[
"df['Good Site'].value_counts()",
"_____no_output_____"
]
],
[
[
"So we have 65 labeled observations for the positive class, 24 labeled observations for the negative class, and almost 1,400 unlabeled observations.",
"_____no_output_____"
],
[
"### 4 recommendations:\n\n- Use **semi-supervised learning**, which \"combines a small amount of labeled data with a large amount of unlabeled data\". See Wikipedia notes below. Python implementations are available in [scikit-learn](https://scikit-learn.org/stable/modules/label_propagation.html) and [pomegranate](https://pomegranate.readthedocs.io/en/latest/semisupervised.html). Another way to get started: feature engineering + feature selection + K-Means Clustering + PCA in 2 dimensions. Then visualize the clusters on a scatterplot, with colors for the labels.\n- Use [**leave-one-out cross-validation**](https://en.wikipedia.org/wiki/Cross-validation_(statistics)#Leave-one-out_cross-validation), without an independent test set, because we have so few labeled observations. It's implemented in [scikit-learn](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.LeaveOneOut.html). Or maybe 10-fold cross-validation with stratified sampling (and no independent test set).\n- Consider **\"over-sampling\"** techniques for imbalanced classification. Python implementations are available in [imbalanced-learn](https://github.com/scikit-learn-contrib/imbalanced-learn).\n- Consider using [**Snorkel**](https://www.snorkel.org/) to write \"labeling functions\" for \"weakly supervised learning.\" The site has many [tutorials](https://www.snorkel.org/use-cases/). \n\n",
"_____no_output_____"
],
[
"### [Semi-supervised learning - Wikipedia](https://en.wikipedia.org/wiki/Semi-supervised_learning)\n\n> Semi-supervised learning is an approach to machine learning that combines a small amount of labeled data with a large amount of unlabeled data during training. Semi-supervised learning falls between unsupervised learning (with no labeled training data) and supervised learning (with only labeled training data).\n\n> Unlabeled data, when used in conjunction with a small amount of labeled data, can produce considerable improvement in learning accuracy. The acquisition of labeled data for a learning problem often requires a skilled human agent ... The cost associated with the labeling process thus may render large, fully labeled training sets infeasible, whereas acquisition of unlabeled data is relatively inexpensive. In such situations, semi-supervised learning can be of great practical value.",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"> An example of the influence of unlabeled data in semi-supervised learning. The top panel shows a decision boundary we might adopt after seeing only one positive (white circle) and one negative (black circle) example. The bottom panel shows a decision boundary we might adopt if, in addition to the two labeled examples, we were given a collection of unlabeled data (gray circles). This could be viewed as performing clustering and then labeling the clusters with the labeled data, pushing the decision boundary away from high-density regions ...",
"_____no_output_____"
],
[
"See also:\n\n- “Positive-Unlabeled Learning”\n- https://en.wikipedia.org/wiki/One-class_classification",
"_____no_output_____"
],
[
"# Model attempt - Smaller Dataset Not utilizing world data\n\n- Here I am attempting to build a model using less \"created\" data than we did in previous attempts using the world data set. This had more successful bridge builds but those bridge builds did not include pertainant feature for building a predictive model. ",
"_____no_output_____"
]
],
[
[
"df.info()",
"_____no_output_____"
],
[
"# Columns suggeested bt stakeholder to utilize while model building\nkeep_list = ['Bridge Opportunity: Span (m)',\n 'Bridge Opportunity: Individuals Directly Served', \n 'Form: Created By',\n 'Height differential between banks', 'Flag for Rejection',\n 'Good Site']\n",
"_____no_output_____"
],
[
"# isolating the dataset to just the modelset\nmodelset = df[keep_list]\n\nmodelset.head()",
"_____no_output_____"
],
[
"# built modelset based off of original dataset - not much cleaning here.\n# further cleaning could be an area for improvement. \nmodelset['Good Site'].value_counts()",
"_____no_output_____"
],
[
"!pip install category_encoders",
"Collecting category_encoders\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/44/57/fcef41c248701ee62e8325026b90c432adea35555cbc870aff9cfba23727/category_encoders-2.2.2-py2.py3-none-any.whl (80kB)\n\r\u001b[K |████ | 10kB 16.3MB/s eta 0:00:01\r\u001b[K |████████▏ | 20kB 20.6MB/s eta 0:00:01\r\u001b[K |████████████▏ | 30kB 25.0MB/s eta 0:00:01\r\u001b[K |████████████████▎ | 40kB 25.4MB/s eta 0:00:01\r\u001b[K |████████████████████▎ | 51kB 17.4MB/s eta 0:00:01\r\u001b[K |████████████████████████▍ | 61kB 19.2MB/s eta 0:00:01\r\u001b[K |████████████████████████████▍ | 71kB 15.3MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 81kB 6.7MB/s \n\u001b[?25hRequirement already satisfied: scipy>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (1.4.1)\nRequirement already satisfied: pandas>=0.21.1 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (1.1.4)\nRequirement already satisfied: numpy>=1.14.0 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (1.18.5)\nRequirement already satisfied: patsy>=0.5.1 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (0.5.1)\nRequirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (0.22.2.post1)\nRequirement already satisfied: statsmodels>=0.9.0 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (0.10.2)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.21.1->category_encoders) (2018.9)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.21.1->category_encoders) (2.8.1)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from patsy>=0.5.1->category_encoders) (1.15.0)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn>=0.20.0->category_encoders) (0.17.0)\nInstalling collected packages: category-encoders\nSuccessfully installed category-encoders-2.2.2\n"
],
[
"# Imports:\nfrom collections import Counter\nfrom sklearn.pipeline import make_pipeline\nfrom imblearn.pipeline import make_pipeline as make_pipeline_imb\nfrom imblearn.over_sampling import SMOTE\nfrom imblearn.metrics import classification_report_imbalanced\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\nimport category_encoders as ce\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score, accuracy_score, classification_report",
"/usr/local/lib/python3.6/dist-packages/sklearn/externals/six.py:31: FutureWarning: The module is deprecated in version 0.21 and will be removed in version 0.23 since we've dropped support for Python 2.7. Please rely on the official version of six (https://pypi.org/project/six/).\n \"(https://pypi.org/project/six/).\", FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:144: FutureWarning: The sklearn.neighbors.base module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.neighbors. Anything that cannot be imported from sklearn.neighbors is now part of the private API.\n warnings.warn(message, FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:144: FutureWarning: The sklearn.metrics.classification module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.metrics. Anything that cannot be imported from sklearn.metrics is now part of the private API.\n warnings.warn(message, FutureWarning)\n/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"
],
[
"# split data - intial split eliminated all of the \"unlabeled\" sites \ndata = modelset[(modelset['Good Site']== 0) | (modelset['Good Site']== 1)]\ntest = modelset[modelset['Good Site']== -1]\n\ntrain, val = train_test_split(data, test_size=.2, random_state=42)\n",
"_____no_output_____"
],
[
"# splitting our labeled sites into a train and validation set for model building\n\nX_train = train.drop('Good Site', axis=1)\ny_train = train['Good Site']\nX_val = val.drop('Good Site', axis=1)\ny_val = val['Good Site']\n\nX_train.shape, y_train.shape, X_val.shape, y_val.shape",
"_____no_output_____"
],
[
"# Building a base model without SMOTE\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\n\nkf = KFold(n_splits=5, shuffle=False)\n\nbase_pipe = make_pipeline(ce.OrdinalEncoder(),\n SimpleImputer(strategy = 'mean'),\n RandomForestClassifier(n_estimators=100, random_state=42))\ncross_val_score(base_pipe, X_train, y_train, cv=kf, scoring='precision')\n",
"_____no_output_____"
]
],
[
[
"From the results above we can see the variety of the precision scores, looks like we have some overfit values when it comes to different cross validations",
"_____no_output_____"
]
],
[
[
"# use of imb_learn pipeline\nimba_pipe = make_pipeline_imb(ce.OrdinalEncoder(),\n SimpleImputer(strategy = 'mean'),\n SMOTE(random_state=42),\n RandomForestClassifier(n_estimators=100, random_state=42))\n\ncross_val_score(imba_pipe, X_train, y_train, cv=kf, scoring='precision')\n",
"/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n"
]
],
[
[
"Using an imbalanced Pipeline with SMOTE we still see the large variety in precision 1.0 as a high and .625 as a low. \n",
"_____no_output_____"
]
],
[
[
"# using grid search to attempt to further validate the model to use on predicitions\n\nnew_params = {'randomforestclassifier__n_estimators': [100, 200, 50],\n 'randomforestclassifier__max_depth': [4, 6, 10, 12], \n 'simpleimputer__strategy': ['mean', 'median']\n}\n\nimba_grid_1 = GridSearchCV(imba_pipe, param_grid=new_params, cv=kf, \n scoring='precision',\n return_train_score=True)\nimba_grid_1.fit(X_train, y_train);\n",
"_____no_output_____"
],
[
"# Params used and best score on a basis of precision\n\nprint(imba_grid_1.best_params_, imba_grid_1.best_score_)\n",
"{'randomforestclassifier__max_depth': 4, 'randomforestclassifier__n_estimators': 100, 'simpleimputer__strategy': 'median'} 0.8527777777777779\n"
],
[
"# Working with more folds for validation\n\nmore_kf = KFold(n_splits=15)\n\nimba_grid_2 = GridSearchCV(imba_pipe, param_grid=new_params, cv=more_kf, \n scoring='precision',\n return_train_score=True)\nimba_grid_2.fit(X_train, y_train);",
"/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:87: FutureWarning: Function safe_indexing is deprecated; safe_indexing is deprecated in version 0.22 and will be removed in version 0.24.\n warnings.warn(msg, category=FutureWarning)\n"
],
[
"print(imba_grid_2.best_score_, imba_grid_2.best_estimator_)",
"0.87 Pipeline(memory=None,\n steps=[('ordinalencoder',\n OrdinalEncoder(cols=['Form: Created By', 'Flag for Rejection'],\n drop_invariant=False, handle_missing='value',\n handle_unknown='value',\n mapping=[{'col': 'Form: Created By',\n 'data_type': dtype('O'),\n 'mapping': graceumumararungu taroworks 1\nedouardumwanzuro taroworks 2\netiennemutebutsi taroworks 3\nsolangeyandereye taroworks 4\naimablen...\n RandomForestClassifier(bootstrap=True, ccp_alpha=0.0,\n class_weight=None, criterion='gini',\n max_depth=4, max_features='auto',\n max_leaf_nodes=None, max_samples=None,\n min_impurity_decrease=0.0,\n min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0,\n n_estimators=100, n_jobs=None,\n oob_score=False, random_state=42,\n verbose=0, warm_start=False))],\n verbose=False)\n"
],
[
"imba_grid_2.cv_results_\n\n# muted output because it was lenghty\n# during output we did see a lot of 1s... Is this a sign of overfitting? ",
"_____no_output_____"
],
[
"# Now looking to the val set to get some more numbers\n\ny_val_predict = imba_grid_2.predict(X_val)\n\nprecision_score(y_val, y_val_predict)",
"_____no_output_____"
]
],
[
[
"The best score from above was .87, now running the model on the val set, it looks like we end with 92% precision score. ",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] |
[
"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",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac3847f554c62ed10b0f2ba82d6e9c69d649616
| 22,512 |
ipynb
|
Jupyter Notebook
|
examples/colab/tf2_text_classification.ipynb
|
sarvex/hub-1
|
07738578a6dd5ff01e4c9b70cd7cefa765024107
|
[
"Apache-2.0"
] | 3,234 |
2018-03-30T15:58:33.000Z
|
2022-03-31T16:24:25.000Z
|
examples/colab/tf2_text_classification.ipynb
|
sarvex/hub-1
|
07738578a6dd5ff01e4c9b70cd7cefa765024107
|
[
"Apache-2.0"
] | 805 |
2018-03-31T23:10:34.000Z
|
2022-03-18T13:39:31.000Z
|
examples/colab/tf2_text_classification.ipynb
|
sarvex/hub-1
|
07738578a6dd5ff01e4c9b70cd7cefa765024107
|
[
"Apache-2.0"
] | 1,931 |
2018-03-30T19:17:50.000Z
|
2022-03-27T02:39:44.000Z
| 39.219512 | 423 | 0.575115 |
[
[
[
"##### Copyright 2019 The TensorFlow Hub Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");",
"_____no_output_____"
]
],
[
[
"# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.\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# http://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.\n# ==============================================================================",
"_____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_____"
]
],
[
[
"# Text Classification with Movie Reviews",
"_____no_output_____"
],
[
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/hub/tutorials/tf2_text_classification\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/tf2_text_classification.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/hub/blob/master/examples/colab/tf2_text_classification.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/hub/examples/colab/tf2_text_classification.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n <td>\n <a href=\"https://tfhub.dev/google/collections/nnlm/1\"><img src=\"https://www.tensorflow.org/images/hub_logo_32px.png\" />See TF Hub models</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"This notebook classifies movie reviews as *positive* or *negative* using the text of the review. This is an example of *binary*—or two-class—classification, an important and widely applicable kind of machine learning problem. \n\nWe'll use the [IMDB dataset](https://www.tensorflow.org/api_docs/python/tf/keras/datasets/imdb) that contains the text of 50,000 movie reviews from the [Internet Movie Database](https://www.imdb.com/). These are split into 25,000 reviews for training and 25,000 reviews for testing. The training and testing sets are *balanced*, meaning they contain an equal number of positive and negative reviews. \n\nThis notebook uses [tf.keras](https://www.tensorflow.org/guide/keras), a high-level API to build and train models in TensorFlow, and [TensorFlow Hub](https://www.tensorflow.org/hub), a library and platform for transfer learning. For a more advanced text classification tutorial using `tf.keras`, see the [MLCC Text Classification Guide](https://developers.google.com/machine-learning/guides/text-classification/).",
"_____no_output_____"
],
[
"### More models\n[Here](https://tfhub.dev/s?module-type=text-embedding) you can find more expressive or performant models that you could use to generate the text embedding.",
"_____no_output_____"
],
[
"## Setup",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport tensorflow_datasets as tfds\n\nimport matplotlib.pyplot as plt\n\nprint(\"Version: \", tf.__version__)\nprint(\"Eager mode: \", tf.executing_eagerly())\nprint(\"Hub version: \", hub.__version__)\nprint(\"GPU is\", \"available\" if tf.config.list_physical_devices('GPU') else \"NOT AVAILABLE\")",
"_____no_output_____"
]
],
[
[
"## Download the IMDB dataset\n\nThe IMDB dataset is available on [TensorFlow datasets](https://github.com/tensorflow/datasets). The following code downloads the IMDB dataset to your machine (or the colab runtime):",
"_____no_output_____"
]
],
[
[
"train_data, test_data = tfds.load(name=\"imdb_reviews\", split=[\"train\", \"test\"], \n batch_size=-1, as_supervised=True)\n\ntrain_examples, train_labels = tfds.as_numpy(train_data)\ntest_examples, test_labels = tfds.as_numpy(test_data)",
"_____no_output_____"
]
],
[
[
"## Explore the data \n\nLet's take a moment to understand the format of the data. Each example is a sentence representing the movie review and a corresponding label. The sentence is not preprocessed in any way. The label is an integer value of either 0 or 1, where 0 is a negative review, and 1 is a positive review.",
"_____no_output_____"
]
],
[
[
"print(\"Training entries: {}, test entries: {}\".format(len(train_examples), len(test_examples)))",
"_____no_output_____"
]
],
[
[
"Let's print first 10 examples.",
"_____no_output_____"
]
],
[
[
"train_examples[:10]",
"_____no_output_____"
]
],
[
[
"Let's also print the first 10 labels.",
"_____no_output_____"
]
],
[
[
"train_labels[:10]",
"_____no_output_____"
]
],
[
[
"## Build the model\n\nThe neural network is created by stacking layers—this requires three main architectural decisions:\n\n* How to represent the text?\n* How many layers to use in the model?\n* How many *hidden units* to use for each layer?\n\nIn this example, the input data consists of sentences. The labels to predict are either 0 or 1.\n\nOne way to represent the text is to convert sentences into embeddings vectors. We can use a pre-trained text embedding as the first layer, which will have two advantages:\n* we don't have to worry about text preprocessing,\n* we can benefit from transfer learning.\n\nFor this example we will use a model from [TensorFlow Hub](https://www.tensorflow.org/hub) called [google/nnlm-en-dim50/2](https://tfhub.dev/google/nnlm-en-dim50/2).\n\nThere are two other models to test for the sake of this tutorial:\n* [google/nnlm-en-dim50-with-normalization/2](https://tfhub.dev/google/nnlm-en-dim50-with-normalization/2) - same as [google/nnlm-en-dim50/2](https://tfhub.dev/google/nnlm-en-dim50/2), but with additional text normalization to remove punctuation. This can help to get better coverage of in-vocabulary embeddings for tokens on your input text.\n* [google/nnlm-en-dim128-with-normalization/2](https://tfhub.dev/google/nnlm-en-dim128-with-normalization/2) - A larger model with an embedding dimension of 128 instead of the smaller 50.",
"_____no_output_____"
],
[
"Let's first create a Keras layer that uses a TensorFlow Hub model to embed the sentences, and try it out on a couple of input examples. Note that the output shape of the produced embeddings is a expected: `(num_examples, embedding_dimension)`.",
"_____no_output_____"
]
],
[
[
"model = \"https://tfhub.dev/google/nnlm-en-dim50/2\"\nhub_layer = hub.KerasLayer(model, input_shape=[], dtype=tf.string, trainable=True)\nhub_layer(train_examples[:3])",
"_____no_output_____"
]
],
[
[
"Let's now build the full model:",
"_____no_output_____"
]
],
[
[
"model = tf.keras.Sequential()\nmodel.add(hub_layer)\nmodel.add(tf.keras.layers.Dense(16, activation='relu'))\nmodel.add(tf.keras.layers.Dense(1))\n\nmodel.summary()",
"_____no_output_____"
]
],
[
[
"The layers are stacked sequentially to build the classifier:\n\n1. The first layer is a TensorFlow Hub layer. This layer uses a pre-trained Saved Model to map a sentence into its embedding vector. The model that we are using ([google/nnlm-en-dim50/2](https://tfhub.dev/google/nnlm-en-dim50/2)) splits the sentence into tokens, embeds each token and then combines the embedding. The resulting dimensions are: `(num_examples, embedding_dimension)`.\n2. This fixed-length output vector is piped through a fully-connected (`Dense`) layer with 16 hidden units.\n3. The last layer is densely connected with a single output node. This outputs logits: the log-odds of the true class, according to the model.",
"_____no_output_____"
],
[
"### Hidden units\n\nThe above model has two intermediate or \"hidden\" layers, between the input and output. The number of outputs (units, nodes, or neurons) is the dimension of the representational space for the layer. In other words, the amount of freedom the network is allowed when learning an internal representation.\n\nIf a model has more hidden units (a higher-dimensional representation space), and/or more layers, then the network can learn more complex representations. However, it makes the network more computationally expensive and may lead to learning unwanted patterns—patterns that improve performance on training data but not on the test data. This is called *overfitting*, and we'll explore it later.",
"_____no_output_____"
],
[
"### Loss function and optimizer\n\nA model needs a loss function and an optimizer for training. Since this is a binary classification problem and the model outputs a probability (a single-unit layer with a sigmoid activation), we'll use the `binary_crossentropy` loss function. \n\nThis isn't the only choice for a loss function, you could, for instance, choose `mean_squared_error`. But, generally, `binary_crossentropy` is better for dealing with probabilities—it measures the \"distance\" between probability distributions, or in our case, between the ground-truth distribution and the predictions.\n\nLater, when we are exploring regression problems (say, to predict the price of a house), we will see how to use another loss function called mean squared error.\n\nNow, configure the model to use an optimizer and a loss function:",
"_____no_output_____"
]
],
[
[
"model.compile(optimizer='adam',\n loss=tf.losses.BinaryCrossentropy(from_logits=True),\n metrics=[tf.metrics.BinaryAccuracy(threshold=0.0, name='accuracy')])",
"_____no_output_____"
]
],
[
[
"## Create a validation set\n\nWhen training, we want to check the accuracy of the model on data it hasn't seen before. Create a *validation set* by setting apart 10,000 examples from the original training data. (Why not use the testing set now? Our goal is to develop and tune our model using only the training data, then use the test data just once to evaluate our accuracy).",
"_____no_output_____"
]
],
[
[
"x_val = train_examples[:10000]\npartial_x_train = train_examples[10000:]\n\ny_val = train_labels[:10000]\npartial_y_train = train_labels[10000:]",
"_____no_output_____"
]
],
[
[
"## Train the model\n\nTrain the model for 40 epochs in mini-batches of 512 samples. This is 40 iterations over all samples in the `x_train` and `y_train` tensors. While training, monitor the model's loss and accuracy on the 10,000 samples from the validation set:",
"_____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_____"
]
],
[
[
"## Evaluate the model\n\nAnd let's see how the model performs. Two values will be returned. Loss (a number which represents our error, lower values are better), and accuracy.",
"_____no_output_____"
]
],
[
[
"results = model.evaluate(test_examples, test_labels)\n\nprint(results)",
"_____no_output_____"
]
],
[
[
"This fairly naive approach achieves an accuracy of about 87%. With more advanced approaches, the model should get closer to 95%.",
"_____no_output_____"
],
[
"## Create a graph of accuracy and loss over time\n\n`model.fit()` returns a `History` object that contains a dictionary with everything that happened during training:",
"_____no_output_____"
]
],
[
[
"history_dict = history.history\nhistory_dict.keys()",
"_____no_output_____"
]
],
[
[
"There are four entries: one for each monitored metric during training and validation. We can use these to plot the training and validation loss for comparison, as well as the training and validation accuracy:",
"_____no_output_____"
]
],
[
[
"acc = history_dict['accuracy']\nval_acc = history_dict['val_accuracy']\nloss = history_dict['loss']\nval_loss = history_dict['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\n# \"bo\" is for \"blue dot\"\nplt.plot(epochs, loss, 'bo', label='Training loss')\n# b is for \"solid blue line\"\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() # clear figure\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_____"
]
],
[
[
"In this plot, the dots represent the training loss and accuracy, and the solid lines are the validation loss and accuracy.\n\nNotice the training loss *decreases* with each epoch and the training accuracy *increases* with each epoch. This is expected when using a gradient descent optimization—it should minimize the desired quantity on every iteration.\n\nThis isn't the case for the validation loss and accuracy—they seem to peak after about twenty epochs. This is an example of overfitting: the model performs better on the training data than it does on data it has never seen before. After this point, the model over-optimizes and learns representations *specific* to the training data that do not *generalize* to test data.\n\nFor this particular case, we could prevent overfitting by simply stopping the training after twenty or so epochs. Later, you'll see how to do this automatically with a 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"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
4ac3940fc299b42cc8684d983462d00024fe078c
| 58,732 |
ipynb
|
Jupyter Notebook
|
Coursera/Data Visualization with Python-IBM/Week-3/Excercise/Waffle-Charts-Word-Clouds-and-Regression-Plots-py-v2.0.ipynb
|
manipiradi/Online-Courses-Learning
|
2a4ce7590d1f6d1dfa5cfde632660b562fcff596
|
[
"MIT"
] | 331 |
2019-10-22T09:06:28.000Z
|
2022-03-27T13:36:03.000Z
|
Coursera/Data Visualization with Python-IBM/Week-3/Excercise/Waffle-Charts-Word-Clouds-and-Regression-Plots-py-v2.0.ipynb
|
manipiradi/Online-Courses-Learning
|
2a4ce7590d1f6d1dfa5cfde632660b562fcff596
|
[
"MIT"
] | 8 |
2020-04-10T07:59:06.000Z
|
2022-02-06T11:36:47.000Z
|
Coursera/Data Visualization with Python-IBM/Week-3/Excercise/Waffle-Charts-Word-Clouds-and-Regression-Plots-py-v2.0.ipynb
|
manipiradi/Online-Courses-Learning
|
2a4ce7590d1f6d1dfa5cfde632660b562fcff596
|
[
"MIT"
] | 572 |
2019-07-28T23:43:35.000Z
|
2022-03-27T22:40:08.000Z
| 25.692038 | 451 | 0.563866 |
[
[
[
"<a href=\"https://cognitiveclass.ai\"><img src = \"https://ibm.box.com/shared/static/9gegpsmnsoo25ikkbl4qzlvlyjbgxs5x.png\" width = 400> </a>\n\n<h1 align=center><font size = 5>Waffle Charts, Word Clouds, and Regression Plots</font></h1>",
"_____no_output_____"
],
[
"## Introduction\n\nIn this lab, we will learn how to create word clouds and waffle charts. Furthermore, we will start learning about additional visualization libraries that are based on Matplotlib, namely the library *seaborn*, and we will learn how to create regression plots using the *seaborn* library.",
"_____no_output_____"
],
[
"## Table of Contents\n\n<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n\n1. [Exploring Datasets with *p*andas](#0)<br>\n2. [Downloading and Prepping Data](#2)<br>\n3. [Visualizing Data using Matplotlib](#4) <br>\n4. [Waffle Charts](#6) <br>\n5. [Word Clouds](#8) <br>\n7. [Regression Plots](#10) <br> \n</div>\n<hr>",
"_____no_output_____"
],
[
"# Exploring Datasets with *pandas* and Matplotlib<a id=\"0\"></a>\n\nToolkits: The course heavily relies on [*pandas*](http://pandas.pydata.org/) and [**Numpy**](http://www.numpy.org/) for data wrangling, analysis, and visualization. The primary plotting library we will explore in the course is [Matplotlib](http://matplotlib.org/).\n\nDataset: Immigration to Canada from 1980 to 2013 - [International migration flows to and from selected countries - The 2015 revision](http://www.un.org/en/development/desa/population/migration/data/empirical2/migrationflows.shtml) from United Nation's website\n\nThe dataset contains annual data on the flows of international migrants as recorded by the countries of destination. The data presents both inflows and outflows according to the place of birth, citizenship or place of previous / next residence both for foreigners and nationals. In this lab, we will focus on the Canadian Immigration data.",
"_____no_output_____"
],
[
"# Downloading and Prepping Data <a id=\"2\"></a>",
"_____no_output_____"
],
[
"Import Primary Modules:",
"_____no_output_____"
]
],
[
[
"import numpy as np # useful for many scientific computing in Python\nimport pandas as pd # primary data structure library\nfrom PIL import Image # converting images into arrays",
"_____no_output_____"
]
],
[
[
"Let's download and import our primary Canadian Immigration dataset using *pandas* `read_excel()` method. Normally, before we can do that, we would need to download a module which *pandas* requires to read in excel files. This module is **xlrd**. For your convenience, we have pre-installed this module, so you would not have to worry about that. Otherwise, you would need to run the following line of code to install the **xlrd** module:\n```\n!conda install -c anaconda xlrd --yes\n```",
"_____no_output_____"
],
[
"Download the dataset and read it into a *pandas* dataframe:",
"_____no_output_____"
]
],
[
[
"df_can = pd.read_excel('https://ibm.box.com/shared/static/lw190pt9zpy5bd1ptyg2aw15awomz9pu.xlsx',\n sheet_name='Canada by Citizenship',\n skiprows=range(20),\n skip_footer=2)\n\nprint('Data downloaded and read into a dataframe!')",
"_____no_output_____"
]
],
[
[
"Let's take a look at the first five items in our dataset",
"_____no_output_____"
]
],
[
[
"df_can.head()",
"_____no_output_____"
]
],
[
[
"Let's find out how many entries there are in our dataset",
"_____no_output_____"
]
],
[
[
"# print the dimensions of the dataframe\nprint(df_can.shape)",
"_____no_output_____"
]
],
[
[
"Clean up data. We will make some modifications to the original dataset to make it easier to create our visualizations. Refer to *Introduction to Matplotlib and Line Plots* and *Area Plots, Histograms, and Bar Plots* for a detailed description of this preprocessing.",
"_____no_output_____"
]
],
[
[
"# clean up the dataset to remove unnecessary columns (eg. REG) \ndf_can.drop(['AREA','REG','DEV','Type','Coverage'], axis = 1, inplace = True)\n\n# let's rename the columns so that they make sense\ndf_can.rename (columns = {'OdName':'Country', 'AreaName':'Continent','RegName':'Region'}, inplace = True)\n\n# for sake of consistency, let's also make all column labels of type string\ndf_can.columns = list(map(str, df_can.columns))\n\n# set the country name as index - useful for quickly looking up countries using .loc method\ndf_can.set_index('Country', inplace = True)\n\n# add total column\ndf_can['Total'] = df_can.sum (axis = 1)\n\n# years that we will be using in this lesson - useful for plotting later on\nyears = list(map(str, range(1980, 2014)))\nprint ('data dimensions:', df_can.shape)",
"_____no_output_____"
]
],
[
[
"# Visualizing Data using Matplotlib<a id=\"4\"></a>",
"_____no_output_____"
],
[
"Import `matplotlib`:",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches # needed for waffle Charts\n\nmpl.style.use('ggplot') # optional: for ggplot-like style\n\n# check for latest version of Matplotlib\nprint ('Matplotlib version: ', mpl.__version__) # >= 2.0.0",
"_____no_output_____"
]
],
[
[
"# Waffle Charts <a id=\"6\"></a>\n\n\nA `waffle chart` is an interesting visualization that is normally created to display progress toward goals. It is commonly an effective option when you are trying to add interesting visualization features to a visual that consists mainly of cells, such as an Excel dashboard.",
"_____no_output_____"
],
[
"Let's revisit the previous case study about Denmark, Norway, and Sweden.",
"_____no_output_____"
]
],
[
[
"# let's create a new dataframe for these three countries \ndf_dsn = df_can.loc[['Denmark', 'Norway', 'Sweden'], :]\n\n# let's take a look at our dataframe\ndf_dsn",
"_____no_output_____"
]
],
[
[
"Unfortunately, unlike R, `waffle` charts are not built into any of the Python visualization libraries. Therefore, we will learn how to create them from scratch.",
"_____no_output_____"
],
[
"**Step 1.** The first step into creating a waffle chart is determing the proportion of each category with respect to the total.",
"_____no_output_____"
]
],
[
[
"# compute the proportion of each category with respect to the total\ntotal_values = sum(df_dsn['Total'])\ncategory_proportions = [(float(value) / total_values) for value in df_dsn['Total']]\n\n# print out proportions\nfor i, proportion in enumerate(category_proportions):\n print (df_dsn.index.values[i] + ': ' + str(proportion))",
"_____no_output_____"
]
],
[
[
"**Step 2.** The second step is defining the overall size of the `waffle` chart.",
"_____no_output_____"
]
],
[
[
"width = 40 # width of chart\nheight = 10 # height of chart\n\ntotal_num_tiles = width * height # total number of tiles\n\nprint ('Total number of tiles is ', total_num_tiles)",
"_____no_output_____"
]
],
[
[
"**Step 3.** The third step is using the proportion of each category to determe it respective number of tiles",
"_____no_output_____"
]
],
[
[
"# compute the number of tiles for each catagory\ntiles_per_category = [round(proportion * total_num_tiles) for proportion in category_proportions]\n\n# print out number of tiles per category\nfor i, tiles in enumerate(tiles_per_category):\n print (df_dsn.index.values[i] + ': ' + str(tiles))",
"_____no_output_____"
]
],
[
[
"Based on the calculated proportions, Denmark will occupy 129 tiles of the `waffle` chart, Norway will occupy 77 tiles, and Sweden will occupy 194 tiles.",
"_____no_output_____"
],
[
"**Step 4.** The fourth step is creating a matrix that resembles the `waffle` chart and populating it.",
"_____no_output_____"
]
],
[
[
"# initialize the waffle chart as an empty matrix\nwaffle_chart = np.zeros((height, width))\n\n# define indices to loop through waffle chart\ncategory_index = 0\ntile_index = 0\n\n# populate the waffle chart\nfor col in range(width):\n for row in range(height):\n tile_index += 1\n\n # if the number of tiles populated for the current category is equal to its corresponding allocated tiles...\n if tile_index > sum(tiles_per_category[0:category_index]):\n # ...proceed to the next category\n category_index += 1 \n \n # set the class value to an integer, which increases with class\n waffle_chart[row, col] = category_index\n \nprint ('Waffle chart populated!')",
"_____no_output_____"
]
],
[
[
"Let's take a peek at how the matrix looks like.",
"_____no_output_____"
]
],
[
[
"waffle_chart",
"_____no_output_____"
]
],
[
[
"As expected, the matrix consists of three categories and the total number of each category's instances matches the total number of tiles allocated to each category.",
"_____no_output_____"
],
[
"**Step 5.** Map the `waffle` chart matrix into a visual.",
"_____no_output_____"
]
],
[
[
"# instantiate a new figure object\nfig = plt.figure()\n\n# use matshow to display the waffle chart\ncolormap = plt.cm.coolwarm\nplt.matshow(waffle_chart, cmap=colormap)\nplt.colorbar()",
"_____no_output_____"
]
],
[
[
"**Step 6.** Prettify the chart.",
"_____no_output_____"
]
],
[
[
"# instantiate a new figure object\nfig = plt.figure()\n\n# use matshow to display the waffle chart\ncolormap = plt.cm.coolwarm\nplt.matshow(waffle_chart, cmap=colormap)\nplt.colorbar()\n\n# get the axis\nax = plt.gca()\n\n# set minor ticks\nax.set_xticks(np.arange(-.5, (width), 1), minor=True)\nax.set_yticks(np.arange(-.5, (height), 1), minor=True)\n \n# add gridlines based on minor ticks\nax.grid(which='minor', color='w', linestyle='-', linewidth=2)\n\nplt.xticks([])\nplt.yticks([])",
"_____no_output_____"
]
],
[
[
"**Step 7.** Create a legend and add it to chart.",
"_____no_output_____"
]
],
[
[
"# instantiate a new figure object\nfig = plt.figure()\n\n# use matshow to display the waffle chart\ncolormap = plt.cm.coolwarm\nplt.matshow(waffle_chart, cmap=colormap)\nplt.colorbar()\n\n# get the axis\nax = plt.gca()\n\n# set minor ticks\nax.set_xticks(np.arange(-.5, (width), 1), minor=True)\nax.set_yticks(np.arange(-.5, (height), 1), minor=True)\n \n# add gridlines based on minor ticks\nax.grid(which='minor', color='w', linestyle='-', linewidth=2)\n\nplt.xticks([])\nplt.yticks([])\n\n# compute cumulative sum of individual categories to match color schemes between chart and legend\nvalues_cumsum = np.cumsum(df_dsn['Total'])\ntotal_values = values_cumsum[len(values_cumsum) - 1]\n\n# create legend\nlegend_handles = []\nfor i, category in enumerate(df_dsn.index.values):\n label_str = category + ' (' + str(df_dsn['Total'][i]) + ')'\n color_val = colormap(float(values_cumsum[i])/total_values)\n legend_handles.append(mpatches.Patch(color=color_val, label=label_str))\n\n# add legend to chart\nplt.legend(handles=legend_handles,\n loc='lower center', \n ncol=len(df_dsn.index.values),\n bbox_to_anchor=(0., -0.2, 0.95, .1)\n )",
"_____no_output_____"
]
],
[
[
"And there you go! What a good looking *delicious* `waffle` chart, don't you think?",
"_____no_output_____"
],
[
"Now it would very inefficient to repeat these seven steps every time we wish to create a `waffle` chart. So let's combine all seven steps into one function called *create_waffle_chart*. This function would take the following parameters as input:\n\n> 1. **categories**: Unique categories or classes in dataframe.\n> 2. **values**: Values corresponding to categories or classes.\n> 3. **height**: Defined height of waffle chart.\n> 4. **width**: Defined width of waffle chart.\n> 5. **colormap**: Colormap class\n> 6. **value_sign**: In order to make our function more generalizable, we will add this parameter to address signs that could be associated with a value such as %, $, and so on. **value_sign** has a default value of empty string.",
"_____no_output_____"
]
],
[
[
"def create_waffle_chart(categories, values, height, width, colormap, value_sign=''):\n\n # compute the proportion of each category with respect to the total\n total_values = sum(values)\n category_proportions = [(float(value) / total_values) for value in values]\n\n # compute the total number of tiles\n total_num_tiles = width * height # total number of tiles\n print ('Total number of tiles is', total_num_tiles)\n \n # compute the number of tiles for each catagory\n tiles_per_category = [round(proportion * total_num_tiles) for proportion in category_proportions]\n\n # print out number of tiles per category\n for i, tiles in enumerate(tiles_per_category):\n print (df_dsn.index.values[i] + ': ' + str(tiles))\n \n # initialize the waffle chart as an empty matrix\n waffle_chart = np.zeros((height, width))\n\n # define indices to loop through waffle chart\n category_index = 0\n tile_index = 0\n\n # populate the waffle chart\n for col in range(width):\n for row in range(height):\n tile_index += 1\n\n # if the number of tiles populated for the current category \n # is equal to its corresponding allocated tiles...\n if tile_index > sum(tiles_per_category[0:category_index]):\n # ...proceed to the next category\n category_index += 1 \n \n # set the class value to an integer, which increases with class\n waffle_chart[row, col] = category_index\n \n # instantiate a new figure object\n fig = plt.figure()\n\n # use matshow to display the waffle chart\n colormap = plt.cm.coolwarm\n plt.matshow(waffle_chart, cmap=colormap)\n plt.colorbar()\n\n # get the axis\n ax = plt.gca()\n\n # set minor ticks\n ax.set_xticks(np.arange(-.5, (width), 1), minor=True)\n ax.set_yticks(np.arange(-.5, (height), 1), minor=True)\n \n # add dridlines based on minor ticks\n ax.grid(which='minor', color='w', linestyle='-', linewidth=2)\n\n plt.xticks([])\n plt.yticks([])\n\n # compute cumulative sum of individual categories to match color schemes between chart and legend\n values_cumsum = np.cumsum(values)\n total_values = values_cumsum[len(values_cumsum) - 1]\n\n # create legend\n legend_handles = []\n for i, category in enumerate(categories):\n if value_sign == '%':\n label_str = category + ' (' + str(values[i]) + value_sign + ')'\n else:\n label_str = category + ' (' + value_sign + str(values[i]) + ')'\n \n color_val = colormap(float(values_cumsum[i])/total_values)\n legend_handles.append(mpatches.Patch(color=color_val, label=label_str))\n\n # add legend to chart\n plt.legend(\n handles=legend_handles,\n loc='lower center', \n ncol=len(categories),\n bbox_to_anchor=(0., -0.2, 0.95, .1)\n )",
"_____no_output_____"
]
],
[
[
"Now to create a `waffle` chart, all we have to do is call the function `create_waffle_chart`. Let's define the input parameters:",
"_____no_output_____"
]
],
[
[
"width = 40 # width of chart\nheight = 10 # height of chart\n\ncategories = df_dsn.index.values # categories\nvalues = df_dsn['Total'] # correponding values of categories\n\ncolormap = plt.cm.coolwarm # color map class",
"_____no_output_____"
]
],
[
[
"And now let's call our function to create a `waffle` chart.",
"_____no_output_____"
]
],
[
[
"create_waffle_chart(categories, values, height, width, colormap)",
"_____no_output_____"
]
],
[
[
"There seems to be a new Python package for generating `waffle charts` called [PyWaffle](https://github.com/ligyxy/PyWaffle), but the repository has barely any documentation on the package. Accordingly, I couldn't use the package to prepare enough content to incorporate into this lab. But feel free to check it out and play with it. In the event that the package becomes complete with full documentation, then I will update this lab accordingly.",
"_____no_output_____"
],
[
"# Word Clouds <a id=\"8\"></a>\n\n\n`Word` clouds (also known as text clouds or tag clouds) work in a simple way: the more a specific word appears in a source of textual data (such as a speech, blog post, or database), the bigger and bolder it appears in the word cloud.",
"_____no_output_____"
],
[
"Luckily, a Python package already exists in Python for generating `word` clouds. The package, called `word_cloud` was developed by **Andreas Mueller**. You can learn more about the package by following this [link](https://github.com/amueller/word_cloud/).\n\nLet's use this package to learn how to generate a word cloud for a given text document.",
"_____no_output_____"
],
[
"First, let's install the package.",
"_____no_output_____"
]
],
[
[
"# install wordcloud\n!conda install -c conda-forge wordcloud==1.4.1 --yes\n\n# import package and its set of stopwords\nfrom wordcloud import WordCloud, STOPWORDS\n\nprint ('Wordcloud is installed and imported!')",
"_____no_output_____"
]
],
[
[
"`Word` clouds are commonly used to perform high-level analysis and visualization of text data. Accordinly, let's digress from the immigration dataset and work with an example that involves analyzing text data. Let's try to analyze a short novel written by **Lewis Carroll** titled *Alice's Adventures in Wonderland*. Let's go ahead and download a _.txt_ file of the novel.",
"_____no_output_____"
]
],
[
[
"# download file and save as alice_novel.txt\n!wget --quiet https://ibm.box.com/shared/static/m54sjtrshpt5su20dzesl5en9xa5vfz1.txt -O alice_novel.txt\n\n# open the file and read it into a variable alice_novel\nalice_novel = open('alice_novel.txt', 'r').read()\n \nprint ('File downloaded and saved!')",
"_____no_output_____"
]
],
[
[
"Next, let's use the stopwords that we imported from `word_cloud`. We use the function *set* to remove any redundant stopwords.",
"_____no_output_____"
]
],
[
[
"stopwords = set(STOPWORDS)",
"_____no_output_____"
]
],
[
[
"Create a word cloud object and generate a word cloud. For simplicity, let's generate a word cloud using only the first 2000 words in the novel.",
"_____no_output_____"
]
],
[
[
"# instantiate a word cloud object\nalice_wc = WordCloud(\n background_color='white',\n max_words=2000,\n stopwords=stopwords\n)\n\n# generate the word cloud\nalice_wc.generate(alice_novel)",
"_____no_output_____"
]
],
[
[
"Awesome! Now that the `word` cloud is created, let's visualize it.",
"_____no_output_____"
]
],
[
[
"# display the word cloud\nplt.imshow(alice_wc, interpolation='bilinear')\nplt.axis('off')\nplt.show()",
"_____no_output_____"
]
],
[
[
"Interesting! So in the first 2000 words in the novel, the most common words are **Alice**, **said**, **little**, **Queen**, and so on. Let's resize the cloud so that we can see the less frequent words a little better.",
"_____no_output_____"
]
],
[
[
"fig = plt.figure()\nfig.set_figwidth(14) # set width\nfig.set_figheight(18) # set height\n\n# display the cloud\nplt.imshow(alice_wc, interpolation='bilinear')\nplt.axis('off')\nplt.show()",
"_____no_output_____"
]
],
[
[
"Much better! However, **said** isn't really an informative word. So let's add it to our stopwords and re-generate the cloud.",
"_____no_output_____"
]
],
[
[
"stopwords.add('said') # add the words said to stopwords\n\n# re-generate the word cloud\nalice_wc.generate(alice_novel)\n\n# display the cloud\nfig = plt.figure()\nfig.set_figwidth(14) # set width\nfig.set_figheight(18) # set height\n\nplt.imshow(alice_wc, interpolation='bilinear')\nplt.axis('off')\nplt.show()",
"_____no_output_____"
]
],
[
[
"Excellent! This looks really interesting! Another cool thing you can implement with the `word_cloud` package is superimposing the words onto a mask of any shape. Let's use a mask of Alice and her rabbit. We already created the mask for you, so let's go ahead and download it and call it *alice_mask.png*.",
"_____no_output_____"
]
],
[
[
"# download image\n!wget --quiet https://ibm.box.com/shared/static/3mpxgaf6muer6af7t1nvqkw9cqj85ibm.png -O alice_mask.png\n \n# save mask to alice_mask\nalice_mask = np.array(Image.open('alice_mask.png'))\n \nprint('Image downloaded and saved!')",
"_____no_output_____"
]
],
[
[
"Let's take a look at how the mask looks like.",
"_____no_output_____"
]
],
[
[
"fig = plt.figure()\nfig.set_figwidth(14) # set width\nfig.set_figheight(18) # set height\n\nplt.imshow(alice_mask, cmap=plt.cm.gray, interpolation='bilinear')\nplt.axis('off')\nplt.show()",
"_____no_output_____"
]
],
[
[
"Shaping the `word` cloud according to the mask is straightforward using `word_cloud` package. For simplicity, we will continue using the first 2000 words in the novel.",
"_____no_output_____"
]
],
[
[
"# instantiate a word cloud object\nalice_wc = WordCloud(background_color='white', max_words=2000, mask=alice_mask, stopwords=stopwords)\n\n# generate the word cloud\nalice_wc.generate(alice_novel)\n\n# display the word cloud\nfig = plt.figure()\nfig.set_figwidth(14) # set width\nfig.set_figheight(18) # set height\n\nplt.imshow(alice_wc, interpolation='bilinear')\nplt.axis('off')\nplt.show()",
"_____no_output_____"
]
],
[
[
"Really impressive!",
"_____no_output_____"
],
[
"Unfortunately, our immmigration data does not have any text data, but where there is a will there is a way. Let's generate sample text data from our immigration dataset, say text data of 90 words.",
"_____no_output_____"
],
[
"Let's recall how our data looks like.",
"_____no_output_____"
]
],
[
[
"df_can.head()",
"_____no_output_____"
]
],
[
[
"And what was the total immigration from 1980 to 2013?",
"_____no_output_____"
]
],
[
[
"total_immigration = df_can['Total'].sum()\ntotal_immigration",
"_____no_output_____"
]
],
[
[
"Using countries with single-word names, let's duplicate each country's name based on how much they contribute to the total immigration.",
"_____no_output_____"
]
],
[
[
"max_words = 90\nword_string = ''\nfor country in df_can.index.values:\n # check if country's name is a single-word name\n if len(country.split(' ')) == 1:\n repeat_num_times = int(df_can.loc[country, 'Total']/float(total_immigration)*max_words)\n word_string = word_string + ((country + ' ') * repeat_num_times)\n \n# display the generated text\nword_string",
"_____no_output_____"
]
],
[
[
"We are not dealing with any stopwords here, so there is no need to pass them when creating the word cloud.",
"_____no_output_____"
]
],
[
[
"# create the word cloud\nwordcloud = WordCloud(background_color='white').generate(word_string)\n\nprint('Word cloud created!')",
"_____no_output_____"
],
[
"# display the cloud\nfig = plt.figure()\nfig.set_figwidth(14)\nfig.set_figheight(18)\n\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.axis('off')\nplt.show()",
"_____no_output_____"
]
],
[
[
"According to the above word cloud, it looks like the majority of the people who immigrated came from one of 15 countries that are displayed by the word cloud. One cool visual that you could build, is perhaps using the map of Canada and a mask and superimposing the word cloud on top of the map of Canada. That would be an interesting visual to build!",
"_____no_output_____"
],
[
"# Regression Plots <a id=\"10\"></a>\n\n\n> Seaborn is a Python visualization library based on matplotlib. It provides a high-level interface for drawing attractive statistical graphics. You can learn more about *seaborn* by following this [link](https://seaborn.pydata.org/) and more about *seaborn* regression plots by following this [link](http://seaborn.pydata.org/generated/seaborn.regplot.html).",
"_____no_output_____"
],
[
"In lab *Pie Charts, Box Plots, Scatter Plots, and Bubble Plots*, we learned how to create a scatter plot and then fit a regression line. It took ~20 lines of code to create the scatter plot along with the regression fit. In this final section, we will explore *seaborn* and see how efficient it is to create regression lines and fits using this library!",
"_____no_output_____"
],
[
"Let's first install *seaborn*",
"_____no_output_____"
]
],
[
[
"# install seaborn\n!pip install seaborn\n\n# import library\nimport seaborn as sns\n\nprint('Seaborn installed and imported!')",
"_____no_output_____"
]
],
[
[
"Create a new dataframe that stores that total number of landed immigrants to Canada per year from 1980 to 2013.",
"_____no_output_____"
]
],
[
[
"# we can use the sum() method to get the total population per year\ndf_tot = pd.DataFrame(df_can[years].sum(axis=0))\n\n# change the years to type float (useful for regression later on)\ndf_tot.index = map(float,df_tot.index)\n\n# reset the index to put in back in as a column in the df_tot dataframe\ndf_tot.reset_index(inplace = True)\n\n# rename columns\ndf_tot.columns = ['year', 'total']\n\n# view the final dataframe\ndf_tot.head()",
"_____no_output_____"
]
],
[
[
"With *seaborn*, generating a regression plot is as simple as calling the **regplot** function.",
"_____no_output_____"
]
],
[
[
"import seaborn as sns\nax = sns.regplot(x='year', y='total', data=df_tot)",
"_____no_output_____"
]
],
[
[
"This is not magic; it is *seaborn*! You can also customize the color of the scatter plot and regression line. Let's change the color to green.",
"_____no_output_____"
]
],
[
[
"import seaborn as sns\nax = sns.regplot(x='year', y='total', data=df_tot, color='green')",
"_____no_output_____"
]
],
[
[
"You can always customize the marker shape, so instead of circular markers, let's use '+'.",
"_____no_output_____"
]
],
[
[
"import seaborn as sns\nax = sns.regplot(x='year', y='total', data=df_tot, color='green', marker='+')",
"_____no_output_____"
]
],
[
[
"Let's blow up the plot a little bit so that it is more appealing to the sight.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(15, 10))\nax = sns.regplot(x='year', y='total', data=df_tot, color='green', marker='+')",
"_____no_output_____"
]
],
[
[
"And let's increase the size of markers so they match the new size of the figure, and add a title and x- and y-labels.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(15, 10))\nax = sns.regplot(x='year', y='total', data=df_tot, color='green', marker='+', scatter_kws={'s': 200})\n\nax.set(xlabel='Year', ylabel='Total Immigration') # add x- and y-labels\nax.set_title('Total Immigration to Canada from 1980 - 2013') # add title",
"_____no_output_____"
]
],
[
[
"And finally increase the font size of the tickmark labels, the title, and the x- and y-labels so they don't feel left out!",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(15, 10))\n\nsns.set(font_scale=1.5)\n\nax = sns.regplot(x='year', y='total', data=df_tot, color='green', marker='+', scatter_kws={'s': 200})\nax.set(xlabel='Year', ylabel='Total Immigration')\nax.set_title('Total Immigration to Canada from 1980 - 2013')",
"_____no_output_____"
]
],
[
[
"Amazing! A complete scatter plot with a regression fit with 5 lines of code only. Isn't this really amazing?",
"_____no_output_____"
],
[
"If you are not a big fan of the purple background, you can easily change the style to a white plain background.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(15, 10))\n\nsns.set(font_scale=1.5)\nsns.set_style('ticks') # change background to white background\n\nax = sns.regplot(x='year', y='total', data=df_tot, color='green', marker='+', scatter_kws={'s': 200})\nax.set(xlabel='Year', ylabel='Total Immigration')\nax.set_title('Total Immigration to Canada from 1980 - 2013')",
"_____no_output_____"
]
],
[
[
"Or to a white background with gridlines.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(15, 10))\n\nsns.set(font_scale=1.5)\nsns.set_style('whitegrid')\n\nax = sns.regplot(x='year', y='total', data=df_tot, color='green', marker='+', scatter_kws={'s': 200})\nax.set(xlabel='Year', ylabel='Total Immigration')\nax.set_title('Total Immigration to Canada from 1980 - 2013')",
"_____no_output_____"
]
],
[
[
"**Question**: Use seaborn to create a scatter plot with a regression line to visualize the total immigration from Denmark, Sweden, and Norway to Canada from 1980 to 2013.",
"_____no_output_____"
]
],
[
[
"### type your answer here\n\n\n\n",
"_____no_output_____"
]
],
[
[
"Double-click __here__ for the solution.\n<!-- The correct answer is:\n\\\\ # create df_countries dataframe\ndf_countries = df_can.loc[['Denmark', 'Norway', 'Sweden'], years].transpose()\n-->\n\n<!--\n\\\\ # create df_total by summing across three countries for each year\ndf_total = pd.DataFrame(df_countries.sum(axis=1))\n-->\n\n<!--\n\\\\ # reset index in place\ndf_total.reset_index(inplace=True)\n-->\n\n<!--\n\\\\ # rename columns\ndf_total.columns = ['year', 'total']\n-->\n\n<!--\n\\\\ # change column year from string to int to create scatter plot\ndf_total['year'] = df_total['year'].astype(int)\n-->\n\n<!--\n\\\\ # define figure size\nplt.figure(figsize=(15, 10))\n-->\n\n<!--\n\\\\ # define background style and font size\nsns.set(font_scale=1.5)\nsns.set_style('whitegrid')\n-->\n\n<!--\n\\\\ # generate plot and add title and axes labels\nax = sns.regplot(x='year', y='total', data=df_total, color='green', marker='+', scatter_kws={'s': 200})\nax.set(xlabel='Year', ylabel='Total Immigration')\nax.set_title('Total Immigrationn from Denmark, Sweden, and Norway to Canada from 1980 - 2013')\n-->",
"_____no_output_____"
],
[
"### Thank you for completing this lab!\n\nThis notebook was created by [Alex Aklson](https://www.linkedin.com/in/aklson/). I hope you found this lab interesting and educational. Feel free to contact me if you have any questions!",
"_____no_output_____"
],
[
"This notebook is part of a course on **Coursera** called *Data Visualization with Python*. If you accessed this notebook outside the course, you can take this course online by clicking [here](http://cocl.us/DV0101EN_Coursera_Week3_LAB1).",
"_____no_output_____"
],
[
"<hr>\nCopyright © 2018 [Cognitive Class](https://cognitiveclass.ai/?utm_source=bducopyrightlink&utm_medium=dswb&utm_campaign=bdu). This notebook and its source code are released under the terms of the [MIT License](https://bigdatauniversity.com/mit-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",
"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"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"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"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4ac39ecccdbfafae3fb73f2a2f83211c7568ca9d
| 44,028 |
ipynb
|
Jupyter Notebook
|
src/viz/compare_interpro_vs_eggnog.ipynb
|
realmarcin/KE
|
ae7529843b874b2efa6a227c3eedd959f6eeb7c0
|
[
"MIT"
] | null | null | null |
src/viz/compare_interpro_vs_eggnog.ipynb
|
realmarcin/KE
|
ae7529843b874b2efa6a227c3eedd959f6eeb7c0
|
[
"MIT"
] | null | null | null |
src/viz/compare_interpro_vs_eggnog.ipynb
|
realmarcin/KE
|
ae7529843b874b2efa6a227c3eedd959f6eeb7c0
|
[
"MIT"
] | null | null | null | 56.30179 | 11,116 | 0.66594 |
[
[
[
"import numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n#from bokeh.io import show, output_file\n#from bokeh.plotting import figure\nfrom sklearn.preprocessing import StandardScaler\nimport os",
"_____no_output_____"
],
[
"df = pd.read_csv(\"merge_data_before_normalization.tsv\", sep=\"\\t\", header=0)#, index_col=0)",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.label[0:20]",
"_____no_output_____"
],
[
"df_new = pd.read_csv(\"../ENIGMA_InterPro/InterPro_GO_summaries/AA_S_11_Prodigal_proteins_InterProScan.tsv.out\", sep=\",\", header=None)#, index_col=0)",
"_____no_output_____"
],
[
"df_new",
"_____no_output_____"
],
[
"x = df.columns.values[2:]\ny = df_new.loc[:,0].values\nlenx = len(x)\nleny = len(y)\nprint(lenx)\nprint(leny)\nif(lenx < leny):\n indices = np.where(np.in1d(x, y))[0]\n indices2 = np.where(np.in1d(y, x))[0]\n index_2ary = np.where(np.in1d(x[indices], y[indices2]))[0]\nelse:\n indices = np.where(np.in1d(y, x))[0]\n indices2 = np.where(np.in1d(x, y))[0]\n index_2ary = np.where(np.in1d(y[indices], x[indices2]))[0]\nprint(len(indices))\nprint(len(indices2))\nprint(len(index_2ary))\nindices2",
"3008\n1610\n1362\n1362\n1362\n"
],
[
"#equivalent\nnp.nonzero(np.in1d(x,y))[0]",
"_____no_output_____"
],
[
"x[indices2].sort()\nx[indices2]",
"_____no_output_____"
],
[
"y[indices].sort()\ny[indices]",
"_____no_output_____"
],
[
"index_2ary",
"_____no_output_____"
],
[
"df_new.loc[:,3].values",
"_____no_output_____"
],
[
"df.iloc[10].values[2:]",
"_____no_output_____"
],
[
"#requires on more sort on one index to they have same order!\nif(lenx < leny):\n x_data = df.iloc[10].values[2:][indices]\n y_data = df_new.loc[:,3].values[indices2]\nelse:\n x_data = df.iloc[10].values[2:][indices2]\n y_data = df_new.loc[:,3].values[indices]\nprint(len(x_data))\nprint(len(y_data))",
"1362\n1362\n"
],
[
"plt.scatter(x_data, y_data, alpha=0.5)\nplt.show()",
"_____no_output_____"
],
[
"#with same order\nif(lenx < leny):\n x_data_sort = df.iloc[10].values[2:][np.argsort(indices)]\n y_data_sort = df_new.loc[:,3].values[indices2]\nelse:\n x_data_sort = df.iloc[10].values[2:][np.argsort(indices2)]\n y_data_sort = df_new.loc[:,3].values[indices]\nprint(len(x_data_sort))\nprint(len(y_data_sort))",
"1362\n1362\n"
],
[
"plt.scatter(x_data_sort, y_data_sort, alpha=0.5)\nplt.show()",
"_____no_output_____"
],
[
"np.argsort(indices)",
"_____no_output_____"
],
[
"indices2",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac3a83acb6cce00934ecf2fec54388e59ef9a7f
| 11,966 |
ipynb
|
Jupyter Notebook
|
fm/fm_cloud_training_template.ipynb
|
nikhilmeghnani/AmazonSageMakerCourse
|
8984e98f5d53ca85de23c071dc7e1523c75508c9
|
[
"Apache-2.0"
] | 1 |
2021-06-15T15:54:24.000Z
|
2021-06-15T15:54:24.000Z
|
fm/fm_cloud_training_template.ipynb
|
nikhilmeghnani/AmazonSageMakerCourse
|
8984e98f5d53ca85de23c071dc7e1523c75508c9
|
[
"Apache-2.0"
] | null | null | null |
fm/fm_cloud_training_template.ipynb
|
nikhilmeghnani/AmazonSageMakerCourse
|
8984e98f5d53ca85de23c071dc7e1523c75508c9
|
[
"Apache-2.0"
] | 4 |
2021-01-07T15:03:51.000Z
|
2021-04-25T07:04:20.000Z
| 27.257403 | 169 | 0.548721 |
[
[
[
"<h2>Factorization Machines - Movie Recommendation Model</h2>\nInput Features: [userId, moveId] <br>\nTarget: rating <br>",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\n\n# Define IAM role\nimport boto3\nimport re\nimport sagemaker\nfrom sagemaker import get_execution_role\n\n# SageMaker SDK Documentation: http://sagemaker.readthedocs.io/en/latest/estimators.html",
"_____no_output_____"
]
],
[
[
"## Upload Data to S3",
"_____no_output_____"
]
],
[
[
"# Specify your bucket name\nbucket_name = 'chandra-ml-sagemaker'\ntraining_file_key = 'movie/user_movie_train.recordio'\ntest_file_key = 'movie/user_movie_test.recordio'\n\ns3_model_output_location = r's3://{0}/movie/model'.format(bucket_name)\ns3_training_file_location = r's3://{0}/{1}'.format(bucket_name,training_file_key)\ns3_test_file_location = r's3://{0}/{1}'.format(bucket_name,test_file_key)",
"_____no_output_____"
],
[
"# Read Dimension: Number of unique users + Number of unique movies in our dataset\ndim_movie = 0\n\n# Update movie dimension - from file used for training \nwith open(r'ml-latest-small/movie_dimension.txt','r') as f:\n dim_movie = int(f.read())",
"_____no_output_____"
],
[
"dim_movie",
"_____no_output_____"
],
[
"print(s3_model_output_location)\nprint(s3_training_file_location)\nprint(s3_test_file_location)",
"_____no_output_____"
],
[
"# Write and Reading from S3 is just as easy\n# files are referred as objects in S3. \n# file name is referred as key name in S3\n# Files stored in S3 are automatically replicated across 3 different availability zones \n# in the region where the bucket was created.\n\n# http://boto3.readthedocs.io/en/latest/guide/s3.html\ndef write_to_s3(filename, bucket, key):\n with open(filename,'rb') as f: # Read in binary mode\n return boto3.Session().resource('s3').Bucket(bucket).Object(key).upload_fileobj(f)",
"_____no_output_____"
],
[
"write_to_s3(r'ml-latest-small/user_movie_train.recordio',bucket_name,training_file_key)",
"_____no_output_____"
],
[
"write_to_s3(r'ml-latest-small/user_movie_test.recordio',bucket_name,test_file_key)",
"_____no_output_____"
]
],
[
[
"## Training Algorithm Docker Image\n### AWS Maintains a separate image for every region and algorithm",
"_____no_output_____"
]
],
[
[
"sess = sagemaker.Session()",
"_____no_output_____"
],
[
"role = get_execution_role()",
"_____no_output_____"
],
[
"# This role contains the permissions needed to train, deploy models\n# SageMaker Service is trusted to assume this role\nprint(role)",
"_____no_output_____"
],
[
"# https://sagemaker.readthedocs.io/en/stable/api/utility/image_uris.html#sagemaker.image_uris.retrieve\n\n# SDK 2 uses image_uris.retrieve the container image location\n\n# Use factorization-machines\ncontainer = sagemaker.image_uris.retrieve(\"factorization-machines\",sess.boto_region_name)\n\nprint (f'Using FM Container {container}')",
"_____no_output_____"
],
[
"container",
"_____no_output_____"
]
],
[
[
"## Build Model",
"_____no_output_____"
]
],
[
[
"# Configure the training job\n# Specify type and number of instances to use\n# S3 location where final artifacts needs to be stored\n\n# Reference: http://sagemaker.readthedocs.io/en/latest/estimators.html\n\n# SDK 2.x version does not require train prefix for instance count and type\n\nestimator = sagemaker.estimator.Estimator(container,\n role, \n instance_count=1, \n instance_type='ml.m4.xlarge',\n output_path=s3_model_output_location,\n sagemaker_session=sess,\n base_job_name ='fm-movie-v4')",
"_____no_output_____"
]
],
[
[
"### New Configuration after Model Tuning\n### Refer to Hyperparameter Tuning Lecture on how to optimize hyperparameters",
"_____no_output_____"
]
],
[
[
"estimator.set_hyperparameters(feature_dim=dim_movie,\n num_factors=8,\n predictor_type='regressor', \n mini_batch_size=994,\n epochs=91,\n bias_init_method='normal',\n bias_lr=0.21899531189430518,\n factors_init_method='normal',\n factors_lr=5.357593337770278e-05,\n linear_init_method='normal',\n linear_lr=0.00021524948053767607)",
"_____no_output_____"
],
[
"estimator.hyperparameters()",
"_____no_output_____"
]
],
[
[
"### Train the model",
"_____no_output_____"
]
],
[
[
"# New Hyperparameters\n# Reference: Supported channels by algorithm\n# https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-algo-docker-registry-paths.html\nestimator.fit({'train':s3_training_file_location, 'test': s3_test_file_location})",
"_____no_output_____"
]
],
[
[
"## Deploy Model",
"_____no_output_____"
]
],
[
[
"# Ref: http://sagemaker.readthedocs.io/en/latest/estimators.html\npredictor = estimator.deploy(initial_instance_count=1,\n instance_type='ml.m4.xlarge',\n endpoint_name = 'fm-movie-v4')",
"_____no_output_____"
]
],
[
[
"## Run Predictions\n### Dense and Sparse Formats\nhttps://docs.aws.amazon.com/sagemaker/latest/dg/cdf-inference.html",
"_____no_output_____"
]
],
[
[
"import json\n\ndef fm_sparse_serializer(data):\n js = {'instances': []}\n for row in data:\n \n column_list = row.tolist()\n value_list = np.ones(len(column_list),dtype=int).tolist()\n \n js['instances'].append({'data':{'features': { 'keys': column_list, 'shape':[dim_movie], 'values': value_list}}})\n return json.dumps(js)",
"_____no_output_____"
],
[
"# SDK 2\nfrom sagemaker.deserializers import JSONDeserializer",
"_____no_output_____"
],
[
"# https://github.com/aws/amazon-sagemaker-examples/blob/master/introduction_to_amazon_algorithms/factorization_machines_mnist/factorization_machines_mnist.ipynb\n\n# Specify custom serializer\npredictor.serializer.serialize = fm_sparse_serializer\npredictor.serializer.content_type = 'application/json'\n\npredictor.deserializer = JSONDeserializer()",
"_____no_output_____"
],
[
"import numpy as np",
"_____no_output_____"
],
[
"fm_sparse_serializer([np.array([341,1416])])",
"_____no_output_____"
],
[
"# Let's test with few entries from test file\n# Movie dataset is updated regularly...so, instead of hard coding userid and movie id, let's\n# use actual values\n\n# Each row is in this format: ['2.5', '426:1', '943:1']\n# ActualRating, UserID, MovieID\n\nwith open(r'ml-latest-small/user_movie_test.svm','r') as f:\n for i in range(3):\n rating = f.readline().split()\n print(f\"Movie {rating}\")\n userID = rating[1].split(':')[0]\n movieID = rating[2].split(':')[0]\n predicted_rating = predictor.predict([np.array([int(userID),int(movieID)])])\n print(f' Actual Rating:\\t{rating[0]}')\n print(f\" Predicted Rating:\\t{predicted_rating['predictions'][0]['score']}\")\n print()",
"_____no_output_____"
]
],
[
[
"## Summary",
"_____no_output_____"
],
[
"1. Ensure Training, Test and Validation data are in S3 Bucket\n2. Select Algorithm Container Registry Path - Path varies by region\n3. Configure Estimator for training - Specify Algorithm container, instance count, instance type, model output location\n4. Specify algorithm specific hyper parameters\n5. Train model\n6. Deploy model - Specify instance count, instance type and endpoint name\n7. Run Predictions",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
4ac3a99c52ee33e1690919d8760879a7d1da081a
| 147,892 |
ipynb
|
Jupyter Notebook
|
notebooks/RetailHero_EN.ipynb
|
firefly-cpp/scikit-uplift
|
7479453d2c6827c92f3160529f360edabe0542e4
|
[
"MIT"
] | 403 |
2019-12-21T09:36:57.000Z
|
2022-03-30T09:36:56.000Z
|
notebooks/RetailHero_EN.ipynb
|
fspofficial/scikit-uplift
|
c9dd56aa0277e81ef7c4be62bf2fd33432e46f36
|
[
"MIT"
] | 100 |
2020-02-29T11:52:21.000Z
|
2022-03-29T23:14:33.000Z
|
notebooks/RetailHero_EN.ipynb
|
fspofficial/scikit-uplift
|
c9dd56aa0277e81ef7c4be62bf2fd33432e46f36
|
[
"MIT"
] | 81 |
2019-12-26T08:28:44.000Z
|
2022-03-22T09:08:54.000Z
| 128.601739 | 27,648 | 0.859174 |
[
[
[
"# The overview of the basic approaches to solving the Uplift Modeling problem\n\n<br>\n<center>\n <a href=\"https://colab.research.google.com/github/maks-sh/scikit-uplift/blob/master/notebooks/RetailHero_EN.ipynb\">\n <img src=\"https://colab.research.google.com/assets/colab-badge.svg\">\n </a>\n <br>\n <b><a href=\"https://github.com/maks-sh/scikit-uplift/\">SCIKIT-UPLIFT REPO</a> | </b>\n <b><a href=\"https://scikit-uplift.readthedocs.io/en/latest/\">SCIKIT-UPLIFT DOCS</a> | </b>\n <b><a href=\"https://scikit-uplift.readthedocs.io/en/latest/user_guide/index.html\">USER GUIDE</a></b>\n <br>\n <b><a href=\"https://nbviewer.jupyter.org/github/maks-sh/scikit-uplift/blob/master/notebooks/RetailHero.ipynb\">RUSSIAN VERSION</a></b>\n</center>",
"_____no_output_____"
],
[
"## Content\n\n* [Introduction](#Introduction)\n* [1. Single model approaches](#1.-Single-model-approaches)\n * [1.1 Single model](#1.1-Single-model-with-treatment-as-feature)\n * [1.2 Class Transformation](#1.2-Class-Transformation)\n* [2. Approaches with two models](#2.-Approaches-with-two-models)\n * [2.1 Two independent models](#2.1-Two-independent-models)\n * [2.2 Two dependent models](#2.2-Two-dependent-models)\n* [Conclusion](#Conclusion)\n\n## Introduction\n\nBefore proceeding to the discussion of uplift modeling, let's imagine some situation:\n\nA customer comes to you with a certain problem: it is necessary to advertise a popular product using the sms.\nYou know that the product is quite popular, and it is often installed by the customers without communication, that the usual binary classification will find the same customers, and the cost of communication is critical for us...\n\nAnd then you begin to understand that the product is already popular, that the product is often installed by customers without communication, that the usual binary classification will find many such customers, and the cost of communication is critical for us...\n\nHistorically, according to the impact of communication, marketers divide all customers into 4 categories:\n\n<p align=\"center\">\n <img src=\"https://raw.githubusercontent.com/maks-sh/scikit-uplift/master/docs/_static/images/user_guide/ug_clients_types.jpg\" alt=\"Customer types\" width='40%'/>\n</p>\n\n- **`Do-Not-Disturbs`** *(a.k.a. Sleeping-dogs)* have a strong negative response to a marketing communication. They are going to purchase if *NOT* treated and will *NOT* purchase *IF* treated. It is not only a wasted marketing budget but also a negative impact. For instance, customers targeted could result in rejecting current products or services. In terms of math: $W_i = 1, Y_i = 0$ or $W_i = 0, Y_i = 1$.\n- **`Lost Causes`** will *NOT* purchase the product *NO MATTER* they are contacted or not. The marketing budget in this case is also wasted because it has no effect. In terms of math: $W_i = 1, Y_i = 0$ or $W_i = 0, Y_i = 0$.\n- **`Sure Things`** will purchase *ANYWAY* no matter they are contacted or not. There is no motivation to spend the budget because it also has no effect. In terms of math: $W_i = 1, Y_i = 1$ or $W_i = 0, Y_i = 1$.\n- **`Persuadables`** will always respond *POSITIVE* to the marketing communication. They is going to purchase *ONLY* if contacted (or sometimes they purchase *MORE* or *EARLIER* only if contacted). This customer's type should be the only target for the marketing campaign. In terms of math: $W_i = 0, Y_i = 0$ or $W_i = 1, Y_i = 1$.\n\n\nBecause we can't communicate and not communicate with the customer at the same time, we will never be able to observe exactly which type a particular customer belongs to.\n\nDepends on the product characteristics and the customer base structure some types may be absent. In addition, a customer response depends heavily on various characteristics of the campaign, such as a communication channel or a type and a size of the marketing offer. To maximize profit, these parameters should be selected.\n\nThus, when predicting uplift score and selecting a segment by the highest score, we are trying to find the only one type: **persuadables**.\n\nThus, in this task, we don’t want to predict the probability of performing a target action, but to focus the advertising budget on the customers who will perform the target action only when we interact. In other words, we want to evaluate two conditional probabilities separately for each client:\n\n\n* Performing a targeted action when we influence the client. \n We will refer such clients to the **test group (aka treatment)**: $P^T = P(Y=1 | W = 1)$,\n* Performing a targeted action without affecting the client. \n We will refer such clients to the **control group (aka control)**: $P^C = P(Y=1 | W = 0)$,\n\nwhere $Y$ is the binary flag for executing the target action, and $W$ is the binary flag for communication (in English literature, _treatment_)\n\nThe very same cause-and-effect effect is called **uplift** and is estimated as the difference between these two probabilities:\n\n$$ uplift = P^T - P^C = P(Y = 1 | W = 1) - P(Y = 1 | W = 0) $$\n\nPredicting uplift is a cause-and-effect inference task. The point is that you need to evaluate the difference between two events that are mutually exclusive for a particular client (either we interact with a person, or not; you can't perform two of these actions at the same time). This is why additional requirements for source data are required for building uplift models.\n\nTo get a training sample for the uplift simulation, you need to conduct an experiment: \n1. Randomly split a representative part of the client base into a test and control group\n2. Communicate with the test group\n\nThe data obtained as part of the design of such a pilot will allow us to build an uplift forecasting model in the future. It is also worth noting that the experiment should be as similar as possible to the campaign, which will be launched later on a larger scale. The only difference between the experiment and the campaign should be the fact that during the pilot, we choose random clients for interaction, and during the campaign - based on the predicted value of the Uplift. If the campaign that is eventually launched differs significantly from the experiment that is used to collect data about the performance of targeted actions by clients, then the model that is built may be less reliable and accurate.\n\nSo, the approaches to predicting uplift are aimed at assessing the net effect of marketing campaigns on customers.\n\nAll classical approaches to uplift modeling can be divided into two classes:\n1. Approaches with the same model\n2. Approaches using two models\n\nLet's download [RetailHero.ai contest data](https://ods.ai/competitions/x5-retailhero-uplift-modeling/data):",
"_____no_output_____"
]
],
[
[
"import sys\n\n# install uplift library scikit-uplift and other libraries \n!{sys.executable} -m pip install scikit-uplift catboost pandas",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nfrom sklift.datasets import fetch_x5\nimport pandas as pd\n\npd.set_option('display.max_columns', None)\n%matplotlib inline",
"_____no_output_____"
],
[
"dataset = fetch_x5()\ndataset.keys()",
"_____no_output_____"
],
[
"print(f\"Dataset type: {type(dataset)}\\n\")\nprint(f\"Dataset features shape: {dataset.data['clients'].shape}\")\nprint(f\"Dataset features shape: {dataset.data['train'].shape}\")\nprint(f\"Dataset target shape: {dataset.target.shape}\")\nprint(f\"Dataset treatment shape: {dataset.treatment.shape}\")",
"Dataset type: <class 'sklearn.utils.Bunch'>\n\nDataset features shape: (400162, 5)\nDataset features shape: (200039, 1)\nDataset target shape: (200039,)\nDataset treatment shape: (200039,)\n"
]
],
[
[
"Read more about dataset <a href=\"https://www.uplift-modeling.com/en/latest/api/datasets/fetch_x5.html\">in the api docs</a>. \n\nNow let's preprocess it a bit:",
"_____no_output_____"
]
],
[
[
"# extract data\ndf_clients = dataset.data['clients'].set_index(\"client_id\")\ndf_train = pd.concat([dataset.data['train'], dataset.treatment , dataset.target], axis=1).set_index(\"client_id\")\nindices_test = pd.Index(set(df_clients.index) - set(df_train.index))\n\n# extracting features\ndf_features = df_clients.copy()\ndf_features['first_issue_time'] = \\\n (pd.to_datetime(df_features['first_issue_date'])\n - pd.Timestamp('1970-01-01')) // pd.Timedelta('1s')\ndf_features['first_redeem_time'] = \\\n (pd.to_datetime(df_features['first_redeem_date'])\n - pd.Timestamp('1970-01-01')) // pd.Timedelta('1s')\ndf_features['issue_redeem_delay'] = df_features['first_redeem_time'] \\\n - df_features['first_issue_time']\ndf_features = df_features.drop(['first_issue_date', 'first_redeem_date'], axis=1)\n\nindices_learn, indices_valid = train_test_split(df_train.index, test_size=0.3, random_state=123)\n",
"_____no_output_____"
]
],
[
[
"For convenience, we will declare some variables:",
"_____no_output_____"
]
],
[
[
"X_train = df_features.loc[indices_learn, :]\ny_train = df_train.loc[indices_learn, 'target']\ntreat_train = df_train.loc[indices_learn, 'treatment_flg']\n\nX_val = df_features.loc[indices_valid, :]\ny_val = df_train.loc[indices_valid, 'target']\ntreat_val = df_train.loc[indices_valid, 'treatment_flg']\n\nX_train_full = df_features.loc[df_train.index, :]\ny_train_full = df_train.loc[:, 'target']\ntreat_train_full = df_train.loc[:, 'treatment_flg']\n\nX_test = df_features.loc[indices_test, :]\n\ncat_features = ['gender']\n\nmodels_results = {\n 'approach': [],\n 'uplift@30%': []\n}",
"_____no_output_____"
]
],
[
[
"## 1. Single model approaches\n\n### 1.1 Single model with treatment as feature\n\nThe most intuitive and simple uplift modeling technique. A training set consists of two groups: treatment samples and control samples. There is also a binary treatment flag added as a feature to the training set. After the model is trained, at the scoring time it is going to be applied twice:\nwith the treatment flag equals `1` and with the treatment flag equals `0`. Subtracting these model's outcomes for each test sample, we will get an estimate of the uplift.\n\n<p align=\"center\">\n <img src=\"https://raw.githubusercontent.com/maks-sh/scikit-uplift/master/docs/_static/images/SoloModel.png\" alt=\"Solo model with treatment as a feature\"/>\n</p>",
"_____no_output_____"
]
],
[
[
"# installation instructions: https://github.com/maks-sh/scikit-uplift\n# link to the documentation: https://scikit-uplift.readthedocs.io/en/latest/\nfrom sklift.metrics import uplift_at_k\nfrom sklift.viz import plot_uplift_preds\nfrom sklift.models import SoloModel\n\n# sklift supports all models, \n# that satisfy scikit-learn convention\n# for example, let's use catboost\nfrom catboost import CatBoostClassifier\n\n\nsm = SoloModel(CatBoostClassifier(iterations=20, thread_count=2, random_state=42, silent=True))\nsm = sm.fit(X_train, y_train, treat_train, estimator_fit_params={'cat_features': cat_features})\n\nuplift_sm = sm.predict(X_val)\n\nsm_score = uplift_at_k(y_true=y_val, uplift=uplift_sm, treatment=treat_val, strategy='by_group', k=0.3)\n\nmodels_results['approach'].append('SoloModel')\nmodels_results['uplift@30%'].append(sm_score)\n\n# get conditional probabilities (predictions) of performing the target action \n# during interaction for each object\nsm_trmnt_preds = sm.trmnt_preds_\n# And conditional probabilities (predictions) of performing the target action \n# without interaction for each object\nsm_ctrl_preds = sm.ctrl_preds_\n\n# draw the probability (predictions) distributions and their difference (uplift)\nplot_uplift_preds(trmnt_preds=sm_trmnt_preds, ctrl_preds=sm_ctrl_preds);",
"_____no_output_____"
],
[
"# You can also access the trained model with the same ease.\n# For example, to build the importance of features:\nsm_fi = pd.DataFrame({\n 'feature_name': sm.estimator.feature_names_,\n 'feature_score': sm.estimator.feature_importances_\n}).sort_values('feature_score', ascending=False).reset_index(drop=True)\n\nsm_fi",
"_____no_output_____"
]
],
[
[
"### 1.2 Class Transformation\n\nSimple yet powerful and mathematically proven uplift modeling method, presented in 2012.\nThe main idea is to predict a slightly changed target $Z_i$:\n\n$$\nZ_i = Y_i \\cdot W_i + (1 - Y_i) \\cdot (1 - W_i),\n$$\n\nwhere \n\n* $Z_i$ - new target variable of the $i$ client; \n* $Y_i$ - target variable of the $i$ client;\n* $W_i$ - flag for communication of the $i$ client; \n\n\nIn other words, the new target equals 1 if a response in the treatment group is as good as a response in the control group and equals 0 otherwise:\n\n$$\nZ_i = \\begin{cases}\n 1, & \\mbox{if } W_i = 1 \\mbox{ and } Y_i = 1 \\\\\n 1, & \\mbox{if } W_i = 0 \\mbox{ and } Y_i = 0 \\\\\n 0, & \\mbox{otherwise}\n \\end{cases}\n$$\n\nLet's go deeper and estimate the conditional probability of the target variable:\n\n$$ \nP(Z=1|X = x) = \\\\\n= P(Z=1|X = x, W = 1) \\cdot P(W = 1|X = x) + \\\\\n+ P(Z=1|X = x, W = 0) \\cdot P(W = 0|X = x) = \\\\\n= P(Y=1|X = x, W = 1) \\cdot P(W = 1|X = x) + \\\\\n+ P(Y=0|X = x, W = 0) \\cdot P(W = 0|X = x).\n$$\n\nWe assume that $ W $ is independent of $X = x$ by design.\nThus we have: $P(W | X = x) = P(W)$ and\n\n$$\nP(Z=1|X = x) = \\\\\n= P^T(Y=1|X = x) \\cdot P(W = 1) + \\\\\n+ P^C(Y=0|X = x) \\cdot P(W = 0)\n$$\n\nAlso, we assume that $P(W = 1) = P(W = 0) = \\frac{1}{2}$, which means that during the experiment the control and the treatment groups were divided in equal proportions. Then we get the following:\n\n$$\nP(Z=1|X = x) = \\\\\n= P^T(Y=1|X = x) \\cdot \\frac{1}{2} + P^C(Y=0|X = x) \\cdot \\frac{1}{2} \\Rightarrow \\\\\n2 \\cdot P(Z=1|X = x) = \\\\\n= P^T(Y=1|X = x) + P^C(Y=0|X = x) = \\\\\n= P^T(Y=1|X = x) + 1 - P^C(Y=1|X = x) \\Rightarrow \\\\\n\\Rightarrow P^T(Y=1|X = x) - P^C(Y=1|X = x) = \\\\\n = uplift = 2 \\cdot P(Z=1|X = x) - 1\n$$\n\nThus, by doubling the estimate of the new target $Z$ and subtracting one we will get an estimation of the uplift:\n\n$$\nuplift = 2 \\cdot P(Z=1) - 1\n$$\n\nThis approach is based on the assumption: $P(W = 1) = P(W = 0) = \\frac{1}{2}$, That is the reason that it has to be used only in cases where the number of treated customers (communication) is equal to the number of control customers (no communication).",
"_____no_output_____"
]
],
[
[
"from sklift.models import ClassTransformation\n\n\nct = ClassTransformation(CatBoostClassifier(iterations=20, thread_count=2, random_state=42, silent=True))\nct = ct.fit(X_train, y_train, treat_train, estimator_fit_params={'cat_features': cat_features})\n\nuplift_ct = ct.predict(X_val)\n\nct_score = uplift_at_k(y_true=y_val, uplift=uplift_ct, treatment=treat_val, strategy='by_group', k=0.3)\n\nmodels_results['approach'].append('ClassTransformation')\nmodels_results['uplift@30%'].append(ct_score)",
"/var/folders/zj/l29x8njj1yncqvpwgkycthvw0000gp/T/ipykernel_74119/2974985256.py:5: UserWarning: It is recommended to use this approach on treatment balanced data. Current sample size is unbalanced.\n ct = ct.fit(X_train, y_train, treat_train, estimator_fit_params={'cat_features': cat_features})\n"
]
],
[
[
"## 2. Approaches with two models\n\nThe two-model approach can be found in almost any uplift modeling work and is often used as a baseline. However, using two models can lead to some unpleasant consequences: if you use fundamentally different models for training, or if the nature of the test and control group data is very different, then the scores returned by the models will not be comparable. As a result, the calculation of the uplift will not be completely correct. To avoid this effect, you need to calibrate the models so that their scores can be interpolated as probabilities. The calibration of model probabilities is described perfectly in [scikit-learn documentation](https://scikit-learn.org/stable/modules/calibration.html).\n\n### 2.1 Two independent models\n\nThe main idea is to estimate the conditional probabilities of the treatment and control groups separately.\n\n1. Train the first model using the treatment set.\n2. Train the second model using the control set.\n3. Inference: subtract the control model scores from the treatment model scores.\n\n<p align= \"center\">\n <img src=\"https://raw.githubusercontent.com/maks-sh/scikit-uplift/master/docs/_static/images/TwoModels_vanila.png\" alt=\"Two Models vanila\"/>\n</p>",
"_____no_output_____"
]
],
[
[
"from sklift.models import TwoModels\n\n\ntm = TwoModels(\n estimator_trmnt=CatBoostClassifier(iterations=20, thread_count=2, random_state=42, silent=True), \n estimator_ctrl=CatBoostClassifier(iterations=20, thread_count=2, random_state=42, silent=True), \n method='vanilla'\n)\ntm = tm.fit(\n X_train, y_train, treat_train,\n estimator_trmnt_fit_params={'cat_features': cat_features}, \n estimator_ctrl_fit_params={'cat_features': cat_features}\n)\n\nuplift_tm = tm.predict(X_val)\n\ntm_score = uplift_at_k(y_true=y_val, uplift=uplift_tm, treatment=treat_val, strategy='by_group', k=0.3)\n\nmodels_results['approach'].append('TwoModels')\nmodels_results['uplift@30%'].append(tm_score)\n\nplot_uplift_preds(trmnt_preds=tm.trmnt_preds_, ctrl_preds=tm.ctrl_preds_);",
"_____no_output_____"
]
],
[
[
"### 2.2 Two dependent models\n\nThe dependent data representation approach is based on the classifier chain method originally developed\nfor multi-class classification problems. The idea is that if there are $L$ different classifiers, each of which solves the problem of binary classification and in the learning process,\neach subsequent classifier uses the predictions of the previous ones as additional features.\nThe authors of this method proposed to use the same idea to solve the problem of uplift modeling in two stages.\n\nAt the beginning we train the classifier based on the control data:\n\n$$\nP^C = P(Y=1| X, W = 0),\n$$\n\nNext, we estimate the $P_C$ predictions and use them as a feature for the second classifier.\nIt effectively reflects a dependency between treatment and control datasets:\n\n$$\nP^T = P(Y=1| X, P_C(X), W = 1)\n$$\n\nTo get the uplift for each observation, calculate the difference:\n\n$$\nuplift(x_i) = P^T(x_i, P_C(x_i)) - P^C(x_i)\n$$\n\nIntuitively, the second classifier learns the difference between the expected probability in the treatment and the control sets which is the uplift.\n\n<p align= \"center\">\n <img src=\"https://raw.githubusercontent.com/maks-sh/scikit-uplift/master/docs/_static/images/TwoModels_ddr_control.png\", alt=\"Two dependent models\"/>\n</p>",
"_____no_output_____"
]
],
[
[
"tm_ctrl = TwoModels(\n estimator_trmnt=CatBoostClassifier(iterations=20, thread_count=2, random_state=42, silent=True), \n estimator_ctrl=CatBoostClassifier(iterations=20, thread_count=2, random_state=42, silent=True), \n method='ddr_control'\n)\ntm_ctrl = tm_ctrl.fit(\n X_train, y_train, treat_train,\n estimator_trmnt_fit_params={'cat_features': cat_features}, \n estimator_ctrl_fit_params={'cat_features': cat_features}\n)\n\nuplift_tm_ctrl = tm_ctrl.predict(X_val)\n\ntm_ctrl_score = uplift_at_k(y_true=y_val, uplift=uplift_tm_ctrl, treatment=treat_val, strategy='by_group', k=0.3)\n\nmodels_results['approach'].append('TwoModels_ddr_control')\nmodels_results['uplift@30%'].append(tm_ctrl_score)\n\nplot_uplift_preds(trmnt_preds=tm_ctrl.trmnt_preds_, ctrl_preds=tm_ctrl.ctrl_preds_);",
"_____no_output_____"
]
],
[
[
"Similarly, you can first train the $P^T$ classifier, and then use its predictions as a feature for the $P^C$ classifier.",
"_____no_output_____"
]
],
[
[
"tm_trmnt = TwoModels(\n estimator_trmnt=CatBoostClassifier(iterations=20, thread_count=2, random_state=42, silent=True), \n estimator_ctrl=CatBoostClassifier(iterations=20, thread_count=2, random_state=42, silent=True), \n method='ddr_treatment'\n)\ntm_trmnt = tm_trmnt.fit(\n X_train, y_train, treat_train,\n estimator_trmnt_fit_params={'cat_features': cat_features}, \n estimator_ctrl_fit_params={'cat_features': cat_features}\n)\n\nuplift_tm_trmnt = tm_trmnt.predict(X_val)\n\ntm_trmnt_score = uplift_at_k(y_true=y_val, uplift=uplift_tm_trmnt, treatment=treat_val, strategy='by_group', k=0.3)\n\nmodels_results['approach'].append('TwoModels_ddr_treatment')\nmodels_results['uplift@30%'].append(tm_trmnt_score)\n\nplot_uplift_preds(trmnt_preds=tm_trmnt.trmnt_preds_, ctrl_preds=tm_trmnt.ctrl_preds_);",
"_____no_output_____"
]
],
[
[
"## Conclusion\n\nLet's consider which method performed best in this task and use it to speed up the test sample:",
"_____no_output_____"
]
],
[
[
"pd.DataFrame(data=models_results).sort_values('uplift@30%', ascending=False)",
"_____no_output_____"
]
],
[
[
"From the table above you can see that the current task suits best for the approach to the transformation of the target line. Let's train the model on the entire sample and predict the test.",
"_____no_output_____"
]
],
[
[
"ct_full = ClassTransformation(CatBoostClassifier(iterations=20, thread_count=2, random_state=42, silent=True))\nct_full = ct_full.fit(\n X_train_full, \n y_train_full, \n treat_train_full, \n estimator_fit_params={'cat_features': cat_features}\n)\n\nX_test.loc[:, 'uplift'] = ct_full.predict(X_test.values)\n\nsub = X_test[['uplift']].to_csv('sub1.csv')\n\n!head -n 5 sub1.csv",
"/var/folders/zj/l29x8njj1yncqvpwgkycthvw0000gp/T/ipykernel_74119/678512574.py:2: UserWarning: It is recommended to use this approach on treatment balanced data. Current sample size is unbalanced.\n ct_full = ct_full.fit(\n"
],
[
"ct_full = pd.DataFrame({\n 'feature_name': ct_full.estimator.feature_names_,\n 'feature_score': ct_full.estimator.feature_importances_\n}).sort_values('feature_score', ascending=False).reset_index(drop=True)\n\nct_full",
"_____no_output_____"
]
],
[
[
"This way we got acquainted with uplift modeling and considered the main basic approaches to its construction. What's next? Then you can plunge them into the intelligence analysis of data, generate some new features, select the models and their hyperparameters and learn new approaches and libraries.\n\n**Thank you for reading to the end.**\n\n**I will be pleased if you support the project with an star on [github](https://github.com/maks-sh/scikit-uplift/) or tell your friends about it.**",
"_____no_output_____"
]
]
] |
[
"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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
4ac3aae39e0cfdbc8fe304fc4f273a1671a73c9f
| 40,264 |
ipynb
|
Jupyter Notebook
|
2017/201705_attributes_talk/Beijing Python.ipynb
|
littlepea/beijing-python-meetup
|
393d7723bc092ae548fe4e6ed82aa30ee3c7801d
|
[
"MIT"
] | 10 |
2016-11-15T10:39:36.000Z
|
2020-01-14T04:59:08.000Z
|
2017/201705_attributes_talk/Beijing Python.ipynb
|
littlepea/beijing-python-meetup
|
393d7723bc092ae548fe4e6ed82aa30ee3c7801d
|
[
"MIT"
] | 7 |
2017-01-10T05:40:05.000Z
|
2020-06-28T05:59:20.000Z
|
2017/201705_attributes_talk/Beijing Python.ipynb
|
littlepea/beijing-python-meetup
|
393d7723bc092ae548fe4e6ed82aa30ee3c7801d
|
[
"MIT"
] | 3 |
2017-09-19T09:12:31.000Z
|
2018-10-31T06:35:21.000Z
| 23.768595 | 572 | 0.505116 |
[
[
[
"s = 'abc'",
"_____no_output_____"
],
[
"s.upper()",
"_____no_output_____"
],
[
"# L E G B\n# local\n# enclosing\n# global\n# builtins\nglobals()",
"_____no_output_____"
],
[
"globals()['s']",
"_____no_output_____"
],
[
"s.upper()",
"_____no_output_____"
],
[
"dir(s)",
"_____no_output_____"
],
[
"s.title()",
"_____no_output_____"
],
[
"x = 'this is a bunch of words to show to people'\nx.title()",
"_____no_output_____"
],
[
"for attrname in dir(s):\n print attrname, s.attrname",
"__add__"
],
[
"for attrname in dir(s):\n print attrname, getattr(s, attrname)",
" __add__ <method-wrapper '__add__' of str object at 0x10e688418>\n__class__ <type 'str'>\n__contains__ <method-wrapper '__contains__' of str object at 0x10e688418>\n__delattr__ <method-wrapper '__delattr__' of str object at 0x10e688418>\n__doc__ str(object='') -> string\n\nReturn a nice string representation of the object.\nIf the argument is a string, the return value is the same object.\n__eq__ <method-wrapper '__eq__' of str object at 0x10e688418>\n__format__ <built-in method __format__ of str object at 0x10e688418>\n__ge__ <method-wrapper '__ge__' of str object at 0x10e688418>\n__getattribute__ <method-wrapper '__getattribute__' of str object at 0x10e688418>\n__getitem__ <method-wrapper '__getitem__' of str object at 0x10e688418>\n__getnewargs__ <built-in method __getnewargs__ of str object at 0x10e688418>\n__getslice__ <method-wrapper '__getslice__' of str object at 0x10e688418>\n__gt__ <method-wrapper '__gt__' of str object at 0x10e688418>\n__hash__ <method-wrapper '__hash__' of str object at 0x10e688418>\n__init__ <method-wrapper '__init__' of str object at 0x10e688418>\n__le__ <method-wrapper '__le__' of str object at 0x10e688418>\n__len__ <method-wrapper '__len__' of str object at 0x10e688418>\n__lt__ <method-wrapper '__lt__' of str object at 0x10e688418>\n__mod__ <method-wrapper '__mod__' of str object at 0x10e688418>\n__mul__ <method-wrapper '__mul__' of str object at 0x10e688418>\n__ne__ <method-wrapper '__ne__' of str object at 0x10e688418>\n__new__ <built-in method __new__ of type object at 0x10e161420>\n__reduce__ <built-in method __reduce__ of str object at 0x10e688418>\n__reduce_ex__ <built-in method __reduce_ex__ of str object at 0x10e688418>\n__repr__ <method-wrapper '__repr__' of str object at 0x10e688418>\n__rmod__ <method-wrapper '__rmod__' of str object at 0x10e688418>\n__rmul__ <method-wrapper '__rmul__' of str object at 0x10e688418>\n__setattr__ <method-wrapper '__setattr__' of str object at 0x10e688418>\n__sizeof__ <built-in method __sizeof__ of str object at 0x10e688418>\n__str__ <method-wrapper '__str__' of str object at 0x10e688418>\n__subclasshook__ <built-in method __subclasshook__ of type object at 0x10e161420>\n_formatter_field_name_split <built-in method _formatter_field_name_split of str object at 0x10e688418>\n_formatter_parser <built-in method _formatter_parser of str object at 0x10e688418>\ncapitalize <built-in method capitalize of str object at 0x10e688418>\ncenter <built-in method center of str object at 0x10e688418>\ncount <built-in method count of str object at 0x10e688418>\ndecode <built-in method decode of str object at 0x10e688418>\nencode <built-in method encode of str object at 0x10e688418>\nendswith <built-in method endswith of str object at 0x10e688418>\nexpandtabs <built-in method expandtabs of str object at 0x10e688418>\nfind <built-in method find of str object at 0x10e688418>\nformat <built-in method format of str object at 0x10e688418>\nindex <built-in method index of str object at 0x10e688418>\nisalnum <built-in method isalnum of str object at 0x10e688418>\nisalpha <built-in method isalpha of str object at 0x10e688418>\nisdigit <built-in method isdigit of str object at 0x10e688418>\nislower <built-in method islower of str object at 0x10e688418>\nisspace <built-in method isspace of str object at 0x10e688418>\nistitle <built-in method istitle of str object at 0x10e688418>\nisupper <built-in method isupper of str object at 0x10e688418>\njoin <built-in method join of str object at 0x10e688418>\nljust <built-in method ljust of str object at 0x10e688418>\nlower <built-in method lower of str object at 0x10e688418>\nlstrip <built-in method lstrip of str object at 0x10e688418>\npartition <built-in method partition of str object at 0x10e688418>\nreplace <built-in method replace of str object at 0x10e688418>\nrfind <built-in method rfind of str object at 0x10e688418>\nrindex <built-in method rindex of str object at 0x10e688418>\nrjust <built-in method rjust of str object at 0x10e688418>\nrpartition <built-in method rpartition of str object at 0x10e688418>\nrsplit <built-in method rsplit of str object at 0x10e688418>\nrstrip <built-in method rstrip of str object at 0x10e688418>\nsplit <built-in method split of str object at 0x10e688418>\nsplitlines <built-in method splitlines of str object at 0x10e688418>\nstartswith <built-in method startswith of str object at 0x10e688418>\nstrip <built-in method strip of str object at 0x10e688418>\nswapcase <built-in method swapcase of str object at 0x10e688418>\ntitle <built-in method title of str object at 0x10e688418>\ntranslate <built-in method translate of str object at 0x10e688418>\nupper <built-in method upper of str object at 0x10e688418>\nzfill <built-in method zfill of str object at 0x10e688418>\n"
],
[
"s.upper",
"_____no_output_____"
],
[
"getattr(s, 'upper')",
"_____no_output_____"
],
[
"while True:\n attrname = raw_input(\"Enter attribute name: \").strip()\n \n if not attrname: # if I got an empty string\n break\n elif attrname in dir(s):\n print getattr(s, attrname)\n else:\n print \"I don't know what {} is\".format(attrname)",
"Enter attribute name: title\n<built-in method title of str object at 0x10e688418>\nEnter attribute name: upcase\nI don't know what upcase is\nEnter attribute name: asdfafafas\nI don't know what asdfafafas is\nEnter attribute name: \n"
],
[
"s.upper",
"_____no_output_____"
],
[
"s.upper()",
"_____no_output_____"
],
[
"5()",
"_____no_output_____"
],
[
"s.upper.__call__",
"_____no_output_____"
],
[
"hasattr(s, 'upper')",
"_____no_output_____"
],
[
"import sys\n",
"_____no_output_____"
],
[
"sys.version",
"_____no_output_____"
],
[
"sys.version = '4.0.0'",
"_____no_output_____"
],
[
"sys.version",
"_____no_output_____"
],
[
"def foo():\n return 5\n\nfoo.x = 100",
"_____no_output_____"
],
[
"def hello(name):\n return \"Hello, {}\".format(name)",
"_____no_output_____"
],
[
"hello('world')",
"_____no_output_____"
],
[
"hello(123)",
"_____no_output_____"
],
[
"hello(hello)",
"_____no_output_____"
],
[
"class Foo(object):\n def __init__(self, x):\n self.x = x\n \n def __add__(self, other):\n return Foo(self.x + other.x)",
"_____no_output_____"
],
[
"f = Foo(10)",
"_____no_output_____"
],
[
"f.x",
"_____no_output_____"
],
[
"class Foo(object):\n pass\n\n",
"_____no_output_____"
],
[
"f = Foo()\nf.x = 100\nf.y = {'a':1, 'b':2, 'c':3}",
"_____no_output_____"
],
[
"vars(f)",
"_____no_output_____"
],
[
"g = Foo()\ng.a = [1,2,3]\ng.b = 'hello'",
"_____no_output_____"
],
[
"vars(g)",
"_____no_output_____"
],
[
"class Foo(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n \nf = Foo(10, [1,2,3])\nvars(f)",
"_____no_output_____"
],
[
"class Person(object):\n population = 0\n def __init__(self, name):\n self.name = name\n Person.population = self.population + 1 \n def hello(self):\n return \"Hello, {}\".format(self.name)\n\n \nprint \"population = {}\".format(Person.population)\np1 = Person('name1')\np2 = Person('name2')\nprint \"population = {}\".format(Person.population)\nprint \"p1.population = {}\".format(p1.population)\nprint \"p2.population = {}\".format(p2.population)\n\nprint p1.hello()",
"population = 0\npopulation = 2\np1.population = 2\np2.population = 2\nHello, name1\n"
],
[
"p1.thing",
"_____no_output_____"
],
[
"Person.thing = 'hello'\n\np1.thing",
"_____no_output_____"
],
[
"class Person(object):\n def __init__(self, name):\n self.name = name\n def hello(self):\n return \"Hello, {}\".format(self.name)\n \nclass Employee(Person):\n def __init__(self, name, id_number):\n Person.__init__(self, name)\n self.id_number = id_number\n \ne = Employee('emp1', 1)\ne.hello()",
"_____no_output_____"
],
[
"e.hello()",
"_____no_output_____"
],
[
"Person.hello(e)",
"_____no_output_____"
]
],
[
[
"OBJECT.METHOD() # CLASS.METHOD(OBJECT)",
"_____no_output_____"
]
],
[
[
"s = 'abc'\ns.upper()",
"_____no_output_____"
],
[
"str.upper(s)",
"_____no_output_____"
],
[
"type(s)",
"_____no_output_____"
],
[
"id(s)",
"_____no_output_____"
],
[
"type(Person.hello)",
"_____no_output_____"
],
[
"id(Person.hello)",
"_____no_output_____"
],
[
"id(Person.hello)",
"_____no_output_____"
],
[
"id(Person.hello)",
"_____no_output_____"
],
[
"Person.__dict__",
"_____no_output_____"
],
[
"Person.__dict__['hello'](e)",
"_____no_output_____"
],
[
"# descriptor protocol",
"_____no_output_____"
],
[
"class Thermostat(object):\n def __init__(self):\n self.temp = 20\n\nt = Thermostat()\nt.temp = 100",
"_____no_output_____"
],
[
"t.temp = 0",
"_____no_output_____"
],
[
"class Thermostat(object):\n def __init__(self):\n self._temp = 20 # now it's private!\n \n @property\n def temp(self):\n print \"getting temp\"\n return self._temp\n \n @temp.setter\n def temp(self, new_temp):\n print \"setting temp\"\n if new_temp > 35:\n print \"Too high!\"\n new_temp = 35\n elif new_temp < 0:\n print \"Too low!\"\n new_temp = 0\n \n self._temp = new_temp\n\nt = Thermostat()\nt.temp = 100\nprint t.temp\nt.temp = -40\nprint t.temp",
"setting temp\nToo high!\ngetting temp\n35\nsetting temp\nToo low!\ngetting temp\n0\n"
],
[
"# Temp will be a descriptor!\nclass Temp(object):\n def __get__(self, obj, objtype):\n return self.temp\n def __set__(self, obj, newval):\n if newval > 35:\n newval = 35\n if newval < 0:\n newval = 0\n self.temp = newval\n\nclass Thermostat(object):\n temp = Temp() # temp is a class attribute, instance of Temp\n \nt1 = Thermostat()\nt2 = Thermostat()\n\nt1.temp = 100\nt2.temp = 20\n\nprint t1.temp\nprint t2.temp",
"20\n20\n"
],
[
"# Temp will be a descriptor!\nclass Temp(object):\n def __init__(self):\n self.temp = {}\n def __get__(self, obj, objtype):\n return self.temp[obj]\n def __set__(self, obj, newval):\n if newval > 35:\n newval = 35\n if newval < 0:\n newval = 0\n self.temp[obj] = newval\n\nclass Thermostat(object):\n temp = Temp() # temp is a class attribute, instance of Temp\n \nt1 = Thermostat()\nt2 = Thermostat()\n\nt1.temp = 100\nt2.temp = 20\n\nprint t1.temp\nprint t2.temp",
"35\n20\n"
]
]
] |
[
"code",
"raw",
"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"
],
[
"raw"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac3ace6e223bd88b17f29ddc680331d5cfdae72
| 380,383 |
ipynb
|
Jupyter Notebook
|
Course-2: Convolutional Neural Networks in TensorFlow/Week-4/C2_W4_Lab_1_multi_class_classifier.ipynb
|
GurpreetMeelu/Tensorflow-Practice
|
07e64e01e5895ed56a008b2e406b949a30821250
|
[
"MIT"
] | 2 |
2021-12-08T07:23:45.000Z
|
2021-12-18T07:29:46.000Z
|
Course-2: Convolutional Neural Networks in TensorFlow/Week-4/C2_W4_Lab_1_multi_class_classifier.ipynb
|
GurpreetMeelu/DeepLearning.AI-TensorFlow-Developer
|
07e64e01e5895ed56a008b2e406b949a30821250
|
[
"MIT"
] | null | null | null |
Course-2: Convolutional Neural Networks in TensorFlow/Week-4/C2_W4_Lab_1_multi_class_classifier.ipynb
|
GurpreetMeelu/DeepLearning.AI-TensorFlow-Developer
|
07e64e01e5895ed56a008b2e406b949a30821250
|
[
"MIT"
] | null | null | null | 608.6128 | 62,458 | 0.931932 |
[
[
[
"##### Copyright 2019 The TensorFlow Authors.",
"_____no_output_____"
],
[
"**IMPORTANT NOTE:** This notebook is designed to run as a Colab. Click the button on top that says, `Open in Colab`, to run this notebook as a Colab. Running the notebook on your local machine might result in some of the code blocks throwing errors.",
"_____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_____"
],
[
"# rps training set\n!gdown --id 1DYVMuV2I_fA6A3er-mgTavrzKuxwpvKV\n \n# rps testing set\n!gdown --id 1RaodrRK1K03J_dGiLu8raeUynwmIbUaM",
"Downloading...\nFrom: https://drive.google.com/uc?id=1DYVMuV2I_fA6A3er-mgTavrzKuxwpvKV\nTo: /content/rps.zip\n100% 201M/201M [00:02<00:00, 75.1MB/s]\nDownloading...\nFrom: https://drive.google.com/uc?id=1RaodrRK1K03J_dGiLu8raeUynwmIbUaM\nTo: /content/rps-test-set.zip\n100% 29.5M/29.5M [00:00<00:00, 81.1MB/s]\n"
],
[
"import os\nimport zipfile\n\nlocal_zip = './rps.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('tmp/rps-train')\nzip_ref.close()\n\nlocal_zip = './rps-test-set.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('tmp/rps-test')\nzip_ref.close()",
"_____no_output_____"
],
[
"base_dir = 'tmp/rps-train/rps'\n\nrock_dir = os.path.join(base_dir, 'rock')\npaper_dir = os.path.join(base_dir, 'paper')\nscissors_dir = os.path.join(base_dir, 'scissors')\n\nprint('total training rock images:', len(os.listdir(rock_dir)))\nprint('total training paper images:', len(os.listdir(paper_dir)))\nprint('total training scissors images:', len(os.listdir(scissors_dir)))\n\nrock_files = os.listdir(rock_dir)\nprint(rock_files[:10])\n\npaper_files = os.listdir(paper_dir)\nprint(paper_files[:10])\n\nscissors_files = os.listdir(scissors_dir)\nprint(scissors_files[:10])",
"total training rock images: 840\ntotal training paper images: 840\ntotal training scissors images: 840\n['rock07-k03-013.png', 'rock04-046.png', 'rock04-060.png', 'rock02-061.png', 'rock03-080.png', 'rock05ck01-026.png', 'rock02-099.png', 'rock03-010.png', 'rock05ck01-100.png', 'rock02-087.png']\n['paper02-055.png', 'paper05-020.png', 'paper02-099.png', 'paper06-099.png', 'paper02-053.png', 'paper05-110.png', 'paper02-014.png', 'paper02-096.png', 'paper07-101.png', 'paper04-027.png']\n['testscissors03-047.png', 'testscissors01-097.png', 'scissors01-115.png', 'testscissors02-114.png', 'scissors03-077.png', 'testscissors02-020.png', 'scissors04-086.png', 'scissors04-112.png', 'scissors03-076.png', 'scissors03-083.png']\n"
],
[
"%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\npic_index = 2\n\nnext_rock = [os.path.join(rock_dir, fname) \n for fname in rock_files[pic_index-2:pic_index]]\nnext_paper = [os.path.join(paper_dir, fname) \n for fname in paper_files[pic_index-2:pic_index]]\nnext_scissors = [os.path.join(scissors_dir, fname) \n for fname in scissors_files[pic_index-2:pic_index]]\n\nfor i, img_path in enumerate(next_rock+next_paper+next_scissors):\n #print(img_path)\n img = mpimg.imread(img_path)\n plt.imshow(img)\n plt.axis('Off')\n plt.show()",
"_____no_output_____"
],
[
"import tensorflow as tf\nimport keras_preprocessing\nfrom keras_preprocessing import image\nfrom keras_preprocessing.image import ImageDataGenerator\n\nTRAINING_DIR = \"tmp/rps-train/rps\"\ntraining_datagen = ImageDataGenerator(\n rescale = 1./255,\n\t rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest')\n\nVALIDATION_DIR = \"tmp/rps-test/rps-test-set\"\nvalidation_datagen = ImageDataGenerator(rescale = 1./255)\n\ntrain_generator = training_datagen.flow_from_directory(\n\tTRAINING_DIR,\n\ttarget_size=(150,150),\n\tclass_mode='categorical',\n batch_size=126\n)\n\nvalidation_generator = validation_datagen.flow_from_directory(\n\tVALIDATION_DIR,\n\ttarget_size=(150,150),\n\tclass_mode='categorical',\n batch_size=126\n)\n\nmodel = tf.keras.models.Sequential([\n # Note the input shape is the desired size of the image 150x150 with 3 bytes color\n # This is the first convolution\n tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(150, 150, 3)),\n tf.keras.layers.MaxPooling2D(2, 2),\n # The second convolution\n tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2,2),\n # The third convolution\n tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2,2),\n # The fourth convolution\n tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2,2),\n # Flatten the results to feed into a DNN\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dropout(0.5),\n # 512 neuron hidden layer\n tf.keras.layers.Dense(512, activation='relu'),\n tf.keras.layers.Dense(3, activation='softmax')\n])\n\n\nmodel.summary()\n\nmodel.compile(loss = 'categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n\nhistory = model.fit(train_generator, epochs=25, steps_per_epoch=20, validation_data = validation_generator, verbose = 1, validation_steps=3)\n\nmodel.save(\"rps.h5\")\n",
"Found 2520 images belonging to 3 classes.\nFound 372 images belonging to 3 classes.\nModel: \"sequential\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n conv2d (Conv2D) (None, 148, 148, 64) 1792 \n \n max_pooling2d (MaxPooling2D (None, 74, 74, 64) 0 \n ) \n \n conv2d_1 (Conv2D) (None, 72, 72, 64) 36928 \n \n max_pooling2d_1 (MaxPooling (None, 36, 36, 64) 0 \n 2D) \n \n conv2d_2 (Conv2D) (None, 34, 34, 128) 73856 \n \n max_pooling2d_2 (MaxPooling (None, 17, 17, 128) 0 \n 2D) \n \n conv2d_3 (Conv2D) (None, 15, 15, 128) 147584 \n \n max_pooling2d_3 (MaxPooling (None, 7, 7, 128) 0 \n 2D) \n \n flatten (Flatten) (None, 6272) 0 \n \n dropout (Dropout) (None, 6272) 0 \n \n dense (Dense) (None, 512) 3211776 \n \n dense_1 (Dense) (None, 3) 1539 \n \n=================================================================\nTotal params: 3,473,475\nTrainable params: 3,473,475\nNon-trainable params: 0\n_________________________________________________________________\nEpoch 1/25\n20/20 [==============================] - 43s 1s/step - loss: 1.1684 - accuracy: 0.3627 - val_loss: 1.1079 - val_accuracy: 0.3333\nEpoch 2/25\n20/20 [==============================] - 24s 1s/step - loss: 1.0562 - accuracy: 0.4290 - val_loss: 1.0197 - val_accuracy: 0.4167\nEpoch 3/25\n20/20 [==============================] - 25s 1s/step - loss: 1.0788 - accuracy: 0.4544 - val_loss: 0.9812 - val_accuracy: 0.4866\nEpoch 4/25\n20/20 [==============================] - 25s 1s/step - loss: 0.9241 - accuracy: 0.5794 - val_loss: 0.5942 - val_accuracy: 0.6667\nEpoch 5/25\n20/20 [==============================] - 24s 1s/step - loss: 0.7309 - accuracy: 0.6806 - val_loss: 0.3707 - val_accuracy: 0.8710\nEpoch 6/25\n20/20 [==============================] - 24s 1s/step - loss: 0.6913 - accuracy: 0.7151 - val_loss: 0.4567 - val_accuracy: 0.8522\nEpoch 7/25\n20/20 [==============================] - 24s 1s/step - loss: 0.4980 - accuracy: 0.7714 - val_loss: 0.6039 - val_accuracy: 0.6694\nEpoch 8/25\n20/20 [==============================] - 24s 1s/step - loss: 0.4587 - accuracy: 0.8095 - val_loss: 0.0950 - val_accuracy: 1.0000\nEpoch 9/25\n20/20 [==============================] - 24s 1s/step - loss: 0.3326 - accuracy: 0.8643 - val_loss: 0.2461 - val_accuracy: 0.9059\nEpoch 10/25\n20/20 [==============================] - 24s 1s/step - loss: 0.5032 - accuracy: 0.8198 - val_loss: 0.5459 - val_accuracy: 0.7742\nEpoch 11/25\n20/20 [==============================] - 24s 1s/step - loss: 0.2713 - accuracy: 0.9000 - val_loss: 0.3186 - val_accuracy: 0.8522\nEpoch 12/25\n20/20 [==============================] - 24s 1s/step - loss: 0.2353 - accuracy: 0.9167 - val_loss: 0.0762 - val_accuracy: 0.9785\nEpoch 13/25\n20/20 [==============================] - 24s 1s/step - loss: 0.2737 - accuracy: 0.9012 - val_loss: 1.4302 - val_accuracy: 0.5968\nEpoch 14/25\n20/20 [==============================] - 24s 1s/step - loss: 0.2178 - accuracy: 0.9278 - val_loss: 0.0201 - val_accuracy: 1.0000\nEpoch 15/25\n20/20 [==============================] - 24s 1s/step - loss: 0.1530 - accuracy: 0.9540 - val_loss: 0.1153 - val_accuracy: 0.9462\nEpoch 16/25\n20/20 [==============================] - 24s 1s/step - loss: 0.1652 - accuracy: 0.9373 - val_loss: 0.0139 - val_accuracy: 1.0000\nEpoch 17/25\n20/20 [==============================] - 24s 1s/step - loss: 0.1589 - accuracy: 0.9433 - val_loss: 0.0118 - val_accuracy: 1.0000\nEpoch 18/25\n20/20 [==============================] - 24s 1s/step - loss: 0.1690 - accuracy: 0.9369 - val_loss: 0.1383 - val_accuracy: 0.9462\nEpoch 19/25\n20/20 [==============================] - 24s 1s/step - loss: 0.0773 - accuracy: 0.9738 - val_loss: 0.3170 - val_accuracy: 0.8844\nEpoch 20/25\n20/20 [==============================] - 24s 1s/step - loss: 0.1121 - accuracy: 0.9615 - val_loss: 0.0299 - val_accuracy: 0.9919\nEpoch 21/25\n20/20 [==============================] - 24s 1s/step - loss: 0.2464 - accuracy: 0.9175 - val_loss: 0.0378 - val_accuracy: 0.9919\nEpoch 22/25\n20/20 [==============================] - 24s 1s/step - loss: 0.0826 - accuracy: 0.9722 - val_loss: 0.0191 - val_accuracy: 0.9946\nEpoch 23/25\n20/20 [==============================] - 24s 1s/step - loss: 0.0705 - accuracy: 0.9766 - val_loss: 0.0127 - val_accuracy: 0.9919\nEpoch 24/25\n20/20 [==============================] - 24s 1s/step - loss: 0.0944 - accuracy: 0.9627 - val_loss: 0.0182 - val_accuracy: 1.0000\nEpoch 25/25\n20/20 [==============================] - 24s 1s/step - loss: 0.0891 - accuracy: 0.9726 - val_loss: 0.0442 - val_accuracy: 0.9812\n"
],
[
"import matplotlib.pyplot as plt\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend(loc=0)\nplt.figure()\n\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"# Here's a codeblock just for fun!\nYou should be able to upload an image here and have it classified without crashing. This codeblock will only work in Google Colab, however.\n\n**Important Note:** Due to some compatibility issues, the following code block will result in an error after you select the images(s) to upload if you are running this notebook as a `Colab` on the `Safari` browser. For `all other broswers`, continue with the next code block and ignore the next one after it.\n\nThe ones running the `Colab` on `Safari`, comment out the code block below, uncomment the next code block and run it.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom google.colab import files\nfrom keras.preprocessing import image\n\nuploaded = files.upload()\n\nfor fn in uploaded.keys():\n \n # predicting images\n path = fn\n img = image.load_img(path, target_size=(150, 150))\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n\n images = np.vstack([x])\n classes = model.predict(images, batch_size=10)\n print(fn)\n print(classes)",
"_____no_output_____"
]
],
[
[
"For those running this `Colab` on `Safari` broswer can upload the images(s) manually. Follow the instructions, uncomment the code block below and run it.\n\nInstructions on how to upload image(s) manually in a Colab:\n\n1. Select the `folder` icon on the left `menu bar`.\n2. Click on the `folder with an arrow pointing upwards` named `..`\n3. Click on the `folder` named `tmp`.\n4. Inside of the `tmp` folder, `create a new folder` called `images`. You'll see the `New folder` option by clicking the `3 vertical dots` menu button next to the `tmp` folder.\n5. Inside of the new `images` folder, upload an image(s) of your choice, preferably of either a horse or a human. Drag and drop the images(s) on top of the `images` folder.\n6. Uncomment and run the code block below. ",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac3b3a460842654cfac57441253f1eedd27e62b
| 18,918 |
ipynb
|
Jupyter Notebook
|
examples/003_pandapower_modelexchange/template.ipynb
|
LBNL-ETA/fmi-for-power-system
|
7f1818278226a4069a6b90a9b3c4045ebad5f5d5
|
[
"BSD-3-Clause-LBNL"
] | 7 |
2019-03-21T16:47:28.000Z
|
2021-12-17T17:39:51.000Z
|
examples/003_pandapower_modelexchange/template.ipynb
|
LBNL-ETA/fmi-for-power-system
|
7f1818278226a4069a6b90a9b3c4045ebad5f5d5
|
[
"BSD-3-Clause-LBNL"
] | 3 |
2018-07-16T21:44:58.000Z
|
2018-07-16T21:47:11.000Z
|
examples/003_pandapower_modelexchange/template.ipynb
|
LBNL-ETA/fmi-for-power-system
|
7f1818278226a4069a6b90a9b3c4045ebad5f5d5
|
[
"BSD-3-Clause-LBNL"
] | 3 |
2019-03-13T13:54:15.000Z
|
2020-07-08T08:24:47.000Z
| 35.69434 | 166 | 0.49186 |
[
[
[
"# ###############################################\n# ########## Default Parameters #################\n# ###############################################\nstart = '2016-06-16 22:00:00'\nend = '2016-06-18 00:00:00'\npv_nominal_kw = 5000 # There are 3 PV locations hardcoded at node 7, 8, 9\ninverter_sizing = 1.05\ninverter_qmax_percentage = 0.44\nthrP = 0.04\nhysP = 0.06\nthrQ = 0.03\nhysQ = 0.03\nfirst_order_time_const = 1 * 60\nsolver_relative_tolerance = 0.1\nsolver_absolute_tolerance = 0.1\nsolver_name = 'CVode'\nresult_filename = 'result'",
"_____no_output_____"
],
[
"import warnings\nwarnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\")\nwarnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\")\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nimport pandas\nimport numpy\nimport datetime\nfrom tabulate import tabulate\nimport json\nimport re\n\n# Imports useful for graphics\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn\nseaborn.set_style(\"whitegrid\")\nseaborn.despine()\n%matplotlib inline\nfont = {'size' : 14}\nmatplotlib.rc('font', **font)\n\n# Date conversion\nbegin = '2016-01-01 00:00:00'\nbegin_dt = datetime.datetime.strptime(begin, '%Y-%m-%d %H:%M:%S')\nstart_dt = datetime.datetime.strptime(start, '%Y-%m-%d %H:%M:%S')\nend_dt = datetime.datetime.strptime(end, '%Y-%m-%d %H:%M:%S')\nstart_s = int((start_dt - begin_dt).total_seconds())\nend_s = int((end_dt - begin_dt).total_seconds())",
"_____no_output_____"
],
[
"inverter_smax = pv_nominal_kw * inverter_sizing\ninverter_qmax = inverter_smax * inverter_qmax_percentage\npv_inverter_parameters = {\n 'weather_file':(path_to_fmiforpowersystems +\n 'examples\\\\002_cosimulation_custom_master\\\\pv_inverter\\\\' +\n 'USA_CA_San.Francisco.Intl.AP.724940_TMY3.mos'),\n 'n': 1,\n 'A': (pv_nominal_kw * 1000) / (0.158 * 1000),\n 'eta': 0.158,\n 'lat': 37.9,\n 'til': 10,\n 'azi': 0,\n 'thrP': thrP, #0.05,\n 'hysP': hysP, #0.04,\n 'thrQ': thrQ, #0.04,\n 'hysQ': hysQ, #0.01,\n 'SMax': inverter_smax,\n 'QMaxInd': inverter_qmax,\n 'QMaxCap': inverter_qmax,\n 'Tfirstorder': first_order_time_const,\n}\n\n\nfirst_order_parameters = {\n 'T': first_order_time_const\n}\n\n\nrun_simulation = True\nconnections_filename = 'connections.xlsx'\npv_inverter_path = 'pv_inverter/Pv_Inv_VoltVarWatt_simple_Slim.fmu'\npv_inverter_path = 'pv_inverter/PV_0Inv_0VoltVarWat_0simple_0Slim_Pv_0Inv_0VoltVarWatt_0simple_0Slim.fmu'\npandapower_path = 'pandapower/pandapower.fmu'\npandapower_folder = 'pandapower'\npandapower_parameter = {}\nfirstorder_path = 'firstorder/FirstOrder.fmu'",
"_____no_output_____"
]
],
[
[
"## Create the connection mapping",
"_____no_output_____"
]
],
[
[
"connections = pandas.DataFrame(columns=['fmu1_id', 'fmu1_path',\n 'fmu2_id', 'fmu2_path',\n 'fmu1_parameters',\n 'fmu2_parameters',\n 'fmu1_output',\n 'fmu2_input'])\n\n# Connection for each customer\nnodes = [7, 9, 24]\nfor index in nodes:\n connections = connections.append(\n {'fmu1_id': 'PV' + str(index),\n 'fmu1_path': pv_inverter_path,\n 'fmu2_id': 'pandapower',\n 'fmu2_path': pandapower_path,\n 'fmu1_parameters': pv_inverter_parameters,\n 'fmu2_parameters': pandapower_parameter,\n 'fmu1_output': 'P',\n 'fmu2_input': 'KW_' + str(index)},\n ignore_index=True) \n connections = connections.append(\n {'fmu1_id': 'PV' + str(index),\n 'fmu1_path': pv_inverter_path,\n 'fmu2_id': 'pandapower',\n 'fmu2_path': pandapower_path,\n 'fmu1_parameters': pv_inverter_parameters,\n 'fmu2_parameters': pandapower_parameter,\n 'fmu1_output': 'Q',\n 'fmu2_input': 'KVAR_' + str(index)},\n ignore_index=True)\n connections = connections.append(\n {'fmu1_id': 'pandapower',\n 'fmu1_path': pandapower_path,\n 'fmu2_id': 'firstorder' + str(index),\n 'fmu2_path': firstorder_path,\n 'fmu1_parameters': pandapower_parameter,\n 'fmu2_parameters': first_order_parameters,\n 'fmu1_output': 'Vpu_' + str(index),\n 'fmu2_input': 'u'},\n ignore_index=True)\n connections = connections.append(\n {'fmu1_id': 'firstorder' + str(index),\n 'fmu1_path': firstorder_path,\n 'fmu2_id': 'PV' + str(index),\n 'fmu2_path': pv_inverter_path,\n 'fmu1_parameters': first_order_parameters,\n 'fmu2_parameters': pv_inverter_parameters,\n 'fmu1_output': 'y',\n 'fmu2_input': 'v'},\n ignore_index=True)\n \ndef _sanitize_name(name):\n \"\"\"\n Make a Modelica valid name.\n In Modelica, a variable name:\n Can contain any of the characters {a-z,A-Z,0-9,_}.\n Cannot start with a number.\n :param name(str): Variable name to be sanitized.\n :return: Sanitized variable name.\n \"\"\"\n\n # Check if variable has a length > 0\n assert(len(name) > 0), 'Require a non-null variable name.'\n\n # If variable starts with a number add 'f_'.\n if(name[0].isdigit()):\n name = 'f_' + name\n\n # Replace all illegal characters with an underscore.\n g_rexBadIdChars = re.compile(r'[^a-zA-Z0-9_]')\n name = g_rexBadIdChars.sub('_', name)\n return name\nconnections['fmu1_output'] = connections['fmu1_output'].apply(lambda x: _sanitize_name(x))\nconnections['fmu2_input'] = connections['fmu2_input'].apply(lambda x: _sanitize_name(x))\n\nprint(tabulate(connections[\n ['fmu1_id', 'fmu2_id', 'fmu1_output', 'fmu2_input']].head(),\n headers='keys', tablefmt='psql'))\nprint(tabulate(connections[\n ['fmu1_id', 'fmu2_id', 'fmu1_output', 'fmu2_input']].tail(),\n headers='keys', tablefmt='psql'))\nconnections.to_excel(connections_filename, index=False)",
"+----+-------------+-------------+---------------+--------------+\n| | fmu1_id | fmu2_id | fmu1_output | fmu2_input |\n|----+-------------+-------------+---------------+--------------|\n| 0 | PV7 | pandapower | P | KW_7 |\n| 1 | PV7 | pandapower | Q | KVAR_7 |\n| 2 | pandapower | firstorder7 | Vpu_7 | u |\n| 3 | firstorder7 | PV7 | y | v |\n| 4 | PV9 | pandapower | P | KW_9 |\n+----+-------------+-------------+---------------+--------------+\n+----+--------------+--------------+---------------+--------------+\n| | fmu1_id | fmu2_id | fmu1_output | fmu2_input |\n|----+--------------+--------------+---------------+--------------|\n| 7 | firstorder9 | PV9 | y | v |\n| 8 | PV24 | pandapower | P | KW_24 |\n| 9 | PV24 | pandapower | Q | KVAR_24 |\n| 10 | pandapower | firstorder24 | Vpu_24 | u |\n| 11 | firstorder24 | PV24 | y | v |\n+----+--------------+--------------+---------------+--------------+\n"
]
],
[
[
"# Launch FMU simulation",
"_____no_output_____"
]
],
[
[
"if run_simulation:\n import shlex, subprocess\n cmd = (\"C:/JModelica.org-2.4/setenv.bat && \" +\n \" cd \" + pandapower_folder + \" && \"\n \"cyderc \" +\n \" --path ./\"\n \" --name pandapower\" +\n \" --io pandapower.xlsx\" +\n \" --path_to_simulatortofmu C:/Users/DRRC/Desktop/Joscha/SimulatorToFMU/simulatortofmu/parser/SimulatorToFMU.py\"\n \" --fmu_struc python\") \n args = shlex.split(cmd)\n process = subprocess.Popen(args, bufsize=1, universal_newlines=True)\n process.wait()\n process.kill()",
"_____no_output_____"
],
[
"if run_simulation:\n import os\n import signal\n import shlex, subprocess\n cmd = (\"C:/JModelica.org-2.4/setenv.bat && \" +\n \"cyders \" +\n \" --start \" + str(start_s) +\n \" --end \" + str(end_s) +\n \" --connections \" + connections_filename +\n \" --nb_steps 25\" +\n \" --solver \" + solver_name +\n \" --rtol \" + str(solver_relative_tolerance) +\n \" --atol \" + str(solver_absolute_tolerance) +\n \" --result \" + 'results/' + result_filename + '.csv') \n args = shlex.split(cmd)\n process = subprocess.Popen(args, bufsize=1, universal_newlines=True,\n creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)\n process.wait()\n process.send_signal(signal.CTRL_BREAK_EVENT)\n process.kill()\n print('Killed')",
"_____no_output_____"
]
],
[
[
"# Plot results",
"_____no_output_____"
]
],
[
[
"# Load results\nresults = pandas.read_csv('results/' + result_filename + '.csv')\nfrom pathlib import Path, PureWindowsPath\nresults = pandas.read_csv(os.path.join(r'C:\\Users\\DRRC\\Desktop\\Jonathan\\voltvarwatt_with_cyme_fmus\\usecases\\004_pp_first_order\\results\\result.csv'))\nepoch = datetime.datetime.utcfromtimestamp(0)\nbegin_since_epoch = (begin_dt - epoch).total_seconds()\nresults['datetime'] = results['time'].apply(\n lambda x: datetime.datetime.utcfromtimestamp(begin_since_epoch + x))\nresults.set_index('datetime', inplace=True, drop=False)\nprint('COLUMNS=')\nprint(results.columns)\nprint('START=')\nprint(results.head(1).index[0])\nprint('END=')\nprint(results.tail(1).index[0])",
"_____no_output_____"
],
[
"# Plot sum of all PVs for P and P curtailled and Q\ncut = '2016-06-17 01:00:00'\nfig, axes = plt.subplots(1, 1, figsize=(11, 3))\nplt.title('PV generation')\nfor node in nodes:\n plt.plot(results['datetime'],\n results['pandapower.KW_' + str(node)] / 1000,\n linewidth=3, alpha=0.7, label='node ' + str(node))\nplt.legend(loc=0)\nplt.ylabel('PV active power [MW]')\nplt.xlabel('Time')\nplt.xlim([cut, end])\nplt.show()\n\nfig, axes = plt.subplots(1, 1, figsize=(11, 3))\nplt.title('Inverter reactive power')\nfor node in nodes:\n plt.plot(results['datetime'],\n results['pandapower.KVAR_' + str(node)] / 1000,\n linewidth=3, alpha=0.7, label='node ' + str(node))\nplt.legend(loc=0)\nplt.ylabel('PV reactive power [MVAR]')\nplt.xlabel('Time')\nplt.xlim([cut, end])\nplt.show()\n\nfig, axes = plt.subplots(1, 1, figsize=(11, 3))\nplt.title('PV voltage')\nfor node in nodes:\n plt.plot(results['datetime'],\n results['pandapower.Vpu_' + str(node)],\n linewidth=3, alpha=0.7, label='node ' + str(node))\nplt.legend(loc=0)\nplt.ylabel('PV voltage [p.u.]')\nplt.xlabel('Time')\nplt.xlim([cut, end])\nplt.ylim([0.95, results[['pandapower.Vpu_' + str(node)\n for node in nodes]].max().max()])\nplt.show()\n",
"_____no_output_____"
],
[
"# Plot time/voltage\nfig, axes = plt.subplots(1, 1, figsize=(11, 3))\nplt.title('Feeder Voltages')\nplt.plot(results['datetime'],\n results[[col for col in results.columns\n if 'Vpu' in col and 'transfer' not in col]],\n linewidth=3, alpha=0.7)\nplt.ylabel('Voltage [p.u.]')\nplt.xlabel('Time')\nplt.ylim([0.95, results[[col for col in results.columns\n if 'Vpu' in col and 'transfer' not in col]].max().max()])\nplt.show()",
"_____no_output_____"
],
[
"# Load results\ndebug = pandas.read_csv('debug.csv', parse_dates=[1])\nepoch = datetime.datetime.utcfromtimestamp(0)\nbegin_since_epoch = (begin_dt - epoch).total_seconds()\ndebug['datetime'] = debug['sim_time'].apply(\n lambda x: datetime.datetime.utcfromtimestamp(begin_since_epoch + x))\ndebug.set_index('datetime', inplace=True, drop=False)\nprint('COLUMNS=')\nprint(debug.columns)\nprint('START=')\nprint(debug.head(1).index[0])\nprint('END=')\nprint(debug.tail(1).index[0])",
"_____no_output_____"
],
[
"# Plot time/voltage\nimport matplotlib.dates as mdates\nprint('Number of evaluation=' + str(len(debug)))\nfig, axes = plt.subplots(1, 1, figsize=(11, 8))\nplt.plot(debug['clock'],\n debug['datetime'],\n linewidth=3, alpha=0.7)\nplt.ylabel('Simulation time')\nplt.xlabel('Computer clock')\nplt.gcf().autofmt_xdate()\nmyFmt = mdates.DateFormatter('%H:%M')\nplt.gca().xaxis.set_major_formatter(myFmt)\nplt.show()\n\nfig, axes = plt.subplots(1, 1, figsize=(11, 3))\nplt.plot(debug['clock'],\n debug['KW_7'],\n linewidth=3, alpha=0.7)\nplt.plot(debug['clock'],\n debug['KW_9'],\n linewidth=3, alpha=0.7)\nplt.plot(debug['clock'],\n debug['KW_24'],\n linewidth=3, alpha=0.7)\nplt.ylabel('KW')\nplt.xlabel('Computer clock')\nplt.legend([17, 31, 24], loc=0)\nplt.show()\n\nfig, axes = plt.subplots(1, 1, figsize=(11, 3))\nplt.plot(debug['clock'],\n debug['Vpu_7'],\n linewidth=3, alpha=0.7)\nplt.plot(debug['clock'],\n debug['Vpu_9'],\n linewidth=3, alpha=0.7)\nplt.plot(debug['clock'],\n debug['Vpu_24'],\n linewidth=3, alpha=0.7)\nplt.ylabel('Vpu')\nplt.xlabel('Computer clock')\nplt.show()\n\nfig, axes = plt.subplots(1, 1, figsize=(11, 3))\nplt.plot(debug['clock'],\n debug['Vpu_7'].diff(),\n linewidth=3, alpha=0.7)\nplt.plot(debug['clock'],\n debug['Vpu_9'].diff(),\n linewidth=3, alpha=0.7)\nplt.plot(debug['clock'],\n debug['Vpu_24'].diff(),\n linewidth=3, alpha=0.7)\nplt.ylabel('Vpu Diff')\nplt.xlabel('Computer clock')\nplt.show()\n\nfig, axes = plt.subplots(1, 1, figsize=(11, 3))\nplt.plot(debug['clock'],\n debug['KVAR_7'],\n linewidth=3, alpha=0.7)\nplt.plot(debug['clock'],\n debug['KVAR_9'],\n linewidth=3, alpha=0.7)\nplt.plot(debug['clock'],\n debug['KVAR_24'],\n linewidth=3, alpha=0.7)\nplt.ylabel('KVAR')\nplt.xlabel('Computer clock')\nplt.show()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
4ac3c147d9bd498b5ccf6ce1761f374ed1210501
| 7,681 |
ipynb
|
Jupyter Notebook
|
examples/models/custom_metrics/customMetrics.ipynb
|
ttapjinda/seldon-core
|
b3ca7684b4882f2499a0ab636074d8c19f3f2797
|
[
"Apache-2.0"
] | null | null | null |
examples/models/custom_metrics/customMetrics.ipynb
|
ttapjinda/seldon-core
|
b3ca7684b4882f2499a0ab636074d8c19f3f2797
|
[
"Apache-2.0"
] | null | null | null |
examples/models/custom_metrics/customMetrics.ipynb
|
ttapjinda/seldon-core
|
b3ca7684b4882f2499a0ab636074d8c19f3f2797
|
[
"Apache-2.0"
] | null | null | null | 23.346505 | 197 | 0.538862 |
[
[
[
"# Basic Examples with Different Protocols\n\n## Prerequisites\n\n * A kubernetes cluster with kubectl configured\n * curl\n * grpcurl\n * pygmentize\n \n\n## Setup Seldon Core\n\nUse the setup notebook to [Setup Cluster](seldon_core_setup.ipynb) to setup Seldon Core with an ingress - either Ambassador or Istio.\n\nThen port-forward to that ingress on localhost:8003 in a separate terminal either with:\n\n * Ambassador: `kubectl port-forward $(kubectl get pods -n seldon -l app.kubernetes.io/name=ambassador -o jsonpath='{.items[0].metadata.name}') -n seldon 8003:8080`\n * Istio: `kubectl port-forward $(kubectl get pods -l istio=ingressgateway -n istio-system -o jsonpath='{.items[0].metadata.name}') -n istio-system 8003:80`",
"_____no_output_____"
],
[
"## Install Seldon Analytics",
"_____no_output_____"
]
],
[
[
"!helm install seldon-core-analytics ../../../helm-charts/seldon-core-analytics -n seldon-system --wait",
"_____no_output_____"
],
[
"!kubectl create namespace seldon",
"_____no_output_____"
],
[
"!kubectl config set-context $(kubectl config current-context) --namespace=seldon",
"_____no_output_____"
],
[
"import json\nimport time",
"_____no_output_____"
]
],
[
[
"## Custom Metrics with a REST model",
"_____no_output_____"
]
],
[
[
"!pygmentize model_rest.yaml",
"_____no_output_____"
],
[
"!kubectl create -f model_rest.yaml",
"_____no_output_____"
],
[
"!kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=seldon-model \\\n -o jsonpath='{.items[0].metadata.name}')",
"_____no_output_____"
],
[
"responseRaw=!curl -s -d '{\"data\": {\"ndarray\":[[1.0, 2.0, 5.0]]}}' -X POST http://localhost:8003/seldon/seldon/seldon-model/api/v1.0/predictions -H \"Content-Type: application/json\"",
"_____no_output_____"
],
[
"response=json.loads(responseRaw[0])\nprint(response)\nassert(len(response[\"meta\"][\"metrics\"]) == 3)",
"_____no_output_____"
],
[
"print(\"Waiting so metrics can be scraped\")\ntime.sleep(3)",
"_____no_output_____"
],
[
"%%writefile get-metrics.sh\n\nkubectl run --quiet=true -it --rm curl --image=tutum/curl --restart=Never -- \\\n curl -s seldon-core-analytics-prometheus-seldon.seldon-system/api/v1/query?query=mycounter_total",
"_____no_output_____"
],
[
"responseRaw =! bash get-metrics.sh",
"_____no_output_____"
],
[
"responseRaw[0]",
"_____no_output_____"
],
[
"response=json.loads(responseRaw[0])\nprint(response)\nassert(response['data'][\"result\"][0][\"metric\"][\"__name__\"]=='mycounter_total')",
"_____no_output_____"
],
[
"!kubectl delete -f model_rest.yaml",
"_____no_output_____"
]
],
[
[
"## Custom Metrics with a GRPC model",
"_____no_output_____"
]
],
[
[
"!pygmentize model_grpc.yaml",
"_____no_output_____"
],
[
"!kubectl create -f model_grpc.yaml",
"_____no_output_____"
],
[
"!kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=seldon-model \\\n -o jsonpath='{.items[0].metadata.name}')",
"_____no_output_____"
],
[
"responseRaw=!curl -s -d '{\"data\": {\"ndarray\":[[1.0, 2.0, 5.0]]}}' -X POST http://localhost:8003/seldon/seldon/seldon-model/api/v1.0/predictions -H \"Content-Type: application/json\"",
"_____no_output_____"
],
[
"responseRaw=!cd ../../../executor/proto && grpcurl -d '{\"data\":{\"ndarray\":[[1.0,2.0,5.0]]}}' \\\n -rpc-header seldon:seldon-model -rpc-header namespace:seldon \\\n -plaintext \\\n -proto ./prediction.proto 0.0.0.0:8003 seldon.protos.Seldon/Predict",
"_____no_output_____"
],
[
"response=json.loads(\"\".join(responseRaw))\nprint(response)\nassert(len(response[\"meta\"][\"metrics\"]) == 3)",
"_____no_output_____"
],
[
"print(\"Waiting so metrics can be scraped\")\ntime.sleep(3)",
"_____no_output_____"
],
[
"responseRaw =! bash get-metrics.sh",
"_____no_output_____"
],
[
"response=json.loads(responseRaw[0])\nprint(response)\nassert(response['data'][\"result\"][0][\"metric\"][\"__name__\"]=='mycounter_total')\nassert(response['data'][\"result\"][0][\"metric\"][\"image_name\"]=='seldonio/model-with-metrics_grpc')",
"_____no_output_____"
],
[
"!kubectl delete -f model_grpc.yaml",
"_____no_output_____"
],
[
"!helm delete seldon-core-analytics --namespace seldon-system",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac3ced8267b72737fa57271fab5b523fcd4dfe1
| 20,637 |
ipynb
|
Jupyter Notebook
|
prerequisites/Python/Python reference.ipynb
|
mbeni12333/machine-learning
|
3421b86c75452a7c285326ae52747f3dc9083553
|
[
"MIT"
] | null | null | null |
prerequisites/Python/Python reference.ipynb
|
mbeni12333/machine-learning
|
3421b86c75452a7c285326ae52747f3dc9083553
|
[
"MIT"
] | null | null | null |
prerequisites/Python/Python reference.ipynb
|
mbeni12333/machine-learning
|
3421b86c75452a7c285326ae52747f3dc9083553
|
[
"MIT"
] | null | null | null | 18.344 | 122 | 0.442119 |
[
[
[
"# Welcome to Python reference\n this notebook contains pretty much every thing, if you want to refresh your knowledge or what so ever \n it will help you ;D",
"_____no_output_____"
],
[
"<ul>\n <li>Data types<ul>\n <li>Numbers</li>\n <li>Strings</li>\n <li>Lists</li>\n <li>Dictionairies</li>\n <li>Booleans</li>\n <li>Tuples</li>\n <li>Sets</li>\n <li>Printing</li>\n </ul></li>\n <li>Comparaison operators</li>\n <li>if, elif, else Statements</li>\n <li>for loops</li>\n <li>while loops</li>\n <li>range()</li>\n <li>functions</li>\n <li>lambda expressions</li>\n <li>map and filter</li>\n <li>inputs and castings</li>\n<ul>",
"_____no_output_____"
],
[
"## Data types :",
"_____no_output_____"
],
[
"### 1 - Numbers :",
"_____no_output_____"
]
],
[
[
"# operations on numbers \nprint(\"Addition 1 + 1 : \" + str(1 + 1) + \" Type of the output : \" + str(type(1 + 1))) #Addition\nprint(\"Devision 1 / 2 : \" + str(1 / 2) + \" Type of the output : \" + str(type(1 / 2))) #Devision\nprint(\"Multiplication 2 * 3 : \" + str(2 * 3) + \" Type of the output : \" + str(type(2 * 3))) #Multiplication\nprint(\"Modulus 2 % 3 : \" + str(2 % 3) + \" Type of the output : \" + str(type(2 % 3))) #Modulus\nprint(\"Exponential 2** 3 : \" + str(2** 3) + \" Type of the output :\" + str(type(2** 3))) #Exponential",
"Addition 1 + 1 : 2 Type of the output : <class 'int'>\nDevision 1 / 2 : 0.5 Type of the output : <class 'float'>\nMultiplication 2 * 3 : 6 Type of the output : <class 'int'>\nModulus 2 % 3 : 2 Type of the output : <class 'int'>\nExponential 2** 3 : 8 Type of the output :<class 'int'>\n"
]
],
[
[
"### 2 - Strings :",
"_____no_output_____"
]
],
[
[
"'this is a string'\n\"and this is also a string\"",
"_____no_output_____"
],
[
"hello = 'hello'",
"_____no_output_____"
],
[
"#format the print \nage = 17 \nname = 'titiche'\nprint('My name is {} and i\\'am {} years old'.format(name, age))",
"My name is titiche and i'am 17 years old\n"
],
[
"#strings are also arrays with indexes , remember indexes start with 0\nprint(\"full string : \" + name)#the full string\nprint(\"index : \" + name[3])#character in the index 3\nprint(\"slicing : \" + name[2:])#you can slice a string starting from an index to the end \nprint(\"slicing : \" + name[:-2])#also another slicing starting from the begenning to the -2 index before last ",
"full string : titiche\nindex : i\nslicing : tiche\nslicing : titic\n"
]
],
[
[
"### 3 - Lists :",
"_____no_output_____"
]
],
[
[
"#lists are sequence of elements separated by commas\na = [1, 2, 3] # this is a list\na",
"_____no_output_____"
],
[
"a = ['A', 'B', 'C', 3] # this is also a list",
"_____no_output_____"
],
[
"a",
"_____no_output_____"
],
[
"# to Add an element to the end of list\na.append(name)\na",
"_____no_output_____"
],
[
"#you can slice a list or access it with an index \nprint(a[2])#index \nprint(a[3:])#slicing",
"C\n[3, 'titiche']\n"
],
[
"#you can have a list in a list \nb = ['a', 2, a]",
"_____no_output_____"
],
[
"b",
"_____no_output_____"
],
[
"#you can duplicate the list many times \nb = [1, 2]*4",
"_____no_output_____"
],
[
"b",
"_____no_output_____"
],
[
"#you can concatenate two lists\na + b",
"_____no_output_____"
]
],
[
[
"### 4 - Dictionaries :",
"_____no_output_____"
]
],
[
[
"#dictionary is some key value pairs \nd = {} #empty dictionary\nd[name] = age #the key is titich and the value is age",
"_____no_output_____"
],
[
"d",
"_____no_output_____"
],
[
"#you can access it with key\nd[name]",
"_____no_output_____"
]
],
[
[
"### 5 - Booleans :",
"_____no_output_____"
]
],
[
[
"# booleans ... this is the hardest part of the notebook :P\n#there is two types of booleans\nTrue #either true\nFalse #or false",
"_____no_output_____"
]
],
[
[
"### 6 - Tuples :",
"_____no_output_____"
]
],
[
[
"#tuples are just like lists , at the exception of you can't change elements inside a tuple\ntup = (1, 2, 3)#nothing to e afraid of",
"_____no_output_____"
],
[
"tup",
"_____no_output_____"
]
],
[
[
"### 7 - Sets",
"_____no_output_____"
]
],
[
[
"#sets are collection of unique elements\na = {1, 2, 3, 3, 2, 2, 3, 3, 4, 5, 4}",
"_____no_output_____"
],
[
"a",
"_____no_output_____"
],
[
"#you can convert a list to a set \nset([1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 5])",
"_____no_output_____"
],
[
"#you can add an element to a set \na.add(100)",
"_____no_output_____"
],
[
"a",
"_____no_output_____"
],
[
"#if it already exist it ignores it\na.add(100)",
"_____no_output_____"
],
[
"a",
"_____no_output_____"
]
],
[
[
"## Comparaison operators :",
"_____no_output_____"
]
],
[
[
"1 > 2 #greater than",
"_____no_output_____"
],
[
"3 <= 5 #lower or equal than",
"_____no_output_____"
],
[
"3 == 5 - 2 #equals ### double equal sign to compare ",
"_____no_output_____"
],
[
"'hello' != name ## not equals",
"_____no_output_____"
],
[
"(1 < 2) and (3 > 2) #combine two statements with and ",
"_____no_output_____"
],
[
"(1 < 2) or (3 <= 2) #combine two statements with or",
"_____no_output_____"
]
],
[
[
"## if, elif, else statements : ",
"_____no_output_____"
]
],
[
[
"if 1 < 2:\n print('something')",
"something\n"
],
[
"#you can make multiple cases\nif 1 > 2:\n print('hello')\nelif 2 > 3:\n print('i don\\'t know what to write')\nelif name == 'titiche':\n print('hello master {} '.format(name))\nelse:\n print('Default case')",
"hello master titiche \n"
]
],
[
[
"## for loops : ",
"_____no_output_____"
]
],
[
[
"seq = [1, 2, 3, 4]",
"_____no_output_____"
],
[
"#do some stuff many times\nfor item in seq:\n print(item, end='->')",
"1->2->3->4->"
]
],
[
[
"## while loops :",
"_____no_output_____"
]
],
[
[
"i = 1\nwhile i <= 20:\n print(i, end='->')\n i = i+1 #ahha we don't whant to have an infinite loop do we ?\n",
"1->2->3->4->5->6->7->8->9->10->11->12->13->14->15->16->17->18->19->20->"
]
],
[
[
"## range :",
"_____no_output_____"
]
],
[
[
"#this is a generator \nfor i in range(20):\n print(i, end='->')",
"0->1->2->3->4->5->6->7->8->9->10->11->12->13->14->15->16->17->18->19->"
],
[
"range(10)",
"_____no_output_____"
],
[
"list(range(10)) # this is called casting we basicly convert the type from range to list",
"_____no_output_____"
]
],
[
[
"## List Comprehension :",
"_____no_output_____"
]
],
[
[
"x = []\nfor num in range(5):\n x.append(num)\nx",
"_____no_output_____"
],
[
"# a better way to do it\nx = [num for num in range(5)]\nx",
"_____no_output_____"
]
],
[
[
"## Functions :",
"_____no_output_____"
]
],
[
[
"#function definition\ndef my_function(param):\n \"\"\" \n This is a doctstring\n basicly you write how to use this function here\n \"\"\"\n print(param)",
"_____no_output_____"
],
[
"my_function('titiche')",
"titiche\n"
]
],
[
[
"## map :",
"_____no_output_____"
]
],
[
[
"def square(x):\n return x**2\nx = [1, 2, 3, 4]",
"_____no_output_____"
],
[
"# use map to apply the function to every element in list\nlist(map(square, x))",
"_____no_output_____"
]
],
[
[
"## lambda expression :",
"_____no_output_____"
]
],
[
[
"square = lambda x: x**2 + 1\n#define a function quickly",
"_____no_output_____"
]
],
[
[
"## filter :",
"_____no_output_____"
]
],
[
[
"x = [1, 2, 3, 4, 5, 6, 7]\nlist(filter(lambda x: x%2 == 0, x))",
"_____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",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac3d875f7aaa926579b16ed2e3c3c046dc342dc
| 220,207 |
ipynb
|
Jupyter Notebook
|
4.ML_models.ipynb
|
piyush224/Quora_Question_Pair_Similarity
|
bdf2eb6b5259ef389b6e1496893a464c91bbde3d
|
[
"CC0-1.0"
] | null | null | null |
4.ML_models.ipynb
|
piyush224/Quora_Question_Pair_Similarity
|
bdf2eb6b5259ef389b6e1496893a464c91bbde3d
|
[
"CC0-1.0"
] | null | null | null |
4.ML_models.ipynb
|
piyush224/Quora_Question_Pair_Similarity
|
bdf2eb6b5259ef389b6e1496893a464c91bbde3d
|
[
"CC0-1.0"
] | null | null | null | 220,207 | 220,207 | 0.886843 |
[
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt\nimport re\nimport time\nimport warnings\nimport sqlite3\nfrom sqlalchemy import create_engine # database connection\nimport csv\nimport os\nwarnings.filterwarnings(\"ignore\")\nimport datetime as dt\nimport numpy as np\nfrom nltk.corpus import stopwords\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.preprocessing import normalize\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.manifold import TSNE\nimport seaborn as sns\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics.classification import accuracy_score, log_loss\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom collections import Counter\nfrom scipy.sparse import hstack\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.cross_validation import StratifiedKFold \nfrom collections import Counter, defaultdict\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\nimport math\nfrom sklearn.metrics import normalized_mutual_info_score\nfrom sklearn.ensemble import RandomForestClassifier\n\n\n\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import SGDClassifier\nfrom mlxtend.classifier import StackingClassifier\n\nfrom sklearn import model_selection\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import precision_recall_curve, auc, roc_curve",
"C:\\Users\\brahm\\Anaconda3\\lib\\site-packages\\sklearn\\cross_validation.py:41: DeprecationWarning: This 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 \"This module will be removed in 0.20.\", DeprecationWarning)\n"
]
],
[
[
"<h1>4. Machine Learning Models </h1>",
"_____no_output_____"
],
[
"<h2> 4.1 Reading data from file and storing into sql table </h2>",
"_____no_output_____"
]
],
[
[
"#Creating db file from csv\nif not os.path.isfile('train.db'):\n disk_engine = create_engine('sqlite:///train.db')\n start = dt.datetime.now()\n chunksize = 180000\n j = 0\n index_start = 1\n for df in pd.read_csv('final_features.csv', names=['Unnamed: 0','id','is_duplicate','cwc_min','cwc_max','csc_min','csc_max','ctc_min','ctc_max','last_word_eq','first_word_eq','abs_len_diff','mean_len','token_set_ratio','token_sort_ratio','fuzz_ratio','fuzz_partial_ratio','longest_substr_ratio','freq_qid1','freq_qid2','q1len','q2len','q1_n_words','q2_n_words','word_Common','word_Total','word_share','freq_q1+q2','freq_q1-q2','0_x','1_x','2_x','3_x','4_x','5_x','6_x','7_x','8_x','9_x','10_x','11_x','12_x','13_x','14_x','15_x','16_x','17_x','18_x','19_x','20_x','21_x','22_x','23_x','24_x','25_x','26_x','27_x','28_x','29_x','30_x','31_x','32_x','33_x','34_x','35_x','36_x','37_x','38_x','39_x','40_x','41_x','42_x','43_x','44_x','45_x','46_x','47_x','48_x','49_x','50_x','51_x','52_x','53_x','54_x','55_x','56_x','57_x','58_x','59_x','60_x','61_x','62_x','63_x','64_x','65_x','66_x','67_x','68_x','69_x','70_x','71_x','72_x','73_x','74_x','75_x','76_x','77_x','78_x','79_x','80_x','81_x','82_x','83_x','84_x','85_x','86_x','87_x','88_x','89_x','90_x','91_x','92_x','93_x','94_x','95_x','96_x','97_x','98_x','99_x','100_x','101_x','102_x','103_x','104_x','105_x','106_x','107_x','108_x','109_x','110_x','111_x','112_x','113_x','114_x','115_x','116_x','117_x','118_x','119_x','120_x','121_x','122_x','123_x','124_x','125_x','126_x','127_x','128_x','129_x','130_x','131_x','132_x','133_x','134_x','135_x','136_x','137_x','138_x','139_x','140_x','141_x','142_x','143_x','144_x','145_x','146_x','147_x','148_x','149_x','150_x','151_x','152_x','153_x','154_x','155_x','156_x','157_x','158_x','159_x','160_x','161_x','162_x','163_x','164_x','165_x','166_x','167_x','168_x','169_x','170_x','171_x','172_x','173_x','174_x','175_x','176_x','177_x','178_x','179_x','180_x','181_x','182_x','183_x','184_x','185_x','186_x','187_x','188_x','189_x','190_x','191_x','192_x','193_x','194_x','195_x','196_x','197_x','198_x','199_x','200_x','201_x','202_x','203_x','204_x','205_x','206_x','207_x','208_x','209_x','210_x','211_x','212_x','213_x','214_x','215_x','216_x','217_x','218_x','219_x','220_x','221_x','222_x','223_x','224_x','225_x','226_x','227_x','228_x','229_x','230_x','231_x','232_x','233_x','234_x','235_x','236_x','237_x','238_x','239_x','240_x','241_x','242_x','243_x','244_x','245_x','246_x','247_x','248_x','249_x','250_x','251_x','252_x','253_x','254_x','255_x','256_x','257_x','258_x','259_x','260_x','261_x','262_x','263_x','264_x','265_x','266_x','267_x','268_x','269_x','270_x','271_x','272_x','273_x','274_x','275_x','276_x','277_x','278_x','279_x','280_x','281_x','282_x','283_x','284_x','285_x','286_x','287_x','288_x','289_x','290_x','291_x','292_x','293_x','294_x','295_x','296_x','297_x','298_x','299_x','300_x','301_x','302_x','303_x','304_x','305_x','306_x','307_x','308_x','309_x','310_x','311_x','312_x','313_x','314_x','315_x','316_x','317_x','318_x','319_x','320_x','321_x','322_x','323_x','324_x','325_x','326_x','327_x','328_x','329_x','330_x','331_x','332_x','333_x','334_x','335_x','336_x','337_x','338_x','339_x','340_x','341_x','342_x','343_x','344_x','345_x','346_x','347_x','348_x','349_x','350_x','351_x','352_x','353_x','354_x','355_x','356_x','357_x','358_x','359_x','360_x','361_x','362_x','363_x','364_x','365_x','366_x','367_x','368_x','369_x','370_x','371_x','372_x','373_x','374_x','375_x','376_x','377_x','378_x','379_x','380_x','381_x','382_x','383_x','0_y','1_y','2_y','3_y','4_y','5_y','6_y','7_y','8_y','9_y','10_y','11_y','12_y','13_y','14_y','15_y','16_y','17_y','18_y','19_y','20_y','21_y','22_y','23_y','24_y','25_y','26_y','27_y','28_y','29_y','30_y','31_y','32_y','33_y','34_y','35_y','36_y','37_y','38_y','39_y','40_y','41_y','42_y','43_y','44_y','45_y','46_y','47_y','48_y','49_y','50_y','51_y','52_y','53_y','54_y','55_y','56_y','57_y','58_y','59_y','60_y','61_y','62_y','63_y','64_y','65_y','66_y','67_y','68_y','69_y','70_y','71_y','72_y','73_y','74_y','75_y','76_y','77_y','78_y','79_y','80_y','81_y','82_y','83_y','84_y','85_y','86_y','87_y','88_y','89_y','90_y','91_y','92_y','93_y','94_y','95_y','96_y','97_y','98_y','99_y','100_y','101_y','102_y','103_y','104_y','105_y','106_y','107_y','108_y','109_y','110_y','111_y','112_y','113_y','114_y','115_y','116_y','117_y','118_y','119_y','120_y','121_y','122_y','123_y','124_y','125_y','126_y','127_y','128_y','129_y','130_y','131_y','132_y','133_y','134_y','135_y','136_y','137_y','138_y','139_y','140_y','141_y','142_y','143_y','144_y','145_y','146_y','147_y','148_y','149_y','150_y','151_y','152_y','153_y','154_y','155_y','156_y','157_y','158_y','159_y','160_y','161_y','162_y','163_y','164_y','165_y','166_y','167_y','168_y','169_y','170_y','171_y','172_y','173_y','174_y','175_y','176_y','177_y','178_y','179_y','180_y','181_y','182_y','183_y','184_y','185_y','186_y','187_y','188_y','189_y','190_y','191_y','192_y','193_y','194_y','195_y','196_y','197_y','198_y','199_y','200_y','201_y','202_y','203_y','204_y','205_y','206_y','207_y','208_y','209_y','210_y','211_y','212_y','213_y','214_y','215_y','216_y','217_y','218_y','219_y','220_y','221_y','222_y','223_y','224_y','225_y','226_y','227_y','228_y','229_y','230_y','231_y','232_y','233_y','234_y','235_y','236_y','237_y','238_y','239_y','240_y','241_y','242_y','243_y','244_y','245_y','246_y','247_y','248_y','249_y','250_y','251_y','252_y','253_y','254_y','255_y','256_y','257_y','258_y','259_y','260_y','261_y','262_y','263_y','264_y','265_y','266_y','267_y','268_y','269_y','270_y','271_y','272_y','273_y','274_y','275_y','276_y','277_y','278_y','279_y','280_y','281_y','282_y','283_y','284_y','285_y','286_y','287_y','288_y','289_y','290_y','291_y','292_y','293_y','294_y','295_y','296_y','297_y','298_y','299_y','300_y','301_y','302_y','303_y','304_y','305_y','306_y','307_y','308_y','309_y','310_y','311_y','312_y','313_y','314_y','315_y','316_y','317_y','318_y','319_y','320_y','321_y','322_y','323_y','324_y','325_y','326_y','327_y','328_y','329_y','330_y','331_y','332_y','333_y','334_y','335_y','336_y','337_y','338_y','339_y','340_y','341_y','342_y','343_y','344_y','345_y','346_y','347_y','348_y','349_y','350_y','351_y','352_y','353_y','354_y','355_y','356_y','357_y','358_y','359_y','360_y','361_y','362_y','363_y','364_y','365_y','366_y','367_y','368_y','369_y','370_y','371_y','372_y','373_y','374_y','375_y','376_y','377_y','378_y','379_y','380_y','381_y','382_y','383_y'], chunksize=chunksize, iterator=True, encoding='utf-8', ):\n df.index += index_start\n j+=1\n print('{} rows'.format(j*chunksize))\n df.to_sql('data', disk_engine, if_exists='append')\n index_start = df.index[-1] + 1",
"_____no_output_____"
],
[
"#http://www.sqlitetutorial.net/sqlite-python/create-tables/\ndef create_connection(db_file):\n \"\"\" create a database connection to the SQLite database\n specified by db_file\n :param db_file: database file\n :return: Connection object or None\n \"\"\"\n try:\n conn = sqlite3.connect(db_file)\n return conn\n except Error as e:\n print(e)\n \n return None\n\n\ndef checkTableExists(dbcon):\n cursr = dbcon.cursor()\n str = \"select name from sqlite_master where type='table'\"\n table_names = cursr.execute(str)\n print(\"Tables in the databse:\")\n tables =table_names.fetchall() \n print(tables[0][0])\n return(len(tables))",
"_____no_output_____"
],
[
"read_db = 'train.db'\nconn_r = create_connection(read_db)\ncheckTableExists(conn_r)\nconn_r.close()",
"Tables in the databse:\ndata\n"
],
[
"# try to sample data according to the computing power you have\nif os.path.isfile(read_db):\n conn_r = create_connection(read_db)\n if conn_r is not None:\n # for selecting first 1M rows\n # data = pd.read_sql_query(\"\"\"SELECT * FROM data LIMIT 100001;\"\"\", conn_r)\n \n # for selecting random points\n data = pd.read_sql_query(\"SELECT * From data ORDER BY RANDOM() LIMIT 100001;\", conn_r)\n conn_r.commit()\n conn_r.close()",
"_____no_output_____"
],
[
"# remove the first row \ndata.drop(data.index[0], inplace=True)\ny_true = data['is_duplicate']\ndata.drop(['Unnamed: 0', 'id','index','is_duplicate'], axis=1, inplace=True)",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
]
],
[
[
"<h2> 4.2 Converting strings to numerics </h2>",
"_____no_output_____"
]
],
[
[
"# after we read from sql table each entry was read it as a string\n# we convert all the features into numaric before we apply any model\ncols = list(data.columns)\nfor i in cols:\n data[i] = data[i].apply(pd.to_numeric)\n print(i)",
"cwc_min\ncwc_max\ncsc_min\ncsc_max\nctc_min\nctc_max\nlast_word_eq\nfirst_word_eq\nabs_len_diff\nmean_len\ntoken_set_ratio\ntoken_sort_ratio\nfuzz_ratio\nfuzz_partial_ratio\nlongest_substr_ratio\nfreq_qid1\nfreq_qid2\nq1len\nq2len\nq1_n_words\nq2_n_words\nword_Common\nword_Total\nword_share\nfreq_q1+q2\nfreq_q1-q2\n0_x\n1_x\n2_x\n3_x\n4_x\n5_x\n6_x\n7_x\n8_x\n9_x\n10_x\n11_x\n12_x\n13_x\n14_x\n15_x\n16_x\n17_x\n18_x\n19_x\n20_x\n21_x\n22_x\n23_x\n24_x\n25_x\n26_x\n27_x\n28_x\n29_x\n30_x\n31_x\n32_x\n33_x\n34_x\n35_x\n36_x\n37_x\n38_x\n39_x\n40_x\n41_x\n42_x\n43_x\n44_x\n45_x\n46_x\n47_x\n48_x\n49_x\n50_x\n51_x\n52_x\n53_x\n54_x\n55_x\n56_x\n57_x\n58_x\n59_x\n60_x\n61_x\n62_x\n63_x\n64_x\n65_x\n66_x\n67_x\n68_x\n69_x\n70_x\n71_x\n72_x\n73_x\n74_x\n75_x\n76_x\n77_x\n78_x\n79_x\n80_x\n81_x\n82_x\n83_x\n84_x\n85_x\n86_x\n87_x\n88_x\n89_x\n90_x\n91_x\n92_x\n93_x\n94_x\n95_x\n96_x\n97_x\n98_x\n99_x\n100_x\n101_x\n102_x\n103_x\n104_x\n105_x\n106_x\n107_x\n108_x\n109_x\n110_x\n111_x\n112_x\n113_x\n114_x\n115_x\n116_x\n117_x\n118_x\n119_x\n120_x\n121_x\n122_x\n123_x\n124_x\n125_x\n126_x\n127_x\n128_x\n129_x\n130_x\n131_x\n132_x\n133_x\n134_x\n135_x\n136_x\n137_x\n138_x\n139_x\n140_x\n141_x\n142_x\n143_x\n144_x\n145_x\n146_x\n147_x\n148_x\n149_x\n150_x\n151_x\n152_x\n153_x\n154_x\n155_x\n156_x\n157_x\n158_x\n159_x\n160_x\n161_x\n162_x\n163_x\n164_x\n165_x\n166_x\n167_x\n168_x\n169_x\n170_x\n171_x\n172_x\n173_x\n174_x\n175_x\n176_x\n177_x\n178_x\n179_x\n180_x\n181_x\n182_x\n183_x\n184_x\n185_x\n186_x\n187_x\n188_x\n189_x\n190_x\n191_x\n192_x\n193_x\n194_x\n195_x\n196_x\n197_x\n198_x\n199_x\n200_x\n201_x\n202_x\n203_x\n204_x\n205_x\n206_x\n207_x\n208_x\n209_x\n210_x\n211_x\n212_x\n213_x\n214_x\n215_x\n216_x\n217_x\n218_x\n219_x\n220_x\n221_x\n222_x\n223_x\n224_x\n225_x\n226_x\n227_x\n228_x\n229_x\n230_x\n231_x\n232_x\n233_x\n234_x\n235_x\n236_x\n237_x\n238_x\n239_x\n240_x\n241_x\n242_x\n243_x\n244_x\n245_x\n246_x\n247_x\n248_x\n249_x\n250_x\n251_x\n252_x\n253_x\n254_x\n255_x\n256_x\n257_x\n258_x\n259_x\n260_x\n261_x\n262_x\n263_x\n264_x\n265_x\n266_x\n267_x\n268_x\n269_x\n270_x\n271_x\n272_x\n273_x\n274_x\n275_x\n276_x\n277_x\n278_x\n279_x\n280_x\n281_x\n282_x\n283_x\n284_x\n285_x\n286_x\n287_x\n288_x\n289_x\n290_x\n291_x\n292_x\n293_x\n294_x\n295_x\n296_x\n297_x\n298_x\n299_x\n300_x\n301_x\n302_x\n303_x\n304_x\n305_x\n306_x\n307_x\n308_x\n309_x\n310_x\n311_x\n312_x\n313_x\n314_x\n315_x\n316_x\n317_x\n318_x\n319_x\n320_x\n321_x\n322_x\n323_x\n324_x\n325_x\n326_x\n327_x\n328_x\n329_x\n330_x\n331_x\n332_x\n333_x\n334_x\n335_x\n336_x\n337_x\n338_x\n339_x\n340_x\n341_x\n342_x\n343_x\n344_x\n345_x\n346_x\n347_x\n348_x\n349_x\n350_x\n351_x\n352_x\n353_x\n354_x\n355_x\n356_x\n357_x\n358_x\n359_x\n360_x\n361_x\n362_x\n363_x\n364_x\n365_x\n366_x\n367_x\n368_x\n369_x\n370_x\n371_x\n372_x\n373_x\n374_x\n375_x\n376_x\n377_x\n378_x\n379_x\n380_x\n381_x\n382_x\n383_x\n0_y\n1_y\n2_y\n3_y\n4_y\n5_y\n6_y\n7_y\n8_y\n9_y\n10_y\n11_y\n12_y\n13_y\n14_y\n15_y\n16_y\n17_y\n18_y\n19_y\n20_y\n21_y\n22_y\n23_y\n24_y\n25_y\n26_y\n27_y\n28_y\n29_y\n30_y\n31_y\n32_y\n33_y\n34_y\n35_y\n36_y\n37_y\n38_y\n39_y\n40_y\n41_y\n42_y\n43_y\n44_y\n45_y\n46_y\n47_y\n48_y\n49_y\n50_y\n51_y\n52_y\n53_y\n54_y\n55_y\n56_y\n57_y\n58_y\n59_y\n60_y\n61_y\n62_y\n63_y\n64_y\n65_y\n66_y\n67_y\n68_y\n69_y\n70_y\n71_y\n72_y\n73_y\n74_y\n75_y\n76_y\n77_y\n78_y\n79_y\n80_y\n81_y\n82_y\n83_y\n84_y\n85_y\n86_y\n87_y\n88_y\n89_y\n90_y\n91_y\n92_y\n93_y\n94_y\n95_y\n96_y\n97_y\n98_y\n99_y\n100_y\n101_y\n102_y\n103_y\n104_y\n105_y\n106_y\n107_y\n108_y\n109_y\n110_y\n111_y\n112_y\n113_y\n114_y\n115_y\n116_y\n117_y\n118_y\n119_y\n120_y\n121_y\n122_y\n123_y\n124_y\n125_y\n126_y\n127_y\n128_y\n129_y\n130_y\n131_y\n132_y\n133_y\n134_y\n135_y\n136_y\n137_y\n138_y\n139_y\n140_y\n141_y\n142_y\n143_y\n144_y\n145_y\n146_y\n147_y\n148_y\n149_y\n150_y\n151_y\n152_y\n153_y\n154_y\n155_y\n156_y\n157_y\n158_y\n159_y\n160_y\n161_y\n162_y\n163_y\n164_y\n165_y\n166_y\n167_y\n168_y\n169_y\n170_y\n171_y\n172_y\n173_y\n174_y\n175_y\n176_y\n177_y\n178_y\n179_y\n180_y\n181_y\n182_y\n183_y\n184_y\n185_y\n186_y\n187_y\n188_y\n189_y\n190_y\n191_y\n192_y\n193_y\n194_y\n195_y\n196_y\n197_y\n198_y\n199_y\n200_y\n201_y\n202_y\n203_y\n204_y\n205_y\n206_y\n207_y\n208_y\n209_y\n210_y\n211_y\n212_y\n213_y\n214_y\n215_y\n216_y\n217_y\n218_y\n219_y\n220_y\n221_y\n222_y\n223_y\n224_y\n225_y\n226_y\n227_y\n228_y\n229_y\n230_y\n231_y\n232_y\n233_y\n234_y\n235_y\n236_y\n237_y\n238_y\n239_y\n240_y\n241_y\n242_y\n243_y\n244_y\n245_y\n246_y\n247_y\n248_y\n249_y\n250_y\n251_y\n252_y\n253_y\n254_y\n255_y\n256_y\n257_y\n258_y\n259_y\n260_y\n261_y\n262_y\n263_y\n264_y\n265_y\n266_y\n267_y\n268_y\n269_y\n270_y\n271_y\n272_y\n273_y\n274_y\n275_y\n276_y\n277_y\n278_y\n279_y\n280_y\n281_y\n282_y\n283_y\n284_y\n285_y\n286_y\n287_y\n288_y\n289_y\n290_y\n291_y\n292_y\n293_y\n294_y\n295_y\n296_y\n297_y\n298_y\n299_y\n300_y\n301_y\n302_y\n303_y\n304_y\n305_y\n306_y\n307_y\n308_y\n309_y\n310_y\n311_y\n312_y\n313_y\n314_y\n315_y\n316_y\n317_y\n318_y\n319_y\n320_y\n321_y\n322_y\n323_y\n324_y\n325_y\n326_y\n327_y\n328_y\n329_y\n330_y\n331_y\n332_y\n333_y\n334_y\n335_y\n336_y\n337_y\n338_y\n339_y\n340_y\n341_y\n342_y\n343_y\n344_y\n345_y\n346_y\n347_y\n348_y\n349_y\n350_y\n351_y\n352_y\n353_y\n354_y\n355_y\n356_y\n357_y\n358_y\n359_y\n360_y\n361_y\n362_y\n363_y\n364_y\n365_y\n366_y\n367_y\n368_y\n369_y\n370_y\n371_y\n372_y\n373_y\n374_y\n375_y\n376_y\n377_y\n378_y\n379_y\n380_y\n381_y\n382_y\n383_y\n"
],
[
"# https://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int\ny_true = list(map(int, y_true.values))",
"_____no_output_____"
]
],
[
[
"<h2> 4.3 Random train test split( 70:30) </h2>",
"_____no_output_____"
]
],
[
[
"X_train,X_test, y_train, y_test = train_test_split(data, y_true, stratify=y_true, test_size=0.3)",
"_____no_output_____"
],
[
"print(\"Number of data points in train data :\",X_train.shape)\nprint(\"Number of data points in test data :\",X_test.shape)",
"Number of data points in train data : (70000, 794)\nNumber of data points in test data : (30000, 794)\n"
],
[
"print(\"-\"*10, \"Distribution of output variable in train data\", \"-\"*10)\ntrain_distr = Counter(y_train)\ntrain_len = len(y_train)\nprint(\"Class 0: \",int(train_distr[0])/train_len,\"Class 1: \", int(train_distr[1])/train_len)\nprint(\"-\"*10, \"Distribution of output variable in train data\", \"-\"*10)\ntest_distr = Counter(y_test)\ntest_len = len(y_test)\nprint(\"Class 0: \",int(test_distr[1])/test_len, \"Class 1: \",int(test_distr[1])/test_len)",
"---------- Distribution of output variable in train data ----------\nClass 0: 0.6324857142857143 Class 1: 0.36751428571428574\n---------- Distribution of output variable in train data ----------\nClass 0: 0.3675 Class 1: 0.3675\n"
],
[
"# This function plots the confusion matrices given y_i, y_i_hat.\ndef plot_confusion_matrix(test_y, predict_y):\n C = confusion_matrix(test_y, predict_y)\n # C = 9,9 matrix, each cell (i,j) represents number of points of class i are predicted class j\n \n A =(((C.T)/(C.sum(axis=1))).T)\n #divid each element of the confusion matrix with the sum of elements in that column\n \n # C = [[1, 2],\n # [3, 4]]\n # C.T = [[1, 3],\n # [2, 4]]\n # C.sum(axis = 1) axis=0 corresonds to columns and axis=1 corresponds to rows in two diamensional array\n # C.sum(axix =1) = [[3, 7]]\n # ((C.T)/(C.sum(axis=1))) = [[1/3, 3/7]\n # [2/3, 4/7]]\n\n # ((C.T)/(C.sum(axis=1))).T = [[1/3, 2/3]\n # [3/7, 4/7]]\n # sum of row elements = 1\n \n B =(C/C.sum(axis=0))\n #divid each element of the confusion matrix with the sum of elements in that row\n # C = [[1, 2],\n # [3, 4]]\n # C.sum(axis = 0) axis=0 corresonds to columns and axis=1 corresponds to rows in two diamensional array\n # C.sum(axix =0) = [[4, 6]]\n # (C/C.sum(axis=0)) = [[1/4, 2/6],\n # [3/4, 4/6]] \n plt.figure(figsize=(20,4))\n \n labels = [1,2]\n # representing A in heatmap format\n cmap=sns.light_palette(\"blue\")\n plt.subplot(1, 3, 1)\n sns.heatmap(C, annot=True, cmap=cmap, fmt=\".3f\", xticklabels=labels, yticklabels=labels)\n plt.xlabel('Predicted Class')\n plt.ylabel('Original Class')\n plt.title(\"Confusion matrix\")\n \n plt.subplot(1, 3, 2)\n sns.heatmap(B, annot=True, cmap=cmap, fmt=\".3f\", xticklabels=labels, yticklabels=labels)\n plt.xlabel('Predicted Class')\n plt.ylabel('Original Class')\n plt.title(\"Precision matrix\")\n \n plt.subplot(1, 3, 3)\n # representing B in heatmap format\n sns.heatmap(A, annot=True, cmap=cmap, fmt=\".3f\", xticklabels=labels, yticklabels=labels)\n plt.xlabel('Predicted Class')\n plt.ylabel('Original Class')\n plt.title(\"Recall matrix\")\n \n plt.show()",
"_____no_output_____"
]
],
[
[
"<h2> 4.4 Building a random model (Finding worst-case log-loss) </h2>",
"_____no_output_____"
]
],
[
[
"# we need to generate 9 numbers and the sum of numbers should be 1\n# one solution is to genarate 9 numbers and divide each of the numbers by their sum\n# ref: https://stackoverflow.com/a/18662466/4084039\n# we create a output array that has exactly same size as the CV data\npredicted_y = np.zeros((test_len,2))\nfor i in range(test_len):\n rand_probs = np.random.rand(1,2)\n predicted_y[i] = ((rand_probs/sum(sum(rand_probs)))[0])\nprint(\"Log loss on Test Data using Random Model\",log_loss(y_test, predicted_y, eps=1e-15))\n\npredicted_y =np.argmax(predicted_y, axis=1)\nplot_confusion_matrix(y_test, predicted_y)",
"Log loss on Test Data using Random Model 0.887242646958\n"
]
],
[
[
"<h2> 4.4 Logistic Regression with hyperparameter tuning </h2>",
"_____no_output_____"
]
],
[
[
"alpha = [10 ** x for x in range(-5, 2)] # hyperparam for SGD classifier.\n\n# read more about SGDClassifier() at http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html\n# ------------------------------\n# default parameters\n# SGDClassifier(loss=’hinge’, penalty=’l2’, alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=None, tol=None, \n# shuffle=True, verbose=0, epsilon=0.1, n_jobs=1, random_state=None, learning_rate=’optimal’, eta0=0.0, power_t=0.5, \n# class_weight=None, warm_start=False, average=False, n_iter=None)\n\n# some of methods\n# fit(X, y[, coef_init, intercept_init, …])\tFit linear model with Stochastic Gradient Descent.\n# predict(X)\tPredict class labels for samples in X.\n\n#-------------------------------\n# video link: \n#------------------------------\n\n\nlog_error_array=[]\nfor i in alpha:\n clf = SGDClassifier(alpha=i, penalty='l2', loss='log', random_state=42)\n clf.fit(X_train, y_train)\n sig_clf = CalibratedClassifierCV(clf, method=\"sigmoid\")\n sig_clf.fit(X_train, y_train)\n predict_y = sig_clf.predict_proba(X_test)\n log_error_array.append(log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))\n print('For values of alpha = ', i, \"The log loss is:\",log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))\n\nfig, ax = plt.subplots()\nax.plot(alpha, log_error_array,c='g')\nfor i, txt in enumerate(np.round(log_error_array,3)):\n ax.annotate((alpha[i],np.round(txt,3)), (alpha[i],log_error_array[i]))\nplt.grid()\nplt.title(\"Cross Validation Error for each alpha\")\nplt.xlabel(\"Alpha i's\")\nplt.ylabel(\"Error measure\")\nplt.show()\n\n\nbest_alpha = np.argmin(log_error_array)\nclf = SGDClassifier(alpha=alpha[best_alpha], penalty='l2', loss='log', random_state=42)\nclf.fit(X_train, y_train)\nsig_clf = CalibratedClassifierCV(clf, method=\"sigmoid\")\nsig_clf.fit(X_train, y_train)\n\npredict_y = sig_clf.predict_proba(X_train)\nprint('For values of best alpha = ', alpha[best_alpha], \"The train log loss is:\",log_loss(y_train, predict_y, labels=clf.classes_, eps=1e-15))\npredict_y = sig_clf.predict_proba(X_test)\nprint('For values of best alpha = ', alpha[best_alpha], \"The test log loss is:\",log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))\npredicted_y =np.argmax(predict_y,axis=1)\nprint(\"Total number of data points :\", len(predicted_y))\nplot_confusion_matrix(y_test, predicted_y)",
"For values of alpha = 1e-05 The log loss is: 0.592800211149\nFor values of alpha = 0.0001 The log loss is: 0.532351700629\nFor values of alpha = 0.001 The log loss is: 0.527562275995\nFor values of alpha = 0.01 The log loss is: 0.534535408885\nFor values of alpha = 0.1 The log loss is: 0.525117052926\nFor values of alpha = 1 The log loss is: 0.520035530431\nFor values of alpha = 10 The log loss is: 0.521097925307\n"
]
],
[
[
"<h2> 4.5 Linear SVM with hyperparameter tuning </h2>",
"_____no_output_____"
]
],
[
[
"alpha = [10 ** x for x in range(-5, 2)] # hyperparam for SGD classifier.\n\n# read more about SGDClassifier() at http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html\n# ------------------------------\n# default parameters\n# SGDClassifier(loss=’hinge’, penalty=’l2’, alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=None, tol=None, \n# shuffle=True, verbose=0, epsilon=0.1, n_jobs=1, random_state=None, learning_rate=’optimal’, eta0=0.0, power_t=0.5, \n# class_weight=None, warm_start=False, average=False, n_iter=None)\n\n# some of methods\n# fit(X, y[, coef_init, intercept_init, …])\tFit linear model with Stochastic Gradient Descent.\n# predict(X)\tPredict class labels for samples in X.\n\n#-------------------------------\n# video link: \n#------------------------------\n\n\nlog_error_array=[]\nfor i in alpha:\n clf = SGDClassifier(alpha=i, penalty='l1', loss='hinge', random_state=42)\n clf.fit(X_train, y_train)\n sig_clf = CalibratedClassifierCV(clf, method=\"sigmoid\")\n sig_clf.fit(X_train, y_train)\n predict_y = sig_clf.predict_proba(X_test)\n log_error_array.append(log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))\n print('For values of alpha = ', i, \"The log loss is:\",log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))\n\nfig, ax = plt.subplots()\nax.plot(alpha, log_error_array,c='g')\nfor i, txt in enumerate(np.round(log_error_array,3)):\n ax.annotate((alpha[i],np.round(txt,3)), (alpha[i],log_error_array[i]))\nplt.grid()\nplt.title(\"Cross Validation Error for each alpha\")\nplt.xlabel(\"Alpha i's\")\nplt.ylabel(\"Error measure\")\nplt.show()\n\n\nbest_alpha = np.argmin(log_error_array)\nclf = SGDClassifier(alpha=alpha[best_alpha], penalty='l1', loss='hinge', random_state=42)\nclf.fit(X_train, y_train)\nsig_clf = CalibratedClassifierCV(clf, method=\"sigmoid\")\nsig_clf.fit(X_train, y_train)\n\npredict_y = sig_clf.predict_proba(X_train)\nprint('For values of best alpha = ', alpha[best_alpha], \"The train log loss is:\",log_loss(y_train, predict_y, labels=clf.classes_, eps=1e-15))\npredict_y = sig_clf.predict_proba(X_test)\nprint('For values of best alpha = ', alpha[best_alpha], \"The test log loss is:\",log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))\npredicted_y =np.argmax(predict_y,axis=1)\nprint(\"Total number of data points :\", len(predicted_y))\nplot_confusion_matrix(y_test, predicted_y)",
"For values of alpha = 1e-05 The log loss is: 0.657611721261\nFor values of alpha = 0.0001 The log loss is: 0.489669093534\nFor values of alpha = 0.001 The log loss is: 0.521829068562\nFor values of alpha = 0.01 The log loss is: 0.566295616914\nFor values of alpha = 0.1 The log loss is: 0.599957866217\nFor values of alpha = 1 The log loss is: 0.635059427016\nFor values of alpha = 10 The log loss is: 0.654159467907\n"
]
],
[
[
"<h2> 4.6 XGBoost </h2>",
"_____no_output_____"
]
],
[
[
"import xgboost as xgb\nparams = {}\nparams['objective'] = 'binary:logistic'\nparams['eval_metric'] = 'logloss'\nparams['eta'] = 0.02\nparams['max_depth'] = 4\n\nd_train = xgb.DMatrix(X_train, label=y_train)\nd_test = xgb.DMatrix(X_test, label=y_test)\n\nwatchlist = [(d_train, 'train'), (d_test, 'valid')]\n\nbst = xgb.train(params, d_train, 400, watchlist, early_stopping_rounds=20, verbose_eval=10)\n\nxgdmat = xgb.DMatrix(X_train,y_train)\npredict_y = bst.predict(d_test)\nprint(\"The test log loss is:\",log_loss(y_test, predict_y, labels=clf.classes_, eps=1e-15))",
"[0]\ttrain-logloss:0.684819\tvalid-logloss:0.684845\nMultiple eval metrics have been passed: 'valid-logloss' will be used for early stopping.\n\nWill train until valid-logloss hasn't improved in 20 rounds.\n[10]\ttrain-logloss:0.61583\tvalid-logloss:0.616104\n[20]\ttrain-logloss:0.564616\tvalid-logloss:0.565273\n[30]\ttrain-logloss:0.525758\tvalid-logloss:0.52679\n[40]\ttrain-logloss:0.496661\tvalid-logloss:0.498021\n[50]\ttrain-logloss:0.473563\tvalid-logloss:0.475182\n[60]\ttrain-logloss:0.455315\tvalid-logloss:0.457186\n[70]\ttrain-logloss:0.440442\tvalid-logloss:0.442482\n[80]\ttrain-logloss:0.428424\tvalid-logloss:0.430795\n[90]\ttrain-logloss:0.418803\tvalid-logloss:0.421447\n[100]\ttrain-logloss:0.41069\tvalid-logloss:0.413583\n[110]\ttrain-logloss:0.403831\tvalid-logloss:0.40693\n[120]\ttrain-logloss:0.398076\tvalid-logloss:0.401402\n[130]\ttrain-logloss:0.393305\tvalid-logloss:0.396851\n[140]\ttrain-logloss:0.38913\tvalid-logloss:0.392952\n[150]\ttrain-logloss:0.385469\tvalid-logloss:0.389521\n[160]\ttrain-logloss:0.382327\tvalid-logloss:0.386667\n[170]\ttrain-logloss:0.379541\tvalid-logloss:0.384148\n[180]\ttrain-logloss:0.377014\tvalid-logloss:0.381932\n[190]\ttrain-logloss:0.374687\tvalid-logloss:0.379883\n[200]\ttrain-logloss:0.372585\tvalid-logloss:0.378068\n[210]\ttrain-logloss:0.370615\tvalid-logloss:0.376367\n[220]\ttrain-logloss:0.368559\tvalid-logloss:0.374595\n[230]\ttrain-logloss:0.366545\tvalid-logloss:0.372847\n[240]\ttrain-logloss:0.364708\tvalid-logloss:0.371311\n[250]\ttrain-logloss:0.363021\tvalid-logloss:0.369886\n[260]\ttrain-logloss:0.36144\tvalid-logloss:0.368673\n[270]\ttrain-logloss:0.359899\tvalid-logloss:0.367421\n[280]\ttrain-logloss:0.358465\tvalid-logloss:0.366395\n[290]\ttrain-logloss:0.357128\tvalid-logloss:0.365361\n[300]\ttrain-logloss:0.355716\tvalid-logloss:0.364315\n[310]\ttrain-logloss:0.354425\tvalid-logloss:0.363403\n[320]\ttrain-logloss:0.353276\tvalid-logloss:0.362595\n[330]\ttrain-logloss:0.352084\tvalid-logloss:0.361823\n[340]\ttrain-logloss:0.351051\tvalid-logloss:0.361167\n[350]\ttrain-logloss:0.349867\tvalid-logloss:0.36043\n[360]\ttrain-logloss:0.348829\tvalid-logloss:0.359773\n[370]\ttrain-logloss:0.347689\tvalid-logloss:0.359019\n[380]\ttrain-logloss:0.346607\tvalid-logloss:0.358311\n[390]\ttrain-logloss:0.345568\tvalid-logloss:0.357674\nThe test log loss is: 0.357054433715\n"
],
[
"predicted_y =np.array(predict_y>0.5,dtype=int)\nprint(\"Total number of data points :\", len(predicted_y))\nplot_confusion_matrix(y_test, predicted_y)",
"Total number of data points : 30000\n"
]
],
[
[
"<h1> 5. Assignments </h1>",
"_____no_output_____"
],
[
"1. Try out models (Logistic regression, Linear-SVM) with simple TF-IDF vectors instead of TD_IDF weighted word2Vec.\n2. Perform hyperparameter tuning of XgBoost models using RandomsearchCV with vectorizer as TF-IDF W2V to reduce the log-loss.\n\n",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
4ac3ddcfbd8f3092eab09c1eb6ac6cfb1d5ae264
| 4,426 |
ipynb
|
Jupyter Notebook
|
Practicas/Practica 1/P1_A.ipynb
|
sramos02/IA
|
6738327bcd3362fd2cb13690f517644d73ef97ba
|
[
"Apache-2.0"
] | null | null | null |
Practicas/Practica 1/P1_A.ipynb
|
sramos02/IA
|
6738327bcd3362fd2cb13690f517644d73ef97ba
|
[
"Apache-2.0"
] | null | null | null |
Practicas/Practica 1/P1_A.ipynb
|
sramos02/IA
|
6738327bcd3362fd2cb13690f517644d73ef97ba
|
[
"Apache-2.0"
] | null | null | null | 26.662651 | 243 | 0.52892 |
[
[
[
"## Resuelve los siguientes ejercicios en este archivo y entregalo en el campus al final de la clase.",
"_____no_output_____"
],
[
"**_Ejercicio 1_**. Escribe un programa que calcule el volumen de un cono a partir del radio de la base y su altura. Usa la siguiente fórmula:\nvolumen = pi * radio * radio * altura / 3\nSolicita los valores de radio y altura al usuario. El valor aproximado de pi es 3.14159.\n\n",
"_____no_output_____"
]
],
[
[
"# Escribe aquí la solución del ejercicio 1.\npi = 3.14159\nradio = int(input('Dime el radio:'))\naltura = int(input('Dime la altura:'))\npi * radio * radio * altura / 3",
"Dime el radio:5\nDime la altura:5\n"
]
],
[
[
"**_Ejercicio 2_**. Escribe un programa que clasifique los elementos de una lista en positivos y negativos. Los elementos positivos deben añadirse a una lista y los negativos a otra. Si la lista original contiene ceros, se deben ignorar.",
"_____no_output_____"
]
],
[
[
"# Escribe aquí la solución del ejercicio 2.\n\n#lista_original = [7, 6, -9, 234, -4, 0, -7]\n#Positivos: [7, 6, 234]\n#Negativos: [-9, -4, -7]\n\npositivos = []\nnegativos = []\n#----------------------------------------\n#SIN ENTRADA VARIABLE\n\nlista = [7,6,-9,234,-4,0,-7]\nlength = len(lista)\nfor i in range(length):\n if lista[i] >= 0:\n positivos.append(lista[i])\n else:\n negativos.append(lista[i])\nprint(positivos)\nprint(negativos)\n\n#----------------------------------------\n#CON ENTRADA VARIABLE\nlong = int(input('Longitud de la lista:'))\nprint('Introduzca los valores:')\nfor i in range(long):\n nuevo = int(input(''))\n if nuevo >= 0:\n positivos.append(nuevo)\n else:\n negativos.append(nuevo)\n\nprint(positivos)\nprint(negativos)\n\n",
"_____no_output_____"
]
],
[
[
"**_Ejercicio 3_**. Escribir una función cuadrados(l) que recibiendo una secuencia l de números, devuelve la lista de los cuadrados de esos números, en el mismo orden. Por ejemplo:\n\tcuadrados([4,1,5.2,3,8])\n\t[16, 1, 27.040000000000003, 9, 64]\n\tHacer dos versiones: una usando un bucle explícito, y la otra mediante definición de listas por comprensión.",
"_____no_output_____"
]
],
[
[
"# Escribe aquí la solución del ejercicio 3.\n# >>> cuadrados([4,1,5.2,3,8])\n# [16, 1, 27.040000000000003, 9, 64]\nlista = [4,1,5.2,3,8]\ncuadrados = []\nlength = len(lista)\n\n\n#bucle explícito\nfor i in range(length):\n cuadrados.append(lista[i] * lista[i]) #Esto es para que no muestre el decimal todo el rato\nprint(cuadrados)\n\n# definición de listas por comprensión.\ncuadrados = [n * n for n in lista]\nprint(cuadrados)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac3ed1c9ca482a81d60573827919563e2d404d9
| 11,884 |
ipynb
|
Jupyter Notebook
|
01_Tabular_Q_learning/01_Practice_Tabular_Q_learning.ipynb
|
jmstar85/rl_practice
|
e4fe7d3142f924c786f29b670a41ff846e49a30a
|
[
"MIT"
] | null | null | null |
01_Tabular_Q_learning/01_Practice_Tabular_Q_learning.ipynb
|
jmstar85/rl_practice
|
e4fe7d3142f924c786f29b670a41ff846e49a30a
|
[
"MIT"
] | null | null | null |
01_Tabular_Q_learning/01_Practice_Tabular_Q_learning.ipynb
|
jmstar85/rl_practice
|
e4fe7d3142f924c786f29b670a41ff846e49a30a
|
[
"MIT"
] | null | null | null | 23.301961 | 255 | 0.467014 |
[
[
[
"# 01. Tabular Q Learning\n\nTabular Q Learning을 실습해봅니다.\n- 모든 state의 value function을 table에 저장하고 테이블의 각 요소를 Q Learning으로 업데이트 하는 것으로 학습합니다.",
"_____no_output_____"
],
[
"## Colab 용 package 설치 코드",
"_____no_output_____"
]
],
[
[
"!pip install gym",
"_____no_output_____"
],
[
"import tensorflow as tf\nimport numpy as np\nimport random\nimport gym\n# from gym.wrappers import Monitor\n\nnp.random.seed(777)\ntf.set_random_seed(777)\n\nprint(\"tensorflow version: \", tf.__version__)\nprint(\"gym version: \", gym.__version__)",
"tensorflow version: 1.8.0\ngym version: 0.11.0\n"
]
],
[
[
"## Frozen Lake\n\n**[state]**\n\n SFFF\n FHFH\n FFFH\n HFFG\n\n S : starting point, safe\n F : frozen surface, safe\n H : hole, fall to your doom\n G : goal, where the frisbee is located\n \n**[action]**\n\n LEFT = 0\n DOWN = 1\n RIGHT = 2\n UP = 3",
"_____no_output_____"
]
],
[
[
"from IPython.display import clear_output\n\n# Load Environment\nenv = gym.make(\"FrozenLake-v0\")\n# init envrionmnet\nenv.reset()\n# only 'Right' action agent\nfor _ in range(5):\n env.render()\n next_state, reward, done, _ = env.step(2)",
"\n\u001b[41mS\u001b[0mFFF\nFHFH\nFFFH\nHFFG\n (Right)\n\u001b[41mS\u001b[0mFFF\nFHFH\nFFFH\nHFFG\n (Right)\nS\u001b[41mF\u001b[0mFF\nFHFH\nFFFH\nHFFG\n (Right)\nSFFF\nF\u001b[41mH\u001b[0mFH\nFFFH\nHFFG\n (Right)\nSFFF\nF\u001b[41mH\u001b[0mFH\nFFFH\nHFFG\n"
]
],
[
[
"### Frozen Lake (not Slippery)",
"_____no_output_____"
]
],
[
[
"def register_frozen_lake_not_slippery(name):\n from gym.envs.registration import register\n register(\n id=name,\n entry_point='gym.envs.toy_text:FrozenLakeEnv',\n kwargs={'map_name' : '4x4', 'is_slippery': False},\n max_episode_steps=100,\n reward_threshold=0.78, # optimum = .8196\n )\n\nregister_frozen_lake_not_slippery('FrozenLakeNotSlippery-v0')",
"_____no_output_____"
],
[
"env = gym.make(\"FrozenLakeNotSlippery-v0\")\nenv.reset()\nenv.render()\n'''\nenv.step()을 이용해서 Goal까지 직접 이동해보세요.\nLEFT = 0\nDOWN = 1\nRIGHT = 2\nUP = 3\n'''\nenv.step(0); env.render()\n# env.step(); env.render()",
"\n\u001b[41mS\u001b[0mFFF\nFHFH\nFFFH\nHFFG\n (Left)\n\u001b[41mS\u001b[0mFFF\nFHFH\nFFFH\nHFFG\n"
]
],
[
[
"## Q-Learning\n**Pseudo code** \n<img src=\"./img/qlearning_pseudo.png\" width=\"80%\" align=\"left\"> ",
"_____no_output_____"
],
[
"### Epsilon greedy",
"_____no_output_____"
]
],
[
[
"# epsilon greedy policy\n\ndef epsilon_greedy_action(epsilon, n_action, state, q_table):\n \n # 구현해보세요.\n # if epsilon이 random 값보다 클때\n # random action\n # else\n # 가장 큰 Q값을 갖는 action을 고른다.\n \n return action",
"_____no_output_____"
],
[
"# epsilon greedy test\n\nepsilon = 0\nq_table = np.array([[1,0,0,0],\n [0,0,0,1],\n [0,1,0,0]])\nfor state in range(3):\n action = epsilon_greedy_action(epsilon, 4, state, q_table)\n print(\"state: {} action: {}\".format(state, action))",
"_____no_output_____"
]
],
[
[
"### Q-value update",
"_____no_output_____"
]
],
[
[
"def q_update(q_table, state, next_state, action, reward, alpha, gamma):\n \n # 구현해보세요.\n # update 수식은 pseudo code 참조\n # q_table[s, a] = q_table[s, a] + TD error\n \n return q_table",
"_____no_output_____"
],
[
"np.set_printoptions(formatter={'float': '{: 0.3f}'.format})\n\nq_table = np.array([[0,0,0,0],\n [0,1,0,0]], dtype=np.float)\nprint(\"start\\n\", q_table)\n\nreward = 1.0\nalpha = 0.1\ngamma = 0.9\n\nfor i in range(10):\n print(\"update {}\".format(i))\n q_table = q_update(q_table, 0, 1, 2, reward, alpha, gamma)\n print(q_table)",
"_____no_output_____"
]
],
[
[
"### Agent class",
"_____no_output_____"
],
[
"## Goal에 도착하기 위해 생각해야 하는것\n1. Goal에 한번이라도 도착해야만 reward가 나와서 update 된다 $\\rightarrow$ goal에 어떻게 가게 할까?\n2. hole에 빠졌을 때 episode가 끝나긴 하지만 reward에 차이는 없다. $\\rightarrow$ hole에 빠져서 끝나면 negative reward를 주도록 한다.\n3. 학습이 잘 되어도 epsilon 만큼의 확률로 random action을 한다. $\\rightarrow$ 학습이 진행될수록 epsilon을 줄인다.",
"_____no_output_____"
]
],
[
[
"class Tabular_Q_agent:\n def __init__(self, q_table, n_action, epsilon, alpha, gamma):\n self.q_table = q_table\n self.epsilon = epsilon\n self.alpha = alpha\n self.gamma = gamma\n self.n_action = n_action\n \n def get_action(self, state):\n \n # 구현해보세요. (e-greedy policy)\n \n return action\n \n def q_update(self, state, next_state, action, reward):\n \n # 구현해보세요.\n # update 수식은 pseudo code 참조\n \n return q_table",
"_____no_output_____"
]
],
[
[
"### Training agent",
"_____no_output_____"
]
],
[
[
"env = gym.make(\"FrozenLakeNotSlippery-v0\")\n\nEPISODE = 500\nepsilon = 0.9\nalpha = 0.8 # learning rate\ngamma = 0.9 # discount factor\nn_action = \n\nrlist = []\nslist = []\n\nis_render = False\n\n# initialize Q-Table \nq_table = np.random.rand(env.observation_space.n, env.action_space.n)\nprint(\"Q table size: \", q_table.shape)\n\n# agent 생성\nagent = \n\n# Epiode 수만큼 반복\nfor e in range(EPISODE):\n state = env.reset()\n print(\"[Episode {}]\".format(e))\n if is_render:\n env.render()\n \n total_reward = 0\n goal = 0\n done = False\n limit = 0\n \n # 게임이 끝날때까지 반복 또는 100번 step할 때까지 반복\n while not done and limit < 100:\n # 1. select action by e-greedy policy\n # e-greedy로 action을 선택.\n \n # 2. do action and go to next state\n # env.step()을 사용해 1 step 이동 후 next state와 reward, done 값을 받아옴.\n \n # 2.1. hole 에 빠졌을 때 (-) reward를 받도록 함.\n if reward == 1.0:\n print(\"GOAL\")\n goal = 1\n elif done:\n reward = reward - 1\n \n # 3. Q update\n # Q table에서 현재 state의 Q값을 update 한다.\n \n slist.append(state)\n state = next_state\n \n total_reward += reward\n limit += 1\n \n print(slist)\n slist = []\n print(\"total reward: \", total_reward)\n rlist.append(goal)\n \nprint(\"성공한 확률\" + str(sum(rlist) / EPISODE) + \"%\")\n",
"_____no_output_____"
],
[
"np.set_printoptions(formatter={'float': '{: 0.3f}'.format})\nprint(agent.q_table)",
"_____no_output_____"
]
],
[
[
"### Test agent",
"_____no_output_____"
]
],
[
[
"state = env.reset()\ndone = False\nlimit = 0\n\nagent.epsilon = 0.0\nwhile not done and limit < 30:\n action = agent.get_action(state)\n next_state, reward, done, _ = env.step(action)\n env.render()\n state = next_state\n limit += 1",
"_____no_output_____"
]
]
] |
[
"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"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac3ed732c4a6c33e5ed561f3da3e087520c13b0
| 24,245 |
ipynb
|
Jupyter Notebook
|
Day_6_Numpy_Part_2.ipynb
|
swetarani-G/Python-Deep-Learning-Bootcamp
|
a426f094f408172b57f13881ea71c956194aa6f1
|
[
"Apache-2.0"
] | null | null | null |
Day_6_Numpy_Part_2.ipynb
|
swetarani-G/Python-Deep-Learning-Bootcamp
|
a426f094f408172b57f13881ea71c956194aa6f1
|
[
"Apache-2.0"
] | null | null | null |
Day_6_Numpy_Part_2.ipynb
|
swetarani-G/Python-Deep-Learning-Bootcamp
|
a426f094f408172b57f13881ea71c956194aa6f1
|
[
"Apache-2.0"
] | null | null | null | 30.30625 | 497 | 0.41988 |
[
[
[
"## **Accessing Elements in ndarays:**\nElements can be accessed using indices inside square brackets, [ ]. NumPy allows you to use both positive and negative indices to access elements in the ndarray. Positive indices are used to access elements from the beginning of the array, while negative indices are used to access elements from the end of the array. ",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\n# We create a rank 1 ndarray that contains integers from 1 to 5\nx = np.array([1, 2, 3, 4, 5])\n\n# We print x\nprint()\nprint('x = ', x)\nprint()\n\n# Let's access some elements with positive indices\nprint('This is First Element in x:', x[0]) \nprint('This is Second Element in x:', x[1])\nprint('This is Fifth (Last) Element in x:', x[4])\nprint()\n\n# Let's access the same elements with negative indices\nprint('This is First Element in x:', x[-5])\nprint('This is Second Element in x:', x[-4])\nprint('This is Fifth (Last) Element in x:', x[-1])",
"\nx = [1 2 3 4 5]\n\nThis is First Element in x: 1\nThis is Second Element in x: 2\nThis is Fifth (Last) Element in x: 5\n\nThis is First Element in x: 1\nThis is Second Element in x: 2\nThis is Fifth (Last) Element in x: 5\n"
]
],
[
[
"## **Modifying ndarrays:**\nNow let's see how we can change the elements in rank 1 ndarrays. We do this by accessing the element we want to change and then using the = sign to assign the new value:",
"_____no_output_____"
]
],
[
[
"# We create a rank 1 ndarray that contains integers from 1 to 5\nx = np.array([1, 2, 3, 4, 5])\n\n# We print the original x\nprint()\nprint('Original:\\n x = ', x)\nprint()\n\n# We change the fourth element in x from 4 to 20\nx[3] = 20\n\n# We print x after it was modified \nprint('Modified:\\n x = ', x)\n",
"\nOriginal:\n x = [1 2 3 4 5]\n\nModified:\n x = [ 1 2 3 20 5]\n"
]
],
[
[
"Similarly, we can also access and modify specific elements of rank 2 ndarrays. To access elements in rank 2 ndarrays we need to provide 2 indices in the form [row, column]. Let's see some examples",
"_____no_output_____"
]
],
[
[
"# We create a 3 x 3 rank 2 ndarray that contains integers from 1 to 9\nX = np.array([[1,2,3],[4,5,6],[7,8,9]])\n\n# We print X\nprint()\nprint('X = \\n', X)\nprint()\n\n# Let's access some elements in X\nprint('This is (0,0) Element in X:', X[0,0])\nprint('This is (0,1) Element in X:', X[0,1])\nprint('This is (2,2) Element in X:', X[2,2])",
"\nX = \n [[1 2 3]\n [4 5 6]\n [7 8 9]]\n\nThis is (0,0) Element in X: 1\nThis is (0,1) Element in X: 2\nThis is (2,2) Element in X: 9\n"
]
],
[
[
"Elements in rank 2 ndarrays can be modified in the same way as with rank 1 ndarrays. Let's see an example:",
"_____no_output_____"
]
],
[
[
"# We create a 3 x 3 rank 2 ndarray that contains integers from 1 to 9\nX = np.array([[1,2,3],[4,5,6],[7,8,9]])\n\n# We print the original x\nprint()\nprint('Original:\\n X = \\n', X)\nprint()\n\n# We change the (0,0) element in X from 1 to 20\nX[0,0] = 20\n\n# We print X after it was modified \nprint('Modified:\\n X = \\n', X)\n",
"\nOriginal:\n X = \n [[1 2 3]\n [4 5 6]\n [7 8 9]]\n\nModified:\n X = \n [[20 2 3]\n [ 4 5 6]\n [ 7 8 9]]\n"
]
],
[
[
"## **Adding and Deleting elements:**\nNow, let's take a look at how we can add and delete elements from ndarrays. We can delete elements using the np.delete(ndarray, elements, axis) function. This function deletes the given list of elements from the given ndarray along the specified axis. For rank 1 ndarrays the axis keyword is not required. For rank 2 ndarrays, axis = 0 is used to select rows, and axis = 1 is used to select columns. Let's see some examples:",
"_____no_output_____"
]
],
[
[
"# We create a rank 1 ndarray \nx = np.array([1, 2, 3, 4, 5])\n\n# We create a rank 2 ndarray\nY = np.array([[1,2,3],[4,5,6],[7,8,9]])\n\n# We print x\nprint()\nprint('Original x = ', x)\n\n# We delete the first and last element of x\nx = np.delete(x, [0,4])\n\n# We print x with the first and last element deleted\nprint()\nprint('Modified x = ', x)\n\n# We print Y\nprint()\nprint('Original Y = \\n', Y)\n\n# We delete the first row of y\nw = np.delete(Y, 0, axis=0)\n\n# We delete the first and last column of y\nv = np.delete(Y, [0,2], axis=1)\n\n# We print w\nprint()\nprint('w = \\n', w)\n\n# We print v\nprint()\nprint('v = \\n', v)",
"\nOriginal x = [1 2 3 4 5]\n\nModified x = [2 3 4]\n\nOriginal Y = \n [[1 2 3]\n [4 5 6]\n [7 8 9]]\n\nw = \n [[4 5 6]\n [7 8 9]]\n\nv = \n [[2]\n [5]\n [8]]\n"
]
],
[
[
"We can append values to ndarrays using the np.append(ndarray, elements, axis) function. This function appends the given list of elements to ndarray along the specified axis. Let's see some examples:",
"_____no_output_____"
]
],
[
[
"# We create a rank 1 ndarray \nx = np.array([1, 2, 3, 4, 5])\n\n# We create a rank 2 ndarray \nY = np.array([[1,2,3],[4,5,6]])\n\n# We print x\nprint()\nprint('Original x = ', x)\n\n# We append the integer 6 to x\nx = np.append(x, 6)\n\n# We print x\nprint()\nprint('x = ', x)\n\n# We append the integer 7 and 8 to x\nx = np.append(x, [7,8])\n\n# We print x\nprint()\nprint('x = ', x)\n\n# We print Y\nprint()\nprint('Original Y = \\n', Y)\n\n# We append a new row containing 7,8,9 to y\nv = np.append(Y, [[7,8,9]], axis=0)\n\n# We append a new column containing 9 and 10 to y\nq = np.append(Y,[[9],[10]], axis=1)\n\n# We print v\nprint()\nprint('v = \\n', v)\n\n# We print q\nprint()\nprint('q = \\n', q)",
"\nOriginal x = [1 2 3 4 5]\n\nx = [1 2 3 4 5 6]\n\nx = [1 2 3 4 5 6 7 8]\n\nOriginal Y = \n [[1 2 3]\n [4 5 6]]\n\nv = \n [[1 2 3]\n [4 5 6]\n [7 8 9]]\n\nq = \n [[ 1 2 3 9]\n [ 4 5 6 10]]\n"
]
],
[
[
"Now let's see now how we can insert values to ndarrays. We can insert values to ndarrays using the np.insert(ndarray, index, elements, axis) function. This function inserts the given list of elements to ndarray right before the given index along the specified axis. Let's see some examples:",
"_____no_output_____"
]
],
[
[
"# We create a rank 1 ndarray \nx = np.array([1, 2, 5, 6, 7])\n\n# We create a rank 2 ndarray \nY = np.array([[1,2,3],[7,8,9]])\n\n# We print x\nprint()\nprint('Original x = ', x)\n\n# We insert the integer 3 and 4 between 2 and 5 in x. \nx = np.insert(x,2,[3,4])\n\n# We print x with the inserted elements\nprint()\nprint('x = ', x)\n\n# We print Y\nprint()\nprint('Original Y = \\n', Y)\n\n# We insert a row between the first and last row of y\nw = np.insert(Y,1,[4,5,6],axis=0)\n\n# We insert a column full of 5s between the first and second column of y\nv = np.insert(Y,1,5, axis=1)\n\n# We print w\nprint()\nprint('w = \\n', w)\n\n# We print v\nprint()\nprint('v = \\n', v)",
"\nOriginal x = [1 2 5 6 7]\n\nx = [1 2 3 4 5 6 7]\n\nOriginal Y = \n [[1 2 3]\n [7 8 9]]\n\nw = \n [[1 2 3]\n [4 5 6]\n [7 8 9]]\n\nv = \n [[1 5 2 3]\n [7 5 8 9]]\n"
]
],
[
[
"NumPy also allows us to stack ndarrays on top of each other, or to stack them side by side. The stacking is done using either the np.vstack() function for vertical stacking, or the np.hstack() function for horizontal stacking. It is important to note that in order to stack ndarrays, the shape of the ndarrays must match. Let's see some examples:",
"_____no_output_____"
]
],
[
[
"# We create a rank 1 ndarray \nx = np.array([1,2])\n\n# We create a rank 2 ndarray \nY = np.array([[3,4],[5,6]])\n\n# We print x\nprint()\nprint('x = ', x)\n\n# We print Y\nprint()\nprint('Y = \\n', Y)\n\n# We stack x on top of Y\nz = np.vstack((x,Y))\n\n# We stack x on the right of Y. We need to reshape x in order to stack it on the right of Y. \nw = np.hstack((Y,x.reshape(2,1)))\n\n# We print z\nprint()\nprint('z = \\n', z)\n\n# We print w\nprint()\nprint('w = \\n', w)",
"\nx = [1 2]\n\nY = \n [[3 4]\n [5 6]]\n\nz = \n [[1 2]\n [3 4]\n [5 6]]\n\nw = \n [[3 4 1]\n [5 6 2]]\n"
]
],
[
[
"## **Slicing ndarrays:**\nAs we mentioned earlier, in addition to being able to access individual elements one at a time, NumPy provides a way to access subsets of ndarrays. This is known as slicing. Slicing is performed by combining indices with the colon : symbol inside the square brackets. In general you will come across three types of slicing:\n\n```\n1. ndarray[start:end]\n2. ndarray[start:]\n3. ndarray[:end]\n```\nThe first method is used to select elements between the start and end indices. The second method is used to select all elements from the start index till the last index. The third method is used to select all elements from the first index till the end index. We should note that in methods one and three, the end index is excluded. We should also note that since ndarrays can be multidimensional, when doing slicing you usually have to specify a slice for each dimension of the array.\n\nWe will now see some examples of how to use the above methods to select different subsets of a rank 2 ndarray.\n",
"_____no_output_____"
]
],
[
[
"# We create a 4 x 5 ndarray that contains integers from 0 to 19\nX = np.arange(20).reshape(4, 5)\n\n# We print X\nprint()\nprint('X = \\n', X)\nprint()\n\n# We select all the elements that are in the 2nd through 4th rows and in the 3rd to 5th columns\nZ = X[1:4,2:5]\n\n# We print Z\nprint('Z = \\n', Z)\n\n# We can select the same elements as above using method 2\nW = X[1:,2:5]\n\n# We print W\nprint()\nprint('W = \\n', W)\n\n# We select all the elements that are in the 1st through 3rd rows and in the 3rd to 4th columns\nY = X[:3,2:5]\n\n# We print Y\nprint()\nprint('Y = \\n', Y)\n\n# We select all the elements in the 3rd row\nv = X[2,:]\n\n# We print v\nprint()\nprint('v = ', v)\n\n# We select all the elements in the 3rd column\nq = X[:,2]\n\n# We print q\nprint()\nprint('q = ', q)\n\n# We select all the elements in the 3rd column but return a rank 2 ndarray\nR = X[:,2:3]\n\n# We print R\nprint()\nprint('R = \\n', R)",
"\nX = \n [[ 0 1 2 3 4]\n [ 5 6 7 8 9]\n [10 11 12 13 14]\n [15 16 17 18 19]]\n\nZ = \n [[ 7 8 9]\n [12 13 14]\n [17 18 19]]\n\nW = \n [[ 7 8 9]\n [12 13 14]\n [17 18 19]]\n\nY = \n [[ 2 3 4]\n [ 7 8 9]\n [12 13 14]]\n\nv = [10 11 12 13 14]\n\nq = [ 2 7 12 17]\n\nR = \n [[ 2]\n [ 7]\n [12]\n [17]]\n"
]
],
[
[
"Notice that when we selected all the elements in the 3rd column, variable q above, the slice returned a rank 1 ndarray instead of a rank 2 ndarray. However, slicing X in a slightly different way, variable R above, we can actually get a rank 2 ndarray instead.\n\nIt is important to note that when we perform slices on ndarrays and save them into new variables, as we did above, the data is not copied into the new variable. This is one feature that often causes confusion for beginners. Therefore, we will look at this in a bit more detail.\n\nIn the above examples, when we make assignments, such as:\n```\nZ = X[1:4,2:5]\n```\nthe slice of the original array X is not copied in the variable Z. Rather, X and Z are now just two different names for the same ndarray. We say that slicing only creates a view of the original array. This means that if you make changes in Z you will be in effect changing the elements in X as well. Let's see this with an example:",
"_____no_output_____"
]
],
[
[
"# We create a 4 x 5 ndarray that contains integers from 0 to 19\nX = np.arange(20).reshape(4, 5)\n\n# We print X\nprint()\nprint('X = \\n', X)\nprint()\n\n# We select all the elements that are in the 2nd through 4th rows and in the 3rd to 4th columns\nZ = X[1:4,2:5]\n\n# We print Z\nprint()\nprint('Z = \\n', Z)\nprint()\n\n# We change the last element in Z to 555\nZ[2,2] = 555\n\n# We print X\nprint()\nprint('X = \\n', X)\nprint()",
"\nX = \n [[ 0 1 2 3 4]\n [ 5 6 7 8 9]\n [10 11 12 13 14]\n [15 16 17 18 19]]\n\n\nZ = \n [[ 7 8 9]\n [12 13 14]\n [17 18 19]]\n\n\nX = \n [[ 0 1 2 3 4]\n [ 5 6 7 8 9]\n [ 10 11 12 13 14]\n [ 15 16 17 18 555]]\n\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",
"code"
]
] |
4ac3fcc97753e4645b965829a1dbba6048155023
| 144,016 |
ipynb
|
Jupyter Notebook
|
examples/gallery.ipynb
|
yitzchak/delta-vega
|
e750e053c6c0ff1f7af7c4efd0f6a9e2eff8c788
|
[
"MIT"
] | null | null | null |
examples/gallery.ipynb
|
yitzchak/delta-vega
|
e750e053c6c0ff1f7af7c4efd0f6a9e2eff8c788
|
[
"MIT"
] | null | null | null |
examples/gallery.ipynb
|
yitzchak/delta-vega
|
e750e053c6c0ff1f7af7c4efd0f6a9e2eff8c788
|
[
"MIT"
] | null | null | null | 217.875946 | 45,113 | 0.900858 |
[
[
[
"(ql:quickload :delta-vega)",
"To load \"delta-vega\":\n Load 1 ASDF system:\n delta-vega\n"
]
],
[
[
"# Single-View Plots\n## Bar Charts\n### Simple Bar Chart\nA bar chart encodes quantitative values as the extent of rectangular bars.",
"_____no_output_____"
]
],
[
[
"(jupyter:vega-lite\n (delta-vega:make-top-view :description \"A simple bar chart with embedded data.\"\n :data (delta-vega:make-vector-data \"a\" #(\"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\")\n \"b\" #(28 55 43 91 81 53 19 87 52))\n :mark (delta-vega:make-bar-mark)\n :encoding (delta-vega:make-encoding :x (delta-vega:make-field-definition :field \"a\" :type :nominal)\n :y (delta-vega:make-field-definition :field \"b\" :type :quantitative)))\n :display t)",
"_____no_output_____"
]
],
[
[
"***\n## Scatter & Strip Plots\n### Scatterplot\nA scatterplot showing horsepower and miles per gallons for various cars.",
"_____no_output_____"
]
],
[
[
"(jupyter:vega-lite\n (delta-vega:make-top-view :description \"A scatterplot showing horsepower and miles per gallons for various cars.\"\n :data (j:make-object \"url\" \"data/cars.json\")\n :mark (delta-vega:make-point-mark)\n :encoding (delta-vega:make-encoding :x (delta-vega:make-field-definition :field \"Horsepower\" :type :quantitative)\n :y (delta-vega:make-field-definition :field \"Miles_per_Gallon\" :type :quantitative)))\n :display t)",
"_____no_output_____"
]
],
[
[
"***\n### 1D Strip Plot",
"_____no_output_____"
]
],
[
[
"(jupyter:vega-lite\n (delta-vega:make-top-view :data (j:make-object \"url\" \"data/seattle-weather.csv\")\n :mark (delta-vega:make-tick-mark)\n :encoding (delta-vega:make-encoding :x (delta-vega:make-field-definition :field \"precipitation\" :type :quantitative)))\n :display t)",
"_____no_output_____"
]
],
[
[
"***\n### Strip Plot\nShows the relationship between horsepower and the number of cylinders using tick marks.",
"_____no_output_____"
]
],
[
[
"(jupyter:vega-lite\n (delta-vega:make-top-view :description \"Shows the relationship between horsepower and the number of cylinders using tick marks.\"\n :data (j:make-object \"url\" \"data/cars.json\")\n :mark (delta-vega:make-tick-mark)\n :encoding (delta-vega:make-encoding :x (delta-vega:make-field-definition :field \"Horsepower\" :type :quantitative)\n :y (delta-vega:make-field-definition :field \"Cylinders\" :type :ordinal)))\n :display t)",
"_____no_output_____"
]
],
[
[
"***\n### Colored Scatterplot\nA scatterplot showing body mass and flipper lengths of penguins.",
"_____no_output_____"
]
],
[
[
"(jupyter:vega-lite\n (delta-vega:make-top-view :description \"A scatterplot showing body mass and flipper lengths of penguins.\"\n :data (j:make-object \"url\" \"data/penguins.json\")\n :mark (delta-vega:make-point-mark)\n :encoding (delta-vega:make-encoding :x (delta-vega:make-field-definition :field \"Flipper Length (mm)\" :type :quantitative :scale '(:object-plist \"zero\" nil))\n :y (delta-vega:make-field-definition :field \"Body Mass (g)\" :type :quantitative :scale '(:object-plist \"zero\" nil))\n :color (delta-vega:make-field-definition :field \"Species\" :type :nominal)\n :shape (delta-vega:make-field-definition :field \"Species\" :type :nominal)))\n :display t)",
"_____no_output_____"
]
],
[
[
"***\n## Circular Plots\n### Simple Pie Chart\nA pie chart encodes proportional differences among a set of numeric values as the angular extent and area of a circular slice.",
"_____no_output_____"
]
],
[
[
"(jupyter:vega-lite\n (delta-vega:make-top-view :description \"A simple pie chart with embedded data.\"\n :data (delta-vega:make-vector-data \"category\" #(1 2 3 4 5 6)\n \"value\" #(4 6 10 3 7 8))\n :mark (delta-vega:make-arc-mark)\n :view '(:object-plist \"stroke\" :null)\n :encoding (delta-vega:make-encoding :theta (delta-vega:make-field-definition :field \"value\" :type :quantitative)\n :color (delta-vega:make-field-definition :field \"category\" :type :nominal)))\n :display t)",
"_____no_output_____"
]
],
[
[
"***\n### Simple Donut Chart\nA donut chart encodes proportional differences among a set of numeric values using angular extents.",
"_____no_output_____"
]
],
[
[
"(jupyter:vega-lite\n (delta-vega:make-top-view :description \"A simple dounut chart with embedded data.\"\n :data (delta-vega:make-vector-data \"category\" #(1 2 3 4 5 6)\n \"value\" #(4 6 10 3 7 8))\n :mark (delta-vega:make-arc-mark :inner-radius 50)\n :view '(:object-plist \"stroke\" :null)\n :encoding (delta-vega:make-encoding :theta (delta-vega:make-field-definition :field \"value\" :type :quantitative)\n :color (delta-vega:make-field-definition :field \"category\" :type :nominal)))\n :display t)",
"_____no_output_____"
]
],
[
[
"***\n### Pie Chart with Labels\nLayering text over arc marks to label pie charts. For now, you need to `:stack t` to theta to force the text to apply the same polar stacking layout.",
"_____no_output_____"
]
],
[
[
"(jupyter:vega-lite\n (delta-vega:make-top-view :description \"A simple dounut chart with embedded data.\"\n :data (delta-vega:make-vector-data \"category\" #(\"a\" \"b\" \"c\" \"d\" \"e\" \"f\")\n \"value\" #(4 6 10 3 7 8))\n :view '(:object-plist \"stroke\" :null)\n :layer (list (dv:make-view :mark (delta-vega:make-arc-mark :outer-radius 80))\n (dv:make-view :mark (dv:make-text-mark :radius 90)\n :encoding (dv:make-encoding :text (delta-vega:make-field-definition :field \"category\" :type :nominal))))\n :encoding (delta-vega:make-encoding :theta (delta-vega:make-field-definition :field \"value\" :type :quantitative :stack t)\n :color (delta-vega:make-field-definition :field \"category\" :type :nominal :legend nil)))\n :display t)",
"_____no_output_____"
]
]
] |
[
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac40794d0bfe0278e385b7f01c5f5f748e065d7
| 20,869 |
ipynb
|
Jupyter Notebook
|
docs/Examples/Performing Large Numbers of Calculations with Thermo in Parallel.ipynb
|
andr1976/thermo
|
42d10b3702373aacc88167d4046ea9af92abd570
|
[
"MIT"
] | null | null | null |
docs/Examples/Performing Large Numbers of Calculations with Thermo in Parallel.ipynb
|
andr1976/thermo
|
42d10b3702373aacc88167d4046ea9af92abd570
|
[
"MIT"
] | null | null | null |
docs/Examples/Performing Large Numbers of Calculations with Thermo in Parallel.ipynb
|
andr1976/thermo
|
42d10b3702373aacc88167d4046ea9af92abd570
|
[
"MIT"
] | null | null | null | 83.143426 | 12,756 | 0.823662 |
[
[
[
"# Performing Large Numbers of Calculations with Thermo in Parallel",
"_____no_output_____"
],
[
"A common request is to obtain a large number of properties from Thermo at once. Thermo is not NumPy - it cannot just automatically do all of the calculations in parallel. \n\nIf you have a specific property that does not require phase equilibrium calculations to obtain, it is possible to\nuse the `chemicals.numba` interface to in your own numba-accelerated code.\nhttps://chemicals.readthedocs.io/chemicals.numba.html\n\nFor those cases where lots of flashes are needed, your best bet is to brute force it - use multiprocessing (and maybe a beefy machine) to obtain the results faster. The following code sample uses `joblib` to facilitate the calculation. Note that joblib won't show any benefits on sub-second calculations. Also note that the `threading` backend of joblib will not offer any performance improvements due to the CPython GIL.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom thermo import *\nfrom chemicals import *\n\nconstants, properties = ChemicalConstantsPackage.from_IDs(\n ['methane', 'ethane', 'propane', 'isobutane', 'n-butane', 'isopentane', \n 'n-pentane', 'hexane', 'heptane', 'octane', 'nonane', 'nitrogen'])\nT, P = 200, 5e6\nzs = [.8, .08, .032, .00963, .0035, .0034, .0003, .0007, .0004, .00005, .00002, .07]\neos_kwargs = dict(Tcs=constants.Tcs, Pcs=constants.Pcs, omegas=constants.omegas)\ngas = CEOSGas(SRKMIX, eos_kwargs, HeatCapacityGases=properties.HeatCapacityGases, T=T, P=P, zs=zs)\nliq = CEOSLiquid(SRKMIX, eos_kwargs, HeatCapacityGases=properties.HeatCapacityGases, T=T, P=P, zs=zs)\n# Set up a two-phase flash engine, ignoring kijs\nflasher = FlashVL(constants, properties, liquid=liq, gas=gas)\n\n# Set a composition - it could be modified in the inner loop as well\n# Do a test flash\nflasher.flash(T=T, P=P, zs=zs).gas_beta",
"_____no_output_____"
],
[
"def get_properties(T, P):\n # This is the function that will be called in parallel\n # note that Python floats are faster than numpy floats\n res = flasher.flash(T=float(T), P=float(P), zs=zs)\n return [res.rho_mass(), res.Cp_mass(), res.gas_beta]",
"_____no_output_____"
],
[
"from joblib import Parallel, delayed\npts = 30\nTs = np.linspace(200, 400, pts)\nPs = np.linspace(1e5, 1e7, pts)\nTs_grid, Ps_grid = np.meshgrid(Ts, Ps)\n# processed_data = Parallel(n_jobs=16)(delayed(get_properties)(T, P) for T, P in zip(Ts_grid.flat, Ps_grid.flat))",
"_____no_output_____"
],
[
"# Naive loop in Python\n%timeit -r 1 -n 1 processed_data = [get_properties(T, P) for T, P in zip(Ts_grid.flat, Ps_grid.flat)]",
"15.3 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)\n"
],
[
"# Use the threading feature of Joblib\n# Because the calculation is CPU-bound, the threads do not improve speed and Joblib's overhead slows down the calculation\n%timeit -r 1 -n 1 processed_data = Parallel(n_jobs=16, prefer=\"threads\")(delayed(get_properties)(T, P) for T, P in zip(Ts_grid.flat, Ps_grid.flat))",
"43.9 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)\n"
],
[
"# Use the multiprocessing feature of joblib\n# We were able to improve the speed by 5x\n%timeit -r 1 -n 1 processed_data = Parallel(n_jobs=16, batch_size=30)(delayed(get_properties)(T, P) for T, P in zip(Ts_grid.flat, Ps_grid.flat))",
"3.55 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)\n"
],
[
"# For small multiprocessing jobs, the slowest job can cause a significant delay\n# For longer and larger jobs the full benefit of using all cores is shown better.\n%timeit -r 1 -n 1 processed_data = Parallel(n_jobs=8, batch_size=30)(delayed(get_properties)(T, P) for T, P in zip(Ts_grid.flat, Ps_grid.flat))",
"4.42 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)\n"
],
[
"# Joblib returns the data as a flat structure, but we can re-construct it into a grid\nprocessed_data = Parallel(n_jobs=16, batch_size=30)(delayed(get_properties)(T, P) for T, P in zip(Ts_grid.flat, Ps_grid.flat))\nphase_fractions = np.array([[processed_data[j*pts+i][2] for j in range(pts)] for i in range(pts)])",
"_____no_output_____"
],
[
"# Make a plot to show the results\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import ticker, cm\nfrom matplotlib.colors import LogNorm\nfig, ax = plt.subplots()\ncolor_map = cm.viridis\nim = ax.pcolormesh(Ts_grid, Ps_grid, phase_fractions.T, cmap=color_map)\ncbar = fig.colorbar(im, ax=ax)\ncbar.set_label('Gas phase fraction')\n\nax.set_yscale('log')\nax.set_xlabel('Temperature [K]')\nax.set_ylabel('Pressure [Pa]')\nplt.show()",
"<ipython-input-10-719d0a113f9b>:8: 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 = ax.pcolormesh(Ts_grid, Ps_grid, phase_fractions.T, cmap=color_map)\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac414582ce579959ec0ffb6f290488cd3b6a128
| 14,494 |
ipynb
|
Jupyter Notebook
|
notebook/models/electra-training.ipynb
|
vinay9986/CommonLit
|
48e12b297c8f1187926384ef3d513152ee75e6a7
|
[
"Apache-2.0"
] | null | null | null |
notebook/models/electra-training.ipynb
|
vinay9986/CommonLit
|
48e12b297c8f1187926384ef3d513152ee75e6a7
|
[
"Apache-2.0"
] | null | null | null |
notebook/models/electra-training.ipynb
|
vinay9986/CommonLit
|
48e12b297c8f1187926384ef3d513152ee75e6a7
|
[
"Apache-2.0"
] | null | null | null | 14,494 | 14,494 | 0.678833 |
[
[
[
"import os\nimport numpy as np\nimport pandas as pd\nimport random\n\n\nfrom transformers import (AdamW, get_linear_schedule_with_warmup, logging, \n ElectraConfig, ElectraTokenizer, ElectraForSequenceClassification, \n ElectraPreTrainedModel, ElectraModel)\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import TensorDataset, SequentialSampler, RandomSampler, DataLoader\n\nfrom tqdm.notebook import tqdm\n\nimport gc; gc.enable()\nfrom IPython.display import clear_output\n\nfrom sklearn.model_selection import StratifiedKFold\n\nlogging.set_verbosity_error()",
"_____no_output_____"
],
[
"INPUT_DIR = '../input/commonlitreadabilityprize'\nMODEL_NAME = 'roberta-large'\n\nMAX_LENGTH = 256\nLR = 2e-5\nEPS = 1e-8\n\nSEED = 42\n\nNUM_FOLDS = 5\nSEEDS = [113, 71, 17, 43, 37]\n\nEPOCHS = 5\nTRAIN_BATCH_SIZE = 8\nVAL_BATCH_SIZE = 32\n\nDEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')",
"_____no_output_____"
],
[
"def set_seed(seed = 0):\n np.random.seed(seed)\n random_state = np.random.RandomState(seed)\n random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n os.environ['PYTHONHASHSEED'] = str(seed)\n return random_state\n\nrandom_state = set_seed(SEED)",
"_____no_output_____"
],
[
"class ContinuousStratifiedKFold(StratifiedKFold):\n def split(self, x, y, groups=None):\n num_bins = int(np.floor(1 + np.log2(len(y))))\n bins = pd.cut(y, bins=num_bins, labels=False)\n return super().split(x, bins, groups)\n \ndef get_data_loaders(data, fold):\n \n x_train = data.loc[data.fold != fold, 'excerpt'].tolist()\n y_train = data.loc[data.fold != fold, 'target'].values\n x_val = data.loc[data.fold == fold, 'excerpt'].tolist()\n y_val = data.loc[data.fold == fold, 'target'].values\n \n encoded_train = tokenizer.batch_encode_plus(\n x_train, \n add_special_tokens=True, \n return_attention_mask=True, \n padding='max_length', \n truncation=True,\n max_length=MAX_LENGTH, \n return_tensors='pt'\n )\n \n encoded_val = tokenizer.batch_encode_plus(\n x_val, \n add_special_tokens=True, \n return_attention_mask=True, \n padding='max_length', \n truncation=True,\n max_length=MAX_LENGTH, \n return_tensors='pt'\n )\n \n dataset_train = TensorDataset(\n encoded_train['input_ids'],\n encoded_train['attention_mask'],\n torch.tensor(y_train)\n )\n dataset_val = TensorDataset(\n encoded_val['input_ids'],\n encoded_val['attention_mask'],\n torch.tensor(y_val)\n )\n \n dataloader_train = DataLoader(\n dataset_train,\n sampler = RandomSampler(dataset_train),\n batch_size=TRAIN_BATCH_SIZE\n )\n\n dataloader_val = DataLoader(\n dataset_val,\n sampler = SequentialSampler(dataset_val),\n batch_size=VAL_BATCH_SIZE\n )\n\n return dataloader_train, dataloader_val",
"_____no_output_____"
],
[
"data = pd.read_csv(os.path.join(INPUT_DIR, 'train.csv'))\n\n# Create stratified folds\nkf = ContinuousStratifiedKFold(n_splits=5, shuffle=True, random_state=SEED)\nfor f, (t_, v_) in enumerate(kf.split(data, data.target)):\n data.loc[v_, 'fold'] = f\ndata['fold'] = data['fold'].astype(int)",
"_____no_output_____"
],
[
"def evaluate(model, val_dataloader):\n model.eval()\n loss_val_total = 0\n for batch in val_dataloader:\n batch = tuple(b.to(DEVICE) for b in batch)\n labels = batch[2].type(torch.float)\n inputs = {'input_ids': batch[0],\n 'attention_mask': batch[1],\n 'labels': labels,\n }\n with torch.no_grad():\n # To be used when using default architecture from transformers\n output = model(**inputs)\n loss = output.loss\n # To be used with custome head\n# loss = model(**inputs)\n loss_val_total += loss.item()\n loss_val_avg = loss_val_total/len(val_dataloader) \n return loss_val_avg\n\ndef train(model, train_dataloader, val_dataloader):\n optimizer = AdamW(model.parameters(), lr = LR, eps = EPS)\n scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=len(train_dataloader) * EPOCHS)\n best_val_loss = 1\n model.train()\n for epoch in range(EPOCHS):\n loss_train_total = 0\n for batch in tqdm(train_dataloader):\n model.zero_grad()\n batch = tuple(b.to(DEVICE) for b in batch)\n labels = batch[2].type(torch.float)\n inputs = {\n 'input_ids': batch[0],\n 'attention_mask': batch[1],\n 'labels': labels,\n }\n # To be used when using default architecture from transformers\n output = model(**inputs)\n loss = output.loss\n # To be used with custome head\n# loss = model(**inputs)\n loss_train_total += loss.item()\n loss.backward()\n optimizer.step()\n scheduler.step()\n loss_train_avg = loss_train_total / len(train_dataloader)\n loss_val_avg = evaluate(model, val_dataloader)\n print(f'epoch:{epoch+1}/{EPOCHS} train loss={loss_train_avg} val loss={loss_val_avg}')\n \n if loss_val_avg < best_val_loss:\n best_val_loss = loss_val_avg \n return best_val_loss",
"_____no_output_____"
],
[
"class ElectraForRegression(ElectraPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n self.config = config\n self.electra = ElectraModel(config)\n self.dropout = nn.Dropout(0.1)\n self.out_proj = nn.Linear(config.hidden_size, config.num_labels)\n self.loss = nn.MSELoss()\n\n self.init_weights()\n\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n labels=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.electra(\n input_ids,\n attention_mask,\n token_type_ids,\n position_ids,\n head_mask,\n inputs_embeds,\n output_attentions,\n output_hidden_states,\n return_dict,\n )\n\n last_hidden_state = outputs[0]\n input_mask_expanded = attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float()\n sum_embeddings = torch.sum(last_hidden_state * input_mask_expanded, 1)\n sum_mask = input_mask_expanded.sum(1)\n sum_mask = torch.clamp(sum_mask, min=1e-9)\n mean_embeddings = sum_embeddings / sum_mask\n \n dropped = self.dropout(mean_embeddings)\n logits = self.out_proj(dropped)\n\n preds = logits.squeeze(-1).squeeze(-1)\n \n if labels is not None:\n loss = self.loss(preds.view(-1).float(), labels.view(-1).float())\n return loss\n else:\n return preds",
"_____no_output_____"
],
[
"tokenizer = ElectraTokenizer.from_pretrained('google/electra-large-discriminator')\nconfig = ElectraConfig.from_pretrained('google/electra-large-discriminator')\nconfig.update({'problem_type': 'regression', 'num_labels': 1})\nmodel = ElectraForSequenceClassification.from_pretrained('google/electra-large-discriminator', config=config)\n# model = ElectraForRegression.from_pretrained('google/electra-large-discriminator', config=config)\nmodel.to(DEVICE)\nclear_output()",
"_____no_output_____"
],
[
"losses = []\n\nMAX_RUNS = 2\nruns = 0 # Variable to control termination condition\n\nfor i, seed in enumerate(SEEDS): \n # Termination condition\n if runs == MAX_RUNS:\n print(f'{runs} runs termination condition reached.')\n break \n \n print(f'********* seed({i}) = {seed} ***********')\n \n for fold in range(NUM_FOLDS):\n print(f'*** fold = {fold} ***')\n set_seed(seed)\n train_dataloader, val_dataloader = get_data_loaders(data, fold)\n \n loss = train(model, train_dataloader, val_dataloader)\n losses.append(loss)\n \n # Termination condition\n runs += 1\n if runs == MAX_RUNS:\n break",
"_____no_output_____"
],
[
"from sklearn.metrics import mean_squared_error\n\ntrain_dataloader, val_dataloader = get_data_loaders(data, 2)\nmodel.eval()\npredictions = []\ntargets = []\nwith torch.no_grad():\n for batch in val_dataloader:\n batch = tuple(b.to(DEVICE) for b in batch)\n targets.extend(batch[2].cpu().detach().numpy().ravel().tolist())\n inputs = {\n 'input_ids': batch[0],\n 'attention_mask': batch[1],\n }\n outputs = model(**inputs)\n# predictions.extend(outputs.cpu().detach().numpy().ravel().tolist()) #Custome head\n predictions.extend(outputs.logits.cpu().detach().numpy().ravel().tolist()) #Default head\n\nmean_squared_error(targets, predictions, squared=False)\n# Default head score\n# 0.035847414585227534\n# Custome head score\n# 0.1438390363656116",
"_____no_output_____"
],
[
"model.save_pretrained('/kaggle/working')",
"_____no_output_____"
],
[
"tokenizer.save_pretrained('/kaggle/working')",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac423a155ce5f018918dc7dbc800564525ea0be
| 51,225 |
ipynb
|
Jupyter Notebook
|
build/visualisation/Periodic Gaussian Plasma PMC - large lattice.ipynb
|
nimachm81/YEEFDTD
|
b6a757d574ad5475193c24c0bf83af445568a3fa
|
[
"MIT"
] | null | null | null |
build/visualisation/Periodic Gaussian Plasma PMC - large lattice.ipynb
|
nimachm81/YEEFDTD
|
b6a757d574ad5475193c24c0bf83af445568a3fa
|
[
"MIT"
] | null | null | null |
build/visualisation/Periodic Gaussian Plasma PMC - large lattice.ipynb
|
nimachm81/YEEFDTD
|
b6a757d574ad5475193c24c0bf83af445568a3fa
|
[
"MIT"
] | null | null | null | 138.821138 | 24,144 | 0.881933 |
[
[
[
"## plot plasma density\n\n%pylab inline\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom ReadBinary import *\n\nfilename = \"../data/Wp2-x.data\"\narrayInfo = GetArrayInfo(filename)\n\nprint(\"typeCode: \", arrayInfo[\"typeCode\"])\nprint(\"typeSize: \", arrayInfo[\"typeSize\"])\nprint(\"shape: \", arrayInfo[\"shape\"])\nprint(\"numOfArrays: \", arrayInfo[\"numOfArrays\"])\n\nWp2 = GetArrays(filename, 0, 1)[0,0,:,:]\nprint(\"shape: \", Wp2.shape)\n\nshape = Wp2.shape\n\nplt.figure(figsize=(6, 6*(shape[0]/shape[1])))\nplt.imshow(np.real(Wp2[:,:]), cmap=\"rainbow\", origin='lower', aspect='auto')\nplt.show()",
"Populating the interactive namespace from numpy and matplotlib\ntypeCode: 1\ntypeSize: 4\nshape: (1, 101, 1301)\nnumOfArrays: 21\nshape: (101, 1301)\n"
],
[
"## animate Electric field\n\n%pylab tk\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom ReadBinary import *\n\nfilename = \"../data/E-x.data\"\narrayInfo = GetArrayInfo(filename)\n\nprint(\"typeCode: \", arrayInfo[\"typeCode\"])\nprint(\"typeSize: \", arrayInfo[\"typeSize\"])\nprint(\"shape: \", arrayInfo[\"shape\"])\nprint(\"numOfArrays: \", arrayInfo[\"numOfArrays\"])\n\nE = GetArrays(filename, indStart=-500, indEnd=None)[:, 0, :, :]\nprint(\"shape: \", E.shape)\n\nshape = E.shape[1:]\n\nplt.ion()\nplt.figure(figsize=(7,6*(shape[0]/shape[1])))\n\nfor n in range(E.shape[0]):\n plt.clf()\n plt.imshow(np.real(E[n, :,:]), cmap=\"rainbow\", origin='lower', aspect='auto')\n plt.colorbar()\n plt.pause(0.05)",
"Populating the interactive namespace from numpy and matplotlib\ntypeCode: 1\ntypeSize: 4\nshape: (1, 101, 1301)\nnumOfArrays: 2001\nshape: (500, 101, 1301)\n"
],
[
"%pylab tk\n\nshape = E.shape[1:]\nion()\n\nnz_ignore = 300\n\nfor n in range(E.shape[0]): \n clf()\n plot(E[n, int(shape[0]/2), nz_ignore:])\n pause(0.05)\n",
"Populating the interactive namespace from numpy and matplotlib\n"
],
[
"## Get Spectrum 1D\n\nE = GetArrays(filename, indStart=-600, indEnd=None)[:, 0, :, :]\nshape = E.shape\nprint(\"shape : \", shape)\n\nNt, Ny, Nz = shape\nprint(\"Nt: {}, Ny: {}, Nz: {}\".format(Nt, Ny, Nz))\n\n#E_tz = np.sum(E, axis=1)/Ny\nE_tz = E[:, int(Ny/2), nz_ignore:]\n\nE_f = np.fft.fft2(E_tz)",
"shape : (600, 101, 1301)\nNt: 600, Ny: 101, Nz: 1301\n"
],
[
"%pylab inline\nimshow(np.real(E_f)[0:100, 0:100], origin=\"lower\", cmap=\"rainbow\")\n",
"Populating the interactive namespace from numpy and matplotlib\n"
],
[
"## Get Spectrum 2D\n\nE = GetArrays(filename, indStart=-600, indEnd=None)[:, 0, :, :]\nshape = E.shape\nprint(\"shape : \", shape)\n\nnz_ignore = 300\n\nNt, Ny, Nz = shape\nprint(\"Nt: {}, Ny: {}, Nz: {}\".format(Nt, Ny, Nz))\n\nE_tz = (np.sum(E, axis=1)/Ny)[:, nz_ignore:]\n#E_tz = E[:, int(Ny/2), nz_ignore:]\n\nNky, Nkz = 100, 100\nNw = 100\n\nky_max, kz_max = 4.0*np.pi, 4.0*np.pi\nw_max = 30.0\n\nw = np.linspace(0, w_max, Nw)\nkz = np.linspace(0, kz_max, Nkz)\nE_f = np.zeros((Nw, Nkz), dtype=complex)\n\nS = 0.95\ndy = 10/Ny\ndz = 12/Nz\ndt = 1.0/np.sqrt(1.0/dy**2 + 1.0/dz**2)*S\n\nt = np.linspace(0.0, Nt*dt, Nt, endpoint=True)\nz = np.linspace(0.0, Nz*dz, Nz)[nz_ignore:]\n\nt_mesh, z_mesh = np.meshgrid(t, z, indexing=\"ij\")\n\nfor i in range(Nw):\n w_i = w[i]\n print(i, end=\" \")\n for j in range(Nkz):\n kz_j = kz[j]\n E_f[i, j] = np.sum(E_tz*np.exp(-1j*w_i*t_mesh + 1j*kz_j*z_mesh))\n \nE_f *= dt*dy/(2.0*np.pi)**2\n\n\n",
"shape : (600, 101, 1301)\nNt: 600, Ny: 101, Nz: 1301\n0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 "
],
[
"%pylab inline\nfigsize(8, 8)\n\nE_f_max = np.max(np.abs(E_f))\n\nimshow(np.abs(E_f), origin=\"lower\")",
"Populating the interactive namespace from numpy and matplotlib\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac42dff7a4ed006d5dc278793d98d63e762b3ac
| 12,694 |
ipynb
|
Jupyter Notebook
|
notebooks/PET/image_creation_and_simulation.ipynb
|
DANAJK/SIRF-Exercises
|
033a03e468c1b7f569cdd1b58caa7e4b958a1e98
|
[
"Apache-2.0"
] | null | null | null |
notebooks/PET/image_creation_and_simulation.ipynb
|
DANAJK/SIRF-Exercises
|
033a03e468c1b7f569cdd1b58caa7e4b958a1e98
|
[
"Apache-2.0"
] | null | null | null |
notebooks/PET/image_creation_and_simulation.ipynb
|
DANAJK/SIRF-Exercises
|
033a03e468c1b7f569cdd1b58caa7e4b958a1e98
|
[
"Apache-2.0"
] | null | null | null | 30.441247 | 370 | 0.618796 |
[
[
[
"# Creating images using shapes and simple simulation with attenuation\nThis exercise shows how to create images via geometric shapes. It then uses forward projection without\nand with attenuation.\n\nIt is recommended you complete the [Introductory](../Introductory) notebooks first (or alternatively the [display_and_projection.ipynb](display_and_projection.ipynb)). There is some overlap with [acquisition_model_mr_pet_ct.ipynb](../Introductory/acquisition_model_mr_pet_ct.ipynb), but here we use some geometric shapes to create an image and add attenuation etc.",
"_____no_output_____"
],
[
"Authors: Kris Thielemans and Evgueni Ovtchinnikov \nFirst version: 8th of September 2016 \nSecond Version: 17th of May 2018\n\nCCP SyneRBI Synergistic Image Reconstruction Framework (SIRF). \nCopyright 2015 - 2017 Rutherford Appleton Laboratory STFC. \nCopyright 2015 - 2018 University College London.\n\nThis is software developed for the Collaborative Computational\nProject in Synergistic Reconstruction for Biomedical Imaging\n(http://www.ccpsynerbi.ac.uk/).\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.",
"_____no_output_____"
],
[
"# Initial set-up",
"_____no_output_____"
]
],
[
[
"#%% make sure figures appears inline and animations works\n%matplotlib notebook\n\n# Setup the working directory for the notebook\nimport notebook_setup\nfrom sirf_exercises import cd_to_working_dir\ncd_to_working_dir('PET', 'image_creation_and_simulation')",
"_____no_output_____"
],
[
"import notebook_setup\n\n#%% Initial imports etc\nimport numpy\nfrom numpy.linalg import norm\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport os\nimport sys\nimport shutil",
"_____no_output_____"
],
[
"#%% Use the 'pet' prefix for all SIRF functions\n# This is done here to explicitly differentiate between SIRF pet functions and \n# anything else.\nimport sirf.STIR as pet\nfrom sirf.Utilities import show_2D_array, show_3D_array, examples_data_path\nfrom sirf_exercises import exercises_data_path",
"_____no_output_____"
],
[
"# define the directory with input files\ndata_path = os.path.join(examples_data_path('PET'), 'brain')",
"_____no_output_____"
]
],
[
[
"# Creation of images",
"_____no_output_____"
]
],
[
[
"#%% Read in image\n# We will use an image provided with the demo to have correct voxel-sizes etc\nimage = pet.ImageData(os.path.join(data_path, 'emission.hv'))\nprint(image.dimensions())\nprint(image.voxel_sizes())",
"_____no_output_____"
],
[
"#%% create a shape\nshape = pet.EllipticCylinder()\n# define its size (in mm)\nshape.set_length(50)\nshape.set_radii((40, 30))\n# centre of shape in (x,y,z) coordinates where (0,0,0) is centre of first plane\nshape.set_origin((20, -30, 60))",
"_____no_output_____"
],
[
"#%% add the shape to the image\n# first set the image values to 0\nimage.fill(0)\nimage.add_shape(shape, scale=1)",
"_____no_output_____"
],
[
"#%% add same shape at different location and with different intensity\nshape.set_origin((40, -30, -60))\nimage.add_shape(shape, scale=0.75)",
"_____no_output_____"
],
[
"#%% show the phantom image as a sequence of transverse images\nshow_3D_array(image.as_array());",
"_____no_output_____"
]
],
[
[
"# Simple simulation\nLet's first do simple ray-tracing without attenuation",
"_____no_output_____"
]
],
[
[
"#%% Create a SIRF acquisition model\nacq_model = pet.AcquisitionModelUsingRayTracingMatrix()\n# Specify sinogram dimensions via the template\ntemplate = pet.AcquisitionData(os.path.join(data_path, 'template_sinogram.hs'))\n# Now set-up our acquisition model with all information that it needs about the data and image.\nacq_model.set_up(template,image); ",
"_____no_output_____"
],
[
"#%% forward project this image and display all sinograms\nacquired_data_no_attn = acq_model.forward(image)\nacquired_data_no_attn_array = acquired_data_no_attn.as_array()[0,:,:,:]\nshow_3D_array(acquired_data_no_attn_array);",
"_____no_output_____"
],
[
"#%% Show every 8th view \n# Doing this here with a complicated one-liner...\nshow_3D_array(\n acquired_data_no_attn_array[:,0:acquired_data_no_attn_array.shape[1]:8,:].transpose(1,0,2),\n show=False)\n# You could now of course try the animation of the previous demo...",
"_____no_output_____"
]
],
[
[
"# Adding attenuation\nAttenuation in PET follows the Lambert-Beer law:\n\n$$\\exp\\left\\{-\\int\\mu(x) dx\\right\\},$$\n\nwith $\\mu(x)$ the linear attenuation coefficients (roughly proportional to density), \nand the line integral being performed between the 2 detectors.\n\nIn SIRF, we model this via an `AcquisitionSensitivityModel` object. The rationale for the name is that attenuation reduces the sensitivity of the detector-pair.",
"_____no_output_____"
]
],
[
[
"#%% create an attenuation image\n# we will use the \"emission\" image as a template for sizes (although xy size doesn't have to be identical)\nattn_image = image.get_uniform_copy(0)\n#%% create a shape for a uniform cylinder in the centre\nshape = pet.EllipticCylinder()\nshape.set_length(150)\nshape.set_radii((60, 60))\nshape.set_origin((0, 0, 40))\n# add it to the attenuation image with mu=-.096 cm^-1 (i.e. water)\nattn_image.add_shape(shape, scale=0.096)",
"_____no_output_____"
],
[
"#%% show the phantom image as a sequence of transverse images\nshow_3D_array(attn_image.as_array());",
"_____no_output_____"
],
[
"#%% Create the acquisition sensitivity model\n# First create the ray-tracer\nacq_model_for_attn = pet.AcquisitionModelUsingRayTracingMatrix()\n# Now create the attenuation model\nasm_attn = pet.AcquisitionSensitivityModel(attn_image, acq_model_for_attn)",
"_____no_output_____"
],
[
"attn_image.as_array().max()",
"_____no_output_____"
],
[
"# Use this to find the 'detection efficiencies' as sinograms\nasm_attn.set_up(template)\nattn_factors = asm_attn.forward(template.get_uniform_copy(1))\n# We will store these directly as an `AcquisitionSensitivityModel`, \n# such that we don't have to redo the line integrals\nasm_attn = pet.AcquisitionSensitivityModel(attn_factors)",
"_____no_output_____"
],
[
"#%% check a single sinogram (they are all the same of course)\nshow_2D_array('Attenuation factor sinogram', attn_factors.as_array()[0,5,:,:]);",
"_____no_output_____"
],
[
"#%% check a profile (they are also all the same as the object is a cylinder in the centre)\nplt.figure()\nplt.plot(attn_factors.as_array()[0,5,0,:]);",
"_____no_output_____"
],
[
"#%% Create a SIRF acquisition model\n# start with ray-tracing\nacq_model_with_attn = pet.AcquisitionModelUsingRayTracingMatrix()\n# add the 'sensitivity'\nacq_model_with_attn.set_acquisition_sensitivity(asm_attn)\n# set-up\nacq_model_with_attn.set_up(template,attn_image);",
"_____no_output_____"
],
[
"#%% forward project the original image, now including attenuation modelling, and display all sinograms\nacquired_data_with_attn = acq_model_with_attn.forward(image)\nacquired_data_with_attn_array = acquired_data_with_attn.as_array()[0,:,:,:]\nshow_3D_array(acquired_data_with_attn_array);",
"_____no_output_____"
],
[
"#%% Plot some profiles\nslice = 40\nplt.figure()\nprofile_no_attn = acquired_data_no_attn_array[5,slice,:]\nprofile_with_attn = acquired_data_with_attn_array[5,slice,:]\nprofile_attn_factors = attn_factors.as_array()[0,5,slice,:]\n\nplt.plot(profile_no_attn,label='no atten')\nplt.plot(profile_with_attn,label='with atten')\nplt.plot(profile_no_attn * profile_attn_factors,'bo',label='check')\nplt.legend();",
"_____no_output_____"
]
],
[
[
"# Further things to try\n- Back project the data with and without attenuation\n- Add noise to the data before backprojection (not so easy unfortunately. Adding noise is done in the [ML_reconstruction](ML_reconstruction.ipynb) exercise).\nHint: use `acquired_data.clone()` to create a copy, `numpy.random.poisson`, and `acquired_data.fill()`.\n- Add an additive background to the model. Check if it modifies the forward projection (it should!) and the back-projection? \nHint: read the help for `AcquisitionModel`. Create a simple background by using `AcquisitionData.get_uniform_copy`.",
"_____no_output_____"
]
],
[
[
"help(pet.AcquisitionModel)",
"_____no_output_____"
],
[
"help(pet.AcquisitionData.get_uniform_copy)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4ac44443f1dbfe54a8c1ce97f6b5ae783417d164
| 10,266 |
ipynb
|
Jupyter Notebook
|
Question_2.ipynb
|
shrinidhi-prog/Letsupgrade-python
|
0012d62696b2fa29b94dff6e4485b2a997b61d16
|
[
"Apache-2.0"
] | null | null | null |
Question_2.ipynb
|
shrinidhi-prog/Letsupgrade-python
|
0012d62696b2fa29b94dff6e4485b2a997b61d16
|
[
"Apache-2.0"
] | null | null | null |
Question_2.ipynb
|
shrinidhi-prog/Letsupgrade-python
|
0012d62696b2fa29b94dff6e4485b2a997b61d16
|
[
"Apache-2.0"
] | null | null | null | 28.837079 | 123 | 0.414767 |
[
[
[
"Dictionary and its default functions.",
"_____no_output_____"
]
],
[
[
"# Creating a Dictionary \n# with Integer Keys \nDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} \nprint(\"\\nDictionary with the use of Integer Keys: \") \nprint(Dict) \n\n# Creating a Dictionary \n# with Mixed keys \nDict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} \nprint(\"\\nDictionary with the use of Mixed Keys: \") \nprint(Dict) \n",
"\nDictionary with the use of Integer Keys: \n{1: 'Geeks', 2: 'For', 3: 'Geeks'}\n\nDictionary with the use of Mixed Keys: \n{'Name': 'Geeks', 1: [1, 2, 3, 4]}\n"
],
[
"# Creating an empty Dictionary \nDict = {} \nprint(\"Empty Dictionary: \") \nprint(Dict) \n\n# Adding elements one at a time \nDict[0] = 'Geeks'\nDict[2] = 'For'\nDict[3] = 1\nprint(\"\\nDictionary after adding 3 elements: \") \nprint(Dict) \n\n# Adding set of values \n# to a single Key \nDict['Value_set'] = 2, 3, 4\nprint(\"\\nDictionary after adding 3 elements: \") \nprint(Dict) \n\n# Updating existing Key's Value \nDict[2] = 'Welcome'\nprint(\"\\nUpdated key value: \") \nprint(Dict) \n\n# Adding Nested Key value to Dictionary \nDict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}} \nprint(\"\\nAdding a Nested Key: \") \nprint(Dict) \n",
"Empty Dictionary: \n{}\n\nDictionary after adding 3 elements: \n{0: 'Geeks', 2: 'For', 3: 1}\n\nDictionary after adding 3 elements: \n{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}\n\nUpdated key value: \n{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}\n\nAdding a Nested Key: \n{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Life', '2': 'Geeks'}}}\n"
],
[
"# Python program to demonstrate \n# accessing a element from a Dictionary \n\n# Creating a Dictionary \nDict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} \n\n# accessing a element using key \nprint(\"Accessing a element using key:\") \nprint(Dict['name']) \n\n# accessing a element using key \nprint(\"Accessing a element using key:\") \nprint(Dict[1]) \n",
"Accessing a element using key:\nFor\nAccessing a element using key:\nGeeks\n"
],
[
"# Creating a Dictionary \nDict = {'Dict1': {1: 'Geeks'}, \n\t\t'Dict2': {'Name': 'For'}} \n\n# Accessing element using key \nprint(Dict['Dict1']) \nprint(Dict['Dict1'][1]) \nprint(Dict['Dict2']['Name']) \n",
"{1: 'Geeks'}\nGeeks\nFor\n"
],
[
"# Initial Dictionary \nDict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks', \n\t\t'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'}, \n\t\t'B' : {1 : 'Geeks', 2 : 'Life'}} \nprint(\"Initial Dictionary: \") \nprint(Dict) \n\n# Deleting a Key value \ndel Dict[6] \nprint(\"\\nDeleting a specific key: \") \nprint(Dict) \n\n# Deleting a Key from \n# Nested Dictionary \ndel Dict['A'][2] \nprint(\"\\nDeleting a key from Nested Dictionary: \") \nprint(Dict) \n",
"Initial Dictionary: \n{5: 'Welcome', 6: 'To', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}\n\nDeleting a specific key: \n{5: 'Welcome', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}\n\nDeleting a key from Nested Dictionary: \n{5: 'Welcome', 7: 'Geeks', 'A': {1: 'Geeks', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}\n"
],
[
"\n# Creating a Dictionary \nDict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} \n \n# Deleting a key \n# using pop() method \npop_ele = Dict.pop(1) \nprint('\\nDictionary after deletion: ' + str(Dict)) \nprint('Value associated to poped key is: ' + str(pop_ele))",
"\nDictionary after deletion: {'name': 'For', 3: 'Geeks'}\nValue associated to poped key is: Geeks\n"
],
[
"# Creating Dictionary \nDict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} \n \n# Deleting an arbitrary key \n# using popitem() function \npop_ele = Dict.popitem() \nprint(\"\\nDictionary after deletion: \" + str(Dict)) \nprint(\"The arbitrary pair returned is: \" + str(pop_ele))",
"\nDictionary after deletion: {1: 'Geeks', 'name': 'For'}\nThe arbitrary pair returned is: (3, 'Geeks')\n"
],
[
"# Creating a Dictionary \nDict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} \n\n\n# Deleting entire Dictionary \nDict.clear() \nprint(\"\\nDeleting Entire Dictionary: \") \nprint(Dict) \n",
"\nDeleting Entire Dictionary: \n{}\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac4459199455cf4cac1a6e98b3416a4019ae9f4
| 17,087 |
ipynb
|
Jupyter Notebook
|
2-NMT-Training.ipynb
|
PJ-Finlay/OpenNMT-Tutorial
|
705092aa4f74211efccacd5fcc3aaf49b7f5125c
|
[
"MIT"
] | 12 |
2022-01-21T05:27:14.000Z
|
2022-03-28T20:57:43.000Z
|
2-NMT-Training.ipynb
|
PJ-Finlay/OpenNMT-Tutorial
|
705092aa4f74211efccacd5fcc3aaf49b7f5125c
|
[
"MIT"
] | null | null | null |
2-NMT-Training.ipynb
|
PJ-Finlay/OpenNMT-Tutorial
|
705092aa4f74211efccacd5fcc3aaf49b7f5125c
|
[
"MIT"
] | 1 |
2022-01-22T01:15:41.000Z
|
2022-01-22T01:15:41.000Z
| 34.729675 | 463 | 0.552876 |
[
[
[
"<a href=\"https://colab.research.google.com/github/ymoslem/OpenNMT-Tutorial/blob/main/2-NMT-Training.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"# Install OpenNMT-py 2.x\n!pip3 install OpenNMT-py",
"_____no_output_____"
]
],
[
[
"# Prepare Your Datasets\nPlease make sure you have completed the [first exercise](https://colab.research.google.com/drive/1rsFPnAQu9-_A6e2Aw9JYK3C8mXx9djsF?usp=sharing).",
"_____no_output_____"
]
],
[
[
"# Open the folder where you saved your prepapred datasets from the first exercise\n%cd drive/MyDrive/nmt/\n!ls",
"_____no_output_____"
]
],
[
[
"# Create the Training Configuration File\n\nThe following config file matches most of the recommended values for the Transformer model [Vaswani et al., 2017](https://arxiv.org/abs/1706.03762). As the current dataset is small, we reduced the following values: \n* `train_steps` - for datasets with a few millions of sentences, consider using a value between 100000 and 200000, or more! Enabling the option `early_stopping` can help stop the training when there is no considerable improvement.\n* `valid_steps` - 10000 can be good if the value `train_steps` is big enough. \n* `warmup_steps` - obviously, its value must be less than `train_steps`. Try 4000 and 8000 values.\n\nRefer to [OpenNMT-py training parameters](https://opennmt.net/OpenNMT-py/options/train.html) for more details. If you are interested in further explanation of the Transformer model, you can check this article, [Illustrated Transformer](https://jalammar.github.io/illustrated-transformer/).",
"_____no_output_____"
]
],
[
[
"# Create the YAML configuration file\n# On a regular machine, you can create it manually or with nano\n# Note here we are using some smaller values because the dataset is small\n# For larger datasets, consider increasing: train_steps, valid_steps, warmup_steps, save_checkpoint_steps, keep_checkpoint\n\nconfig = '''# config.yaml\n\n\n## Where the samples will be written\nsave_data: run\n\n# Training files\ndata:\n corpus_1:\n path_src: UN.en-fr.fr-filtered.fr.subword.train\n path_tgt: UN.en-fr.en-filtered.en.subword.train\n transforms: [filtertoolong]\n valid:\n path_src: UN.en-fr.fr-filtered.fr.subword.dev\n path_tgt: UN.en-fr.en-filtered.en.subword.dev\n transforms: [filtertoolong]\n\n# Vocabulary files, generated by onmt_build_vocab\nsrc_vocab: run/source.vocab\ntgt_vocab: run/target.vocab\n\n# Vocabulary size - should be the same as in sentence piece\nsrc_vocab_size: 50000\ntgt_vocab_size: 50000\n\n# Filter out source/target longer than n if [filtertoolong] enabled\n#src_seq_length: 200\n#src_seq_length: 200\n\n# Tokenization options\nsrc_subword_model: source.model\ntgt_subword_model: target.model\n\n# Where to save the log file and the output models/checkpoints\nlog_file: train.log\nsave_model: models/model.fren\n\n# Stop training if it does not imporve after n validations\nearly_stopping: 4\n\n# Default: 5000 - Save a model checkpoint for each n\nsave_checkpoint_steps: 1000\n\n# To save space, limit checkpoints to last n\n# keep_checkpoint: 3\n\nseed: 3435\n\n# Default: 100000 - Train the model to max n steps \n# Increase for large datasets\ntrain_steps: 3000\n\n# Default: 10000 - Run validation after n steps\nvalid_steps: 1000\n\n# Default: 4000 - for large datasets, try up to 8000\nwarmup_steps: 1000\nreport_every: 100\n\ndecoder_type: transformer\nencoder_type: transformer\nword_vec_size: 512\nrnn_size: 512\nlayers: 6\ntransformer_ff: 2048\nheads: 8\n\naccum_count: 4\noptim: adam\nadam_beta1: 0.9\nadam_beta2: 0.998\ndecay_method: noam\nlearning_rate: 2.0\nmax_grad_norm: 0.0\n\n# Tokens per batch, change if out of GPU memory\nbatch_size: 4096\nvalid_batch_size: 4096\nbatch_type: tokens\nnormalization: tokens\ndropout: 0.1\nlabel_smoothing: 0.1\n\nmax_generator_batches: 2\n\nparam_init: 0.0\nparam_init_glorot: 'true'\nposition_encoding: 'true'\n\n# Number of GPUs, and IDs of GPUs\nworld_size: 1\ngpu_ranks: [0]\n\n'''\n\nwith open(\"config.yaml\", \"w+\") as config_yaml:\n config_yaml.write(config)",
"_____no_output_____"
],
[
"# [Optional] Check the content of the configuration file\n!cat config.yaml",
"_____no_output_____"
]
],
[
[
"# Build Vocabulary\n\nFor large datasets, it is not feasable to use all words/tokens found in the corpus. Instead, a specific set of vocabulary is extracted from the training dataset, usually betweeen 32k and 100k words. This is the main purpose of the vocabulary building step.",
"_____no_output_____"
]
],
[
[
"# Find the number of CPUs/cores on the machine\n!nproc --all",
"_____no_output_____"
],
[
"# Build Vocabulary\n\n# -config: path to your config.yaml file\n# -n_sample: use -1 to build vocabulary on all the segment in the training dataset\n# -num_threads: change it to match the number of CPUs to run it faster\n\n!onmt_build_vocab -config config.yaml -n_sample -1 -num_threads 2",
"_____no_output_____"
]
],
[
[
"From the **Runtime menu** > **Change runtime type**, make sure that the \"**Hardware accelerator**\" is \"**GPU**\".\n",
"_____no_output_____"
]
],
[
[
"# Check if the GPU is active\n!nvidia-smi -L",
"_____no_output_____"
],
[
"# Check if the GPU is visable to PyTorch\n\nimport torch\n\nprint(torch.cuda.is_available())\nprint(torch.cuda.get_device_name(0))",
"_____no_output_____"
]
],
[
[
"# Training\n\nNow, start training your NMT model! 🎉 🎉 🎉",
"_____no_output_____"
]
],
[
[
"# Train the NMT model\n!onmt_train -config config.yaml",
"_____no_output_____"
]
],
[
[
"# Translation\n\nTranslation Options:\n* `-model` - specify the last model checkpoint name; try testing the quality of multiple checkpoints\n* `-src` - the subworded test dataset, source file\n* `-output` - give any file name to the new translation output file\n* `-gpu` - GPU ID, usually 0 if you have one GPU. Otherwise, it will translate on CPU, which would be slower.\n* `-min_length` - [optional] to avoid empty translations\n* `-verbose` - [optional] if you want to print translations\n\nRefer to [OpenNMT-py translation options](https://opennmt.net/OpenNMT-py/options/translate.html) for more details.",
"_____no_output_____"
]
],
[
[
"# Translate - change the model name\n!onmt_translate -model models/model.fren_step_3000.pt -src UN.en-fr.fr-filtered.fr.subword.test -output UN.en.translated -gpu 0 -min_length 1",
"_____no_output_____"
],
[
"# Check the first 5 lines of the translation file\n!head -n 5 UN.en.translated",
"_____no_output_____"
],
[
"# Desubword the translation file\n!python3 MT-Preparation/subwording/3-desubword.py target.model UN.en.translated",
"_____no_output_____"
],
[
"# Check the first 5 lines of the desubworded translation file\n!head -n 5 UN.en.translated.desubword",
"_____no_output_____"
],
[
"# Desubword the source test\n# Note: You might as well have split files *before* subwording during dataset preperation, \n# but sometimes datasets have tokeniztion issues, so this way you are sure the file is really untokenized.\n!python3 MT-Preparation/subwording/3-desubword.py target.model UN.en-fr.en-filtered.en.subword.test",
"_____no_output_____"
],
[
"# Check the first 5 lines of the desubworded source\n!head -n 5 UN.en-fr.en-filtered.en.subword.test.desubword",
"_____no_output_____"
]
],
[
[
"# MT Evaluation\n\nThere are several MT Evaluation metrics such as BLEU, TER, METEOR, COMET, BERTScore, among others.\n\nHere we are using BLEU. Files must be detokenized/desubworded beforehand.",
"_____no_output_____"
]
],
[
[
"# Download the BLEU script\n!wget https://raw.githubusercontent.com/ymoslem/MT-Evaluation/main/BLEU/compute-bleu.py",
"_____no_output_____"
],
[
"# Install sacrebleu\n!pip3 install sacrebleu",
"_____no_output_____"
],
[
"# Evaluate the translation (without subwording)\n!python3 compute-bleu.py UN.en-fr.en-filtered.en.subword.test.desubword UN.en.translated.desubword",
"_____no_output_____"
]
],
[
[
"# More Features and Directions to Explore\n\nExperiment with the following ideas:\n* Icrease `train_steps` and see to what extent new checkpoints provide better translation, in terms of both BLEU and your human evaluation.\n\n* Check other MT Evaluation mentrics other than BLEU such as [TER](https://github.com/mjpost/sacrebleu#ter), [WER](https://blog.machinetranslation.io/compute-wer-score/), [METEOR](https://blog.machinetranslation.io/compute-bleu-score/#meteor), [COMET](https://github.com/Unbabel/COMET), and [BERTScore](https://github.com/Tiiiger/bert_score). What are the conceptual differences between them? Is there there special cases for using a specific metric?\n\n* Continue training from the last model checkpoint using the `-train_from` option, only if the training stopped and you want to continue it. In this case, `train_steps` in the config file should be larger than the steps of the last checkpoint you train from.\n```\n!onmt_train -config config.yaml -train_from models/model.fren_step_3000.pt\n```\n\n* **Ensemble Decoding:** During translation, instead of adding one model/checkpoint to the `-model` argument, add multiple checkpoints. For example, try the two last checkpoints. Does it improve quality of translation? Does it affect translation seepd?\n\n* **Averaging Models:** Try to average multiple models into one model using the [average_models.py](https://github.com/OpenNMT/OpenNMT-py/blob/master/onmt/bin/average_models.py) script, and see how this affects translation quality.\n```\npython3 average_models.py -models model_step_xxx.pt model_step_yyy.pt -output model_avg.pt\n```\n* **Release the model:** Try this command and see how it reduce the model size.\n```\nonmt_release_model --model \"model.pt\" --output \"model_released.pt\n```\n* **Use CTranslate2:** For efficient translation, consider using [CTranslate2](https://github.com/OpenNMT/CTranslate2), a fast inference engine. Check out an [example](https://gist.github.com/ymoslem/60e1d1dc44fe006f67e130b6ad703c4b).\n\n* **Work on low-resource languages:** Find out more details about [how to train NMT models for low-resource languages](https://blog.machinetranslation.io/low-resource-nmt/).\n\n* **Train a multilingual model:** Find out helpful notes about [training multilingual models](https://blog.machinetranslation.io/multilingual-nmt).\n\n* **Publish a demo:** Show off your work through a [simple demo with CTranslate2 and Streamlit](https://blog.machinetranslation.io/nmt-web-interface/).\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",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
4ac44d49109bff6927908d3f1ae4fb1387b29bfd
| 260,956 |
ipynb
|
Jupyter Notebook
|
example/wls2.ipynb
|
nufeng1999/jupyter-MyWLS-kernel
|
e2b23642fe984e209890704ae8eebf45e896fc2b
|
[
"MIT"
] | null | null | null |
example/wls2.ipynb
|
nufeng1999/jupyter-MyWLS-kernel
|
e2b23642fe984e209890704ae8eebf45e896fc2b
|
[
"MIT"
] | null | null | null |
example/wls2.ipynb
|
nufeng1999/jupyter-MyWLS-kernel
|
e2b23642fe984e209890704ae8eebf45e896fc2b
|
[
"MIT"
] | null | null | null | 2,211.491525 | 254,355 | 0.96358 |
[
[
[
"Graphics3D[Sphere[ ]]",
"_____no_output_____"
],
[
"//%overwritefile\n//%file:src/test2.sh\n//%runprgargs:-print -format png -f\n//%outputtype:image/png\nListLinePlot[RandomFunction[WienerProcess[],{0,10,0.01},10]]",
"_____no_output_____"
],
[
"PacletInstall[\"WolframLanguageForJupyter-0.9.2.paclet\"]",
"_____no_output_____"
],
[
"DynamicModule[{x}, {Slider[Dynamic[1.5]], Dynamic[3]}]",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
4ac48088907e991612acfb1632cdba5ab8a0d162
| 21,029 |
ipynb
|
Jupyter Notebook
|
sagemaker-python-sdk/chainer_cifar10/chainermn_distributed_cifar10.ipynb
|
can-sun/amazon-sagemaker-examples
|
6908559125336128ef4533d657053828e85a68c6
|
[
"Apache-2.0"
] | null | null | null |
sagemaker-python-sdk/chainer_cifar10/chainermn_distributed_cifar10.ipynb
|
can-sun/amazon-sagemaker-examples
|
6908559125336128ef4533d657053828e85a68c6
|
[
"Apache-2.0"
] | null | null | null |
sagemaker-python-sdk/chainer_cifar10/chainermn_distributed_cifar10.ipynb
|
can-sun/amazon-sagemaker-examples
|
6908559125336128ef4533d657053828e85a68c6
|
[
"Apache-2.0"
] | null | null | null | 44.458774 | 563 | 0.649769 |
[
[
[
"## Distributed Training with Chainer and ChainerMN\n\nChainer can train in two modes: single-machine, and distributed. Unlike the single-machine notebook example that trains an image classification model on the CIFAR-10 dataset, we will write a Chainer script that uses `chainermn` to distribute training to multiple instances.\n\n[VGG](https://arxiv.org/pdf/1409.1556v6.pdf) is an architecture for deep convolution networks. In this example, we train a convolutional network to perform image classification using the CIFAR-10 dataset on multiple instances. CIFAR-10 consists of 60000 32x32 colour images in 10 classes, with 6000 images per class. There are 50000 training images and 10000 test images. We'll train a model on SageMaker, deploy it to Amazon SageMaker, and then classify images using the deployed model.\n\nThe Chainer script runs inside of a Docker container running on SageMaker. For more information about the Chainer container, see the sagemaker-chainer-containers repository and the sagemaker-python-sdk repository:\n\n* https://github.com/aws/sagemaker-chainer-containers\n* https://github.com/aws/sagemaker-python-sdk\n\nFor more on Chainer and ChainerMN, please visit the Chainer and ChainerMN repositories:\n\n* https://github.com/chainer/chainer\n* https://github.com/chainer/chainermn\n\nThis notebook is adapted from the [CIFAR-10](https://github.com/chainer/chainer/tree/master/examples/cifar) example in the Chainer repository.",
"_____no_output_____"
]
],
[
[
"# Setup\nfrom sagemaker import get_execution_role\nimport sagemaker\n\nsagemaker_session = sagemaker.Session()\n\n# This role retrieves the SageMaker-compatible role used by this Notebook Instance.\nrole = get_execution_role()",
"_____no_output_____"
]
],
[
[
"## Downloading training and test data\n\nWe use helper functions provided by `chainer` to download and preprocess the CIFAR10 data. ",
"_____no_output_____"
]
],
[
[
"import chainer\n\nfrom chainer.datasets import get_cifar10\n\ntrain, test = get_cifar10()",
"_____no_output_____"
]
],
[
[
"## Uploading the data\n\nWe save the preprocessed data to the local filesystem, and then use the `sagemaker.Session.upload_data` function to upload our datasets to an S3 location. The return value `inputs` identifies the S3 location, which we will use when we start the Training Job.",
"_____no_output_____"
]
],
[
[
"import os\nimport shutil\n\nimport numpy as np\n\ntrain_data = [element[0] for element in train]\ntrain_labels = [element[1] for element in train]\n\ntest_data = [element[0] for element in test]\ntest_labels = [element[1] for element in test]\n\n\ntry:\n os.makedirs(\"/tmp/data/distributed_train_cifar\")\n os.makedirs(\"/tmp/data/distributed_test_cifar\")\n np.savez(\"/tmp/data/distributed_train_cifar/train.npz\", data=train_data, labels=train_labels)\n np.savez(\"/tmp/data/distributed_test_cifar/test.npz\", data=test_data, labels=test_labels)\n train_input = sagemaker_session.upload_data(\n path=os.path.join(\"/tmp\", \"data\", \"distributed_train_cifar\"),\n key_prefix=\"notebook/distributed_chainer_cifar/train\",\n )\n test_input = sagemaker_session.upload_data(\n path=os.path.join(\"/tmp\", \"data\", \"distributed_test_cifar\"),\n key_prefix=\"notebook/distributed_chainer_cifar/test\",\n )\nfinally:\n shutil.rmtree(\"/tmp/data\")\nprint(\"training data at \", train_input)\nprint(\"test data at \", test_input)",
"_____no_output_____"
]
],
[
[
"## Writing the Chainer script to run on Amazon SageMaker\n\n### Training\n\nWe need to provide a training script that can run on the SageMaker platform. The training script is very similar to a training script you might run outside of SageMaker, but you can access useful properties about the training environment through various environment variables, such as:\n\n* `SM_MODEL_DIR`: A string representing the path to the directory to write model artifacts to.\n These artifacts are uploaded to S3 for model hosting.\n* `SM_NUM_GPUS`: An integer representing the number of GPUs available to the host.\n* `SM_OUTPUT_DIR`: A string representing the filesystem path to write output artifacts to. Output artifacts may\n include checkpoints, graphs, and other files to save, not including model artifacts. These artifacts are compressed\n and uploaded to S3 to the same S3 prefix as the model artifacts.\n\nSupposing two input channels, 'train' and 'test', were used in the call to the Chainer estimator's ``fit()`` method,\nthe following will be set, following the format `SM_CHANNEL_[channel_name]`:\n\n* `SM_CHANNEL_TRAIN`: A string representing the path to the directory containing data in the 'train' channel\n* `SM_CHANNEL_TEST`: Same as above, but for the 'test' channel.\n\nA typical training script loads data from the input channels, configures training with hyperparameters, trains a model, and saves a model to `model_dir` so that it can be hosted later. Hyperparameters are passed to your script as arguments and can be retrieved with an `argparse.ArgumentParser` instance. For example, the script run by this notebook starts with the following:\n\n```python\nimport argparse\nimport os\n\nif __name__ =='__main__':\n training_env = sagemaker_containers.training_env()\n \n num_gpus = int(os.environ['SM_NUM_GPUS'])\n \n parser = argparse.ArgumentParser()\n\n # retrieve the hyperparameters we set from the client in the notebook (with some defaults)\n parser.add_argument('--epochs', type=int, default=30)\n parser.add_argument('--batch-size', type=int, default=256)\n parser.add_argument('--learning-rate', type=float, default=0.05)\n parser.add_argument('--communicator', type=str, default='pure_nccl' if num_gpus > 0 else 'naive')\n\n # Data, model, and output directories. These are required.\n parser.add_argument('--output-data-dir', type=str, default=os.environ['SM_OUTPUT_DATA_DIR'])\n parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])\n parser.add_argument('--train', type=str, default=os.environ['SM_CHANNEL_TRAIN'])\n parser.add_argument('--test', type=str, default=os.environ['SM_OUTPUT_DATA_DIR'])\n \n args, _ = parser.parse_known_args()\n \n # ... load from args.train and args.test, train a model, write model to args.model_dir.\n```\n\nBecause the Chainer container imports your training script, you should always put your training code in a main guard (`if __name__=='__main__':`) so that the container does not inadvertently run your training code at the wrong point in execution.\n\nFor more information about training environment variables, please visit https://github.com/aws/sagemaker-containers.\n\n### Hosting and Inference\n\nWe use a single script to train and host the Chainer model. You can also write separate scripts for training and hosting. In contrast with the training script, the hosting script requires you to implement functions with particular function signatures (or rely on defaults for those functions).\n\nThese functions load your model, deserialize data sent by a client, obtain inferences from your hosted model, and serialize predictions back to a client:\n\n* **`model_fn(model_dir)` (always required for hosting)**: This function is invoked to load model artifacts from those that were written into `model_dir` during training.\n\nThe script that this notebook runs uses the following `model_fn` function for hosting:\n```python\ndef model_fn(model_dir):\n chainer.config.train = False\n model = L.Classifier(net.VGG(10))\n serializers.load_npz(os.path.join(model_dir, 'model.npz'), model)\n return model.predictor\n```\n\n* `input_fn(input_data, content_type)`: This function is invoked to deserialize prediction data when a prediction request is made. The return value is passed to predict_fn. `input_data` is the serialized input data in the body of the prediction request, and `content_type`, the MIME type of the data.\n \n \n* `predict_fn(input_data, model)`: This function accepts the return value of `input_fn` as the `input_data` parameter and the return value of `model_fn` as the `model` parameter and returns inferences obtained from the model.\n \n \n* `output_fn(prediction, accept)`: This function is invoked to serialize the return value from `predict_fn`, which is passed in as the `prediction` parameter, back to the SageMaker client in response to prediction requests.\n\n\n`model_fn` is always required, but default implementations exist for the remaining functions. These default implementations can deserialize a NumPy array, invoking the model's `__call__` method on the input data, and serialize a NumPy array back to the client.\n\nThis notebook relies on the default `input_fn`, `predict_fn`, and `output_fn` implementations. See the Chainer sentiment analysis notebook for an example of how one can implement these hosting functions.\n\nPlease examine the script below, reproduced in its entirety. Training occurs behind the main guard, which prevents the function from being run when the script is imported, and `model_fn` loads the model saved into `model_dir` during training.\n\nThe script uses a chainermn Communicator to distribute training to multiple nodes. The Communicator depends on MPI (Message Passing Interface), so the Chainer container running on SageMaker runs this script with mpirun if the Chainer Estimator specifies a train_instance_count of two or greater, or if use_mpi in the Chainer estimator is true.\n\nBy default, one process is created per GPU (on GPU instances), or one per host (on CPU instances, which are not recommended for this notebook).\n\nFor more on writing Chainer scripts to run on SageMaker, or for more on the Chainer container itself, please see the following repositories: \n\n* For writing Chainer scripts to run on SageMaker: https://github.com/aws/sagemaker-python-sdk\n* For more on the Chainer container and default hosting functions: https://github.com/aws/sagemaker-chainer-containers\n",
"_____no_output_____"
]
],
[
[
"!pygmentize 'src/chainer_cifar_vgg_distributed.py'",
"_____no_output_____"
]
],
[
[
"## Running the training script on SageMaker\n\nTo train a model with a Chainer script, we construct a ```Chainer``` estimator using the [sagemaker-python-sdk](https://github.com/aws/sagemaker-python-sdk). We pass in an `entry_point`, the name of a script that contains a couple of functions with certain signatures (`train` and `model_fn`), and a `source_dir`, a directory containing all code to run inside the Chainer container. This script will be run on SageMaker in a container that invokes these functions to train and load Chainer models. \n\nThe ```Chainer``` class allows us to run our training function as a training job on SageMaker infrastructure. We need to configure it with our training script, an IAM role, the number of training instances, and the training instance type. In this case we will run our training job on two `ml.p2.xlarge` instances, but you may need to request a service limit increase on the number of training instances in order to train.\n\nThis script uses the `chainermn` package, which distributes training with MPI. Your script is run with `mpirun`, so a ChainerMN Communicator object can be used to distribute training. Arguments to `mpirun` are set to sensible defaults, but you can configure how your script is run in distributed mode. See the ```Chainer``` class documentation for more on configuring MPI.",
"_____no_output_____"
]
],
[
[
"from sagemaker.chainer.estimator import Chainer\n\nchainer_estimator = Chainer(\n entry_point=\"chainer_cifar_vgg_distributed.py\",\n source_dir=\"src\",\n role=role,\n sagemaker_session=sagemaker_session,\n use_mpi=True,\n train_instance_count=2,\n train_instance_type=\"ml.p3.2xlarge\",\n hyperparameters={\"epochs\": 30, \"batch-size\": 256},\n)\n\nchainer_estimator.fit({\"train\": train_input, \"test\": test_input})",
"_____no_output_____"
]
],
[
[
"Our Chainer script writes various artifacts, such as plots, to a directory `output_data_dir`, the contents of which which SageMaker uploads to S3. Now we download and extract these artifacts.",
"_____no_output_____"
]
],
[
[
"from s3_util import retrieve_output_from_s3\n\nchainer_training_job = chainer_estimator.latest_training_job.name\n\ndesc = sagemaker_session.sagemaker_client.describe_training_job(\n TrainingJobName=chainer_training_job\n)\noutput_data = desc[\"ModelArtifacts\"][\"S3ModelArtifacts\"].replace(\"model.tar.gz\", \"output.tar.gz\")\n\nretrieve_output_from_s3(output_data, \"output/distributed_cifar\")",
"_____no_output_____"
]
],
[
[
"These plots show the accuracy and loss over epochs:",
"_____no_output_____"
]
],
[
[
"from IPython.display import Image\nfrom IPython.display import display\n\naccuracy_graph = Image(filename=\"output/distributed_cifar/accuracy.png\", width=800, height=800)\nloss_graph = Image(filename=\"output/distributed_cifar/loss.png\", width=800, height=800)\n\ndisplay(accuracy_graph, loss_graph)",
"_____no_output_____"
]
],
[
[
"## Deploying the Trained Model\n\nAfter training, we use the Chainer estimator object to create and deploy a hosted prediction endpoint. We can use a CPU-based instance for inference (in this case an `ml.m4.xlarge`), even though we trained on GPU instances.\n\nThe predictor object returned by `deploy` lets us call the new endpoint and perform inference on our sample images. ",
"_____no_output_____"
]
],
[
[
"predictor = chainer_estimator.deploy(initial_instance_count=1, instance_type=\"ml.m4.xlarge\")",
"_____no_output_____"
]
],
[
[
"### CIFAR10 sample images\n\nWe'll use these CIFAR10 sample images to test the service:\n\n<img style=\"display: inline; height: 32px; margin: 0.25em\" src=\"images/airplane1.png\" />\n<img style=\"display: inline; height: 32px; margin: 0.25em\" src=\"images/automobile1.png\" />\n<img style=\"display: inline; height: 32px; margin: 0.25em\" src=\"images/bird1.png\" />\n<img style=\"display: inline; height: 32px; margin: 0.25em\" src=\"images/cat1.png\" />\n<img style=\"display: inline; height: 32px; margin: 0.25em\" src=\"images/deer1.png\" />\n<img style=\"display: inline; height: 32px; margin: 0.25em\" src=\"images/dog1.png\" />\n<img style=\"display: inline; height: 32px; margin: 0.25em\" src=\"images/frog1.png\" />\n<img style=\"display: inline; height: 32px; margin: 0.25em\" src=\"images/horse1.png\" />\n<img style=\"display: inline; height: 32px; margin: 0.25em\" src=\"images/ship1.png\" />\n<img style=\"display: inline; height: 32px; margin: 0.25em\" src=\"images/truck1.png\" />\n\n",
"_____no_output_____"
],
[
"## Predicting using SageMaker Endpoint\n\nWe batch the images together into a single NumPy array to obtain multiple inferences with a single prediction request.",
"_____no_output_____"
]
],
[
[
"from skimage import io\nimport numpy as np\n\n\ndef read_image(filename):\n img = io.imread(filename)\n img = np.array(img).transpose(2, 0, 1)\n img = np.expand_dims(img, axis=0)\n img = img.astype(np.float32)\n img *= 1.0 / 255.0\n img = img.reshape(3, 32, 32)\n return img\n\n\ndef read_images(filenames):\n return np.array([read_image(f) for f in filenames])\n\n\nfilenames = [\n \"images/airplane1.png\",\n \"images/automobile1.png\",\n \"images/bird1.png\",\n \"images/cat1.png\",\n \"images/deer1.png\",\n \"images/dog1.png\",\n \"images/frog1.png\",\n \"images/horse1.png\",\n \"images/ship1.png\",\n \"images/truck1.png\",\n]\n\nimage_data = read_images(filenames)",
"_____no_output_____"
]
],
[
[
"The predictor runs inference on our input data and returns a list of predictions whose argmax gives the predicted label of the input data. ",
"_____no_output_____"
]
],
[
[
"response = predictor.predict(image_data)\n\nfor i, prediction in enumerate(response):\n print(\"image {}: prediction: {}\".format(i, prediction.argmax(axis=0)))",
"_____no_output_____"
]
],
[
[
"## Cleanup\n\nAfter you have finished with this example, remember to delete the prediction endpoint to release the instance(s) associated with it.",
"_____no_output_____"
]
],
[
[
"chainer_estimator.delete_endpoint()",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac4858d4cc2c394d78e9b595d76c500666b2733
| 23,687 |
ipynb
|
Jupyter Notebook
|
04-Support Vector Machines with Python.ipynb
|
AhmetTuranBalkan/ML-Algorithms
|
aa72ce43e88689ef1425f09bc9c2519a03170165
|
[
"MIT"
] | 1 |
2018-12-13T08:11:52.000Z
|
2018-12-13T08:11:52.000Z
|
04-Support Vector Machines with Python.ipynb
|
AhmetTuranBalkan/ML-Algorithms
|
aa72ce43e88689ef1425f09bc9c2519a03170165
|
[
"MIT"
] | null | null | null |
04-Support Vector Machines with Python.ipynb
|
AhmetTuranBalkan/ML-Algorithms
|
aa72ce43e88689ef1425f09bc9c2519a03170165
|
[
"MIT"
] | 3 |
2020-04-22T11:50:06.000Z
|
2021-05-19T12:20:14.000Z
| 38.767594 | 120 | 0.431038 |
[
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline",
"_____no_output_____"
],
[
"#The dataset is taken from Kaggle. The specific URL is https://www.kaggle.com/uciml/iris\n# Read dataset to pandas dataframe\niris_dataset = pd.read_csv('iris.csv') \n",
"_____no_output_____"
],
[
"iris_dataset.head(5)",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"y = iris_dataset['Species'] \nX = iris_dataset.drop('Species', axis=1) ",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state=101) ",
"_____no_output_____"
],
[
"from sklearn.svm import SVC",
"_____no_output_____"
],
[
"model = SVC()",
"_____no_output_____"
],
[
"model.fit(X_train,y_train)",
"_____no_output_____"
],
[
"predictions = model.predict(X_test)",
"_____no_output_____"
],
[
"from sklearn.metrics import classification_report,confusion_matrix",
"_____no_output_____"
],
[
"print(confusion_matrix(y_test,predictions))",
"[[15 0 0]\n [ 0 22 0]\n [ 0 0 13]]\n"
],
[
"print(classification_report(y_test,predictions))",
" precision recall f1-score support\n\n Iris-setosa 1.00 1.00 1.00 15\nIris-versicolor 1.00 1.00 1.00 22\n Iris-virginica 1.00 1.00 1.00 13\n\n avg / total 1.00 1.00 1.00 50\n\n"
],
[
"param_grid = {'C': [0.1,1, 10, 100, 1000], 'gamma': [1,0.1,0.01,0.001,0.0001], 'kernel': ['rbf']} ",
"_____no_output_____"
],
[
"from sklearn.model_selection import GridSearchCV",
"_____no_output_____"
],
[
"grid = GridSearchCV(SVC(),param_grid,refit=True,verbose=3)",
"_____no_output_____"
],
[
"# May take awhile!\ngrid.fit(X_train,y_train)",
"Fitting 3 folds for each of 25 candidates, totalling 75 fits\n[CV] C=0.1, gamma=1, kernel=rbf ......................................\n[CV] C=0.1, gamma=1, kernel=rbf, score=0.37142857142857144, total= 0.0s\n[CV] C=0.1, gamma=1, kernel=rbf ......................................\n[CV] C=0.1, gamma=1, kernel=rbf, score=0.36363636363636365, total= 0.0s\n[CV] C=0.1, gamma=1, kernel=rbf ......................................\n[CV] .......... C=0.1, gamma=1, kernel=rbf, score=0.375, total= 0.0s\n[CV] C=0.1, gamma=0.1, kernel=rbf ....................................\n[CV] C=0.1, gamma=0.1, kernel=rbf, score=0.37142857142857144, total= 0.0s\n[CV] C=0.1, gamma=0.1, kernel=rbf ....................................\n[CV] C=0.1, gamma=0.1, kernel=rbf, score=0.36363636363636365, total= 0.0s\n[CV] C=0.1, gamma=0.1, kernel=rbf ....................................\n[CV] ........ C=0.1, gamma=0.1, kernel=rbf, score=0.375, total= 0.0s\n[CV] C=0.1, gamma=0.01, kernel=rbf ...................................\n[CV] C=0.1, gamma=0.01, kernel=rbf, score=0.8857142857142857, total= 0.0s\n[CV] C=0.1, gamma=0.01, kernel=rbf ...................................\n[CV] C=0.1, gamma=0.01, kernel=rbf, score=0.9393939393939394, total= 0.0s\n[CV] C=0.1, gamma=0.01, kernel=rbf ...................................\n[CV] ..... C=0.1, gamma=0.01, kernel=rbf, score=0.96875, total= 0.0s\n[CV] C=0.1, gamma=0.001, kernel=rbf ..................................\n[CV] ........ C=0.1, gamma=0.001, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=0.1, gamma=0.001, kernel=rbf ..................................\n[CV] C=0.1, gamma=0.001, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=0.1, gamma=0.001, kernel=rbf ..................................\n[CV] ..... C=0.1, gamma=0.001, kernel=rbf, score=0.9375, total= 0.0s\n[CV] C=0.1, gamma=0.0001, kernel=rbf .................................\n[CV] C=0.1, gamma=0.0001, kernel=rbf, score=0.7142857142857143, total= 0.0s\n[CV] C=0.1, gamma=0.0001, kernel=rbf .................................\n[CV] C=0.1, gamma=0.0001, kernel=rbf, score=0.7272727272727273, total= 0.0s\n[CV] C=0.1, gamma=0.0001, kernel=rbf .................................\n[CV] ... C=0.1, gamma=0.0001, kernel=rbf, score=0.71875, total= 0.0s\n[CV] C=1, gamma=1, kernel=rbf ........................................\n[CV] C=1, gamma=1, kernel=rbf, score=0.6285714285714286, total= 0.0s\n[CV] C=1, gamma=1, kernel=rbf ........................................\n[CV] C=1, gamma=1, kernel=rbf, score=0.696969696969697, total= 0.0s\n[CV] C=1, gamma=1, kernel=rbf ........................................\n[CV] ........... C=1, gamma=1, kernel=rbf, score=0.6875, total= 0.0s\n[CV] C=1, gamma=0.1, kernel=rbf ......................................\n[CV] C=1, gamma=0.1, kernel=rbf, score=0.9714285714285714, total= 0.0s\n[CV] C=1, gamma=0.1, kernel=rbf ......................................\n[CV] C=1, gamma=0.1, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=1, gamma=0.1, kernel=rbf ......................................\n[CV] ............ C=1, gamma=0.1, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=1, gamma=0.01, kernel=rbf .....................................\n[CV] ........... C=1, gamma=0.01, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=1, gamma=0.01, kernel=rbf .....................................\n[CV] C=1, gamma=0.01, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=1, gamma=0.01, kernel=rbf .....................................\n[CV] ........... C=1, gamma=0.01, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=1, gamma=0.001, kernel=rbf ....................................\n[CV] .......... C=1, gamma=0.001, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=1, gamma=0.001, kernel=rbf ....................................\n[CV] C=1, gamma=0.001, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=1, gamma=0.001, kernel=rbf ....................................\n[CV] ...... C=1, gamma=0.001, kernel=rbf, score=0.96875, total= 0.0s\n[CV] C=1, gamma=0.0001, kernel=rbf ...................................\n[CV] ......... C=1, gamma=0.0001, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=1, gamma=0.0001, kernel=rbf ...................................\n[CV] C=1, gamma=0.0001, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=1, gamma=0.0001, kernel=rbf ...................................\n[CV] ......... C=1, gamma=0.0001, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=10, gamma=1, kernel=rbf .......................................\n[CV] C=10, gamma=1, kernel=rbf, score=0.6571428571428571, total= 0.0s\n[CV] C=10, gamma=1, kernel=rbf .......................................\n[CV] C=10, gamma=1, kernel=rbf, score=0.7878787878787878, total= 0.0s\n[CV] C=10, gamma=1, kernel=rbf .......................................\n[CV] ............ C=10, gamma=1, kernel=rbf, score=0.75, total= 0.0s\n[CV] C=10, gamma=0.1, kernel=rbf .....................................\n[CV] C=10, gamma=0.1, kernel=rbf, score=0.9714285714285714, total= 0.0s\n[CV] C=10, gamma=0.1, kernel=rbf .....................................\n[CV] C=10, gamma=0.1, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=10, gamma=0.1, kernel=rbf .....................................\n[CV] ........... C=10, gamma=0.1, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=10, gamma=0.01, kernel=rbf ....................................\n[CV] C=10, gamma=0.01, kernel=rbf, score=0.9714285714285714, total= 0.0s\n[CV] C=10, gamma=0.01, kernel=rbf ....................................\n[CV] C=10, gamma=0.01, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=10, gamma=0.01, kernel=rbf ....................................\n[CV] .......... C=10, gamma=0.01, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=10, gamma=0.001, kernel=rbf ...................................\n[CV] ......... C=10, gamma=0.001, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=10, gamma=0.001, kernel=rbf ...................................\n[CV] C=10, gamma=0.001, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=10, gamma=0.001, kernel=rbf ...................................\n[CV] ......... C=10, gamma=0.001, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=10, gamma=0.0001, kernel=rbf ..................................\n[CV] ........ C=10, gamma=0.0001, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=10, gamma=0.0001, kernel=rbf ..................................\n[CV] C=10, gamma=0.0001, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=10, gamma=0.0001, kernel=rbf ..................................\n[CV] .... C=10, gamma=0.0001, kernel=rbf, score=0.96875, total= 0.0s\n[CV] C=100, gamma=1, kernel=rbf ......................................\n[CV] C=100, gamma=1, kernel=rbf, score=0.6571428571428571, total= 0.0s\n[CV] C=100, gamma=1, kernel=rbf ......................................\n[CV] C=100, gamma=1, kernel=rbf, score=0.7878787878787878, total= 0.0s\n[CV] C=100, gamma=1, kernel=rbf ......................................\n[CV] ........... C=100, gamma=1, kernel=rbf, score=0.75, total= 0.0s\n[CV] C=100, gamma=0.1, kernel=rbf ....................................\n[CV] C=100, gamma=0.1, kernel=rbf, score=0.9714285714285714, total= 0.0s\n[CV] C=100, gamma=0.1, kernel=rbf ....................................\n[CV] C=100, gamma=0.1, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=100, gamma=0.1, kernel=rbf ....................................\n[CV] .......... C=100, gamma=0.1, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=100, gamma=0.01, kernel=rbf ...................................\n[CV] C=100, gamma=0.01, kernel=rbf, score=0.9714285714285714, total= 0.0s\n[CV] C=100, gamma=0.01, kernel=rbf ...................................\n[CV] C=100, gamma=0.01, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=100, gamma=0.01, kernel=rbf ...................................\n[CV] ......... C=100, gamma=0.01, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=100, gamma=0.001, kernel=rbf ..................................\n[CV] C=100, gamma=0.001, kernel=rbf, score=0.9714285714285714, total= 0.0s\n[CV] C=100, gamma=0.001, kernel=rbf ..................................\n[CV] C=100, gamma=0.001, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=100, gamma=0.001, kernel=rbf ..................................\n[CV] ........ C=100, gamma=0.001, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=100, gamma=0.0001, kernel=rbf .................................\n[CV] ....... C=100, gamma=0.0001, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=100, gamma=0.0001, kernel=rbf .................................\n[CV] C=100, gamma=0.0001, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=100, gamma=0.0001, kernel=rbf .................................\n[CV] ....... C=100, gamma=0.0001, kernel=rbf, score=1.0, total= 0.0s\n[CV] C=1000, gamma=1, kernel=rbf .....................................\n[CV] C=1000, gamma=1, kernel=rbf, score=0.6571428571428571, total= 0.0s\n[CV] C=1000, gamma=1, kernel=rbf .....................................\n[CV] C=1000, gamma=1, kernel=rbf, score=0.7878787878787878, total= 0.0s\n[CV] C=1000, gamma=1, kernel=rbf .....................................\n[CV] .......... C=1000, gamma=1, kernel=rbf, score=0.75, total= 0.0s\n[CV] C=1000, gamma=0.1, kernel=rbf ...................................\n[CV] C=1000, gamma=0.1, kernel=rbf, score=0.9714285714285714, total= 0.0s\n[CV] C=1000, gamma=0.1, kernel=rbf ...................................\n[CV] C=1000, gamma=0.1, kernel=rbf, score=0.9696969696969697, total= 0.0s\n[CV] C=1000, gamma=0.1, kernel=rbf ...................................\n"
],
[
"grid.best_params_",
"_____no_output_____"
],
[
"grid.best_estimator_",
"_____no_output_____"
],
[
"grid_predictions = grid.predict(X_test)",
"_____no_output_____"
],
[
"print(confusion_matrix(y_test,grid_predictions))",
"[[15 0 0]\n [ 0 22 0]\n [ 0 0 13]]\n"
],
[
"print(classification_report(y_test,grid_predictions))",
" precision recall f1-score support\n\n Iris-setosa 1.00 1.00 1.00 15\nIris-versicolor 1.00 1.00 1.00 22\n Iris-virginica 1.00 1.00 1.00 13\n\n avg / total 1.00 1.00 1.00 50\n\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac485bb5d59eb926d800c1a80dc36e98c75457f
| 9,474 |
ipynb
|
Jupyter Notebook
|
code/backup/0_Pyspark_Transform_Action.ipynb
|
kaopanboonyuen/GISTDA2022
|
c8ce181179c293d899817d04cc52f02934596a84
|
[
"Apache-2.0"
] | null | null | null |
code/backup/0_Pyspark_Transform_Action.ipynb
|
kaopanboonyuen/GISTDA2022
|
c8ce181179c293d899817d04cc52f02934596a84
|
[
"Apache-2.0"
] | null | null | null |
code/backup/0_Pyspark_Transform_Action.ipynb
|
kaopanboonyuen/GISTDA2022
|
c8ce181179c293d899817d04cc52f02934596a84
|
[
"Apache-2.0"
] | null | null | null | 26.027473 | 283 | 0.424319 |
[
[
[
"# Spark Preparation\nWe check if we are in Google Colab. If this is the case, install all necessary packages.\n\nTo run spark in Colab, we need to first install all the dependencies in Colab environment i.e. Apache Spark 3.2.1 with hadoop 3.2, Java 8 and Findspark to locate the spark in the system. The tools installation can be carried out inside the Jupyter Notebook of the Colab.\nLearn more from [A Must-Read Guide on How to Work with PySpark on Google Colab for Data Scientists!](https://www.analyticsvidhya.com/blog/2020/11/a-must-read-guide-on-how-to-work-with-pyspark-on-google-colab-for-data-scientists/)",
"_____no_output_____"
]
],
[
[
"try:\n import google.colab\n IN_COLAB = True\nexcept:\n IN_COLAB = False",
"_____no_output_____"
],
[
"if IN_COLAB:\n !apt-get install openjdk-8-jdk-headless -qq > /dev/null\n !wget -q https://dlcdn.apache.org/spark/spark-3.2.1/spark-3.2.1-bin-hadoop3.2.tgz\n !tar xf spark-3.2.1-bin-hadoop3.2.tgz\n !mv spark-3.2.1-bin-hadoop3.2 spark\n !pip install -q findspark",
"_____no_output_____"
],
[
"if IN_COLAB:\n import os\n os.environ[\"JAVA_HOME\"] = \"/usr/lib/jvm/java-8-openjdk-amd64\"\n os.environ[\"SPARK_HOME\"] = \"/content/spark\"",
"_____no_output_____"
],
[
"import findspark\nfindspark.init()",
"_____no_output_____"
]
],
[
[
"# Pyspark_Transform_Action",
"_____no_output_____"
]
],
[
[
"from pyspark import SparkContext\nimport numpy as np\n\nsc = sc = SparkContext.getOrCreate()\nsc",
"_____no_output_____"
],
[
"rdd = sc.parallelize([\"Dog\", \"Cat\", \"Bird\"])\nrdd.map(lambda x: (x, 1)).collect()",
"_____no_output_____"
],
[
"##Transform\nrdd2 = rdd.map(lambda x: (x, 1 * np.random.normal()))",
"_____no_output_____"
],
[
"#Action\nrdd2.collect()",
"_____no_output_____"
],
[
"#Action\nrdd2.collect()",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"#cache\nrdd2.cache()",
"_____no_output_____"
],
[
"#Action\nrdd2.collect()",
"_____no_output_____"
],
[
"#Action\nrdd2.collect()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac492735a80d55d98dd59dc36fa48cb7a46c4b9
| 16,273 |
ipynb
|
Jupyter Notebook
|
openmdao/docs/openmdao_book/features/building_blocks/solvers/nonlinear_block_gs.ipynb
|
tong0711/OpenMDAO
|
d8496a0e606df405b2472f1c96b3c543eacaca5a
|
[
"Apache-2.0"
] | 451 |
2015-07-20T11:52:35.000Z
|
2022-03-28T08:04:56.000Z
|
openmdao/docs/openmdao_book/features/building_blocks/solvers/nonlinear_block_gs.ipynb
|
tong0711/OpenMDAO
|
d8496a0e606df405b2472f1c96b3c543eacaca5a
|
[
"Apache-2.0"
] | 1,096 |
2015-07-21T03:08:26.000Z
|
2022-03-31T11:59:17.000Z
|
openmdao/docs/openmdao_book/features/building_blocks/solvers/nonlinear_block_gs.ipynb
|
tong0711/OpenMDAO
|
d8496a0e606df405b2472f1c96b3c543eacaca5a
|
[
"Apache-2.0"
] | 301 |
2015-07-16T20:02:11.000Z
|
2022-03-28T08:04:39.000Z
| 32.546 | 189 | 0.589197 |
[
[
[
"try:\n from openmdao.utils.notebook_utils import notebook_mode\nexcept ImportError:\n !python -m pip install openmdao[notebooks]",
"_____no_output_____"
]
],
[
[
"# NonlinearBlockGS\n\nNonlinearBlockGS applies Block Gauss-Seidel (also known as fixed-point iteration) to the\ncomponents and subsystems in the system. This is mainly used to solve cyclic connections. You\nshould try this solver for systems that satisfy the following conditions:\n\n1. System (or subsystem) contains a cycle, though subsystems may.\n2. System does not contain any implicit states, though subsystems may.\n\nNonlinearBlockGS is a block solver, so you can specify different nonlinear solvers in the subsystems and they\nwill be utilized to solve the subsystem nonlinear problem.\n\nNote that you may not know if you satisfy the second condition, so choosing a solver can be a trial-and-error proposition. If\nNonlinearBlockGS doesn't work, then you will need to use [NewtonSolver](../../../_srcdocs/packages/solvers.nonlinear/newton).\n\nHere, we choose NonlinearBlockGS to solve the Sellar problem, which has two components with a\ncyclic dependency, has no implicit states, and works very well with Gauss-Seidel.",
"_____no_output_____"
]
],
[
[
"from openmdao.utils.notebook_utils import get_code\nfrom myst_nb import glue\nglue(\"code_src33\", get_code(\"openmdao.test_suite.components.sellar.SellarDis1withDerivatives\"), display=False)",
"_____no_output_____"
]
],
[
[
":::{Admonition} `SellarDis1withDerivatives` class definition \n:class: dropdown\n\n{glue:}`code_src33`\n:::",
"_____no_output_____"
]
],
[
[
"from openmdao.utils.notebook_utils import get_code\nfrom myst_nb import glue\nglue(\"code_src34\", get_code(\"openmdao.test_suite.components.sellar.SellarDis2withDerivatives\"), display=False)",
"_____no_output_____"
]
],
[
[
":::{Admonition} `SellarDis2withDerivatives` class definition \n:class: dropdown\n\n{glue:}`code_src34`\n:::",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport openmdao.api as om\nfrom openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives\n\nprob = om.Problem()\nmodel = prob.model\n\nmodel.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\nmodel.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\nmodel.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\nmodel.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\nmodel.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\nmodel.nonlinear_solver = om.NonlinearBlockGS()\n\nprob.setup()\n\nprob.set_val('x', 1.)\nprob.set_val('z', np.array([5.0, 2.0]))\n\nprob.run_model()\n\nprint(prob.get_val('y1'))\nprint(prob.get_val('y2'))",
"_____no_output_____"
],
[
"from openmdao.utils.assert_utils import assert_near_equal\n\nassert_near_equal(prob.get_val('y1'), 25.58830273, .00001)\nassert_near_equal(prob.get_val('y2'), 12.05848819, .00001)",
"_____no_output_____"
]
],
[
[
"This solver runs all of the subsystems each iteration, passing data along all connections\nincluding the cyclic ones. After each iteration, the iteration count and the residual norm are\nchecked to see if termination has been satisfied.\n\nYou can control the termination criteria for the solver using the following options:\n\n# NonlinearBlockGS Options",
"_____no_output_____"
]
],
[
[
"om.show_options_table(\"openmdao.solvers.nonlinear.nonlinear_block_gs.NonlinearBlockGS\")",
"_____no_output_____"
]
],
[
[
"## NonlinearBlockGS Constructor\n\nThe call signature for the `NonlinearBlockGS` constructor is:\n\n```{eval-rst}\n .. automethod:: openmdao.solvers.nonlinear.nonlinear_block_gs.NonlinearBlockGS.__init__\n :noindex:\n```\n\n## Aitken relaxation\n\nThis solver implements Aitken relaxation, as described in Algorithm 1 of this paper on aerostructual design [optimization](http://www.umich.edu/~mdolaboratory/pdf/Kenway2014a.pdf).\nThe relaxation is turned off by default, but it may help convergence for more tightly coupled models.\n\n## Residual Calculation\n\nThe `Unified Derivatives Equations` are formulated so that explicit equations (via `ExplicitComponent`) are also expressed\nas implicit relationships, and their residual is also calculated in \"apply_nonlinear\", which runs the component a second time and\nsaves the difference in the output vector as the residual. However, this would require an extra call to `compute`, which is\ninefficient for slower components. To eliminate the inefficiency of running the model twice every iteration the NonlinearBlockGS\ndriver saves a copy of the output vector and uses that to calculate the residual without rerunning the model. This does require\na little more memory, so if you are solving a model where memory is more of a concern than execution time, you can set the\n\"use_apply_nonlinear\" option to True to use the original formulation that calls \"apply_nonlinear\" on the subsystem.\n\n\n## NonlinearBlockGS Option Examples\n\n**maxiter**\n\n `maxiter` lets you specify the maximum number of Gauss-Seidel iterations to apply. In this example, we\n cut it back from the default, ten, down to two, so that it terminates a few iterations earlier and doesn't\n reach the specified absolute or relative tolerance.",
"_____no_output_____"
]
],
[
[
"from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives\n\nprob = om.Problem()\nmodel = prob.model\n\nmodel.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\nmodel.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\nmodel.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\nmodel.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\nmodel.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\nprob.setup()\nnlbgs = model.nonlinear_solver = om.NonlinearBlockGS()\n\n#basic test of number of iterations\nnlbgs.options['maxiter'] = 1\nprob.run_model()\nprint(model.nonlinear_solver._iter_count)",
"_____no_output_____"
],
[
"assert(model.nonlinear_solver._iter_count == 1)",
"_____no_output_____"
],
[
"nlbgs.options['maxiter'] = 5\nprob.run_model()\nprint(model.nonlinear_solver._iter_count)",
"_____no_output_____"
],
[
"assert(model.nonlinear_solver._iter_count == 5)",
"_____no_output_____"
],
[
"#test of number of iterations AND solution after exit at maxiter\nprob.set_val('x', 1.)\nprob.set_val('z', np.array([5.0, 2.0]))\n\nnlbgs.options['maxiter'] = 3\nprob.set_solver_print()\nprob.run_model()\n\nprint(prob.get_val('y1'))\nprint(prob.get_val('y2'))\nprint(model.nonlinear_solver._iter_count)",
"_____no_output_____"
],
[
"assert_near_equal(prob.get_val('y1'), 25.58914915, .00001)\nassert_near_equal(prob.get_val('y2'), 12.05857185, .00001)\nassert(model.nonlinear_solver._iter_count == 3)",
"_____no_output_____"
]
],
[
[
"**atol**\n\n Here, we set the absolute tolerance to a looser value that will trigger an earlier termination. After\n each iteration, the norm of the residuals is calculated one of two ways. If the \"use_apply_nonlinear\" option\n is set to False (its default), then the norm is calculated by subtracting a cached previous value of the\n outputs from the current value. If \"use_apply_nonlinear\" is True, then the norm is calculated by calling\n apply_nonlinear on all of the subsystems. In this case, `ExplicitComponents` are executed a second time.\n If this norm value is lower than the absolute tolerance `atol`, the iteration will terminate.",
"_____no_output_____"
]
],
[
[
"from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives\n\nprob = om.Problem()\nmodel = prob.model\n\nmodel.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\nmodel.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\nmodel.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\nmodel.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\nmodel.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\nnlbgs = model.nonlinear_solver = om.NonlinearBlockGS()\nnlbgs.options['atol'] = 1e-4\n\nprob.setup()\n\nprob.set_val('x', 1.)\nprob.set_val('z', np.array([5.0, 2.0]))\n\nprob.run_model()\n\nprint(prob.get_val('y1'))\nprint(prob.get_val('y2'))",
"_____no_output_____"
],
[
"assert_near_equal(prob.get_val('y1'), 25.5882856302, .00001)\nassert_near_equal(prob.get_val('y2'), 12.05848819, .00001)",
"_____no_output_____"
]
],
[
[
"**rtol**\n\n Here, we set the relative tolerance to a looser value that will trigger an earlier termination. After\n each iteration, the norm of the residuals is calculated one of two ways. If the \"use_apply_nonlinear\" option\n is set to False (its default), then the norm is calculated by subtracting a cached previous value of the\n outputs from the current value. If \"use_apply_nonlinear\" is True, then the norm is calculated by calling\n apply_nonlinear on all of the subsystems. In this case, `ExplicitComponents` are executed a second time.\n If the ratio of the currently calculated norm to the initial residual norm is lower than the relative tolerance\n `rtol`, the iteration will terminate.",
"_____no_output_____"
]
],
[
[
"from openmdao.utils.notebook_utils import get_code\nfrom myst_nb import glue\nglue(\"code_src35\", get_code(\"openmdao.test_suite.components.sellar.SellarDerivatives\"), display=False)",
"_____no_output_____"
]
],
[
[
":::{Admonition} `SellarDerivatives` class definition \n:class: dropdown\n\n{glue:}`code_src35`\n:::",
"_____no_output_____"
]
],
[
[
"from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives, SellarDerivatives\n\nprob = om.Problem()\nmodel = prob.model\n\nmodel.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2'])\nmodel.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2'])\n\nmodel.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',\n z=np.array([0.0, 0.0]), x=0.0),\n promotes=['obj', 'x', 'z', 'y1', 'y2'])\n\nmodel.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])\nmodel.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])\n\nnlbgs = model.nonlinear_solver = om.NonlinearBlockGS()\nnlbgs.options['rtol'] = 1e-3\n\nprob.setup()\n\nprob.set_val('x', 1.)\nprob.set_val('z', np.array([5.0, 2.0]))\n\nprob.run_model()\n\nprint(prob.get_val('y1'), 25.5883027, .00001)\nprint(prob.get_val('y2'), 12.05848819, .00001)",
"_____no_output_____"
],
[
"assert_near_equal(prob.get_val('y1'), 25.5883027, .00001)\nassert_near_equal(prob.get_val('y2'), 12.05848819, .00001)",
"_____no_output_____"
]
]
] |
[
"code",
"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",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4ac4934248d6fc2a48c0241af9e4dd2d0aafc03a
| 8,935 |
ipynb
|
Jupyter Notebook
|
14_AVL.ipynb
|
ChicagoPark/DSA
|
a88c3fb8481f795d2f3aec12e7ac0ef8107b3e02
|
[
"CECILL-B"
] | null | null | null |
14_AVL.ipynb
|
ChicagoPark/DSA
|
a88c3fb8481f795d2f3aec12e7ac0ef8107b3e02
|
[
"CECILL-B"
] | null | null | null |
14_AVL.ipynb
|
ChicagoPark/DSA
|
a88c3fb8481f795d2f3aec12e7ac0ef8107b3e02
|
[
"CECILL-B"
] | null | null | null | 33.464419 | 119 | 0.540795 |
[
[
[
"# AVL Tree",
"_____no_output_____"
]
],
[
[
"from Module.classCollection import Queue\n\nclass AVLNode:\n def __init__(self, data):\n self.data = data\n self.leftChild = None\n self.rightChild = None\n self.height = 1\n \ndef preorderTraversal(rootNode):\n if not rootNode:\n return\n print(rootNode.data)\n preorderTraversal(rootNode.leftChild)\n preorderTraversal(rootNode.rightChild)\n \ndef inorderTraversal(rootNode):\n if not rootNode:\n return\n inorderTraversal(rootNode.leftChild)\n print(root.data)\n inorderTraversal(rootNode.rightChild)\n \ndef postorderTraversal(rootNode):\n if rootNode == None:\n return\n postorderTraversal(rootNode.leftChild)\n postorderTraversal(rootNode.rightChild)\n print(rootNode.data)\n\ndef levelorderTraversal(rootNode):\n if rootNode == None:\n return\n customQueue = Queue()\n customQueue.enqueue(rootNode)\n while customQueue.isEmpty() is not True:\n tempNode = customQueue.dequeue()\n print(tempNode.value.data)\n if tempNode.value.leftChild is not None:\n customQueue.enqueue(tempNode.value.leftChild)\n if tempNode.value.rightChild is not None:\n customQueue.enqueue(tempNode.value.rightChild)\n \ndef searchNode(rootNode, nodeValue):\n if rootNode.data == nodeValue:\n print(\"The value is found\")\n elif nodeValue < rootNode.data:\n searchNode(rootNode.leftChild, nodeValue)\n else:\n searchNode(rootNode.rightChild, nodeValue)\n \ndef rightRotate(disbalanceNode):\n newRoot = disbalanceNode.leftChild\n disbalanceNode.leftChild = disbalanceNode.leftChild.rightChild\n newRoot.leftChild = disbalanceNode\n disbalanceNode.height = 1 + max(getHeight(disbalanceNode.leftChild), getHeight(disbalanceNode.rightChild))\n newRoot.height = 1 + max(getHeight(newRoot.leftChild), getHeight(newRoot.rightChild))\n return newRoot\n\ndef leftRotate(disbalanceNode):\n newRoot = disbalanceNode.rightChild\n disbalanceNode.rightChild = disbalanceNode.rightChild.leftChild\n newRoot.leftChild = disbalanceNode\n disbalanceNode.height = 1 + max(getHeight(disbalanceNode.leftChild), getHeight(disbalanceNode.rightChild))\n newRoot.height = 1 + max(getHeight(newRoot.leftChild), getHeight(newRoot.rightChild))\n return newRoot\n\ndef getHeight(rootNode):\n if not rootNode:\n return 0\n return rootNode.height\n\n\ndef getBalance(rootNode):\n if not rootNode:\n return 0\n return getHeight(rootNode.leftChild) - getHeight(rootNode.rightChild)\n \ndef insertNode(rootNode, nodeValue):\n # (0) put the value first\n if not rootNode:\n return AVLNode(nodeValue)\n # (1) No need to rotate\n elif nodeValue <= rootNode.data:\n rootNode.leftChild = insertNode(rootNode.leftChild, nodeValue)\n else:\n rootNode.rightChild = insertNode(rootNode.rightChild, nodeValue)\n \n rootNode.height = 1+ max(getHeight(rootNode.leftChild), getHeight(rootNode.rightChild))\n balance = getBalance(rootNode)\n \n # LL\n if balance > 1 and nodeValue < rootNode.leftChild.data:\n return rightRotate(rootNode)\n # LR\n if balance > 1 and nodeValue > rootNode.leftChild.data:\n rootNode.leftChild = leftRotate(rootNode.leftChild)\n return rightRotate(rootNode)\n # RR\n if balance < -1 and nodeValue > rootNode.rightChild.data:\n return leftRotate(rootNode)\n # RL\n if balance < -1 and nodeValue < rootNode.rightChild.data:\n rootNode.rightChild = rightRotate(rootNode.rightChild)\n return leftRotate(rootNode)\n return rootNode\n \ndef getMinValueNode(rootNode):\n if rootNode is None or rootNode.leftChild is None:\n return rootNode\n return getMinValueNode(rootNode.leftChild)\n\ndef deleteNode(rootNode, nodeValue):\n if not rootNode:\n return rootNode\n elif nodeValue < rootNode.data:\n rootNode.leftChild = deleteNode(rootNode.leftChild, nodeValue) \n elif nodeValue > rootNode.data:\n rootNode.rightChild = deleteNode(rootNode.rightChild, nodeValue)\n else:\n if rootNode.leftChild is None:\n temp = rootNode.rightChild\n rootNode = None\n return temp\n elif rootNode.rightChild is None:\n temp = rootNode.leftChild\n rootNode = None\n return temp\n \n temp = getMinValueNode(rootNode.rightChild)\n rootNode.data = temp.data\n rootNode.rightChild = deleteNode(rootNode.rightChild, temp.data)\n rootNode.height = 1+max(getHeight(rootNode.leftChild), getHeight(rootNode.rightChild))\n balance = getBalance(rootNode)\n # LL\n if balance > 1 and getBalance(rootNode.leftChild)>0:\n return rightRotate(rootNode)\n \n if balance > 1 and getBalance(rootNode.leftChild)<0:\n rootNode.leftChild = leftRotate(rootNode.leftChild)\n return rightRotate(rootNode)\n #RR\n if balance < -1 and getBalance(rootNode.rightChild)<0:\n return leftRotate(rootNode)\n # RL\n if balance < -1 and getBalance(rootNode.rightChild)>0:\n rootNode.rightChild = rightRotate(rootNode.rightChild)\n return leftRotate(rootNode)\n\n return rootNode\n\ndef deleteAVL(rootNode):\n rootNode.data = None\n rootNode.leftChild = None\n rootNode.rightChild = None\n return \"AVL has been successfully deleted\"\n\nnewAVL = AVLNode(5)\n\nprint(\"----1.preorder----\")\n\nprint(\"----2.inorder----\")\n\nprint(\"----3.postorder----\")\n\nprint(\"----4.levelorder----\")\n\nprint(\"----5.Insertation----\")\nnewAVL = insertNode(newAVL, 10)\nnewAVL = insertNode(newAVL, 15)\nnewAVL = insertNode(newAVL, 20)\n\nlevelorderTraversal(newAVL)\n\nprint(\"----6. Deletion----\")\n\nnewAVL = deleteNode(newAVL, 15)\n\nlevelorderTraversal(newAVL)\n\nprint(\"----7. Delete AVL----\")\n\nprint(deleteAVL(newAVL))\n\nlevelorderTraversal(newAVL)",
"----1.preorder----\n----2.inorder----\n----3.postorder----\n----4.levelorder----\n----5.Insertation----\n10\n5\n15\n20\n----6. Deletion----\n10\n5\n20\n----7. Delete AVL----\nAVL has been successfully deleted\nNone\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
]
] |
4ac4a0296b8f3483588dede5afc25df7297c4f8d
| 1,432 |
ipynb
|
Jupyter Notebook
|
001_TwoSum.ipynb
|
NikhilAshodariya/LeetCode
|
58584be92a23eb01153801560867d3076fbf72b6
|
[
"MIT"
] | null | null | null |
001_TwoSum.ipynb
|
NikhilAshodariya/LeetCode
|
58584be92a23eb01153801560867d3076fbf72b6
|
[
"MIT"
] | null | null | null |
001_TwoSum.ipynb
|
NikhilAshodariya/LeetCode
|
58584be92a23eb01153801560867d3076fbf72b6
|
[
"MIT"
] | null | null | null | 18.842105 | 56 | 0.467877 |
[
[
[
"def twoSum(nums, target):\n for index,num in enumerate(nums):\n comp = target - num\n if comp in nums:\n if index!=nums.index(comp):\n return [index,nums.index(comp)]\n\n return [-1,-1]",
"_____no_output_____"
],
[
"twoSum([2, 7, 11, 15],9)",
"_____no_output_____"
]
],
[
[
"#### nums[0] + nums[1] = 2 + 7 = 9",
"_____no_output_____"
]
]
] |
[
"code",
"markdown"
] |
[
[
"code",
"code"
],
[
"markdown"
]
] |
4ac4c4ed62008a19d992f3ea8b370f6e88511dbd
| 77,519 |
ipynb
|
Jupyter Notebook
|
A7_MongoCharts.ipynb
|
kaimmej/DA320
|
6a98b3d29e1ff300bcb06426f09e19ec532e06a7
|
[
"MIT"
] | null | null | null |
A7_MongoCharts.ipynb
|
kaimmej/DA320
|
6a98b3d29e1ff300bcb06426f09e19ec532e06a7
|
[
"MIT"
] | 1 |
2022-02-03T02:07:10.000Z
|
2022-02-03T02:07:10.000Z
|
A7_MongoCharts.ipynb
|
kaimmej/DA320
|
6a98b3d29e1ff300bcb06426f09e19ec532e06a7
|
[
"MIT"
] | null | null | null | 24.407746 | 302 | 0.312491 |
[
[
[
"# DA320 Assignment 7: Mongo Charts\nJon Kaimmer \nDA320 \nWinter2022\n\n\n ### Introduction\nLets import our chirp data and then chart it. ",
"_____no_output_____"
]
],
[
[
"#IMPORTS\n\nimport pymongo\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport json as json\n\nimport plotly.express as px\n\n\n# import warnings\n# warnings.filterwarnings('ignore') #Ignore the seaborn warnings...\n\n#METHODS\ndef connectToMongoDB():\n with open(credentialLocation, 'r') as myFile: #open seperate file that stores passwords in JSON array format\n data = myFile.read() #read file into memory\n credentialDict = json.loads(data) #parse json file into a python dictionary\n \n return(credentialDict['MONGO']['mDBconnectionString'])\n\n#FIELDS\ncredentialLocation = r\"C:\\Users\\\\jonat\\\\OneDrive\\Documents\\GitHub\\\\DA320\\credentials.json\"\n\nsns.set(rc = {'figure.figsize':(40,8)})",
"_____no_output_____"
]
],
[
[
"### Read MongoDB connection string from my credentials.json file",
"_____no_output_____"
]
],
[
[
"MONGOconnectionString = connectToMongoDB()\nclient = pymongo.MongoClient(MONGOconnectionString)\ndb = client.admin\n\nserverStatusResult=db.command('serverStatus')\n#print(serverStatusResult)",
"_____no_output_____"
]
],
[
[
"### Query MongoDB",
"_____no_output_____"
]
],
[
[
"db = client['MoviesDB'] #<- MoviesDB is the mongoCLUSTER\nchirpCollection = db['movies'] # <-movies is the chirps collection within the mongoCluster\n\nquery = {'comment' : 'I hate ice cream'}\nprint(chirpCollection.find_one(query))",
"{'_id': ObjectId('6201da43350c4e4f36592a2e'), 'name': 'Kingston Gutierrez', 'date': '2019-04-28T20:16:13.931629-07:00', 'comment': 'I hate ice cream', 'location': {'latitude': 51.185218811035156, 'longitude': -114.47618865966797, 'country': 'CA', 'region': 'AB'}, 'likes': 12, 'responses': 6}\n"
]
],
[
[
"### Create a simple pipeline: match to \"i hate ice cream\" and group on the month field. ",
"_____no_output_____"
]
],
[
[
"mongoPipeline = [\n { \n '$match': { 'likes': { '$gte': 10 } }\n }, {\n '$addFields': \n {\n 'Year': {'$toInt': {'$substr': ['$date', 0, 4]}}, \n 'Month': {'$toInt': {'$substr': ['$date', 5, 2]}}, \n 'Day': {'$toInt': {'$substr': ['$date', 8, 2]}}\n }\n }, {\n '$set': \n {\n 'subject': {\n '$switch': {\n 'branches': \n [\n {'case': {'$gte': [{ '$indexOfCP': [ '$comment', 'hiking'] }, 0] }, 'then': 'Hiking'}, \n {'case': {'$gte': [{'$indexOfCP': [ '$comment', 'camping'] }, 0] }, 'then': 'Camping'}, \n {'case': {'$gte': [{'$indexOfCP': ['$comment', 'ice cream']}, 0] }, 'then': 'Ice cream' }, \n {'case': {'$gte': [{'$indexOfCP': ['$comment', 'tacos']}, 0] }, 'then': 'Tacos'}, \n {'case': {'$gte': [{'$indexOfCP': [ '$comment', 'walks on the beach' ] }, 0]}, 'then': 'Walks on the beach'}, \n {'case': { '$gte': [ {'$indexOfCP': [ '$comment', 'skiing'] }, 0]}, 'then': 'Skiing' }\n ],'default': 'DID NOT MATCH'\n }\n }\n }\n }, {\n '$set': {\n 'sentiment': {\n '$switch': {\n 'branches': \n [\n {'case': {'$gte': [{'$indexOfCP': ['$comment', 'I love'] }, 0] }, 'then': 1}, \n {'case': {'$gte': [ {'$indexOfCP': ['$comment', 'Maybe I']}, 0 ]}, 'then': 0.3}, \n {'case': {'$gte': [{'$indexOfCP': ['$comment', 'I like']}, 0] }, 'then': 0.6}, \n {'case': {'$gte': [{'$indexOfCP': ['$comment', 'I think']}, 0]}, 'then': 0.1}, \n {'case': {'$gte': [{'$indexOfCP': ['$comment', 'I hate']}, 0]}, 'then': -0.6},\n {'case': {'$gte': [{'$indexOfCP': ['$comment', 'really hate']}, 0]}, 'then': -1}\n ],'default': 'DID NOT MATCH'\n }\n }\n }\n {\n '$group': {\n '_id': {\n 'subject': '$subject', \n 'year': '$Year', \n 'month': '$Month'\n }, \n 'chirpCount': {'$sum': 1}, \n 'averageSentiment': {'$avg': '$sentiment'}, \n 'chirps': {\n '$push': {\n 'name': '$name', \n 'comment': '$comment', \n 'sentiment': '$sentiment', \n 'location': '$location'\n }\n }\n }\n } \n]\n\nresults = chirpCollection.aggregate(mongoPipeline)\n\n",
"_____no_output_____"
]
],
[
[
"### We then need to clean the data coming out of our data pipeline\n- First lets break out the '_id' JSON Object into their own columns.\n- Then we will rename those columns and reindex them. ",
"_____no_output_____"
]
],
[
[
"### Normalize data using pandas\n#\n# This data has JSON objects nestled within it. To start we will need break out the ['subject', 'year', 'month'] fields that are nestled behind '_.id\". Basically i had created a multilayered key for my _id index in MongoDB. I need to now break that out into a long form datastructure.\n# We can do that with .json_normalize built in pandas funciton. \n# Note that the _id column is a JSON object while the chirps column is a JSON array.\n\ndf= pd.json_normalize(results, sep='>')\ndf",
"_____no_output_____"
],
[
"\n#we want to rename these three columns. We are doing this so that when we chart this data downbelow, we will be able to use \"dot notation\" to access the columns. if there is a period in the name of the column it causes us issues. \n# _id>subject -> subject\n# _id>year -> year\n# _id>month -> month\ndf = df.rename( columns = \n { \n '_id>subject':'subject',\n '_id>year':'year',\n '_id>month':'month',\n }\n)\n#and now lets reorder our columns useing dataFrame.reindex\ndf = df.reindex(columns=['subject', 'year', 'month', 'chirpCount', 'averageSentiment', 'chirps'])\ndf",
"_____no_output_____"
]
],
[
[
"### Better. Now we can graph our Data",
"_____no_output_____"
]
],
[
[
"fig = px.bar(df, x='month', y='chirpCount', facet_col='subject')\nfig.show()",
"_____no_output_____"
],
[
"fig = px.scatter(df, x='month', y='averageSentiment', trendline='ols', title='Canadians overall sentiment towards things they chose to Chirp about')\nfig.update_traces(\n line=dict(width=3, color='gray')\n)\nfig.show()",
"_____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",
"code"
]
] |
4ac4d4480ece08c02595734412d950879aaf2050
| 29,748 |
ipynb
|
Jupyter Notebook
|
ICCT_hr/examples/04/.ipynb_checkpoints/SS-45-Upravljanje_putanjom_zrakoplova-checkpoint.ipynb
|
ICCTerasmus/ICCT
|
fcd56ab6b5fddc00f72521cc87accfdbec6068f6
|
[
"BSD-3-Clause"
] | 6 |
2021-05-22T18:42:14.000Z
|
2021-10-03T14:10:22.000Z
|
ICCT_hr/examples/04/SS-45-Upravljanje_putanjom_zrakoplova.ipynb
|
ICCTerasmus/ICCT
|
fcd56ab6b5fddc00f72521cc87accfdbec6068f6
|
[
"BSD-3-Clause"
] | null | null | null |
ICCT_hr/examples/04/SS-45-Upravljanje_putanjom_zrakoplova.ipynb
|
ICCTerasmus/ICCT
|
fcd56ab6b5fddc00f72521cc87accfdbec6068f6
|
[
"BSD-3-Clause"
] | 2 |
2021-05-24T11:40:09.000Z
|
2021-08-29T16:36:18.000Z
| 42.741379 | 474 | 0.466855 |
[
[
[
"#remove cell visibility\nfrom IPython.display import HTML\ntag = HTML('''<script>\ncode_show=true; \nfunction code_toggle() {\n if (code_show){\n $('div.input').hide()\n } else {\n $('div.input').show()\n }\n code_show = !code_show\n} \n$( document ).ready(code_toggle);\n</script>\nPromijeni vidljivost <a href=\"javascript:code_toggle()\">ovdje</a>.''')\ndisplay(tag)",
"_____no_output_____"
],
[
"%matplotlib inline\nimport control\nimport numpy\nimport sympy as sym\nfrom IPython.display import display, Markdown\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\n\n\n#print a matrix latex-like\ndef bmatrix(a):\n \"\"\"Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)\n\n :a: numpy array\n :returns: LaTeX bmatrix as a string\n \"\"\"\n if len(a.shape) > 2:\n raise ValueError('bmatrix can at most display two dimensions')\n lines = str(a).replace('[', '').replace(']', '').splitlines()\n rv = [r'\\begin{bmatrix}']\n rv += [' ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n rv += [r'\\end{bmatrix}']\n return '\\n'.join(rv)\n\n\n# Display formatted matrix: \ndef vmatrix(a):\n if len(a.shape) > 2:\n raise ValueError('bmatrix can at most display two dimensions')\n lines = str(a).replace('[', '').replace(']', '').splitlines()\n rv = [r'\\begin{vmatrix}']\n rv += [' ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n rv += [r'\\end{vmatrix}']\n return '\\n'.join(rv)\n\n\n#matrixWidget is a matrix looking widget built with a VBox of HBox(es) that returns a numPy array as value !\nclass matrixWidget(widgets.VBox):\n def updateM(self,change):\n for irow in range(0,self.n):\n for icol in range(0,self.m):\n self.M_[irow,icol] = self.children[irow].children[icol].value\n #print(self.M_[irow,icol])\n self.value = self.M_\n\n def dummychangecallback(self,change):\n pass\n \n \n def __init__(self,n,m):\n self.n = n\n self.m = m\n self.M_ = numpy.matrix(numpy.zeros((self.n,self.m)))\n self.value = self.M_\n widgets.VBox.__init__(self,\n children = [\n widgets.HBox(children = \n [widgets.FloatText(value=0.0, layout=widgets.Layout(width='90px')) for i in range(m)]\n ) \n for j in range(n)\n ])\n \n #fill in widgets and tell interact to call updateM each time a children changes value\n for irow in range(0,self.n):\n for icol in range(0,self.m):\n self.children[irow].children[icol].value = self.M_[irow,icol]\n self.children[irow].children[icol].observe(self.updateM, names='value')\n #value = Unicode('[email protected]', help=\"The email value.\").tag(sync=True)\n self.observe(self.updateM, names='value', type= 'All')\n \n def setM(self, newM):\n #disable callbacks, change values, and reenable\n self.unobserve(self.updateM, names='value', type= 'All')\n for irow in range(0,self.n):\n for icol in range(0,self.m):\n self.children[irow].children[icol].unobserve(self.updateM, names='value')\n self.M_ = newM\n self.value = self.M_\n for irow in range(0,self.n):\n for icol in range(0,self.m):\n self.children[irow].children[icol].value = self.M_[irow,icol]\n for irow in range(0,self.n):\n for icol in range(0,self.m):\n self.children[irow].children[icol].observe(self.updateM, names='value')\n self.observe(self.updateM, names='value', type= 'All') \n\n #self.children[irow].children[icol].observe(self.updateM, names='value')\n\n \n#overlaod class for state space systems that DO NOT remove \"useless\" states (what \"professor\" of automatic control would do this?)\nclass sss(control.StateSpace):\n def __init__(self,*args):\n #call base class init constructor\n control.StateSpace.__init__(self,*args)\n #disable function below in base class\n def _remove_useless_states(self):\n pass",
"_____no_output_____"
]
],
[
[
"## Upravljanje putanjom zrakoplova\n\nDinamika rotacije zrakoplova koji se kreće po tlu može se predstaviti kao:\n\n$$\nJ_z\\ddot{\\psi} = bF_1\\delta + F_2\\dot{\\psi} \\, , \n$$\n\ngdje je $J_z = 11067000$ kg$\\text{m}^2$, $b = 15$ , $F_1 = 35000000$ Nm, $F_2 = 500000$ kg$\\text{m}^2$/$\\text{s}$, $\\psi$ je kut rotacije (u radijanima), ili kut zaošijanja u odnosu na vertikalnu os, a $\\delta$ je kut upravljanja prednjih kotača (u radijanima). Kada zrakoplov slijedi ravnu liniju s uzdužnom linearnom brzinom $V$ (u m/s), bočna brzina zrakoplova $V_y$ (u m/s) približno je linearno proporcionalna kutu zaošijanja: $V_y = \\dot{p_y} = V\\psi$.\n\nCilj je dizajnirati regulator za bočni položaj zrakoplova $p_y$, s uzdužnom brzinom $V$ postavljenom na 35 km/h, koristeći kut upravljanja prednjeg kotača $\\delta$ kao ulaz sustava, a prateći sljedeće specifikacije:\n- vrijeme smirivanja za pojas tolerancije od 5% kraće od 4 sekunde;\n- nulta pogreška u stacionarnom stanju u odzivu na promjenu željenog bočnog položaja;\n- u potpunosti nema ili ima minimalnog prekoračenja;\n- kut upravljanja ne prelazi $\\pm8$ stupnjeva kada se prati promjena bočnog položaja od 5 metara.\n\n\nJednadžbe dinamike u formi prostora stanja su:\n\n\\begin{cases}\n \\dot{x} = \\begin{bmatrix} \\frac{F_2}{J_z} & 0 & 0 \\\\ 1 & 0 & 0 \\\\ 0 & V & 0 \\end{bmatrix}x + \\begin{bmatrix} \\frac{bF_1}{J_z} \\\\ 0 \\\\ 0 \\end{bmatrix}u \\\\\n y = \\begin{bmatrix} 0 & 0 & 1 \\end{bmatrix}x \\, ,\n\\end{cases}\n\ngdje je $x=\\begin{bmatrix} x_1 & x_2 & x_3 \\end{bmatrix}^T = \\begin{bmatrix} \\dot{\\psi} & \\psi & p_y \\end{bmatrix}^T$ i $u=\\delta$.\n\nPolovi sustava su $0$, $0$ i $\\frac{F_2}{J_z} \\simeq 0.045$, stoga je sustav nestabilan.\n\n### Dizajn regulatora\n#### Dizajn kontrolera\n\nDa bismo udovoljili zahtjevima nulte pogreške stacionarnog stanja, dodajemo novo stanje:\n$$\n\\dot{x_4} = p_y-y_d = x_3 - y_d\n$$\nRezultirajući prošireni sustav je tada:\n\n\\begin{cases}\n \\dot{x_a} = \\begin{bmatrix} \\frac{F_2}{J_z} & 0 & 0 & 0 \\\\ 1 & 0 & 0 & 0 \\\\ 0 & V & 0 & 0 \\\\ 0 & 0 & 1 & 0 \\end{bmatrix}x_a + \\begin{bmatrix} \\frac{bF_1}{J_z} & 0 \\\\ 0 & 0 \\\\ 0 & 0 \\\\ 0 & -1 \\end{bmatrix}\\begin{bmatrix} u \\\\ y_d \\end{bmatrix} \\\\\n y_a = \\begin{bmatrix} 0 & 0 & 1 & 0 \\\\ 0 & 0 & 0 & 1 \\end{bmatrix}x_a,\n\\end{cases}\n\ngdje je $x_a = \\begin{bmatrix} x_1 & x_2 & x_3 & x_4 \\end{bmatrix}^T$ i dodaje se drugi izlaz kako bi se održala osmotrivost sustava. Sustav ostaje upravljiv s ulazom $u$ i tako, pomoću ovog ulaza, možemo oblikovati povratnu vezu stanja. Moguće rješenje je smjestiti sve polove u $-2$.\n\n\n\n#### Dizajn promatrača\n\nČak i ako se iz mjerenja mogu dobiti stanja $x_3$ i $x_4$, a mi trebamo procijeniti samo $x_2$ i $x_3$, prikladno je raditi sa sustavom 4x4 i dizajnirati promatrač reda 4 sa svim polovima u $-10$.\n\n### Kako koristiti ovaj interaktivni primjer?\n- Provjerite jesu li ispunjeni zahtjevi ako postoje pogreške u procjeni početnog stanja.",
"_____no_output_____"
]
],
[
[
"# Preparatory cell\n\nX0 = numpy.matrix('0.0; 0.0; 0.0; 0.0')\nK = numpy.matrix([0,0,0,0])\nL = numpy.matrix([[0,0],[0,0],[0,0],[0,0]])\n\nX0w = matrixWidget(4,1)\nX0w.setM(X0)\nKw = matrixWidget(1,4)\nKw.setM(K)\nLw = matrixWidget(4,2)\nLw.setM(L)\n\n\neig1c = matrixWidget(1,1)\neig2c = matrixWidget(2,1)\neig3c = matrixWidget(1,1)\neig4c = matrixWidget(2,1)\neig1c.setM(numpy.matrix([-2.])) \neig2c.setM(numpy.matrix([[-2.],[-0.]]))\neig3c.setM(numpy.matrix([-2.]))\neig4c.setM(numpy.matrix([[-2.],[-0.]]))\n\neig1o = matrixWidget(1,1)\neig2o = matrixWidget(2,1)\neig3o = matrixWidget(1,1)\neig4o = matrixWidget(2,1)\neig1o.setM(numpy.matrix([-10.])) \neig2o.setM(numpy.matrix([[-10.],[0.]]))\neig3o.setM(numpy.matrix([-10.]))\neig4o.setM(numpy.matrix([[-10.],[0.]]))",
"_____no_output_____"
],
[
"# Misc\n\n#create dummy widget \nDW = widgets.FloatText(layout=widgets.Layout(width='0px', height='0px'))\n\n#create button widget\nSTART = widgets.Button(\n description='Test',\n disabled=False,\n button_style='', # 'success', 'info', 'warning', 'danger' or ''\n tooltip='Test',\n icon='check'\n)\n \ndef on_start_button_clicked(b):\n #This is a workaround to have intreactive_output call the callback:\n # force the value of the dummy widget to change\n if DW.value> 0 :\n DW.value = -1\n else: \n DW.value = 1\n pass\nSTART.on_click(on_start_button_clicked)\n\n# Define type of method \nselm = widgets.Dropdown(\n options= ['Postavi K i L', 'Postavi svojstvene vrijednosti'],\n value= 'Postavi svojstvene vrijednosti',\n description='',\n disabled=False\n)\n\n# Define the number of complex eigenvalues\nselec = widgets.Dropdown(\n options= ['0 kompleksnih svojstvenih vrijednosti', '2 kompleksne svojstvene vrijednosti', '4 kompleksne svojstvene vrijednosti'],\n value= '0 kompleksnih svojstvenih vrijednosti',\n description='Svojstvene vrijednosti kontrolera:',\n disabled=False\n)\nseleo = widgets.Dropdown(\n options= ['0 kompleksnih svojstvenih vrijednosti', '2 kompleksne svojstvene vrijednosti', '4 kompleksne svojstvene vrijednosti'],\n value= '0 kompleksnih svojstvenih vrijednosti',\n description='Svojstvene vrijednosti promatrača:',\n disabled=False\n)\n\n#define type of ipout \nselu = widgets.Dropdown(\n options=['impuls', 'step', 'sinus', 'Pravokutni val'],\n value='step',\n description='Tip referentnog signala:',\n style = {'description_width': 'initial'},\n disabled=False\n)\n# Define the values of the input\nu = widgets.FloatSlider(\n value=5,\n min=0,\n max=10,\n step=0.1,\n description='Referentni signal [m]:',\n style = {'description_width': 'initial'},\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='.1f',\n)\nv = widgets.FloatSlider(\n value=9.72,\n min=1,\n max=20,\n step=0.1,\n description=r'$V$ [m/s]:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='.2f',\n)\nperiod = widgets.FloatSlider(\n value=0.5,\n min=0.001,\n max=10,\n step=0.001,\n description='Period: ',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='.3f',\n)\n\nsimTime = widgets.FloatText(\n value=5,\n description='',\n disabled=False\n)",
"_____no_output_____"
],
[
"# Support functions\n\ndef eigen_choice(selec,seleo):\n if selec == '0 kompleksnih svojstvenih vrijednosti':\n eig1c.children[0].children[0].disabled = False\n eig2c.children[1].children[0].disabled = True\n eig3c.children[0].children[0].disabled = False\n eig4c.children[0].children[0].disabled = False\n eig4c.children[1].children[0].disabled = True\n eigc = 0\n if seleo == '0 kompleksnih svojstvenih vrijednosti':\n eig1o.children[0].children[0].disabled = False\n eig2o.children[1].children[0].disabled = True\n eig3o.children[0].children[0].disabled = False\n eig4o.children[0].children[0].disabled = False\n eig4o.children[1].children[0].disabled = True\n eigo = 0\n if selec == '2 kompleksne svojstvene vrijednosti':\n eig1c.children[0].children[0].disabled = False\n eig2c.children[1].children[0].disabled = False\n eig3c.children[0].children[0].disabled = False\n eig4c.children[0].children[0].disabled = True\n eig4c.children[1].children[0].disabled = True\n eigc = 2\n if seleo == '2 kompleksne svojstvene vrijednosti':\n eig1o.children[0].children[0].disabled = False\n eig2o.children[1].children[0].disabled = False\n eig3o.children[0].children[0].disabled = False\n eig4o.children[0].children[0].disabled = True\n eig4o.children[1].children[0].disabled = True\n eigo = 2\n if selec == '4 kompleksne svojstvene vrijednosti':\n eig1c.children[0].children[0].disabled = True\n eig2c.children[1].children[0].disabled = False\n eig3c.children[0].children[0].disabled = True\n eig4c.children[0].children[0].disabled = False\n eig4c.children[1].children[0].disabled = False\n eigc = 4\n if seleo == '4 kompleksne svojstvene vrijednosti':\n eig1o.children[0].children[0].disabled = True\n eig2o.children[1].children[0].disabled = False\n eig3o.children[0].children[0].disabled = True\n eig4o.children[0].children[0].disabled = False\n eig4o.children[1].children[0].disabled = False\n eigo = 4\n return eigc, eigo\n\ndef method_choice(selm):\n if selm == 'Postavi K i L':\n method = 1\n selec.disabled = True\n seleo.disabled = True\n if selm == 'Postavi svojstvene vrijednosti':\n method = 2\n selec.disabled = False\n seleo.disabled = False\n return method",
"_____no_output_____"
],
[
"F1 = 35000000\nF2 = 500000\nb = 15\nV = 35/3.6\nJz = 11067000\n\nA = numpy.matrix([[F2/Jz, 0, 0, 0],\n [1, 0, 0, 0],\n [0, V, 0, 0],\n [0, 0, 1, 0]])\nBu = numpy.matrix([[b*F1/Jz],[0],[0],[0]])\nBref = numpy.matrix([[0],[0],[0],[-1]])\nC = numpy.matrix([[0,0,1,0],[0,0,0,1]])\n\ndef main_callback2(v, X0w, K, L, eig1c, eig2c, eig3c, eig4c, eig1o, eig2o, eig3o, eig4o, u, period, selm, selec, seleo, selu, simTime, DW):\n eigc, eigo = eigen_choice(selec,seleo)\n method = method_choice(selm)\n \n A = numpy.matrix([[F2/Jz, 0, 0, 0],\n [1, 0, 0, 0],\n [0, v, 0, 0],\n [0, 0, 1, 0]])\n \n if method == 1:\n solc = numpy.linalg.eig(A-Bu*K)\n solo = numpy.linalg.eig(A-L*C)\n if method == 2:\n #for better numerical stability of place\n if eig1c[0,0]==eig2c[0,0] or eig1c[0,0]==eig3c[0,0] or eig1c[0,0]==eig4c[0,0]:\n eig1c[0,0] *= 1.01\n if eig2c[0,0]==eig3c[0,0] or eig2c[0,0]==eig4c[0,0]:\n eig3c[0,0] *= 1.015\n if eig1o[0,0]==eig2o[0,0] or eig1o[0,0]==eig3o[0,0] or eig1o[0,0]==eig4o[0,0]:\n eig1o[0,0] *= 1.01\n if eig2o[0,0]==eig3o[0,0] or eig2o[0,0]==eig4o[0,0]:\n eig3o[0,0] *= 1.015\n \n if eigc == 0:\n K = control.acker(A, Bu, [eig1c[0,0], eig2c[0,0], eig3c[0,0], eig4c[0,0]])\n Kw.setM(K)\n if eigc == 2:\n K = control.acker(A, Bu, [eig3c[0,0],\n eig1c[0,0],\n numpy.complex(eig2c[0,0], eig2c[1,0]), \n numpy.complex(eig2c[0,0],-eig2c[1,0])])\n Kw.setM(K)\n if eigc == 4:\n K = control.acker(A, Bu, [numpy.complex(eig4c[0,0], eig4c[1,0]), \n numpy.complex(eig4c[0,0],-eig4c[1,0]),\n numpy.complex(eig2c[0,0], eig2c[1,0]), \n numpy.complex(eig2c[0,0],-eig2c[1,0])])\n Kw.setM(K)\n if eigo == 0:\n L = control.place(A.T, C.T, [eig1o[0,0], eig2o[0,0], eig3o[0,0], eig4o[0,0]]).T\n Lw.setM(L)\n if eigo == 2:\n L = control.place(A.T, C.T, [eig3o[0,0],\n eig1o[0,0],\n numpy.complex(eig2o[0,0], eig2o[1,0]), \n numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n Lw.setM(L)\n if eigo == 4:\n L = control.place(A.T, C.T, [numpy.complex(eig4o[0,0], eig4o[1,0]), \n numpy.complex(eig4o[0,0],-eig4o[1,0]),\n numpy.complex(eig2o[0,0], eig2o[1,0]), \n numpy.complex(eig2o[0,0],-eig2o[1,0])]).T\n Lw.setM(L)\n \n sys = sss(A,numpy.hstack((Bu,Bref)),[[0,0,1,0],[0,0,0,1],[0,0,0,0]],[[0,0],[0,0],[0,1]])\n syse = sss(A-L*C,numpy.hstack((Bu,Bref,L)),numpy.eye(4),numpy.zeros((4,4)))\n sysc = sss(0,[0,0,0,0],0,-K)\n sys_append = control.append(sys,syse,sysc)\n try:\n sys_CL = control.connect(sys_append,\n [[1,8],[3,8],[5,1],[6,2],[7,4],[8,5],[9,6],[10,7],[4,3]],\n [2],\n [1,8])\n except:\n sys_CL = control.connect(sys_append,\n [[1,8],[3,8],[5,1],[6,2],[7,4],[8,5],[9,6],[10,7],[4,3]],\n [2],\n [1,8])\n\n X0w1 = numpy.zeros((8,1))\n X0w1[4,0] = X0w[0,0]\n X0w1[5,0] = X0w[1,0]\n X0w1[6,0] = X0w[2,0]\n X0w1[7,0] = X0w[3,0]\n if simTime != 0:\n T = numpy.linspace(0, simTime, 10000)\n else:\n T = numpy.linspace(0, 1, 10000)\n \n if selu == 'impuls': #selu\n U = [0 for t in range(0,len(T))]\n U[0] = u\n T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n if selu == 'step':\n U = [u for t in range(0,len(T))]\n T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n if selu == 'sinus':\n U = u*numpy.sin(2*numpy.pi/period*T)\n T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n if selu == 'Pravokutni val':\n U = u*numpy.sign(numpy.sin(2*numpy.pi/period*T))\n T, yout, xout = control.forced_response(sys_CL,T,U,X0w1)\n \n try:\n step_info_dict = control.step_info(sys_CL[0,0],SettlingTimeThreshold=0.05,T=T)\n print('Informacije o koraku: \\n\\tVrijeme porasta =',step_info_dict['RiseTime'],'\\n\\tVrijeme smirivanja (5%) =',step_info_dict['SettlingTime'],'\\n\\tPrekoračenje (%)=',step_info_dict['Overshoot'])\n print('Maksimalna u vrijednost (% od 8deg)=', max(abs(yout[1]))/(8*numpy.pi/180)*100) \n except:\n print(\"Pogreška u izračunu informacija o koraku.\")\n \n fig = plt.figure(num='Simulation1', figsize=(14,12))\n \n fig.add_subplot(221)\n plt.title('Izlazni odziv')\n plt.ylabel('Izlaz')\n plt.plot(T,yout[0],T,U,'r--')\n plt.xlabel('$t$ [s]')\n plt.legend(['$y$','Referentni signal'])\n plt.axvline(x=0,color='black',linewidth=0.8)\n plt.axhline(y=0,color='black',linewidth=0.8)\n plt.grid()\n \n fig.add_subplot(222)\n plt.title('Ulaz')\n plt.ylabel('$u$ [deg]')\n plt.plot(T,yout[1]*180/numpy.pi)\n plt.plot(T,[8 for i in range(len(T))],'r--')\n plt.plot(T,[-8 for i in range(len(T))],'r--')\n plt.xlabel('$t$ [s]')\n plt.axvline(x=0,color='black',linewidth=0.8)\n plt.axhline(y=0,color='black',linewidth=0.8)\n plt.grid()\n \n fig.add_subplot(223)\n plt.title('Odziv stanja')\n plt.ylabel('Stanja')\n plt.plot(T,xout[0],\n T,xout[1],\n T,xout[2],\n T,xout[3])\n plt.xlabel('$t$ [s]')\n plt.axvline(x=0,color='black',linewidth=0.8)\n plt.axhline(y=0,color='black',linewidth=0.8)\n plt.legend(['$x_{1}$','$x_{2}$','$x_{3}$','$x_{4}$'])\n plt.grid()\n \n fig.add_subplot(224)\n plt.title('Pogreška procjene')\n plt.ylabel('Pogreška')\n plt.plot(T,xout[4]-xout[0])\n plt.plot(T,xout[5]-xout[1])\n plt.plot(T,xout[6]-xout[2])\n plt.plot(T,xout[7]-xout[3])\n plt.xlabel('$t$ [s]')\n plt.axvline(x=0,color='black',linewidth=0.8)\n plt.axhline(y=0,color='black',linewidth=0.8)\n plt.legend(['$e_{1}$','$e_{2}$','$e_{3}$','$e_{4}$'])\n plt.grid()\n #plt.tight_layout()\n \nalltogether2 = widgets.VBox([widgets.HBox([selm, \n selec,\n seleo,\n selu]),\n widgets.Label(' ',border=3),\n widgets.HBox([widgets.HBox([widgets.Label('K:',border=3), Kw, \n widgets.Label('Svojstvene vrijednosti:',border=3),\n widgets.HBox([eig1c, \n eig2c, \n eig3c,\n eig4c])])]),\n widgets.Label(' ',border=3),\n widgets.HBox([widgets.VBox([widgets.HBox([widgets.Label('L:',border=3), Lw, widgets.Label(' ',border=3),\n widgets.Label(' ',border=3),\n widgets.Label('Svojstvene vrijednosti:',border=3), \n eig1o, \n eig2o,\n eig3o, \n eig4o,\n widgets.Label(' ',border=3),\n widgets.Label(' ',border=3),\n widgets.Label('X0 est.:',border=3), X0w]),\n widgets.Label(' ',border=3),\n widgets.HBox([\n widgets.VBox([widgets.Label('Vrijeme simulacije [s]:',border=3)]),\n widgets.VBox([simTime])])]),\n widgets.Label(' ',border=3)]),\n widgets.Label(' ',border=3),\n widgets.HBox([u,\n v,\n period, \n START])])\nout2 = widgets.interactive_output(main_callback2, {'v':v, 'X0w':X0w, 'K':Kw, 'L':Lw,\n 'eig1c':eig1c, 'eig2c':eig2c, 'eig3c':eig3c, 'eig4c':eig4c, \n 'eig1o':eig1o, 'eig2o':eig2o, 'eig3o':eig3o, 'eig4o':eig4o, \n 'u':u, 'period':period, 'selm':selm, 'selec':selec, 'seleo':seleo, 'selu':selu, 'simTime':simTime, 'DW':DW})\nout2.layout.height = '860px'\ndisplay(out2, alltogether2)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4ac4da37010b29d4eac7aed5d4996693af713906
| 12,273 |
ipynb
|
Jupyter Notebook
|
iguanas/metrics/examples/classification_spark_example.ipynb
|
Aditya-Kapadiya/Iguanas
|
dcc2c1e71f00574c3427fa530191e7079834c11b
|
[
"Apache-2.0"
] | null | null | null |
iguanas/metrics/examples/classification_spark_example.ipynb
|
Aditya-Kapadiya/Iguanas
|
dcc2c1e71f00574c3427fa530191e7079834c11b
|
[
"Apache-2.0"
] | 1 |
2022-01-19T12:01:30.000Z
|
2022-01-19T12:01:30.000Z
|
iguanas/metrics/examples/classification_spark_example.ipynb
|
Aditya-Kapadiya/Iguanas
|
dcc2c1e71f00574c3427fa530191e7079834c11b
|
[
"Apache-2.0"
] | null | null | null | 25.253086 | 280 | 0.553573 |
[
[
[
"# Classification Metrics Spark Example",
"_____no_output_____"
],
[
"Classification metrics are used to calculate the performance of binary predictors based on a binary target. They are used extensively in other Iguanas modules. This example shows how they can be applied in Spark and how to create your own.",
"_____no_output_____"
],
[
"## Requirements",
"_____no_output_____"
],
[
"To run, you'll need the following:\n\n* A dataset containing binary predictor columns and a binary target column.",
"_____no_output_____"
],
[
"----",
"_____no_output_____"
],
[
"## Import packages",
"_____no_output_____"
]
],
[
[
"from iguanas.metrics.classification import Precision, Recall, FScore, Revenue\n\nimport numpy as np\nimport databricks.koalas as ks\nfrom typing import Union",
"_____no_output_____"
]
],
[
[
"## Create data",
"_____no_output_____"
],
[
"Let's create some dummy predictor columns and a binary target column. For this example, let's assume the dummy predictor columns represent rules that have been applied to a dataset.",
"_____no_output_____"
]
],
[
[
"np.random.seed(0)\n\ny_pred_ks = ks.Series(np.random.randint(0, 2, 1000), name = 'A')\ny_preds_ks = ks.DataFrame(np.random.randint(0, 2, (1000, 5)), columns=[i for i in 'ABCDE'])\ny_ks = ks.Series(np.random.randint(0, 2, 1000), name = 'label')\namounts_ks = ks.Series(np.random.randint(0, 1000, 1000), name = 'amounts')",
"21/12/06 12:03:25 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable\nUsing Spark's default log4j profile: org/apache/spark/log4j-defaults.properties\nSetting default log level to \"WARN\".\nTo adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).\n21/12/06 12:03:26 WARN Utils: Service 'SparkUI' could not bind on port 4040. Attempting port 4041.\n21/12/06 12:03:26 WARN Utils: Service 'SparkUI' could not bind on port 4041. Attempting port 4042.\n21/12/06 12:03:26 WARN Utils: Service 'SparkUI' could not bind on port 4042. Attempting port 4043.\n"
]
],
[
[
"----",
"_____no_output_____"
],
[
"## Apply optimisation functions",
"_____no_output_____"
],
[
"There are currently four classification metrics available:\n\n* Precision score\n* Recall score\n* Fbeta score\n* Revenue\n\n**Note that the *FScore*, *Precision* or *Recall* classes are ~100 times faster on larger datasets compared to the same functions from Sklearn's *metrics* module. They also work with Koalas DataFrames, whereas the Sklearn functions do not.**",
"_____no_output_____"
],
[
"### Instantiate class and run fit method",
"_____no_output_____"
],
[
"We can run the `fit` method to calculate the optimisation metric for each column in the dataset.",
"_____no_output_____"
],
[
"#### Precision score",
"_____no_output_____"
]
],
[
[
"precision = Precision()\n# Single predictor\nrule_precision_ks = precision.fit(y_preds=y_pred_ks, y_true=y_ks, sample_weight=None)\n# Multiple predictors\nrule_precisions_ks = precision.fit(y_preds=y_preds_ks, y_true=y_ks, sample_weight=None)",
""
]
],
[
[
"#### Recall score",
"_____no_output_____"
]
],
[
[
"recall = Recall()\n# Single predictor\nrule_recall_ks = recall.fit(y_preds=y_pred_ks, y_true=y_ks, sample_weight=None)\n# Multiple predictors\nrule_recalls_ks = recall.fit(y_preds=y_preds_ks, y_true=y_ks, sample_weight=None)",
"_____no_output_____"
]
],
[
[
"#### Fbeta score (beta=1)",
"_____no_output_____"
]
],
[
[
"f1 = FScore(beta=1)\n# Single predictor)\nrule_f1_ks = f1.fit(y_preds=y_pred_ks, y_true=y_ks, sample_weight=None)\n# Multiple predictors)\nrule_f1s_ks = f1.fit(y_preds=y_preds_ks, y_true=y_ks, sample_weight=None)",
"_____no_output_____"
]
],
[
[
"#### Revenue",
"_____no_output_____"
]
],
[
[
"rev = Revenue(y_type='Fraud', chargeback_multiplier=2)\n# Single predictor\nrule_rev_ks = rev.fit(y_preds=y_pred_ks, y_true=y_ks, sample_weight=amounts_ks)\n# Multiple predictors\nrule_revs_ks = rev.fit(y_preds=y_preds_ks, y_true=y_ks, sample_weight=amounts_ks)",
""
]
],
[
[
"### Outputs",
"_____no_output_____"
],
[
"The `fit` method returns the optimisation metric defined by the class:",
"_____no_output_____"
]
],
[
[
"rule_precision_ks, rule_precisions_ks",
"_____no_output_____"
],
[
"rule_recall_ks, rule_recalls_ks",
"_____no_output_____"
],
[
"rule_f1_ks, rule_f1s_ks",
"_____no_output_____"
],
[
"rule_rev_ks, rule_revs_ks",
"_____no_output_____"
]
],
[
[
"The `fit` method can be fed into various Iguanas modules as an argument (wherever the `metric` parameter appears). For example, in the RuleGeneratorOpt module, you can set the metric used to optimise the rules using this methodology.",
"_____no_output_____"
],
[
"----",
"_____no_output_____"
],
[
"## Creating your own optimisation function",
"_____no_output_____"
],
[
"Say we want to create a class which calculates the Positive likelihood ratio (TP rate/FP rate).",
"_____no_output_____"
],
[
"The main class structure involves having a `fit` method which has three arguments - the binary predictor(s), the binary target and any event specific weights to apply. This method should return a single numeric value.",
"_____no_output_____"
]
],
[
[
"class PositiveLikelihoodRatio:\n \n def fit(self, \n y_preds: Union[ks.Series, ks.DataFrame], \n y_true: ks.Series, \n sample_weight: ks.Series) -> float:\n \n def _calc_plr(y_true, y_preds):\n # Calculate TPR\n tpr = (y_true * y_preds).sum() / y_true.sum()\n # Calculate FPR\n fpr = ((1 - y_true) * y_preds).sum()/(1 - y_true).sum()\n return 0 if tpr == 0 or fpr == 0 else tpr/fpr\n \n # Set this option to allow calc of TPR/FPR on Koalas dataframes\n with ks.option_context(\"compute.ops_on_diff_frames\", True):\n if y_preds.ndim == 1: \n return _calc_plr(y_true, y_preds)\n else:\n plrs = np.empty(y_preds.shape[1])\n for i, col in enumerate(y_preds.columns): \n plrs[i] = _calc_plr(y_true, y_preds[col])\n return plrs",
"_____no_output_____"
]
],
[
[
"We can then apply the `fit` method to the dataset to check it works:",
"_____no_output_____"
]
],
[
[
"plr = PositiveLikelihoodRatio()\n# Single predictor\nrule_plr_ks = plr.fit(y_preds=y_pred_ks, y_true=y_ks, sample_weight=None)\n# Multiple predictors\nrule_plrs_ks = plr.fit(y_preds=y_preds_ks, y_true=y_ks, sample_weight=None)",
""
],
[
"rule_plr_ks, rule_plrs_ks",
"_____no_output_____"
]
],
[
[
"Finally, after instantiating the class, we can feed the `fit` method to a relevant Iguanas module (for example, we can feed the `fit` method to the `metric` parameter in the `BayesianOptimiser` class so that rules are generated which maximise the Positive Likelihood Ratio).",
"_____no_output_____"
],
[
"----",
"_____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",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
4ac4dea6f2a5542f299f43e76246574de6198334
| 5,878 |
ipynb
|
Jupyter Notebook
|
notebooks/WebProduct.ipynb
|
hschovanec-usgs/finite-fault-product
|
6f75542616979768e3a2748021a30ad7d281345f
|
[
"CC0-1.0"
] | 4 |
2019-08-22T02:19:43.000Z
|
2021-11-11T14:20:18.000Z
|
notebooks/WebProduct.ipynb
|
hschovanec-usgs/finite-fault-product
|
6f75542616979768e3a2748021a30ad7d281345f
|
[
"CC0-1.0"
] | 20 |
2018-07-02T14:10:52.000Z
|
2018-09-20T20:44:28.000Z
|
notebooks/WebProduct.ipynb
|
hschovanec-usgs/finite-fault-product
|
6f75542616979768e3a2748021a30ad7d281345f
|
[
"CC0-1.0"
] | 5 |
2018-10-02T20:43:21.000Z
|
2019-09-09T03:38:36.000Z
| 29.686869 | 502 | 0.549337 |
[
[
[
"# stdlib imports\nimport json\nimport os\nimport warnings\n\n# Third party imports\nfrom lxml import etree\nimport matplotlib.pyplot as plt \nimport numpy as np\nimport shapely\n\n# Local imports\nfrom product.web_product import WebProduct\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"# fromDirectory\nCreating an instance of WebProduct using formDirectory will gather the timeseries and fault information. The information about download files (filenames, titles, file types, etc.) will be gathered automaticaly unless otherwise specified. Files named timeseries.json, FMM.geojson, and comments.json are written automatically from the original directory. These can be edited before being sent as a product. Consistency of file name conventions can be validated by passing eventid as an argument.\n\n### Note: this assumes only one ffm per event",
"_____no_output_____"
]
],
[
[
"directory = '../tests/data/products/1000dyad'\nproduct = WebProduct.fromDirectory(directory, '1000dyad') ",
"_____no_output_____"
]
],
[
[
"## Event information\nThe event information is contained within a dictionary:",
"_____no_output_____"
]
],
[
[
"for key in sorted(product.event):\n print(key, product.event[key])",
"date 2018-05-04 00:00:00\ndepth 8.0\ndip 20.0\ndx 4.0\ndz 2.5\nhtop 4.15\nlat 19.37\nlocation HAWAII\nlon -155.03\nmag 6.88\nmoment 2.7660745e+19\nrake 114.0\nstrike 240.0\n"
]
],
[
[
"## Segment information\nSegments are provided as a list of dictionaries with the following properties:",
"_____no_output_____"
]
],
[
[
"for prop in sorted(product.segments)[0].items():\n print(prop[0], ': ', type(prop[1]))",
"lat : <class 'numpy.ndarray'>\nstrike : <class 'float'>\nrise : <class 'numpy.ndarray'>\nlength : <class 'float'>\ntrup : <class 'numpy.ndarray'>\ndip : <class 'float'>\nrake : <class 'numpy.ndarray'>\ny==ns : <class 'numpy.ndarray'>\ndepth : <class 'numpy.ndarray'>\nsf_moment : <class 'numpy.ndarray'>\nlon : <class 'numpy.ndarray'>\nx==ew : <class 'numpy.ndarray'>\nwidth : <class 'float'>\nslip : <class 'numpy.ndarray'>\n"
]
],
[
[
"## Contents.xml\n",
"_____no_output_____"
]
],
[
[
"product.createContents(directory)\nprint(etree.tostring(product.contents ,pretty_print=True).decode())",
"<contents>\n <file id=\"modelmaps\" title=\"Finite Fault Model Maps \">\n <caption><![CDATA[Map representation of the finite fault model ]]></caption>\n <format href=\"FFM.geojson\" type=\"text/plain\"/>\n <format href=\"finite_fault.kml\" type=\"application/vnd.google-earth.kml+xml\"/>\n <format href=\"finite_fault.kmz\" type=\"application/vnd.google-earth.kmz\"/>\n <format href=\"basemap.png\" type=\"image/png\"/>\n </file>\n <file id=\"waveplots\" title=\"Wave Plots \">\n <caption><![CDATA[Body and surface wave plots ]]></caption>\n <format href=\"waveplots.zip\" type=\"application/zip\"/>\n </file>\n <file id=\"inpfiles\" title=\"Inversion Parameters \">\n <caption><![CDATA[Files of inversion parameters for the finite fault ]]></caption>\n <format href=\"basic_inversion.param\" type=\"text/plain\"/>\n <format href=\"complete_inversion.fsp\" type=\"text/plain\"/>\n </file>\n <file id=\"coulomb\" title=\"Coulomb Input File \">\n <caption><![CDATA[Format necessary for compatibility with Coulomb3 (http://earthquake.usgs.gov/research/software/coulomb/) ]]></caption>\n <format href=\"coulomb.inp\" type=\"text/plain\"/>\n </file>\n <file id=\"momentrate\" title=\"Moment Rate Function Files \">\n <caption><![CDATA[Files of time vs. moment rate for source time functions ]]></caption>\n <format href=\"moment_rate.mr\" type=\"text/plain\"/>\n <format href=\"moment_rate.png\" type=\"image/png\"/>\n </file>\n</contents>\n\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac4e456bb31c252d0d33fac5cd4c10a5a494a69
| 1,023,207 |
ipynb
|
Jupyter Notebook
|
Detection of Object in Underwater Images by Detecting Edges/project codes/Image Processing - Term Project - Template Matching.ipynb
|
kerimmstfdemir/ITU_Image-Processing-Term-Project
|
ba55a1c0e45ea6e6bff4d4589d1c58e9f1310126
|
[
"MIT"
] | null | null | null |
Detection of Object in Underwater Images by Detecting Edges/project codes/Image Processing - Term Project - Template Matching.ipynb
|
kerimmstfdemir/ITU_Image-Processing-Term-Project
|
ba55a1c0e45ea6e6bff4d4589d1c58e9f1310126
|
[
"MIT"
] | null | null | null |
Detection of Object in Underwater Images by Detecting Edges/project codes/Image Processing - Term Project - Template Matching.ipynb
|
kerimmstfdemir/ITU_Image-Processing-Term-Project
|
ba55a1c0e45ea6e6bff4d4589d1c58e9f1310126
|
[
"MIT"
] | null | null | null | 1,208.0366 | 354,500 | 0.959821 |
[
[
[
"# Template Matching",
"_____no_output_____"
],
[
"### Full Image",
"_____no_output_____"
]
],
[
[
"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"full = cv2.imread('../images/diver_enhanced.jpg')\nfull = cv2.cvtColor(full, cv2.COLOR_BGR2RGB)",
"_____no_output_____"
],
[
"plt.imshow(full)",
"_____no_output_____"
]
],
[
[
"### Template Image",
"_____no_output_____"
]
],
[
[
"face= cv2.imread('../images/dolphin_template.jpg')\nface = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)",
"_____no_output_____"
],
[
"plt.imshow(face)",
"_____no_output_____"
]
],
[
[
"# Template Matching Methods\n\nMake sure to watch the video for an explanation of the different methods!",
"_____no_output_____"
],
[
"-------\n-------",
"_____no_output_____"
],
[
"**Quick Note on **eval()** function in case you haven't seen it before!**",
"_____no_output_____"
]
],
[
[
"sum([1,2,3])",
"_____no_output_____"
],
[
"mystring = 'sum'",
"_____no_output_____"
],
[
"eval(mystring)",
"_____no_output_____"
],
[
"myfunc = eval(mystring)",
"_____no_output_____"
],
[
"myfunc([1,2,3])",
"_____no_output_____"
]
],
[
[
"--------\n--------",
"_____no_output_____"
]
],
[
[
"height, width,channels = face.shape",
"_____no_output_____"
],
[
"width",
"_____no_output_____"
],
[
"height",
"_____no_output_____"
],
[
"# The Full Image to Search\nfull = cv2.imread('../images/diver_enhanced.jpg')\nfull = cv2.cvtColor(full, cv2.COLOR_BGR2RGB)\n\n\n# The Template to Match\nface= cv2.imread('../images/dolphin_template.jpg')\nface = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)\n\n\n# All the 6 methods for comparison in a list\n# Note how we are using strings, later on we'll use the eval() function to convert to function\nmethods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR','cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']",
"_____no_output_____"
],
[
"m = 'cv2.TM_CCORR_NORMED'\n\n# Create a copy of the image\nfull_copy = full.copy()\n \n# Get the actual function instead of the string\nmethod = eval(m)\n\n# Apply template Matching with the method\nres = cv2.matchTemplate(full_copy,face,method)\n \n# Grab the Max and Min values, plus their locations\nmin_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n \n# Set up drawing of Rectangle\n \n# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum\n# Notice the coloring on the last 2 left hand side images.\nif method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:\n top_left = min_loc \nelse:\n top_left = max_loc\n \n# Assign the Bottom Right of the rectangle\nbottom_right = (top_left[0] + width, top_left[1] + height)\n\n# Draw the Red Rectangle\ncv2.rectangle(full_copy,top_left, bottom_right, 255, 10)\n\n# Plot the Images\nfig = plt.figure(figsize=(18,18))\n\nax1 = fig.add_subplot(121)\nplt.imshow(res)\nplt.title('Result of Template Matching')\n \nax1 = fig.add_subplot(122)\nplt.imshow(full_copy)\nplt.title('Detected Point')\nplt.suptitle(m)\n \nplt.show() ",
"_____no_output_____"
],
[
"plt.imshow(full_copy)",
"_____no_output_____"
],
[
"full_copy = cv2.cvtColor(full_copy, cv2.COLOR_RGB2BGR)\ncv2.imwrite('../images/diver_dolphin_bounding_box.jpg', full_copy)",
"_____no_output_____"
],
[
"full = cv2.imread('../images/dolphin.jpg')\nfull = cv2.cvtColor(full, cv2.COLOR_BGR2RGB)",
"_____no_output_____"
],
[
"plt.imshow(full)",
"_____no_output_____"
]
],
[
[
"### Template Image",
"_____no_output_____"
]
],
[
[
"face= cv2.imread('../images/dolphin_template.jpg')\nface = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)",
"_____no_output_____"
],
[
"plt.imshow(face)",
"_____no_output_____"
]
],
[
[
"# Template Matching Methods\n\nMake sure to watch the video for an explanation of the different methods!",
"_____no_output_____"
],
[
"-------\n-------",
"_____no_output_____"
],
[
"**Quick Note on **eval()** function in case you haven't seen it before!**",
"_____no_output_____"
]
],
[
[
"sum([1,2,3])",
"_____no_output_____"
],
[
"mystring = 'sum'",
"_____no_output_____"
],
[
"eval(mystring)",
"_____no_output_____"
],
[
"myfunc = eval(mystring)",
"_____no_output_____"
],
[
"myfunc([1,2,3])",
"_____no_output_____"
]
],
[
[
"--------\n--------",
"_____no_output_____"
]
],
[
[
"width",
"_____no_output_____"
],
[
"height",
"_____no_output_____"
],
[
"# The Full Image to Search\nfull = cv2.imread('../images/dolphin.jpg')\nfull = cv2.cvtColor(full, cv2.COLOR_BGR2RGB)\n\n\n# The Template to Match\nface= cv2.imread('../images/dolphin_template.jpg')\nface = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)\n\n\n# All the 6 methods for comparison in a list\n# Note how we are using strings, later on we'll use the eval() function to convert to function\nmethods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR','cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']",
"_____no_output_____"
],
[
"height, width,channels = face.shape",
"_____no_output_____"
],
[
"m = 'cv2.TM_CCORR_NORMED'\n\n# Create a copy of the image\nfull_copy = full.copy()\n \n# Get the actual function instead of the string\nmethod = eval(m)\n\n# Apply template Matching with the method\nres = cv2.matchTemplate(full_copy,face,method)\n \n# Grab the Max and Min values, plus their locations\nmin_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n \n# Set up drawing of Rectangle\n \n# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum\n# Notice the coloring on the last 2 left hand side images.\nif method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:\n top_left = min_loc \nelse:\n top_left = max_loc\n \n# Assign the Bottom Right of the rectangle\nbottom_right = (top_left[0] + width, top_left[1] + height)\n\n# Draw the Red Rectangle\ncv2.rectangle(full_copy,top_left, bottom_right, 255, 10)\n\n# Plot the Images\nfig = plt.figure(figsize=(18,18))\n\nax1 = fig.add_subplot(121)\nplt.imshow(res)\nplt.title('Result of Template Matching')\n \nax1 = fig.add_subplot(122)\nplt.imshow(full_copy)\nplt.title('Detected Point')\nplt.suptitle(m)\n \nplt.show() ",
"_____no_output_____"
],
[
"plt.imshow(full_copy)",
"_____no_output_____"
],
[
"full_copy = cv2.cvtColor(full_copy, cv2.COLOR_RGB2BGR)\ncv2.imwrite('../images/diver_dolphin_bounding_box.jpg', full_copy)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac4ea166400370ec6419487f7bf6feb8f90aa00
| 11,997 |
ipynb
|
Jupyter Notebook
|
Chapter 12 - Taking TensorFlow to Production/Using multiple executors.ipynb
|
Young-Picasso/TensorFlow2.x_Cookbook
|
8a2126108f576992b89c1087e6de399a4d54437b
|
[
"MIT"
] | null | null | null |
Chapter 12 - Taking TensorFlow to Production/Using multiple executors.ipynb
|
Young-Picasso/TensorFlow2.x_Cookbook
|
8a2126108f576992b89c1087e6de399a4d54437b
|
[
"MIT"
] | null | null | null |
Chapter 12 - Taking TensorFlow to Production/Using multiple executors.ipynb
|
Young-Picasso/TensorFlow2.x_Cookbook
|
8a2126108f576992b89c1087e6de399a4d54437b
|
[
"MIT"
] | null | null | null | 35.81194 | 418 | 0.602234 |
[
[
[
"Many features of TensorFlow including their computational graphs lend themselves naturally to being computed in parallel. Computational graphs can be split over different processors as well as in processing different batches. This recipe demonstrates how to access different processors on the same machine.",
"_____no_output_____"
],
[
"## Getting ready...",
"_____no_output_____"
],
[
"In this recipe, we will explore different commands that will allow one to access various devices on their system. The recipe will also demonstrate how to find out which devices TensorFlow is using.",
"_____no_output_____"
],
[
"## How to do it...",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\ntf.debugging.set_log_device_placement(True)",
"_____no_output_____"
]
],
[
[
"1. To find out which devices TensorFlow is using for operations, we will activates the logs for device placement by setting tf.debugging.set_log_device_placement to True. If a TensorFlow operation is implemented for CPU and GPU devices, the operation will be executed by default on a GPU device if a GPU is available:",
"_____no_output_____"
]
],
[
[
"tf.debugging.set_log_device_placement(True)\n\na = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')\nb = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')\nc = tf.matmul(a, b)",
"Executing op _EagerConst in device /job:localhost/replica:0/task:0/device:GPU:0\nExecuting op _EagerConst in device /job:localhost/replica:0/task:0/device:GPU:0\nExecuting op Reshape in device /job:localhost/replica:0/task:0/device:GPU:0\nExecuting op _EagerConst in device /job:localhost/replica:0/task:0/device:GPU:0\nExecuting op _EagerConst in device /job:localhost/replica:0/task:0/device:GPU:0\nExecuting op Reshape in device /job:localhost/replica:0/task:0/device:GPU:0\nExecuting op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0\n"
]
],
[
[
"2. It is also possible to use the tensor device attribute that returns the name of the device on which this tensor will be assigned:",
"_____no_output_____"
]
],
[
[
"a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')\nprint(a.device)\nb = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')\nprint(b.device)",
"Executing op _EagerConst in device /job:localhost/replica:0/task:0/device:GPU:0\nExecuting op _EagerConst in device /job:localhost/replica:0/task:0/device:GPU:0\nExecuting op Reshape in device /job:localhost/replica:0/task:0/device:GPU:0\n/job:localhost/replica:0/task:0/device:GPU:0\nExecuting op _EagerConst in device /job:localhost/replica:0/task:0/device:GPU:0\nExecuting op _EagerConst in device /job:localhost/replica:0/task:0/device:GPU:0\nExecuting op Reshape in device /job:localhost/replica:0/task:0/device:GPU:0\n/job:localhost/replica:0/task:0/device:GPU:0\n"
]
],
[
[
"3. By default, TensorFlow automatically decides how to distribute computation across computing devices (CPUs and GPUs). Sometimes we need to select the device to use by creating a device context with the tf.device function. Each operation executed in this context will use the selected device:",
"_____no_output_____"
]
],
[
[
"tf.debugging.set_log_device_placement(True)\nwith tf.device('/device:CPU:0'):\n a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')\n b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')\n c = tf.matmul(a, b)",
"Executing op Reshape in device /job:localhost/replica:0/task:0/device:CPU:0\nExecuting op Reshape in device /job:localhost/replica:0/task:0/device:CPU:0\nExecuting op MatMul in device /job:localhost/replica:0/task:0/device:CPU:0\n"
]
],
[
[
"4. If we move the matmul opeartion out of the context, this operation will be executed on a GPU device if it's available:",
"_____no_output_____"
]
],
[
[
"tf.debugging.set_log_device_placement(True)\nwith tf.device('/device:CPU:0'):\n a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')\n b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')\nc = tf.matmul(a, b)",
"Executing op Reshape in device /job:localhost/replica:0/task:0/device:CPU:0\nExecuting op Reshape in device /job:localhost/replica:0/task:0/device:CPU:0\nExecuting op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0\n"
]
],
[
[
"5. When using GPUs, TensorFlow automatically takes up a large portion of the GPU memory. While this is usually desired, we can take steps to be more careful with GPU memory allocation. While TensorFlow never releases GPU memory, we can slowly grow its allocation to the maximum limit (only when needed) by setting a GPU memory growth option. Note that physical devices cannot be modified after being initialized:",
"_____no_output_____"
]
],
[
[
"gpu_devices = tf.config.list_physical_devices('GPU')\nif gpu_devices:\n try:\n tf.config.experimental.set_memory_growth(gpu_devices[0], True)\n except RuntimeError as e:\n # Memory growth cannot be modififed after GPU has been initialized\n print(e)",
"_____no_output_____"
]
],
[
[
"6. If we desire to limit the GPU memory used by TensorFlow, we can also create a virtual GPU device and set the maximum memory limit (in MB) to allocate on this virtual GPU. Note that virtual GPU devices cannot be modififed after being initialized:",
"_____no_output_____"
]
],
[
[
"gpu_devices = tf.config.list_physical_devices('GPU')\nif gpu_devices:\n try:\n tf.config.experimental.set_virtual_device_configuration(gpu_devices[0], \n [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)])\n except RuntimeError as e:\n # Virtual devices cannot be modified after being initialized\n print(e)",
"_____no_output_____"
]
],
[
[
"7. It is also possible to simulate virtual GPU devices with a single physical GPU:",
"_____no_output_____"
]
],
[
[
"gpu_devices = tf.config.list_physical_devices('GPU')\nif gpu_devices:\n try:\n tf.config.experimental.set_virtual_device_configuration(gpu_devices[0],\n [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024),\n tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)])\n except RuntimeError as e:\n print(e)",
"_____no_output_____"
]
],
[
[
"8. Sometimes we need to write robust code that can determine whether it is running with the GPU available or not. TensorFlow has a built-in function that can test whether the GPU is available. This is helpful when we want to write code that takes advantage of the GPU when it is available and assign specific operations to it. This is done with the following code:",
"_____no_output_____"
]
],
[
[
"if tf.test.is_built_with_cuda():\n # Run GPU specific code here\n pass",
"_____no_output_____"
]
],
[
[
"9. If we have to assign specific operations to certain devices, we can use the following code. This will perform simple calculations and assign operations to the main CPU and two auxiliary GPUs:",
"_____no_output_____"
]
],
[
[
"print(\"Num GPUs Available: \", len(tf.config.list_logical_devices('GPU')))\n\nif tf.test.is_built_with_cuda():\n with tf.device('/cpu:0'):\n a = tf.constant([1.0, 3.0, 5.0], shape = [1, 3])\n b = tf.constant([2.0, 4.0, 6.0], shape = [3, 1])\n \n with tf.device('/gpu:0'):\n c = tf.matmul(a, b)\n c = tf.reshape(c, [-1])\n \n with tf.device('/gpu:1'):\n d = tf.matmul(b, a)\n flat_d = tf.reshape(d, [-1])\n \n combined = tf.multiply(c, flat_d)\n print(combined)",
"Num GPUs Available: 2\nExecuting op Reshape in device /job:localhost/replica:0/task:0/device:CPU:0\nExecuting op Reshape in device /job:localhost/replica:0/task:0/device:CPU:0\nExecuting op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0\nExecuting op _EagerConst in device /job:localhost/replica:0/task:0/device:GPU:0\nExecuting op Reshape in device /job:localhost/replica:0/task:0/device:GPU:0\nExecuting op MatMul in device /job:localhost/replica:0/task:0/device:GPU:1\nExecuting op _EagerConst in device /job:localhost/replica:0/task:0/device:GPU:1\nExecuting op Reshape in device /job:localhost/replica:0/task:0/device:GPU:1\nExecuting op Mul in device /job:localhost/replica:0/task:0/device:CPU:0\ntf.Tensor([ 88. 264. 440. 176. 528. 880. 264. 792. 1320.], shape=(9,), dtype=float32)\n"
]
],
[
[
"We can see that the first two operations are performed on the main CPU, while the next two are one our first auxiliary GPU, and the last two on our second auxiliary GPU.",
"_____no_output_____"
]
]
] |
[
"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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4ac4ea1f343d0af7f2aec2e264ee2672f7eb9727
| 703 |
ipynb
|
Jupyter Notebook
|
downloaded_kernels/loan_data/kernel_103.ipynb
|
josepablocam/common-code-extraction
|
a6978fae73eee8ece6f1db09f2f38cf92f03b3ad
|
[
"MIT"
] | null | null | null |
downloaded_kernels/loan_data/kernel_103.ipynb
|
josepablocam/common-code-extraction
|
a6978fae73eee8ece6f1db09f2f38cf92f03b3ad
|
[
"MIT"
] | null | null | null |
downloaded_kernels/loan_data/kernel_103.ipynb
|
josepablocam/common-code-extraction
|
a6978fae73eee8ece6f1db09f2f38cf92f03b3ad
|
[
"MIT"
] | 2 |
2021-07-12T00:48:08.000Z
|
2021-08-11T12:53:05.000Z
| 63.909091 | 446 | 0.687055 |
[
[
[
"%matplotlib inline\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# set seaborn style\nsns.set_style(\"ticks\")\n\n# read in data\ndata_raw = pd.read_csv(\"../input/loan.csv\")\ndata_raw.head(n = 25)\ndata_raw.shape\n\n# initial plots\nsns.distplot(data_raw['loan_amnt']);\nsns.distplot(data_raw['funded_amnt'])\nsns.jointplot(x = 'loan_amnt', y = 'funded_amnt', data = data_raw)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
4ac4ea72fcac39a42fc5449ba35321e2d455a195
| 1,787 |
ipynb
|
Jupyter Notebook
|
notebooks/overfitting.ipynb
|
robdefeo/mlpk
|
b8d8f255aec87b8a2cfc5366951a012887e29b3a
|
[
"Unlicense"
] | null | null | null |
notebooks/overfitting.ipynb
|
robdefeo/mlpk
|
b8d8f255aec87b8a2cfc5366951a012887e29b3a
|
[
"Unlicense"
] | null | null | null |
notebooks/overfitting.ipynb
|
robdefeo/mlpk
|
b8d8f255aec87b8a2cfc5366951a012887e29b3a
|
[
"Unlicense"
] | null | null | null | 52.558824 | 267 | 0.686626 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4ac4ea77015c84d92b427a80104725fc912b7286
| 63,986 |
ipynb
|
Jupyter Notebook
|
section_uncertainty/noise_simulation9.ipynb
|
haritaku/LNPR_BOOK_CODES
|
612c8c52812129aafc2e433056c7a93df78d2831
|
[
"MIT"
] | null | null | null |
section_uncertainty/noise_simulation9.ipynb
|
haritaku/LNPR_BOOK_CODES
|
612c8c52812129aafc2e433056c7a93df78d2831
|
[
"MIT"
] | null | null | null |
section_uncertainty/noise_simulation9.ipynb
|
haritaku/LNPR_BOOK_CODES
|
612c8c52812129aafc2e433056c7a93df78d2831
|
[
"MIT"
] | null | null | null | 62.731373 | 20,923 | 0.638593 |
[
[
[
"import sys\n\nsys.path.append(\"../scripts/\")\nfrom ideal_robot import *\nfrom scipy.stats import expon, norm, uniform",
"_____no_output_____"
],
[
"class Robot(IdealRobot):\n def __init__(\n self,\n pose,\n agent=None,\n sensor=None,\n color=\"black\",\n noise_per_meter=5,\n noise_std=math.pi / 60,\n bias_rate_stds=(0.1, 0.1),\n expected_stuck_time=1e100,\n expected_escape_time=1e-100,\n expected_kidnap_time=1e100,\n kidnap_range_x=(-5.0, 5.0),\n kidnap_range_y=(-5.0, 5.0),\n ): # 追加\n super().__init__(pose, agent, sensor, color)\n self.noise_pdf = expon(scale=1.0 / (1e-100 + noise_per_meter))\n self.distance_until_noise = self.noise_pdf.rvs()\n self.theta_noise = norm(scale=noise_std)\n self.bias_rate_nu = norm.rvs(loc=1.0, scale=bias_rate_stds[0])\n self.bias_rate_omega = norm.rvs(loc=1.0, scale=bias_rate_stds[1])\n\n self.stuck_pdf = expon(scale=expected_stuck_time)\n self.escape_pdf = expon(scale=expected_escape_time)\n self.is_stuck = False\n self.time_until_stuck = self.stuck_pdf.rvs()\n self.time_until_escape = self.escape_pdf.rvs()\n\n self.kidnap_pdf = expon(scale=expected_kidnap_time)\n self.time_until_kidnap = self.kidnap_pdf.rvs()\n rx, ry = kidnap_range_x, kidnap_range_y\n self.kidnap_dist = uniform(\n loc=(rx[0], ry[0], 0.0), scale=(rx[1] - rx[0], ry[1] - ry[0], 2 * math.pi)\n )\n\n def noise(self, pose, nu, omega, time_interval):\n self.distance_until_noise -= (\n abs(nu) * time_interval + self.r * omega * time_interval\n )\n if self.distance_until_noise <= 0.0:\n self.distance_until_noise += self.noise_pdf.rvs()\n pose[2] += self.theta_noise.rvs()\n\n return pose\n\n def bias(self, nu, omega):\n return nu * self.bias_rate_nu, omega * self.bias_rate_omega\n\n def stuck(self, nu, omega, time_interval):\n if self.is_stuck:\n self.time_until_escape -= time_interval\n if self.time_until_escape <= 0.0:\n self.time_until_escape += self.escape_pdf.rvs()\n self.is_stuck = False\n else:\n self.time_until_stuck -= time_interval\n if self.time_until_stuck <= 0.0:\n self.time_until_stuck += self.stuck_pdf.rvs()\n self.is_stuck = True\n\n return nu * (not self.is_stuck), omega * (not self.is_stuck)\n\n def kidnap(self, pose, time_interval):\n self.time_until_kidnap -= time_interval\n if self.time_until_kidnap <= 0.0:\n self.time_until_kidnap += self.kidnap_pdf.rvs()\n return np.array(self.kidnap_dist.rvs()).T\n else:\n return pose\n\n def one_step(self, time_interval):\n if not self.agent:\n return\n obs = self.sensor.data(self.pose) if self.sensor else None\n nu, omega = self.agent.decision(obs)\n nu, omega = self.bias(nu, omega)\n nu, omega = self.stuck(nu, omega, time_interval)\n self.pose = self.state_transition(nu, omega, time_interval, self.pose)\n self.pose = self.noise(self.pose, nu, omega, time_interval)\n self.pose = self.kidnap(self.pose, time_interval)",
"_____no_output_____"
],
[
"class Camera(IdealCamera): ###camera_fourth### (noise,biasは省略)\n def __init__(\n self,\n env_map,\n distance_range=(0.5, 6.0),\n direction_range=(-math.pi / 3, math.pi / 3),\n distance_noise_rate=0.1,\n direction_noise=math.pi / 90,\n distance_bias_rate_stddev=0.1,\n direction_bias_stddev=math.pi / 90,\n phantom_prob=0.0,\n phantom_range_x=(-5.0, 5.0),\n phantom_range_y=(-5.0, 5.0),\n ): # 追加\n super().__init__(env_map, distance_range, direction_range)\n\n self.distance_noise_rate = distance_noise_rate\n self.direction_noise = direction_noise\n self.distance_bias_rate_std = norm.rvs(scale=distance_bias_rate_stddev)\n self.direction_bias = norm.rvs(scale=direction_bias_stddev)\n\n rx, ry = phantom_range_x, phantom_range_y # 以下追加\n self.phantom_dist = uniform(\n loc=(rx[0], ry[0]), scale=(rx[1] - rx[0], ry[1] - ry[0])\n )\n self.phantom_prob = phantom_prob\n\n def noise(self, relpos):\n ell = norm.rvs(loc=relpos[0], scale=relpos[0] * self.distance_noise_rate)\n phi = norm.rvs(loc=relpos[1], scale=self.direction_noise)\n return np.array([ell, phi]).T\n\n def bias(self, relpos):\n return (\n relpos\n + np.array([relpos[0] * self.distance_bias_rate_std, self.direction_bias]).T\n )\n\n def phantom(self, cam_pose, relpos): # 追加\n if uniform.rvs() < self.phantom_prob:\n pos = np.array(self.phantom_dist.rvs()).T\n return self.observation_function(cam_pose, pos)\n else:\n return relpos\n\n def data(self, cam_pose):\n observed = []\n for lm in self.map.landmarks:\n z = self.observation_function(cam_pose, lm.pos)\n z = self.phantom(cam_pose, z) # 追加\n if self.visible(z):\n z = self.bias(z)\n z = self.noise(z)\n observed.append((z, lm.id))\n\n self.lastdata = observed\n return observed",
"_____no_output_____"
],
[
"world = World(30, 0.1)\n\n### 地図を生成して3つランドマークを追加 ###\nm = Map()\nm.append_landmark(Landmark(-4, 2))\nm.append_landmark(Landmark(2, -3))\nm.append_landmark(Landmark(3, 3))\nworld.append(m)\n\n### ロボットを作る ###\nstraight = Agent(0.2, 0.0)\ncircling = Agent(0.2, 10.0 / 180 * math.pi)\nr = Robot(\n np.array([0, 0, math.pi / 6]).T, sensor=Camera(m, phantom_prob=0.5), agent=circling\n)\nworld.append(r)\n\n### アニメーション実行 ###\nworld.draw()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
4ac4ea9c05684d60c2d3f9c973e70cc44b827baf
| 39,431 |
ipynb
|
Jupyter Notebook
|
Section-12-Optuna/01-Search-algorithms.ipynb
|
ankitario/hyperparameter-optimization
|
0dfb1abbe883a64352eafd2ca433ec8770051b2a
|
[
"BSD-3-Clause"
] | 34 |
2021-05-05T09:29:23.000Z
|
2022-03-05T03:16:09.000Z
|
Section-12-Optuna/01-Search-algorithms.ipynb
|
GLASSY-GAIA/ML_Hyperparameter_Optimization_Python
|
2e1b8478c9cd68404c3b415d45748eb5e09fe6c9
|
[
"BSD-3-Clause"
] | null | null | null |
Section-12-Optuna/01-Search-algorithms.ipynb
|
GLASSY-GAIA/ML_Hyperparameter_Optimization_Python
|
2e1b8478c9cd68404c3b415d45748eb5e09fe6c9
|
[
"BSD-3-Clause"
] | 57 |
2021-05-07T10:54:43.000Z
|
2022-03-31T13:05:37.000Z
| 43.9098 | 478 | 0.555248 |
[
[
[
"## Search algorithms within Optuna\n\nIn this notebook, I will demo how to select the search algorithm with Optuna. We will compare the use of:\n\n- Grid Search \n- Randomized search\n- Tree-structured Parzen Estimators\n- CMA-ES\n\n\nWe can select the search algorithm from the [optuna.study.create_study()](https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.create_study.html#optuna.study.create_study) class.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.metrics import accuracy_score, roc_auc_score\nfrom sklearn.model_selection import cross_val_score, train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\n\nimport optuna",
"_____no_output_____"
],
[
"# load dataset\n\nbreast_cancer_X, breast_cancer_y = load_breast_cancer(return_X_y=True)\nX = pd.DataFrame(breast_cancer_X)\ny = pd.Series(breast_cancer_y).map({0:1, 1:0})\n\nX.head()",
"_____no_output_____"
],
[
"# the target:\n# percentage of benign (0) and malign tumors (1)\n\ny.value_counts() / len(y)",
"_____no_output_____"
],
[
"# split dataset into a train and test set\n\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.3, random_state=0)\n\nX_train.shape, X_test.shape",
"_____no_output_____"
]
],
[
[
"## Define the objective function\n\nThis is the hyperparameter response space, the function we want to minimize.",
"_____no_output_____"
]
],
[
[
"# the objective function takes the hyperparameter space\n# as input\n\ndef objective(trial):\n\n rf_n_estimators = trial.suggest_int(\"rf_n_estimators\", 100, 1000)\n rf_criterion = trial.suggest_categorical(\"rf_criterion\", ['gini', 'entropy'])\n rf_max_depth = trial.suggest_int(\"rf_max_depth\", 1, 4)\n rf_min_samples_split = trial.suggest_float(\"rf_min_samples_split\", 0.01, 1)\n \n model = RandomForestClassifier(\n n_estimators=rf_n_estimators,\n criterion=rf_criterion,\n max_depth=rf_max_depth,\n min_samples_split=rf_min_samples_split,\n )\n\n score = cross_val_score(model, X_train, y_train, cv=3)\n accuracy = score.mean()\n return accuracy",
"_____no_output_____"
]
],
[
[
"## Randomized Search\n\nRandomSampler()",
"_____no_output_____"
]
],
[
[
"study = optuna.create_study(\n direction=\"maximize\",\n sampler=optuna.samplers.RandomSampler(),\n)\n\n\nstudy.optimize(objective, n_trials=5)",
"\u001b[32m[I 2021-05-20 13:32:32,020]\u001b[0m A new study created in memory with name: no-name-4c05d223-a14c-42e4-8d41-4e85e52a2f1b\u001b[0m\n\u001b[32m[I 2021-05-20 13:32:36,656]\u001b[0m Trial 0 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 695, 'rf_criterion': 'entropy', 'rf_max_depth': 2, 'rf_min_samples_split': 0.8783579308131435}. Best is trial 0 with value: 0.6256360598465861.\u001b[0m\n\u001b[32m[I 2021-05-20 13:32:39,777]\u001b[0m Trial 1 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 605, 'rf_criterion': 'entropy', 'rf_max_depth': 1, 'rf_min_samples_split': 0.9699877119978241}. Best is trial 0 with value: 0.6256360598465861.\u001b[0m\n\u001b[32m[I 2021-05-20 13:32:42,322]\u001b[0m Trial 2 finished with value: 0.937210450368345 and parameters: {'rf_n_estimators': 424, 'rf_criterion': 'gini', 'rf_max_depth': 3, 'rf_min_samples_split': 0.10419683337955472}. Best is trial 2 with value: 0.937210450368345.\u001b[0m\n\u001b[32m[I 2021-05-20 13:32:43,359]\u001b[0m Trial 3 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 210, 'rf_criterion': 'gini', 'rf_max_depth': 3, 'rf_min_samples_split': 0.7475774305360292}. Best is trial 2 with value: 0.937210450368345.\u001b[0m\n\u001b[32m[I 2021-05-20 13:32:45,301]\u001b[0m Trial 4 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 445, 'rf_criterion': 'gini', 'rf_max_depth': 3, 'rf_min_samples_split': 0.8576211459466486}. Best is trial 2 with value: 0.937210450368345.\u001b[0m\n"
],
[
"study.best_params",
"_____no_output_____"
],
[
"study.best_value",
"_____no_output_____"
],
[
"study.trials_dataframe()",
"_____no_output_____"
]
],
[
[
"## TPE\n\nTPESampler is the default",
"_____no_output_____"
]
],
[
[
"study = optuna.create_study(\n direction=\"maximize\",\n sampler=optuna.samplers.TPESampler(),\n)\n\n\nstudy.optimize(objective, n_trials=5)",
"\u001b[32m[I 2021-05-20 13:32:45,354]\u001b[0m A new study created in memory with name: no-name-2f472476-1aa4-41b3-b983-9128993bfd6e\u001b[0m\n\u001b[32m[I 2021-05-20 13:32:46,964]\u001b[0m Trial 0 finished with value: 0.9171033644717855 and parameters: {'rf_n_estimators': 301, 'rf_criterion': 'entropy', 'rf_max_depth': 1, 'rf_min_samples_split': 0.14385722106431506}. Best is trial 0 with value: 0.9171033644717855.\u001b[0m\n\u001b[32m[I 2021-05-20 13:32:50,692]\u001b[0m Trial 1 finished with value: 0.9045720361509835 and parameters: {'rf_n_estimators': 743, 'rf_criterion': 'gini', 'rf_max_depth': 3, 'rf_min_samples_split': 0.6360216981020187}. Best is trial 0 with value: 0.9171033644717855.\u001b[0m\n\u001b[32m[I 2021-05-20 13:32:52,094]\u001b[0m Trial 2 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 287, 'rf_criterion': 'gini', 'rf_max_depth': 3, 'rf_min_samples_split': 0.7477125830084222}. Best is trial 0 with value: 0.9171033644717855.\u001b[0m\n\u001b[32m[I 2021-05-20 13:32:53,322]\u001b[0m Trial 3 finished with value: 0.9196286169970379 and parameters: {'rf_n_estimators': 258, 'rf_criterion': 'gini', 'rf_max_depth': 1, 'rf_min_samples_split': 0.02246294933654927}. Best is trial 3 with value: 0.9196286169970379.\u001b[0m\n\u001b[32m[I 2021-05-20 13:32:54,562]\u001b[0m Trial 4 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 304, 'rf_criterion': 'entropy', 'rf_max_depth': 3, 'rf_min_samples_split': 0.829546873408442}. Best is trial 3 with value: 0.9196286169970379.\u001b[0m\n"
],
[
"study.best_params",
"_____no_output_____"
],
[
"study.best_value",
"_____no_output_____"
]
],
[
[
"## CMA-ES\n\nCmaEsSampler",
"_____no_output_____"
]
],
[
[
"study = optuna.create_study(\n direction=\"maximize\",\n sampler=optuna.samplers.CmaEsSampler(),\n)\n\nstudy.optimize(objective, n_trials=5)",
"\u001b[32m[I 2021-05-20 13:32:54,590]\u001b[0m A new study created in memory with name: no-name-dc7be453-0f50-433f-892c-5c0a83309477\u001b[0m\n\u001b[32m[I 2021-05-20 13:32:56,816]\u001b[0m Trial 0 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 461, 'rf_criterion': 'entropy', 'rf_max_depth': 1, 'rf_min_samples_split': 0.8157876455065424}. Best is trial 0 with value: 0.6256360598465861.\u001b[0m\n\u001b[33m[W 2021-05-20 13:32:56,820]\u001b[0m The parameter 'rf_criterion' in trial#1 is sampled independently by using `RandomSampler` instead of `CmaEsSampler` (optimization performance may be degraded). `CmaEsSampler` does not support dynamic search space or `CategoricalDistribution`. You can suppress this warning by setting `warn_independent_sampling` to `False` in the constructor of `CmaEsSampler`, if this independent sampling is intended behavior.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:00,973]\u001b[0m Trial 1 finished with value: 0.9146160856687172 and parameters: {'rf_n_estimators': 550, 'rf_criterion': 'entropy', 'rf_max_depth': 2, 'rf_min_samples_split': 0.5703996078457617}. Best is trial 1 with value: 0.9146160856687172.\u001b[0m\n\u001b[33m[W 2021-05-20 13:33:00,975]\u001b[0m The parameter 'rf_criterion' in trial#2 is sampled independently by using `RandomSampler` instead of `CmaEsSampler` (optimization performance may be degraded). `CmaEsSampler` does not support dynamic search space or `CategoricalDistribution`. You can suppress this warning by setting `warn_independent_sampling` to `False` in the constructor of `CmaEsSampler`, if this independent sampling is intended behavior.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:03,841]\u001b[0m Trial 2 finished with value: 0.9171413381939697 and parameters: {'rf_n_estimators': 550, 'rf_criterion': 'gini', 'rf_max_depth': 2, 'rf_min_samples_split': 0.6104522707618539}. Best is trial 2 with value: 0.9171413381939697.\u001b[0m\n\u001b[33m[W 2021-05-20 13:33:03,844]\u001b[0m The parameter 'rf_criterion' in trial#3 is sampled independently by using `RandomSampler` instead of `CmaEsSampler` (optimization performance may be degraded). `CmaEsSampler` does not support dynamic search space or `CategoricalDistribution`. You can suppress this warning by setting `warn_independent_sampling` to `False` in the constructor of `CmaEsSampler`, if this independent sampling is intended behavior.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:06,381]\u001b[0m Trial 3 finished with value: 0.9196286169970379 and parameters: {'rf_n_estimators': 550, 'rf_criterion': 'gini', 'rf_max_depth': 3, 'rf_min_samples_split': 0.4943555698267044}. Best is trial 3 with value: 0.9196286169970379.\u001b[0m\n\u001b[33m[W 2021-05-20 13:33:06,384]\u001b[0m The parameter 'rf_criterion' in trial#4 is sampled independently by using `RandomSampler` instead of `CmaEsSampler` (optimization performance may be degraded). `CmaEsSampler` does not support dynamic search space or `CategoricalDistribution`. You can suppress this warning by setting `warn_independent_sampling` to `False` in the constructor of `CmaEsSampler`, if this independent sampling is intended behavior.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:09,698]\u001b[0m Trial 4 finished with value: 0.9321219715956558 and parameters: {'rf_n_estimators': 550, 'rf_criterion': 'gini', 'rf_max_depth': 3, 'rf_min_samples_split': 0.3532396490443734}. Best is trial 4 with value: 0.9321219715956558.\u001b[0m\n"
],
[
"study.best_params",
"_____no_output_____"
],
[
"study.best_value",
"_____no_output_____"
]
],
[
[
"## Grid Search\n\nGridSampler()\n\nWe are probably not going to perform GridSearch with Optuna, but in case you wanted to, you need to add a variable with the space, with the exact values that you want to be tested.",
"_____no_output_____"
]
],
[
[
"search_space = {\n \"rf_n_estimators\": [100, 500, 1000],\n \"rf_criterion\": ['gini', 'entropy'],\n \"rf_max_depth\": [1, 2, 3],\n \"rf_min_samples_split\": [0.1, 1.0]\n}\n",
"_____no_output_____"
],
[
"study = optuna.create_study(\n direction=\"maximize\",\n sampler=optuna.samplers.GridSampler(search_space),\n)\n\nstudy.optimize(objective)",
"\u001b[32m[I 2021-05-20 13:33:09,736]\u001b[0m A new study created in memory with name: no-name-8d361ba9-6448-4fd0-8b39-426d946d9651\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:13,906]\u001b[0m Trial 0 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 1000, 'rf_criterion': 'gini', 'rf_max_depth': 3, 'rf_min_samples_split': 1.0}. Best is trial 0 with value: 0.6256360598465861.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:14,420]\u001b[0m Trial 1 finished with value: 0.9397357028935976 and parameters: {'rf_n_estimators': 100, 'rf_criterion': 'gini', 'rf_max_depth': 3, 'rf_min_samples_split': 0.1}. Best is trial 1 with value: 0.9397357028935976.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:14,873]\u001b[0m Trial 2 finished with value: 0.9045150755677072 and parameters: {'rf_n_estimators': 100, 'rf_criterion': 'gini', 'rf_max_depth': 1, 'rf_min_samples_split': 0.1}. Best is trial 1 with value: 0.9397357028935976.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:19,585]\u001b[0m Trial 3 finished with value: 0.937210450368345 and parameters: {'rf_n_estimators': 1000, 'rf_criterion': 'gini', 'rf_max_depth': 3, 'rf_min_samples_split': 0.1}. Best is trial 1 with value: 0.9397357028935976.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:23,926]\u001b[0m Trial 4 finished with value: 0.9171223513328776 and parameters: {'rf_n_estimators': 1000, 'rf_criterion': 'gini', 'rf_max_depth': 1, 'rf_min_samples_split': 0.1}. Best is trial 1 with value: 0.9397357028935976.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:25,971]\u001b[0m Trial 5 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 500, 'rf_criterion': 'entropy', 'rf_max_depth': 1, 'rf_min_samples_split': 1.0}. Best is trial 1 with value: 0.9397357028935976.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:30,547]\u001b[0m Trial 6 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 1000, 'rf_criterion': 'entropy', 'rf_max_depth': 1, 'rf_min_samples_split': 1.0}. Best is trial 1 with value: 0.9397357028935976.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:34,879]\u001b[0m Trial 7 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 1000, 'rf_criterion': 'entropy', 'rf_max_depth': 2, 'rf_min_samples_split': 1.0}. Best is trial 1 with value: 0.9397357028935976.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:40,485]\u001b[0m Trial 8 finished with value: 0.9171223513328776 and parameters: {'rf_n_estimators': 1000, 'rf_criterion': 'entropy', 'rf_max_depth': 1, 'rf_min_samples_split': 0.1}. Best is trial 1 with value: 0.9397357028935976.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:41,246]\u001b[0m Trial 9 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 100, 'rf_criterion': 'entropy', 'rf_max_depth': 2, 'rf_min_samples_split': 1.0}. Best is trial 1 with value: 0.9397357028935976.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:41,940]\u001b[0m Trial 10 finished with value: 0.9321979190400244 and parameters: {'rf_n_estimators': 100, 'rf_criterion': 'entropy', 'rf_max_depth': 3, 'rf_min_samples_split': 0.1}. Best is trial 1 with value: 0.9397357028935976.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:44,436]\u001b[0m Trial 11 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 500, 'rf_criterion': 'entropy', 'rf_max_depth': 2, 'rf_min_samples_split': 1.0}. Best is trial 1 with value: 0.9397357028935976.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:44,888]\u001b[0m Trial 12 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 100, 'rf_criterion': 'entropy', 'rf_max_depth': 1, 'rf_min_samples_split': 1.0}. Best is trial 1 with value: 0.9397357028935976.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:49,565]\u001b[0m Trial 13 finished with value: 0.942241968557758 and parameters: {'rf_n_estimators': 1000, 'rf_criterion': 'gini', 'rf_max_depth': 2, 'rf_min_samples_split': 0.1}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:53,627]\u001b[0m Trial 14 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 1000, 'rf_criterion': 'gini', 'rf_max_depth': 2, 'rf_min_samples_split': 1.0}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:54,058]\u001b[0m Trial 15 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 100, 'rf_criterion': 'gini', 'rf_max_depth': 1, 'rf_min_samples_split': 1.0}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:58,234]\u001b[0m Trial 16 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 1000, 'rf_criterion': 'entropy', 'rf_max_depth': 3, 'rf_min_samples_split': 1.0}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:33:58,697]\u001b[0m Trial 17 finished with value: 0.9196476038581302 and parameters: {'rf_n_estimators': 100, 'rf_criterion': 'entropy', 'rf_max_depth': 1, 'rf_min_samples_split': 0.1}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:02,768]\u001b[0m Trial 18 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 1000, 'rf_criterion': 'gini', 'rf_max_depth': 1, 'rf_min_samples_split': 1.0}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:05,433]\u001b[0m Trial 19 finished with value: 0.9397357028935976 and parameters: {'rf_n_estimators': 500, 'rf_criterion': 'entropy', 'rf_max_depth': 2, 'rf_min_samples_split': 0.1}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:07,765]\u001b[0m Trial 20 finished with value: 0.9397167160325055 and parameters: {'rf_n_estimators': 500, 'rf_criterion': 'gini', 'rf_max_depth': 2, 'rf_min_samples_split': 0.1}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:10,281]\u001b[0m Trial 21 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 500, 'rf_criterion': 'gini', 'rf_max_depth': 1, 'rf_min_samples_split': 1.0}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:12,482]\u001b[0m Trial 22 finished with value: 0.9146160856687172 and parameters: {'rf_n_estimators': 500, 'rf_criterion': 'gini', 'rf_max_depth': 1, 'rf_min_samples_split': 0.1}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:14,541]\u001b[0m Trial 23 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 500, 'rf_criterion': 'gini', 'rf_max_depth': 3, 'rf_min_samples_split': 1.0}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:19,427]\u001b[0m Trial 24 finished with value: 0.9397357028935976 and parameters: {'rf_n_estimators': 1000, 'rf_criterion': 'entropy', 'rf_max_depth': 2, 'rf_min_samples_split': 0.1}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:21,716]\u001b[0m Trial 25 finished with value: 0.9171223513328776 and parameters: {'rf_n_estimators': 500, 'rf_criterion': 'entropy', 'rf_max_depth': 1, 'rf_min_samples_split': 0.1}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:22,240]\u001b[0m Trial 26 finished with value: 0.9397357028935976 and parameters: {'rf_n_estimators': 100, 'rf_criterion': 'entropy', 'rf_max_depth': 2, 'rf_min_samples_split': 0.1}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:22,842]\u001b[0m Trial 27 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 100, 'rf_criterion': 'gini', 'rf_max_depth': 2, 'rf_min_samples_split': 1.0}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:23,454]\u001b[0m Trial 28 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 100, 'rf_criterion': 'entropy', 'rf_max_depth': 3, 'rf_min_samples_split': 1.0}. Best is trial 13 with value: 0.942241968557758.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:23,926]\u001b[0m Trial 29 finished with value: 0.9422609554188502 and parameters: {'rf_n_estimators': 100, 'rf_criterion': 'gini', 'rf_max_depth': 2, 'rf_min_samples_split': 0.1}. Best is trial 29 with value: 0.9422609554188502.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:26,110]\u001b[0m Trial 30 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 500, 'rf_criterion': 'gini', 'rf_max_depth': 2, 'rf_min_samples_split': 1.0}. Best is trial 29 with value: 0.9422609554188502.\u001b[0m\n\u001b[32m[I 2021-05-20 13:34:28,169]\u001b[0m Trial 31 finished with value: 0.6256360598465861 and parameters: {'rf_n_estimators': 500, 'rf_criterion': 'entropy', 'rf_max_depth': 3, 'rf_min_samples_split': 1.0}. Best is trial 29 with value: 0.9422609554188502.\u001b[0m\n"
],
[
"study.best_params",
"_____no_output_____"
],
[
"study.best_value",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4ac514c16b2b50cd7bce7be17144ef86ec80dd61
| 3,768 |
ipynb
|
Jupyter Notebook
|
database/tasks/How to test data for normality with the D'Agostino-Pearson test/Python, using SciPy.ipynb
|
nathancarter/how2data
|
7d4f2838661f7ce98deb1b8081470cec5671b03a
|
[
"MIT"
] | null | null | null |
database/tasks/How to test data for normality with the D'Agostino-Pearson test/Python, using SciPy.ipynb
|
nathancarter/how2data
|
7d4f2838661f7ce98deb1b8081470cec5671b03a
|
[
"MIT"
] | null | null | null |
database/tasks/How to test data for normality with the D'Agostino-Pearson test/Python, using SciPy.ipynb
|
nathancarter/how2data
|
7d4f2838661f7ce98deb1b8081470cec5671b03a
|
[
"MIT"
] | 2 |
2021-07-18T19:01:29.000Z
|
2022-03-29T06:47:11.000Z
| 26.34965 | 125 | 0.590764 |
[
[
[
"---\nauthor: Elizabeth Czarniak ([email protected])\n---",
"_____no_output_____"
],
[
"We're going to use some fake restaurant data,\nbut you can replace our fake data with your real data in the code below.\nThe values in our fake data represent the amount of money that customers spent\non a Sunday morning at the restaurant.",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\n# Replace your data here\nspending = [34, 12, 19, 56, 54, 34, 45, 37, 13, 22, 65, 19,\n 16, 45, 19, 50, 36, 23, 28, 56, 40, 61, 45, 47, 37]\n\nnp.mean(spending), np.std(spending, ddof=1)",
"_____no_output_____"
]
],
[
[
"We will now conduct a test of the following null hypothesis:\nThe data comes from a population that is normally distributed with mean 36.52 and standard deviation 15.77.\n\nWe will use a value $\\alpha=0.05$ as our Type I error rate.\nThe `normaltest()` function in SciPy's `stats` package can perform the D'Agostino-Pearson test for normality,\nwhich uses the skew and kurtosis of the data.",
"_____no_output_____"
]
],
[
[
"from scipy import stats\nstats.normaltest(spending)",
"_____no_output_____"
]
],
[
[
"The p-value is apprximately 0.21367, which is greater than $\\alpha=0.05$, so we fail to reject our null hypothesis.\nWe would continue to operate under our original assumption that the data come from a normally distributed population.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4ac515317cb964d3c6500746a52909ea160d44ba
| 147,911 |
ipynb
|
Jupyter Notebook
|
random/01_normal_dist.ipynb
|
boykoatwork/jupyter
|
e68188b4a3ca1a97800ed784d2767c224af1722a
|
[
"Unlicense",
"CC-BY-4.0",
"MIT"
] | null | null | null |
random/01_normal_dist.ipynb
|
boykoatwork/jupyter
|
e68188b4a3ca1a97800ed784d2767c224af1722a
|
[
"Unlicense",
"CC-BY-4.0",
"MIT"
] | null | null | null |
random/01_normal_dist.ipynb
|
boykoatwork/jupyter
|
e68188b4a3ca1a97800ed784d2767c224af1722a
|
[
"Unlicense",
"CC-BY-4.0",
"MIT"
] | 1 |
2021-04-21T12:02:43.000Z
|
2021-04-21T12:02:43.000Z
| 343.180974 | 38,856 | 0.942628 |
[
[
[
"%pylab inline",
"Populating the interactive namespace from numpy and matplotlib\n"
],
[
"import random\nimport math",
"_____no_output_____"
],
[
"x = []\nfor i in range(100):\n x.append(random.random())",
"_____no_output_____"
],
[
"y = []\nfor i in range(len(x)):\n y.append(math.sqrt(x[i] * 2 / 0.001))",
"_____no_output_____"
],
[
"plot(y)\n",
"_____no_output_____"
],
[
"min(y)",
"_____no_output_____"
],
[
"max(y)",
"_____no_output_____"
],
[
"median(y)",
"_____no_output_____"
]
],
[
[
"Думаем как?\n\nЕсть промежуток времени $\\Delta t$ есть функция, которая определяет распределение вероятности на промежутке.\n\n$$ a = \\frac{i}{2} $$",
"_____no_output_____"
]
],
[
[
">>> mu, sigma = 0, 0.1 # mean and standard deviation\n>>> s = np.random.normal(mu, sigma, 1000)\n>>> z = np.zeros(1000)\n>>> o = np.ones(1000)",
"_____no_output_____"
],
[
"plot(s, o, \"+\")",
"_____no_output_____"
],
[
"plot(s,\"o\")",
"_____no_output_____"
],
[
"plot(s, z, \"o\")",
"_____no_output_____"
]
],
[
[
"<!-- Это все хорошо, но мне нужно... что мне нужно? Мне нужен генератор T отказов на t времени. Хорошо. В каких пределах? Допустим... допустим, что есть $T_ср$ - и отсюда уже можно танцевать. -->",
"_____no_output_____"
]
],
[
[
"s = np.random.normal(0, .1, 1000) * 100+50\nt = np.random.rand(1000)*100\nplot(t,'bo',s,'ro')",
"_____no_output_____"
],
[
"\ns = np.random.normal(0, .1, 1000) * 100+50\nt = np.random.rand(1000)*100\nplot(t,'bo',s,'ro')",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4ac522e2f9d8248216e40168787f135336302422
| 46,559 |
ipynb
|
Jupyter Notebook
|
covid_19_india_date_25march1.ipynb
|
sanjoymlp/Dataset
|
578bd61d1d6a3c8dbcab971158518ac88fc24647
|
[
"MIT"
] | null | null | null |
covid_19_india_date_25march1.ipynb
|
sanjoymlp/Dataset
|
578bd61d1d6a3c8dbcab971158518ac88fc24647
|
[
"MIT"
] | null | null | null |
covid_19_india_date_25march1.ipynb
|
sanjoymlp/Dataset
|
578bd61d1d6a3c8dbcab971158518ac88fc24647
|
[
"MIT"
] | null | null | null | 70.866058 | 12,640 | 0.726519 |
[
[
[
"from sklearn.datasets import load_iris\niris = load_iris()",
"_____no_output_____"
],
[
"from sklearn.linear_model import LinearRegression",
"_____no_output_____"
],
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nimport seaborn as sns",
"_____no_output_____"
],
[
"spp=pd.read_csv(r\"C:\\Users\\sanjoy\\Downloads\\secondcar.csv\")\nsppp=pd.read_csv(r\"C:\\Users\\sanjoy\\Downloads\\car_sales.csv\")\nself=pd.read_csv(r\"C:\\Users\\sanjoy\\Downloads\\covid_19_india2.csv\")",
"_____no_output_____"
],
[
"self",
"_____no_output_____"
],
[
"self.describe()",
"_____no_output_____"
],
[
"cdf = self[['date','sno']]",
"_____no_output_____"
],
[
"cdf",
"_____no_output_____"
],
[
"viz = cdf[['date','sno']]\nviz.hist()\nplt.show()",
"_____no_output_____"
],
[
"msk = np.random.rand(len(self)) < 0.8\ntrain = cdf[msk]\ntest = cdf[~msk]",
"_____no_output_____"
],
[
"plt.scatter(train.date, train.sno, color='blue')\nplt.xlabel(\"date\")\nplt.ylabel(\"sno\")\nplt.show()",
"_____no_output_____"
],
[
"from sklearn import linear_model\nregr = linear_model.LinearRegression()\ntrain_x = np.asanyarray(train[['date']])\ntrain_y = np.asanyarray(train[['sno']])\nregr.fit (train_x, train_y)\n# The coefficients\nprint ('Coefficients: ', regr.coef_)\nprint ('Intercept: ',regr.intercept_)",
"Coefficients: [[18.887955]]\nIntercept: [-130.33905838]\n"
],
[
"plt.scatter(train.date, train.sno, color='blue')\nplt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-r')\nplt.xlabel(\"date\")\nplt.ylabel(\"sno\")",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac52fe20e3e56a99db1d2d93b1eff6838f06473
| 1,978 |
ipynb
|
Jupyter Notebook
|
deep-learning/student-admissions/StudentAdmissionsSolutions.ipynb
|
oveis/Deep_Learning_Nanodegree
|
a997ca134792e1ba58e0005a041ee990e21acc07
|
[
"MIT"
] | null | null | null |
deep-learning/student-admissions/StudentAdmissionsSolutions.ipynb
|
oveis/Deep_Learning_Nanodegree
|
a997ca134792e1ba58e0005a041ee990e21acc07
|
[
"MIT"
] | null | null | null |
deep-learning/student-admissions/StudentAdmissionsSolutions.ipynb
|
oveis/Deep_Learning_Nanodegree
|
a997ca134792e1ba58e0005a041ee990e21acc07
|
[
"MIT"
] | null | null | null | 19.584158 | 94 | 0.523761 |
[
[
[
"# Solutions",
"_____no_output_____"
],
[
"### One-hot encoding the rank",
"_____no_output_____"
]
],
[
[
"# Make dummy variables for rank\none_hot_data = pd.concat([data, pd.get_dummies(data['rank'], prefix='rank')], axis=1)\n\n# Drop the previous rank column\none_hot_data = one_hot_data.drop('rank', axis=1)\n\n# Print the first 10 rows of our data\none_hot_data[:10]",
"_____no_output_____"
]
],
[
[
"### Scaling the data",
"_____no_output_____"
]
],
[
[
"# Copying our data\nprocessed_data = one_hot_data[:]\n\n# Scaling the columns\nprocessed_data['gre'] = processed_data['gre']/800\nprocessed_data['gpa'] = processed_data['gpa']/4.0\nprocessed_data[:10]",
"_____no_output_____"
]
],
[
[
"### Backpropagating the data",
"_____no_output_____"
]
],
[
[
"def error_term_formula(y, output):\n return (y-output) * output * (1 - output)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac537c6dae6910e3f6c4348833635621320ea52
| 116,786 |
ipynb
|
Jupyter Notebook
|
UNSW-NB15/1-Constant-Quasi-Constant-Duplicates/1.3-Duplicated-features.ipynb
|
theavila/EmployingFS
|
a2948d9a007eda8d4575a3ce3f093d042b08c7c8
|
[
"Apache-2.0"
] | 1 |
2021-06-20T07:44:45.000Z
|
2021-06-20T07:44:45.000Z
|
UNSW-NB15/1-Constant-Quasi-Constant-Duplicates/1.3-Duplicated-features.ipynb
|
theavila/EmployingFS
|
a2948d9a007eda8d4575a3ce3f093d042b08c7c8
|
[
"Apache-2.0"
] | null | null | null |
UNSW-NB15/1-Constant-Quasi-Constant-Duplicates/1.3-Duplicated-features.ipynb
|
theavila/EmployingFS
|
a2948d9a007eda8d4575a3ce3f093d042b08c7c8
|
[
"Apache-2.0"
] | null | null | null | 40.480416 | 244 | 0.590293 |
[
[
[
"## Duplicated features",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split",
"_____no_output_____"
]
],
[
[
"## Read Data",
"_____no_output_____"
]
],
[
[
"data = pd.read_csv('../UNSW_Train.csv')\ndata.shape",
"_____no_output_____"
],
[
"# check the presence of missing data.\n# (there are no missing data in this dataset)\n[col for col in data.columns if data[col].isnull().sum() > 0]",
"_____no_output_____"
],
[
"data.head(5)",
"_____no_output_____"
]
],
[
[
"### Train - Test Split",
"_____no_output_____"
]
],
[
[
"# separate dataset into train and test\nX_train, X_test, y_train, y_test = train_test_split(\n data.drop(labels=['is_intrusion'], axis=1), # drop the target\n data['is_intrusion'], # just the target\n test_size=0.2,\n random_state=0)\n\nX_train.shape, X_test.shape",
"_____no_output_____"
]
],
[
[
"## Remove constant and quasi-constant (optional)",
"_____no_output_____"
]
],
[
[
"# remove constant and quasi-constant features first:\n# we can remove the 2 types of features together with this code\n\n# create an empty list\nquasi_constant_feat = []\n\n# iterate over every feature\nfor feature in X_train.columns:\n\n # find the predominant value, that is the value that is shared\n # by most observations\n predominant = (X_train[feature].value_counts() / np.float64(\n len(X_train))).sort_values(ascending=False).values[0]\n\n # evaluate predominant feature: do more than 99% of the observations\n # show 1 value?\n if predominant > 0.998:\n quasi_constant_feat.append(feature)\n\nlen(quasi_constant_feat)",
"_____no_output_____"
],
[
"quasi_constant_feat",
"_____no_output_____"
],
[
"# we can then drop these columns from the train and test sets:\n\nX_train.drop(labels=quasi_constant_feat, axis=1, inplace=True)\nX_test.drop(labels=quasi_constant_feat, axis=1, inplace=True)\n\nX_train.shape, X_test.shape",
"_____no_output_____"
]
],
[
[
"## Remove duplicated features",
"_____no_output_____"
]
],
[
[
"# fiding duplicated features\nduplicated_feat_pairs = {}\n_duplicated_feat = []\n\nfor i in range(0, len(X_train.columns)):\n if i % 10 == 0: \n print(i)\n \n feat_1 = X_train.columns[i]\n \n if feat_1 not in _duplicated_feat:\n duplicated_feat_pairs[feat_1] = []\n\n for feat_2 in X_train.columns[i + 1:]:\n if X_train[feat_1].equals(X_train[feat_2]):\n duplicated_feat_pairs[feat_1].append(feat_2)\n _duplicated_feat.append(feat_2)",
"0\n10\n20\n30\n40\n"
],
[
"# let's explore our list of duplicated features\nlen(_duplicated_feat)",
"_____no_output_____"
]
],
[
[
"We found 1 features that were duplicates of others.",
"_____no_output_____"
]
],
[
[
"# these are the ones:\n\n_duplicated_feat",
"_____no_output_____"
],
[
"# let's explore the dictionary we created:\n\nduplicated_feat_pairs",
"_____no_output_____"
]
],
[
[
"We see that for every feature, if it had duplicates, we have entries in the list, otherwise, we have empty lists. Let's explore those features with duplicates now:",
"_____no_output_____"
]
],
[
[
"# let's explore the number of keys in our dictionary\n# we see it is 21, because 2 of the 23 were duplicates,\n# so they were not included as keys\n\nprint(len(duplicated_feat_pairs.keys()))",
"42\n"
],
[
"# print the features with its duplicates\n# iterate over every feature in our dict:\nfor feat in duplicated_feat_pairs.keys():\n # if it has duplicates, the list should not be empty:\n if len(duplicated_feat_pairs[feat]) > 0:\n # print the feature and its duplicates:\n print(feat, duplicated_feat_pairs[feat])\n print()",
"is_ftp_login ['ct_ftp_cmd']\n\n"
],
[
"# to remove the duplicates (if necessary)\nX_train = X_train[duplicated_feat_pairs.keys()]\nX_test = X_test[duplicated_feat_pairs.keys()]\nX_train.shape, X_test.shape",
"_____no_output_____"
]
],
[
[
"1 duplicate features were found in the UNSW-NB15 dataset",
"_____no_output_____"
],
[
"## Standardize Data",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import StandardScaler\nscaler = StandardScaler().fit(X_train)\nX_train = scaler.transform(X_train)",
"_____no_output_____"
]
],
[
[
"## Classifiers",
"_____no_output_____"
]
],
[
[
"from sklearn import linear_model\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom catboost import CatBoostClassifier",
"_____no_output_____"
]
],
[
[
"## Metrics Evaluation",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import roc_curve, f1_score\nfrom sklearn import metrics\nfrom sklearn.model_selection import cross_val_score",
"_____no_output_____"
]
],
[
[
"### Logistic Regression",
"_____no_output_____"
]
],
[
[
"%%time\nclf_LR = linear_model.LogisticRegression(n_jobs=-1, random_state=42, C=25).fit(X_train, y_train)",
"CPU times: user 96.8 ms, sys: 193 ms, total: 290 ms\nWall time: 4.45 s\n"
],
[
"pred_y_test = clf_LR.predict(X_test)\nprint('Accuracy:', accuracy_score(y_test, pred_y_test))\n\nf1 = f1_score(y_test, pred_y_test)\nprint('F1 Score:', f1)\n\nfpr, tpr, thresholds = roc_curve(y_test, pred_y_test)\nprint('FPR:', fpr[1])\nprint('TPR:', tpr[1])",
"Accuracy: 0.33471156862185975\nF1 Score: 0.04479017400204708\nFPR: 0.0048906277787657835\nTPR: 0.02296100407169542\n"
]
],
[
[
"### Naive Bayes",
"_____no_output_____"
]
],
[
[
"%%time\nclf_NB = GaussianNB(var_smoothing=1e-08).fit(X_train, y_train)",
"CPU times: user 110 ms, sys: 22.7 ms, total: 133 ms\nWall time: 131 ms\n"
],
[
"pred_y_testNB = clf_NB.predict(X_test)\nprint('Accuracy:', accuracy_score(y_test, pred_y_testNB))\n\nf1 = f1_score(y_test, pred_y_testNB)\nprint('F1 Score:', f1)\n\nfpr, tpr, thresholds = roc_curve(y_test, pred_y_testNB)\nprint('FPR:', fpr[1])\nprint('TPR:', tpr[1])",
"Accuracy: 0.7423365365422453\nF1 Score: 0.7751791401273885\nFPR: 0.07033611950915881\nTPR: 0.653905889266675\n"
]
],
[
[
"### Random Forest",
"_____no_output_____"
]
],
[
[
"%%time\nclf_RF = RandomForestClassifier(random_state=0,max_depth=100,n_estimators=1000).fit(X_train, y_train)",
"CPU times: user 1min 33s, sys: 698 ms, total: 1min 34s\nWall time: 1min 34s\n"
],
[
"pred_y_testRF = clf_RF.predict(X_test)\nprint('Accuracy:', accuracy_score(y_test, pred_y_testRF))\n\nf1 = f1_score(y_test, pred_y_testRF, average='weighted', zero_division=0)\nprint('F1 Score:', f1)\n\nfpr, tpr, thresholds = roc_curve(y_test, pred_y_testRF)\nprint('FPR:', fpr[1])\nprint('TPR:', tpr[1])",
"Accuracy: 0.6793179161082438\nF1 Score: 0.5495955550990522\nFPR: 1.0\nTPR: 1.0\n"
]
],
[
[
"### KNN",
"_____no_output_____"
]
],
[
[
"%%time\nclf_KNN = KNeighborsClassifier(algorithm='ball_tree',leaf_size=1,n_neighbors=5,weights='uniform').fit(X_train, y_train)",
"CPU times: user 23.7 s, sys: 191 ms, total: 23.9 s\nWall time: 23.8 s\n"
],
[
"pred_y_testKNN = clf_KNN.predict(X_test)\nprint('accuracy_score:', accuracy_score(y_test, pred_y_testKNN))\n\nf1 = f1_score(y_test, pred_y_testKNN)\nprint('f1:', f1)\n\nfpr, tpr, thresholds = roc_curve(y_test, pred_y_testKNN)\nprint('fpr:', fpr[1])\nprint('tpr:', tpr[1])",
"accuracy_score: 0.6842510479340729\nf1: 0.7391703766518267\nfpr: 0.26142628490129827\ntpr: 0.6586072283087773\n"
]
],
[
[
"### CatBoost",
"_____no_output_____"
]
],
[
[
"%%time\nclf_CB = CatBoostClassifier(depth=7,iterations=50,learning_rate=0.04).fit(X_train, y_train)",
"0:\tlearn: 0.5217342\ttotal: 77.2ms\tremaining: 3.78s\n1:\tlearn: 0.3893232\ttotal: 99.2ms\tremaining: 2.38s\n2:\tlearn: 0.2867859\ttotal: 122ms\tremaining: 1.91s\n3:\tlearn: 0.2108494\ttotal: 145ms\tremaining: 1.66s\n4:\tlearn: 0.1560807\ttotal: 166ms\tremaining: 1.5s\n5:\tlearn: 0.1117287\ttotal: 182ms\tremaining: 1.33s\n6:\tlearn: 0.0822786\ttotal: 203ms\tremaining: 1.25s\n7:\tlearn: 0.0617629\ttotal: 223ms\tremaining: 1.17s\n8:\tlearn: 0.0484606\ttotal: 244ms\tremaining: 1.11s\n9:\tlearn: 0.0374214\ttotal: 265ms\tremaining: 1.06s\n10:\tlearn: 0.0289180\ttotal: 288ms\tremaining: 1.02s\n11:\tlearn: 0.0227302\ttotal: 311ms\tremaining: 985ms\n12:\tlearn: 0.0179617\ttotal: 332ms\tremaining: 946ms\n13:\tlearn: 0.0143036\ttotal: 354ms\tremaining: 911ms\n14:\tlearn: 0.0115591\ttotal: 374ms\tremaining: 874ms\n15:\tlearn: 0.0094435\ttotal: 394ms\tremaining: 838ms\n16:\tlearn: 0.0076586\ttotal: 415ms\tremaining: 805ms\n17:\tlearn: 0.0063433\ttotal: 436ms\tremaining: 774ms\n18:\tlearn: 0.0052707\ttotal: 456ms\tremaining: 744ms\n19:\tlearn: 0.0044306\ttotal: 475ms\tremaining: 713ms\n20:\tlearn: 0.0038387\ttotal: 495ms\tremaining: 684ms\n21:\tlearn: 0.0032474\ttotal: 517ms\tremaining: 658ms\n22:\tlearn: 0.0027719\ttotal: 537ms\tremaining: 630ms\n23:\tlearn: 0.0023972\ttotal: 557ms\tremaining: 603ms\n24:\tlearn: 0.0020797\ttotal: 577ms\tremaining: 577ms\n25:\tlearn: 0.0018078\ttotal: 598ms\tremaining: 552ms\n26:\tlearn: 0.0015955\ttotal: 616ms\tremaining: 525ms\n27:\tlearn: 0.0014210\ttotal: 636ms\tremaining: 500ms\n28:\tlearn: 0.0012725\ttotal: 655ms\tremaining: 474ms\n29:\tlearn: 0.0011287\ttotal: 674ms\tremaining: 450ms\n30:\tlearn: 0.0010185\ttotal: 693ms\tremaining: 425ms\n31:\tlearn: 0.0009396\ttotal: 714ms\tremaining: 401ms\n32:\tlearn: 0.0008528\ttotal: 734ms\tremaining: 378ms\n33:\tlearn: 0.0007846\ttotal: 755ms\tremaining: 355ms\n34:\tlearn: 0.0007226\ttotal: 775ms\tremaining: 332ms\n35:\tlearn: 0.0006685\ttotal: 794ms\tremaining: 309ms\n36:\tlearn: 0.0006215\ttotal: 812ms\tremaining: 285ms\n37:\tlearn: 0.0005816\ttotal: 831ms\tremaining: 262ms\n38:\tlearn: 0.0005467\ttotal: 848ms\tremaining: 239ms\n39:\tlearn: 0.0005117\ttotal: 867ms\tremaining: 217ms\n40:\tlearn: 0.0004818\ttotal: 884ms\tremaining: 194ms\n41:\tlearn: 0.0004553\ttotal: 902ms\tremaining: 172ms\n42:\tlearn: 0.0004319\ttotal: 921ms\tremaining: 150ms\n43:\tlearn: 0.0004105\ttotal: 943ms\tremaining: 129ms\n44:\tlearn: 0.0003914\ttotal: 962ms\tremaining: 107ms\n45:\tlearn: 0.0003728\ttotal: 980ms\tremaining: 85.3ms\n46:\tlearn: 0.0003538\ttotal: 998ms\tremaining: 63.7ms\n47:\tlearn: 0.0003384\ttotal: 1.01s\tremaining: 42.3ms\n48:\tlearn: 0.0003219\ttotal: 1.03s\tremaining: 21.1ms\n49:\tlearn: 0.0003130\ttotal: 1.05s\tremaining: 0us\nCPU times: user 7.95 s, sys: 1.63 s, total: 9.58 s\nWall time: 1.14 s\n"
],
[
"pred_y_testCB = clf_CB.predict(X_test)\nprint('Accuracy:', accuracy_score(y_test, pred_y_testCB))\n\nf1 = f1_score(y_test, pred_y_testCB, average='weighted', zero_division=0)\nprint('F1 Score:', f1)\n\nfpr, tpr, thresholds = roc_curve(y_test, pred_y_testCB)\nprint('FPR:', fpr[1])\nprint('TPR:', tpr[1])",
"Accuracy: 0.6793179161082438\nF1 Score: 0.5495955550990522\nFPR: 1.0\nTPR: 1.0\n"
]
],
[
[
"## Model Evaluation",
"_____no_output_____"
]
],
[
[
"import pandas as pd, numpy as np\ntest_df = pd.read_csv(\"../UNSW_Test.csv\")\ntest_df.shape",
"_____no_output_____"
],
[
"# Create feature matrix X and target vextor y\ny_eval = test_df['is_intrusion']\nX_eval = test_df.drop(columns=['is_intrusion','ct_ftp_cmd'])",
"_____no_output_____"
]
],
[
[
"### Model Evaluation - Logistic Regression",
"_____no_output_____"
]
],
[
[
"modelLR = linear_model.LogisticRegression(n_jobs=-1, random_state=42, C=25)\nmodelLR.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# Predict on the new unseen test data\ny_evalpredLR = modelLR.predict(X_eval)\ny_predLR = modelLR.predict(X_test)",
"_____no_output_____"
],
[
"train_scoreLR = modelLR.score(X_train, y_train)\ntest_scoreLR = modelLR.score(X_test, y_test)\nprint(\"Training accuracy is \", train_scoreLR)\nprint(\"Testing accuracy is \", test_scoreLR)",
"Training accuracy is 1.0\nTesting accuracy is 0.33471156862185975\n"
],
[
"from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\nprint('Performance measures for test:')\nprint('--------')\nprint('Accuracy:', test_scoreLR)\nprint('F1 Score:',f1_score(y_test, y_predLR))\nprint('Precision Score:',precision_score(y_test, y_predLR))\nprint('Recall Score:', recall_score(y_test, y_predLR))\nprint('Confusion Matrix:\\n', confusion_matrix(y_test, y_predLR))",
"Performance measures for test:\n--------\nAccuracy: 0.33471156862185975\nF1 Score: 0.04479017400204708\nPrecision Score: 0.9086378737541528\nRecall Score: 0.02296100407169542\nConfusion Matrix:\n [[11191 55]\n [23276 547]]\n"
]
],
[
[
"### Cross validation - Logistic Regression\n\n",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\n\naccuracy = cross_val_score(modelLR, X_eval, y_eval, cv=10, scoring='accuracy')\nprint(\"Accuracy: %0.5f (+/- %0.5f)\" % (accuracy.mean(), accuracy.std() * 2))\n\nf = cross_val_score(modelLR, X_eval, y_eval, cv=10, scoring='f1')\nprint(\"F1 Score: %0.5f (+/- %0.5f)\" % (f.mean(), f.std() * 2))\n\nprecision = cross_val_score(modelLR, X_eval, y_eval, cv=10, scoring='precision')\nprint(\"Precision: %0.5f (+/- %0.5f)\" % (precision.mean(), precision.std() * 2))\n\nrecall = cross_val_score(modelLR, X_eval, y_eval, cv=10, scoring='recall')\nprint(\"Recall: %0.5f (+/- %0.5f)\" % (recall.mean(), recall.std() * 2))",
"/opt/anaconda3/lib/python3.8/site-packages/joblib/externals/loky/process_executor.py:688: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak.\n warnings.warn(\n"
]
],
[
[
"### Model Evaluation - Naive Bayes\n\n",
"_____no_output_____"
]
],
[
[
"modelNB = GaussianNB(var_smoothing=1e-08)\nmodelNB.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# Predict on the new unseen test data\ny_evalpredNB = modelNB.predict(X_eval)\ny_predNB = modelNB.predict(X_test)",
"_____no_output_____"
],
[
"train_scoreNB = modelNB.score(X_train, y_train)\ntest_scoreNB = modelNB.score(X_test, y_test)\nprint(\"Training accuracy is \", train_scoreNB)\nprint(\"Testing accuracy is \", test_scoreNB)",
"Training accuracy is 1.0\nTesting accuracy is 0.7423365365422453\n"
],
[
"from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\nprint('Performance measures for test:')\nprint('--------')\nprint('Accuracy:', test_scoreNB)\nprint('F1 Score:',f1_score(y_test, y_predNB))\nprint('Precision Score:',precision_score(y_test, y_predNB))\nprint('Recall Score:', recall_score(y_test, y_predNB))\nprint('Confusion Matrix:\\n', confusion_matrix(y_test, y_predNB))",
"Performance measures for test:\n--------\nAccuracy: 0.7423365365422453\nF1 Score: 0.7751791401273885\nPrecision Score: 0.9516769503329464\nRecall Score: 0.653905889266675\nConfusion Matrix:\n [[10455 791]\n [ 8245 15578]]\n"
]
],
[
[
"### Cross validation - Naive Bayes\n",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\n\naccuracy = cross_val_score(modelNB, X_eval, y_eval, cv=10, scoring='accuracy')\nprint(\"Accuracy: %0.5f (+/- %0.5f)\" % (accuracy.mean(), accuracy.std() * 2))\n\nf = cross_val_score(modelNB, X_eval, y_eval, cv=10, scoring='f1')\nprint(\"F1 Score: %0.5f (+/- %0.5f)\" % (f.mean(), f.std() * 2))\n\nprecision = cross_val_score(modelNB, X_eval, y_eval, cv=10, scoring='precision')\nprint(\"Precision: %0.5f (+/- %0.5f)\" % (precision.mean(), precision.std() * 2))\n\nrecall = cross_val_score(modelNB, X_eval, y_eval, cv=10, scoring='recall')\nprint(\"Recall: %0.5f (+/- %0.5f)\" % (recall.mean(), recall.std() * 2))",
"Accuracy: 0.81069 (+/- 0.14598)\nF1 Score: 0.87452 (+/- 0.07697)\nPrecision: 0.81743 (+/- 0.15330)\nRecall: 0.94776 (+/- 0.06318)\n"
]
],
[
[
"### Model Evaluation - Random Forest\n\n",
"_____no_output_____"
]
],
[
[
"modelRF = RandomForestClassifier(random_state=0,max_depth=100,n_estimators=1000)\nmodelRF.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# Predict on the new unseen test data\ny_evalpredRF = modelRF.predict(X_eval)\ny_predRF = modelRF.predict(X_test)",
"_____no_output_____"
],
[
"train_scoreRF = modelRF.score(X_train, y_train)\ntest_scoreRF = modelRF.score(X_test, y_test)\nprint(\"Training accuracy is \", train_scoreRF)\nprint(\"Testing accuracy is \", test_scoreRF)",
"Training accuracy is 1.0\nTesting accuracy is 0.6793179161082438\n"
],
[
"from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\nprint('Performance measures for test:')\nprint('--------')\nprint('Accuracy:', test_scoreRF)\nprint('F1 Score:', f1_score(y_test, y_predRF, average='weighted', zero_division=0))\nprint('Precision Score:', precision_score(y_test, y_predRF, average='weighted', zero_division=0))\nprint('Recall Score:', recall_score(y_test, y_predRF, average='weighted', zero_division=0))\nprint('Confusion Matrix:\\n', confusion_matrix(y_test, y_predRF))",
"Performance measures for test:\n--------\nAccuracy: 0.6793179161082438\nF1 Score: 0.5495955550990522\nPrecision Score: 0.4614728311456469\nRecall Score: 0.6793179161082438\nConfusion Matrix:\n [[ 0 11246]\n [ 0 23823]]\n"
]
],
[
[
"### Cross validation - Random Forest\n",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\n\naccuracy = cross_val_score(modelRF, X_eval, y_eval, cv=5, scoring='accuracy')\nprint(\"Accuracy: %0.5f (+/- %0.5f)\" % (accuracy.mean(), accuracy.std() * 2))\n\nf = cross_val_score(modelRF, X_eval, y_eval, cv=5, scoring='f1')\nprint(\"F1 Score: %0.5f (+/- %0.5f)\" % (f.mean(), f.std() * 2))\n\nprecision = cross_val_score(modelRF, X_eval, y_eval, cv=5, scoring='precision')\nprint(\"Precision: %0.5f (+/- %0.5f)\" % (precision.mean(), precision.std() * 2))\n\nrecall = cross_val_score(modelRF, X_eval, y_eval, cv=5, scoring='recall')\nprint(\"Recall: %0.5f (+/- %0.5f)\" % (recall.mean(), recall.std() * 2))",
"Accuracy: 1.00000 (+/- 0.00000)\nF1 Score: 1.00000 (+/- 0.00000)\nPrecision: 1.00000 (+/- 0.00000)\nRecall: 1.00000 (+/- 0.00000)\n"
]
],
[
[
"### Model Evaluation - KNN",
"_____no_output_____"
]
],
[
[
"modelKNN = KNeighborsClassifier(algorithm='ball_tree',leaf_size=1,n_neighbors=5,weights='uniform')\nmodelKNN.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# Predict on the new unseen test data\ny_evalpredKNN = modelKNN.predict(X_eval)\ny_predKNN = modelKNN.predict(X_test)",
"_____no_output_____"
],
[
"train_scoreKNN = modelKNN.score(X_train, y_train)\ntest_scoreKNN = modelKNN.score(X_test, y_test)\nprint(\"Training accuracy is \", train_scoreKNN)\nprint(\"Testing accuracy is \", test_scoreKNN)",
"Training accuracy is 0.9993441314018479\nTesting accuracy is 0.6842510479340729\n"
],
[
"from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\nprint('Performance measures for test:')\nprint('--------')\nprint('Accuracy:', test_scoreKNN)\nprint('F1 Score:', f1_score(y_test, y_predKNN))\nprint('Precision Score:', precision_score(y_test, y_predKNN))\nprint('Recall Score:', recall_score(y_test, y_predKNN))\nprint('Confusion Matrix:\\n', confusion_matrix(y_test, y_predKNN))",
"Performance measures for test:\n--------\nAccuracy: 0.6842510479340729\nF1 Score: 0.7391703766518267\nPrecision Score: 0.8421900161030595\nRecall Score: 0.6586072283087773\nConfusion Matrix:\n [[ 8306 2940]\n [ 8133 15690]]\n"
]
],
[
[
"### Cross validation - KNN\n\n",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\n\naccuracy = cross_val_score(modelKNN, X_eval, y_eval, cv=10, scoring='accuracy')\nprint(\"Accuracy: %0.5f (+/- %0.5f)\" % (accuracy.mean(), accuracy.std() * 2))\n\nf = cross_val_score(modelKNN, X_eval, y_eval, cv=10, scoring='f1')\nprint(\"F1 Score: %0.5f (+/- %0.5f)\" % (f.mean(), f.std() * 2))\n\nprecision = cross_val_score(modelKNN, X_eval, y_eval, cv=10, scoring='precision')\nprint(\"Precision: %0.5f (+/- %0.5f)\" % (precision.mean(), precision.std() * 2))\n\nrecall = cross_val_score(modelKNN, X_eval, y_eval, cv=10, scoring='recall')\nprint(\"Recall: %0.5f (+/- %0.5f)\" % (recall.mean(), recall.std() * 2))",
"Accuracy: 0.87901 (+/- 0.13180)\nF1 Score: 0.91584 (+/- 0.07682)\nPrecision: 0.90359 (+/- 0.17653)\nRecall: 0.93684 (+/- 0.07517)\n"
]
],
[
[
"### Model Evaluation - CatBoost",
"_____no_output_____"
]
],
[
[
"modelCB = CatBoostClassifier(depth=7,iterations=50,learning_rate=0.04)\nmodelCB.fit(X_train, y_train)",
"0:\tlearn: 0.5217342\ttotal: 20.7ms\tremaining: 1.01s\n1:\tlearn: 0.3893232\ttotal: 42.3ms\tremaining: 1.01s\n2:\tlearn: 0.2867859\ttotal: 62.8ms\tremaining: 984ms\n3:\tlearn: 0.2108494\ttotal: 83.3ms\tremaining: 958ms\n4:\tlearn: 0.1560807\ttotal: 104ms\tremaining: 937ms\n5:\tlearn: 0.1117287\ttotal: 120ms\tremaining: 881ms\n6:\tlearn: 0.0822786\ttotal: 140ms\tremaining: 863ms\n7:\tlearn: 0.0617629\ttotal: 162ms\tremaining: 849ms\n8:\tlearn: 0.0484606\ttotal: 183ms\tremaining: 833ms\n9:\tlearn: 0.0374214\ttotal: 204ms\tremaining: 815ms\n10:\tlearn: 0.0289180\ttotal: 225ms\tremaining: 799ms\n11:\tlearn: 0.0227302\ttotal: 246ms\tremaining: 780ms\n12:\tlearn: 0.0179617\ttotal: 266ms\tremaining: 757ms\n13:\tlearn: 0.0143036\ttotal: 286ms\tremaining: 736ms\n14:\tlearn: 0.0115591\ttotal: 307ms\tremaining: 716ms\n15:\tlearn: 0.0094435\ttotal: 326ms\tremaining: 693ms\n16:\tlearn: 0.0076586\ttotal: 347ms\tremaining: 675ms\n17:\tlearn: 0.0063433\ttotal: 368ms\tremaining: 655ms\n18:\tlearn: 0.0052707\ttotal: 389ms\tremaining: 635ms\n19:\tlearn: 0.0044306\ttotal: 409ms\tremaining: 614ms\n20:\tlearn: 0.0038387\ttotal: 430ms\tremaining: 593ms\n21:\tlearn: 0.0032474\ttotal: 450ms\tremaining: 573ms\n22:\tlearn: 0.0027719\ttotal: 470ms\tremaining: 551ms\n23:\tlearn: 0.0023972\ttotal: 489ms\tremaining: 530ms\n24:\tlearn: 0.0020797\ttotal: 508ms\tremaining: 508ms\n25:\tlearn: 0.0018078\ttotal: 528ms\tremaining: 487ms\n26:\tlearn: 0.0015955\ttotal: 546ms\tremaining: 465ms\n27:\tlearn: 0.0014210\ttotal: 565ms\tremaining: 444ms\n28:\tlearn: 0.0012725\ttotal: 584ms\tremaining: 423ms\n29:\tlearn: 0.0011287\ttotal: 603ms\tremaining: 402ms\n30:\tlearn: 0.0010185\ttotal: 622ms\tremaining: 381ms\n31:\tlearn: 0.0009396\ttotal: 640ms\tremaining: 360ms\n32:\tlearn: 0.0008528\ttotal: 660ms\tremaining: 340ms\n33:\tlearn: 0.0007846\ttotal: 679ms\tremaining: 319ms\n34:\tlearn: 0.0007226\ttotal: 697ms\tremaining: 299ms\n35:\tlearn: 0.0006685\ttotal: 716ms\tremaining: 278ms\n36:\tlearn: 0.0006215\ttotal: 734ms\tremaining: 258ms\n37:\tlearn: 0.0005816\ttotal: 752ms\tremaining: 238ms\n38:\tlearn: 0.0005467\ttotal: 771ms\tremaining: 217ms\n39:\tlearn: 0.0005117\ttotal: 789ms\tremaining: 197ms\n40:\tlearn: 0.0004818\ttotal: 806ms\tremaining: 177ms\n41:\tlearn: 0.0004553\ttotal: 824ms\tremaining: 157ms\n42:\tlearn: 0.0004319\ttotal: 842ms\tremaining: 137ms\n43:\tlearn: 0.0004105\ttotal: 861ms\tremaining: 117ms\n44:\tlearn: 0.0003914\ttotal: 880ms\tremaining: 97.8ms\n45:\tlearn: 0.0003728\ttotal: 897ms\tremaining: 78ms\n46:\tlearn: 0.0003538\ttotal: 913ms\tremaining: 58.3ms\n47:\tlearn: 0.0003384\ttotal: 930ms\tremaining: 38.7ms\n48:\tlearn: 0.0003219\ttotal: 948ms\tremaining: 19.3ms\n49:\tlearn: 0.0003130\ttotal: 966ms\tremaining: 0us\n"
],
[
"# Predict on the new unseen test data\ny_evalpredCB = modelCB.predict(X_eval)\ny_predCB = modelCB.predict(X_test)",
"_____no_output_____"
],
[
"train_scoreCB = modelCB.score(X_train, y_train)\ntest_scoreCB = modelCB.score(X_test, y_test)\nprint(\"Training accuracy is \", train_scoreCB)\nprint(\"Testing accuracy is \", test_scoreCB)",
"Training accuracy is 1.0\nTesting accuracy is 0.6793179161082438\n"
],
[
"from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\nprint('Performance measures for test:')\nprint('--------')\nprint('Accuracy:', test_scoreCB)\nprint('F1 Score:',f1_score(y_test, y_predCB, average='weighted', zero_division=0))\nprint('Precision Score:',precision_score(y_test, y_predCB, average='weighted', zero_division=0))\nprint('Recall Score:', recall_score(y_test, y_predCB, average='weighted', zero_division=0))\nprint('Confusion Matrix:\\n', confusion_matrix(y_test, y_predCB))",
"Performance measures for test:\n--------\nAccuracy: 0.6793179161082438\nF1 Score: 0.5495955550990522\nPrecision Score: 0.4614728311456469\nRecall Score: 0.6793179161082438\nConfusion Matrix:\n [[ 0 11246]\n [ 0 23823]]\n"
]
],
[
[
"### Cross validation - CatBoost",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\n\naccuracy = cross_val_score(modelCB, X_eval, y_eval, cv=5, scoring='accuracy')\nf = cross_val_score(modelCB, X_eval, y_eval, cv=5, scoring='f1')\nprecision = cross_val_score(modelCB, X_eval, y_eval, cv=5, scoring='precision')\nrecall = cross_val_score(modelCB, X_eval, y_eval, cv=5, scoring='recall')",
"0:\tlearn: 0.5217568\ttotal: 20.7ms\tremaining: 1.01s\n1:\tlearn: 0.3892948\ttotal: 42.6ms\tremaining: 1.02s\n2:\tlearn: 0.2909019\ttotal: 63.8ms\tremaining: 999ms\n3:\tlearn: 0.2137098\ttotal: 85ms\tremaining: 977ms\n4:\tlearn: 0.1581339\ttotal: 106ms\tremaining: 957ms\n5:\tlearn: 0.1131897\ttotal: 122ms\tremaining: 895ms\n6:\tlearn: 0.0839631\ttotal: 142ms\tremaining: 874ms\n7:\tlearn: 0.0631400\ttotal: 163ms\tremaining: 857ms\n8:\tlearn: 0.0484262\ttotal: 184ms\tremaining: 840ms\n9:\tlearn: 0.0375332\ttotal: 202ms\tremaining: 810ms\n10:\tlearn: 0.0293757\ttotal: 224ms\tremaining: 793ms\n11:\tlearn: 0.0232955\ttotal: 245ms\tremaining: 777ms\n12:\tlearn: 0.0182611\ttotal: 266ms\tremaining: 756ms\n13:\tlearn: 0.0143901\ttotal: 288ms\tremaining: 740ms\n14:\tlearn: 0.0115975\ttotal: 309ms\tremaining: 720ms\n15:\tlearn: 0.0094226\ttotal: 331ms\tremaining: 703ms\n16:\tlearn: 0.0075173\ttotal: 347ms\tremaining: 673ms\n17:\tlearn: 0.0062402\ttotal: 367ms\tremaining: 653ms\n18:\tlearn: 0.0051324\ttotal: 388ms\tremaining: 634ms\n19:\tlearn: 0.0044304\ttotal: 408ms\tremaining: 612ms\n20:\tlearn: 0.0037097\ttotal: 428ms\tremaining: 592ms\n21:\tlearn: 0.0031411\ttotal: 449ms\tremaining: 572ms\n22:\tlearn: 0.0026845\ttotal: 471ms\tremaining: 553ms\n23:\tlearn: 0.0023300\ttotal: 491ms\tremaining: 532ms\n24:\tlearn: 0.0020594\ttotal: 510ms\tremaining: 510ms\n25:\tlearn: 0.0017951\ttotal: 529ms\tremaining: 489ms\n26:\tlearn: 0.0015783\ttotal: 549ms\tremaining: 468ms\n27:\tlearn: 0.0013865\ttotal: 567ms\tremaining: 446ms\n28:\tlearn: 0.0012329\ttotal: 587ms\tremaining: 425ms\n29:\tlearn: 0.0011029\ttotal: 606ms\tremaining: 404ms\n30:\tlearn: 0.0009960\ttotal: 626ms\tremaining: 383ms\n31:\tlearn: 0.0009035\ttotal: 645ms\tremaining: 363ms\n32:\tlearn: 0.0008279\ttotal: 664ms\tremaining: 342ms\n33:\tlearn: 0.0007588\ttotal: 685ms\tremaining: 322ms\n34:\tlearn: 0.0006997\ttotal: 705ms\tremaining: 302ms\n35:\tlearn: 0.0006482\ttotal: 724ms\tremaining: 281ms\n36:\tlearn: 0.0005990\ttotal: 743ms\tremaining: 261ms\n37:\tlearn: 0.0005569\ttotal: 762ms\tremaining: 241ms\n38:\tlearn: 0.0005167\ttotal: 780ms\tremaining: 220ms\n39:\tlearn: 0.0004819\ttotal: 797ms\tremaining: 199ms\n40:\tlearn: 0.0004545\ttotal: 815ms\tremaining: 179ms\n41:\tlearn: 0.0004291\ttotal: 833ms\tremaining: 159ms\n42:\tlearn: 0.0004055\ttotal: 851ms\tremaining: 139ms\n43:\tlearn: 0.0003852\ttotal: 870ms\tremaining: 119ms\n44:\tlearn: 0.0003658\ttotal: 890ms\tremaining: 98.9ms\n45:\tlearn: 0.0003475\ttotal: 908ms\tremaining: 78.9ms\n46:\tlearn: 0.0003295\ttotal: 925ms\tremaining: 59ms\n47:\tlearn: 0.0003149\ttotal: 943ms\tremaining: 39.3ms\n48:\tlearn: 0.0003006\ttotal: 960ms\tremaining: 19.6ms\n49:\tlearn: 0.0002881\ttotal: 977ms\tremaining: 0us\n0:\tlearn: 0.5223626\ttotal: 22.1ms\tremaining: 1.08s\n1:\tlearn: 0.3895522\ttotal: 44ms\tremaining: 1.05s\n2:\tlearn: 0.2910330\ttotal: 65.5ms\tremaining: 1.02s\n3:\tlearn: 0.2138121\ttotal: 85.9ms\tremaining: 988ms\n4:\tlearn: 0.1586902\ttotal: 107ms\tremaining: 966ms\n5:\tlearn: 0.1135920\ttotal: 123ms\tremaining: 902ms\n6:\tlearn: 0.0847379\ttotal: 143ms\tremaining: 878ms\n7:\tlearn: 0.0637391\ttotal: 163ms\tremaining: 858ms\n8:\tlearn: 0.0484280\ttotal: 184ms\tremaining: 839ms\n9:\tlearn: 0.0366514\ttotal: 202ms\tremaining: 809ms\n10:\tlearn: 0.0287114\ttotal: 223ms\tremaining: 790ms\n11:\tlearn: 0.0227502\ttotal: 244ms\tremaining: 773ms\n12:\tlearn: 0.0179209\ttotal: 266ms\tremaining: 757ms\n13:\tlearn: 0.0140511\ttotal: 284ms\tremaining: 731ms\n14:\tlearn: 0.0112590\ttotal: 304ms\tremaining: 710ms\n15:\tlearn: 0.0091976\ttotal: 325ms\tremaining: 690ms\n16:\tlearn: 0.0075300\ttotal: 345ms\tremaining: 669ms\n17:\tlearn: 0.0061439\ttotal: 365ms\tremaining: 649ms\n18:\tlearn: 0.0051113\ttotal: 386ms\tremaining: 631ms\n19:\tlearn: 0.0043623\ttotal: 406ms\tremaining: 609ms\n20:\tlearn: 0.0037072\ttotal: 426ms\tremaining: 589ms\n21:\tlearn: 0.0031371\ttotal: 447ms\tremaining: 569ms\n22:\tlearn: 0.0027482\ttotal: 468ms\tremaining: 550ms\n23:\tlearn: 0.0023896\ttotal: 489ms\tremaining: 530ms\n24:\tlearn: 0.0021060\ttotal: 508ms\tremaining: 508ms\n25:\tlearn: 0.0018788\ttotal: 527ms\tremaining: 486ms\n26:\tlearn: 0.0016608\ttotal: 547ms\tremaining: 466ms\n27:\tlearn: 0.0014804\ttotal: 566ms\tremaining: 445ms\n28:\tlearn: 0.0013258\ttotal: 586ms\tremaining: 424ms\n29:\tlearn: 0.0011838\ttotal: 603ms\tremaining: 402ms\n30:\tlearn: 0.0010777\ttotal: 623ms\tremaining: 382ms\n31:\tlearn: 0.0009957\ttotal: 642ms\tremaining: 361ms\n32:\tlearn: 0.0009196\ttotal: 662ms\tremaining: 341ms\n33:\tlearn: 0.0008366\ttotal: 682ms\tremaining: 321ms\n34:\tlearn: 0.0007687\ttotal: 701ms\tremaining: 300ms\n35:\tlearn: 0.0007086\ttotal: 720ms\tremaining: 280ms\n36:\tlearn: 0.0006547\ttotal: 739ms\tremaining: 260ms\n37:\tlearn: 0.0006036\ttotal: 757ms\tremaining: 239ms\n38:\tlearn: 0.0005590\ttotal: 775ms\tremaining: 219ms\n39:\tlearn: 0.0005203\ttotal: 794ms\tremaining: 198ms\n40:\tlearn: 0.0004907\ttotal: 811ms\tremaining: 178ms\n41:\tlearn: 0.0004638\ttotal: 828ms\tremaining: 158ms\n42:\tlearn: 0.0004381\ttotal: 847ms\tremaining: 138ms\n43:\tlearn: 0.0004152\ttotal: 866ms\tremaining: 118ms\n44:\tlearn: 0.0003925\ttotal: 885ms\tremaining: 98.3ms\n45:\tlearn: 0.0003716\ttotal: 902ms\tremaining: 78.4ms\n46:\tlearn: 0.0003541\ttotal: 918ms\tremaining: 58.6ms\n47:\tlearn: 0.0003362\ttotal: 935ms\tremaining: 39ms\n48:\tlearn: 0.0003209\ttotal: 952ms\tremaining: 19.4ms\n49:\tlearn: 0.0003057\ttotal: 969ms\tremaining: 0us\n0:\tlearn: 0.5218547\ttotal: 20.7ms\tremaining: 1.01s\n1:\tlearn: 0.3896602\ttotal: 42.1ms\tremaining: 1.01s\n2:\tlearn: 0.2912479\ttotal: 62.9ms\tremaining: 985ms\n3:\tlearn: 0.2140785\ttotal: 83.3ms\tremaining: 958ms\n4:\tlearn: 0.1585607\ttotal: 104ms\tremaining: 938ms\n5:\tlearn: 0.1134926\ttotal: 120ms\tremaining: 878ms\n6:\tlearn: 0.0842337\ttotal: 139ms\tremaining: 855ms\n7:\tlearn: 0.0633781\ttotal: 160ms\tremaining: 839ms\n8:\tlearn: 0.0486446\ttotal: 181ms\tremaining: 827ms\n9:\tlearn: 0.0376992\ttotal: 199ms\tremaining: 796ms\n10:\tlearn: 0.0297976\ttotal: 220ms\tremaining: 781ms\n11:\tlearn: 0.0236530\ttotal: 241ms\tremaining: 764ms\n12:\tlearn: 0.0183583\ttotal: 261ms\tremaining: 743ms\n13:\tlearn: 0.0145958\ttotal: 283ms\tremaining: 726ms\n14:\tlearn: 0.0117608\ttotal: 303ms\tremaining: 707ms\n15:\tlearn: 0.0097598\ttotal: 324ms\tremaining: 689ms\n16:\tlearn: 0.0077789\ttotal: 340ms\tremaining: 660ms\n17:\tlearn: 0.0064562\ttotal: 361ms\tremaining: 641ms\n18:\tlearn: 0.0053022\ttotal: 381ms\tremaining: 621ms\n19:\tlearn: 0.0045681\ttotal: 401ms\tremaining: 601ms\n20:\tlearn: 0.0039323\ttotal: 421ms\tremaining: 581ms\n21:\tlearn: 0.0033546\ttotal: 441ms\tremaining: 561ms\n22:\tlearn: 0.0028605\ttotal: 461ms\tremaining: 541ms\n23:\tlearn: 0.0024610\ttotal: 481ms\tremaining: 521ms\n24:\tlearn: 0.0021821\ttotal: 501ms\tremaining: 501ms\n25:\tlearn: 0.0019410\ttotal: 520ms\tremaining: 480ms\n26:\tlearn: 0.0016980\ttotal: 539ms\tremaining: 459ms\n27:\tlearn: 0.0015022\ttotal: 558ms\tremaining: 438ms\n28:\tlearn: 0.0013303\ttotal: 576ms\tremaining: 417ms\n29:\tlearn: 0.0011894\ttotal: 597ms\tremaining: 398ms\n30:\tlearn: 0.0010752\ttotal: 619ms\tremaining: 380ms\n31:\tlearn: 0.0009890\ttotal: 643ms\tremaining: 362ms\n32:\tlearn: 0.0008941\ttotal: 664ms\tremaining: 342ms\n33:\tlearn: 0.0008167\ttotal: 683ms\tremaining: 322ms\n34:\tlearn: 0.0007482\ttotal: 702ms\tremaining: 301ms\n35:\tlearn: 0.0006886\ttotal: 722ms\tremaining: 281ms\n36:\tlearn: 0.0006369\ttotal: 742ms\tremaining: 261ms\n37:\tlearn: 0.0005889\ttotal: 760ms\tremaining: 240ms\n38:\tlearn: 0.0005458\ttotal: 777ms\tremaining: 219ms\n39:\tlearn: 0.0005173\ttotal: 795ms\tremaining: 199ms\n40:\tlearn: 0.0004911\ttotal: 812ms\tremaining: 178ms\n41:\tlearn: 0.0004577\ttotal: 831ms\tremaining: 158ms\n42:\tlearn: 0.0004335\ttotal: 851ms\tremaining: 138ms\n43:\tlearn: 0.0004093\ttotal: 870ms\tremaining: 119ms\n44:\tlearn: 0.0003872\ttotal: 888ms\tremaining: 98.6ms\n45:\tlearn: 0.0003677\ttotal: 905ms\tremaining: 78.7ms\n46:\tlearn: 0.0003508\ttotal: 923ms\tremaining: 58.9ms\n47:\tlearn: 0.0003341\ttotal: 940ms\tremaining: 39.2ms\n48:\tlearn: 0.0003246\ttotal: 956ms\tremaining: 19.5ms\n49:\tlearn: 0.0003092\ttotal: 974ms\tremaining: 0us\n0:\tlearn: 0.5216803\ttotal: 20.5ms\tremaining: 1.01s\n1:\tlearn: 0.3897176\ttotal: 42.4ms\tremaining: 1.02s\n2:\tlearn: 0.2873670\ttotal: 63ms\tremaining: 987ms\n3:\tlearn: 0.2114789\ttotal: 83.5ms\tremaining: 960ms\n4:\tlearn: 0.1565692\ttotal: 105ms\tremaining: 941ms\n5:\tlearn: 0.1120749\ttotal: 120ms\tremaining: 880ms\n6:\tlearn: 0.0824868\ttotal: 139ms\tremaining: 857ms\n7:\tlearn: 0.0619179\ttotal: 160ms\tremaining: 840ms\n8:\tlearn: 0.0480795\ttotal: 181ms\tremaining: 825ms\n9:\tlearn: 0.0364278\ttotal: 200ms\tremaining: 798ms\n10:\tlearn: 0.0284548\ttotal: 220ms\tremaining: 780ms\n11:\tlearn: 0.0226081\ttotal: 241ms\tremaining: 764ms\n12:\tlearn: 0.0179877\ttotal: 262ms\tremaining: 746ms\n13:\tlearn: 0.0142832\ttotal: 283ms\tremaining: 728ms\n14:\tlearn: 0.0115227\ttotal: 304ms\tremaining: 710ms\n15:\tlearn: 0.0094940\ttotal: 324ms\tremaining: 688ms\n16:\tlearn: 0.0078241\ttotal: 345ms\tremaining: 670ms\n17:\tlearn: 0.0065136\ttotal: 365ms\tremaining: 649ms\n18:\tlearn: 0.0054158\ttotal: 386ms\tremaining: 630ms\n19:\tlearn: 0.0045447\ttotal: 406ms\tremaining: 609ms\n"
],
[
"print(\"Accuracy: %0.5f (+/- %0.5f)\" % (accuracy.mean(), accuracy.std() * 2))\nprint(\"F1 Score: %0.5f (+/- %0.5f)\" % (f.mean(), f.std() * 2))\nprint(\"Precision: %0.5f (+/- %0.5f)\" % (precision.mean(), precision.std() * 2))\nprint(\"Recall: %0.5f (+/- %0.5f)\" % (recall.mean(), recall.std() * 2))",
"Accuracy: 1.00000 (+/- 0.00000)\nF1 Score: 1.00000 (+/- 0.00000)\nPrecision: 1.00000 (+/- 0.00000)\nRecall: 1.00000 (+/- 0.00000)\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"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4ac546ed12ac8449b7f8ef832b98b0cbe4407219
| 26,855 |
ipynb
|
Jupyter Notebook
|
.ipynb_aml_checkpoints/04 - Run Experiments-checkpoint2021-9-5-23-43-53Z.ipynb
|
JavierMedel/mslearn-dp100
|
dec1fb68cb3776878d158d24e100fa35ea31fd43
|
[
"MIT"
] | null | null | null |
.ipynb_aml_checkpoints/04 - Run Experiments-checkpoint2021-9-5-23-43-53Z.ipynb
|
JavierMedel/mslearn-dp100
|
dec1fb68cb3776878d158d24e100fa35ea31fd43
|
[
"MIT"
] | null | null | null |
.ipynb_aml_checkpoints/04 - Run Experiments-checkpoint2021-9-5-23-43-53Z.ipynb
|
JavierMedel/mslearn-dp100
|
dec1fb68cb3776878d158d24e100fa35ea31fd43
|
[
"MIT"
] | null | null | null | 40.202096 | 702 | 0.574269 |
[
[
[
"# Run Experiments\n\nYou can use the Azure Machine Learning SDK to run code experiments that log metrics and generate outputs. This is at the core of most machine learning operations in Azure Machine Learning.\n\n## Connect to your workspace\n\nAll experiments and associated resources are managed within your Azure Machine Learning workspace. In most cases, you should store the workspace configuration in a JSON configuration file. This makes it easier to reconnect without needing to remember details like your Azure subscription ID. You can download the JSON configuration file from the blade for your workspace in the Azure portal, but if you're using a Compute Instance within your workspace, the configuration file has already been downloaded to the root folder.\n\nThe code below uses the configuration file to connect to your workspace.\n\n> **Note**: If you haven't already established an authenticated session with your Azure subscription, you'll be prompted to authenticate by clicking a link, entering an authentication code, and signing into Azure.",
"_____no_output_____"
]
],
[
[
"import azureml.core\nfrom azureml.core import Workspace\n\n# Load the workspace from the saved config file\nws = Workspace.from_config()\nprint('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))",
"Ready to use Azure ML 1.34.0 to work with ict-915-02-jmdl\n"
]
],
[
[
"## Run an experiment\n\nOne of the most fundamental tasks that data scientists need to perform is to create and run experiments that process and analyze data. In this exercise, you'll learn how to use an Azure ML *experiment* to run Python code and record values extracted from data. In this case, you'll use a simple dataset that contains details of patients that have been tested for diabetes. You'll run an experiment to explore the data, extracting statistics, visualizations, and data samples. Most of the code you'll use is fairly generic Python, such as you might run in any data exploration process. However, with the addition of a few lines, the code uses an Azure ML *experiment* to log details of the run.",
"_____no_output_____"
]
],
[
[
"from azureml.core import Experiment\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline \n\n# Create an Azure ML experiment in your workspace\nexperiment = Experiment(workspace=ws, name=\"mslearn-diabetes\")\n\n# Start logging data from the experiment, obtaining a reference to the experiment run\nrun = experiment.start_logging()\nprint(\"Starting experiment:\", experiment.name)\n\n# load the data from a local file\ndata = pd.read_csv('data/diabetes.csv')\n\n# Count the rows and log the result\nrow_count = (len(data))\nrun.log('observations', row_count)\nprint('Analyzing {} rows of data'.format(row_count))\n\n# Plot and log the count of diabetic vs non-diabetic patients\ndiabetic_counts = data['Diabetic'].value_counts()\nfig = plt.figure(figsize=(6,6))\nax = fig.gca() \ndiabetic_counts.plot.bar(ax = ax) \nax.set_title('Patients with Diabetes') \nax.set_xlabel('Diagnosis') \nax.set_ylabel('Patients')\nplt.show()\nrun.log_image(name='label distribution', plot=fig)\n\n# log distinct pregnancy counts\npregnancies = data.Pregnancies.unique()\nrun.log_list('pregnancy categories', pregnancies)\n\n# Log summary statistics for numeric columns\nmed_columns = ['PlasmaGlucose', 'DiastolicBloodPressure', 'TricepsThickness', 'SerumInsulin', 'BMI']\nsummary_stats = data[med_columns].describe().to_dict()\nfor col in summary_stats:\n keys = list(summary_stats[col].keys())\n values = list(summary_stats[col].values())\n for index in range(len(keys)):\n run.log_row(col, stat=keys[index], value = values[index])\n \n# Save a sample of the data and upload it to the experiment output\ndata.sample(100).to_csv('sample.csv', index=False, header=True)\nrun.upload_file(name='outputs/sample.csv', path_or_stream='./sample.csv')\n\n# Complete the run\nrun.complete()",
"_____no_output_____"
]
],
[
[
"## View run details\n\nIn Jupyter Notebooks, you can use the **RunDetails** widget to see a visualization of the run details.",
"_____no_output_____"
]
],
[
[
"from azureml.widgets import RunDetails\n\nRunDetails(run).show()",
"_____no_output_____"
]
],
[
[
"### View more details in Azure Machine Learning studio\n\nNote that the **RunDetails** widget includes a link to **view run details** in Azure Machine Learning studio. Click this to open a new browser tab with the run details (you can also just open [Azure Machine Learning studio](https://ml.azure.com) and find the run on the **Experiments** page). When viewing the run in Azure Machine Learning studio, note the following:\n\n- The **Details** tab contains the general properties of the experiment run.\n- The **Metrics** tab enables you to select logged metrics and view them as tables or charts.\n- The **Images** tab enables you to select and view any images or plots that were logged in the experiment (in this case, the *Label Distribution* plot)\n- The **Child Runs** tab lists any child runs (in this experiment there are none).\n- The **Outputs + Logs** tab shows the output or log files generated by the experiment.\n- The **Snapshot** tab contains all files in the folder where the experiment code was run (in this case, everything in the same folder as this notebook).\n- The **Explanations** tab is used to show model explanations generated by the experiment (in this case, there are none).\n- The **Fairness** tab is used to visualize predictive performance disparities that help you evaluate the fairness of machine learning models (in this case, there are none).",
"_____no_output_____"
],
[
"### Retrieve experiment details using the SDK\n\nThe **run** variable in the code you ran previously is an instance of a **Run** object, which is a reference to an individual run of an experiment in Azure Machine Learning. You can use this reference to get information about the run and its outputs:",
"_____no_output_____"
]
],
[
[
"import json\n\n# Get logged metrics\nprint(\"Metrics:\")\nmetrics = run.get_metrics()\nfor metric_name in metrics:\n print(metric_name, \":\", metrics[metric_name])\n\n# Get output files\nprint(\"\\nFiles:\")\nfiles = run.get_file_names()\nfor file in files:\n print(file)",
"_____no_output_____"
]
],
[
[
"You can download the files produced by the experiment, either individually by using the **download_file** method, or by using the **download_files** method to retrieve multiple files. The following code downloads all of the files in the run's **output** folder:",
"_____no_output_____"
]
],
[
[
"import os\n\ndownload_folder = 'downloaded-files'\n\n# Download files in the \"outputs\" folder\nrun.download_files(prefix='outputs', output_directory=download_folder)\n\n# Verify the files have been downloaded\nfor root, directories, filenames in os.walk(download_folder): \n for filename in filenames: \n print (os.path.join(root,filename))",
"_____no_output_____"
]
],
[
[
"If you need to troubleshoot the experiment run, you can use the **get_details** method to retrieve basic details about the run, or you can use the **get_details_with_logs** method to retrieve the run details as well as the contents of log files generated during the run:",
"_____no_output_____"
]
],
[
[
"run.get_details_with_logs()",
"_____no_output_____"
]
],
[
[
"Note that the details include information about the compute target on which the experiment was run, the date and time when it started and ended. Additionally, because the notebook containing the experiment code (this one) is in a cloned Git repository, details about the repo, branch, and status are recorded in the run history.\n\nIn this case, note that the **logFiles** entry in the details indicates that no log files were generated. That's typical for an inline experiment like the one you ran, but things get more interesting when you run a script as an experiment; which is what we'll look at next.",
"_____no_output_____"
],
[
"## Run an experiment script\n\nIn the previous example, you ran an experiment inline in this notebook. A more flexible solution is to create a separate script for the experiment, and store it in a folder along with any other files it needs, and then use Azure ML to run the experiment based on the script in the folder.\n\nFirst, let's create a folder for the experiment files, and copy the data into it:",
"_____no_output_____"
]
],
[
[
"import os, shutil\n\n# Create a folder for the experiment files\nfolder_name = 'diabetes-experiment-files'\nexperiment_folder = './' + folder_name\nos.makedirs(folder_name, exist_ok=True)\n\n# Copy the data file into the experiment folder\nshutil.copy('data/diabetes.csv', os.path.join(folder_name, \"diabetes.csv\"))",
"_____no_output_____"
]
],
[
[
"Now we'll create a Python script containing the code for our experiment, and save it in the experiment folder.\n\n> **Note**: running the following cell just *creates* the script file - it doesn't run it!",
"_____no_output_____"
]
],
[
[
"%%writefile $folder_name/diabetes_experiment.py\nfrom azureml.core import Run\nimport pandas as pd\nimport os\n\n# Get the experiment run context\nrun = Run.get_context()\n\n# load the diabetes dataset\ndata = pd.read_csv('diabetes.csv')\n\n# Count the rows and log the result\nrow_count = (len(data))\nrun.log('observations', row_count)\nprint('Analyzing {} rows of data'.format(row_count))\n\n# Count and log the label counts\ndiabetic_counts = data['Diabetic'].value_counts()\nprint(diabetic_counts)\nfor k, v in diabetic_counts.items():\n run.log('Label:' + str(k), v)\n \n# Save a sample of the data in the outputs folder (which gets uploaded automatically)\nos.makedirs('outputs', exist_ok=True)\ndata.sample(100).to_csv(\"outputs/sample.csv\", index=False, header=True)\n\n# Complete the run\nrun.complete()",
"_____no_output_____"
]
],
[
[
"This code is a simplified version of the inline code used before. However, note the following:\n- It uses the `Run.get_context()` method to retrieve the experiment run context when the script is run.\n- It loads the diabetes data from the folder where the script is located.\n- It creates a folder named **outputs** and writes the sample file to it - this folder is automatically uploaded to the experiment run",
"_____no_output_____"
],
[
"Now you're almost ready to run the experiment. To run the script, you must create a **ScriptRunConfig** that identifies the Python script file to be run in the experiment, and then run an experiment based on it.\n\n> **Note**: The ScriptRunConfig also determines the compute target and Python environment. In this case, the Python environment is defined to include some Conda and pip packages, but the compute target is omitted; so the default local compute will be used.\n\nThe following cell configures and submits the script-based experiment.",
"_____no_output_____"
]
],
[
[
"from azureml.core import Experiment, ScriptRunConfig, Environment\nfrom azureml.widgets import RunDetails\n\n# Create a Python environment for the experiment (from a .yml file)\nenv = Environment.from_conda_specification(\"experiment_env\", \"environment.yml\")\n\n# Create a script config\nscript_config = ScriptRunConfig(source_directory=experiment_folder,\n script='diabetes_experiment.py',\n environment=env)\n\n# submit the experiment\nexperiment = Experiment(workspace=ws, name='mslearn-diabetes')\nrun = experiment.submit(config=script_config)\nRunDetails(run).show()\nrun.wait_for_completion()",
"_____no_output_____"
]
],
[
[
"As before, you can use the widget or the link to the experiment in [Azure Machine Learning studio](https://ml.azure.com) to view the outputs generated by the experiment, and you can also write code to retrieve the metrics and files it generated:",
"_____no_output_____"
]
],
[
[
"# Get logged metrics\nmetrics = run.get_metrics()\nfor key in metrics.keys():\n print(key, metrics.get(key))\nprint('\\n')\nfor file in run.get_file_names():\n print(file)",
"_____no_output_____"
]
],
[
[
"Note that this time, the run generated some log files. You can view these in the widget, or you can use the **get_details_with_logs** method like we did before, only this time the output will include the log data.",
"_____no_output_____"
]
],
[
[
"run.get_details_with_logs()",
"_____no_output_____"
]
],
[
[
"Although you can view the log details in the output above, it's usually easier to download the log files and view them in a text editor.",
"_____no_output_____"
]
],
[
[
"import os\n\nlog_folder = 'downloaded-logs'\n\n# Download all files\nrun.get_all_logs(destination=log_folder)\n\n# Verify the files have been downloaded\nfor root, directories, filenames in os.walk(log_folder): \n for filename in filenames: \n print (os.path.join(root,filename))",
"_____no_output_____"
]
],
[
[
"## View experiment run history\n\nNow that you've run the same experiment multiple times, you can view the history in [Azure Machine Learning studio](https://ml.azure.com) and explore each logged run. Or you can retrieve an experiment by name from the workspace and iterate through its runs using the SDK:",
"_____no_output_____"
]
],
[
[
"from azureml.core import Experiment, Run\n\ndiabetes_experiment = ws.experiments['mslearn-diabetes']\nfor logged_run in diabetes_experiment.get_runs():\n print('Run ID:', logged_run.id)\n metrics = logged_run.get_metrics()\n for key in metrics.keys():\n print('-', key, metrics.get(key))",
"_____no_output_____"
]
],
[
[
"## Use MLflow\n\nMLflow is an open source platform for managing machine learning processes. It's commonly (but not exclusively) used in Databricks environments to coordinate experiments and track metrics. In Azure Machine Learning experiments, you can use MLflow to track metrics as an alternative to the native log functionality.\n\nTo take advantage of this capability, you'll need the **azureml-mlflow** package, so let's ensure it's installed.",
"_____no_output_____"
]
],
[
[
"!pip show azureml-mlflow",
"_____no_output_____"
]
],
[
[
"### Use MLflow with an inline experiment\n\nTo use MLflow to track metrics for an inline experiment, you must set the MLflow *tracking URI* to the workspace where the experiment is being run. This enables you to use **mlflow** tracking methods to log data to the experiment run.",
"_____no_output_____"
]
],
[
[
"from azureml.core import Experiment\nimport pandas as pd\nimport mlflow\n\n# Set the MLflow tracking URI to the workspace\nmlflow.set_tracking_uri(ws.get_mlflow_tracking_uri())\n\n# Create an Azure ML experiment in your workspace\nexperiment = Experiment(workspace=ws, name='mslearn-diabetes-mlflow')\nmlflow.set_experiment(experiment.name)\n\n# start the MLflow experiment\nwith mlflow.start_run():\n \n print(\"Starting experiment:\", experiment.name)\n \n # Load data\n data = pd.read_csv('data/diabetes.csv')\n\n # Count the rows and log the result\n row_count = (len(data))\n mlflow.log_metric('observations', row_count)\n print(\"Run complete\")",
"_____no_output_____"
]
],
[
[
"Now let's look at the metrics logged during the run",
"_____no_output_____"
]
],
[
[
"# Get the latest run of the experiment\nrun = list(experiment.get_runs())[0]\n\n# Get logged metrics\nprint(\"\\nMetrics:\")\nmetrics = run.get_metrics()\nfor key in metrics.keys():\n print(key, metrics.get(key))\n \n# Get a link to the experiment in Azure ML studio \nexperiment_url = experiment.get_portal_url()\nprint('See details at', experiment_url)",
"_____no_output_____"
]
],
[
[
"After running the code above, you can use the link that is displayed to view the experiment in Azure Machine Learning studio. Then select the latest run of the experiment and view its **Metrics** tab to see the logged metric.\n\n### Use MLflow in an experiment script\n\nYou can also use MLflow to track metrics in an experiment script.\n\nRun the following two cells to create a folder and a script for an experiment that uses MLflow.",
"_____no_output_____"
]
],
[
[
"import os, shutil\n\n# Create a folder for the experiment files\nfolder_name = 'mlflow-experiment-files'\nexperiment_folder = './' + folder_name\nos.makedirs(folder_name, exist_ok=True)\n\n# Copy the data file into the experiment folder\nshutil.copy('data/diabetes.csv', os.path.join(folder_name, \"diabetes.csv\"))",
"_____no_output_____"
],
[
"%%writefile $folder_name/mlflow_diabetes.py\nfrom azureml.core import Run\nimport pandas as pd\nimport mlflow\n\n\n# start the MLflow experiment\nwith mlflow.start_run():\n \n # Load data\n data = pd.read_csv('diabetes.csv')\n\n # Count the rows and log the result\n row_count = (len(data))\n print('observations:', row_count)\n mlflow.log_metric('observations', row_count)",
"_____no_output_____"
]
],
[
[
"When you use MLflow tracking in an Azure ML experiment script, the MLflow tracking URI is set automatically when you start the experiment run. However, the environment in which the script is to be run must include the required **mlflow** packages.",
"_____no_output_____"
]
],
[
[
"from azureml.core import Experiment, ScriptRunConfig, Environment\nfrom azureml.widgets import RunDetails\n\n\n# Create a Python environment for the experiment (from a .yml file)\nenv = Environment.from_conda_specification(\"experiment_env\", \"environment.yml\")\n\n# Create a script config\nscript_mlflow = ScriptRunConfig(source_directory=experiment_folder,\n script='mlflow_diabetes.py',\n environment=env) \n\n# submit the experiment\nexperiment = Experiment(workspace=ws, name='mslearn-diabetes-mlflow')\nrun = experiment.submit(config=script_mlflow)\nRunDetails(run).show()\nrun.wait_for_completion()",
"_____no_output_____"
]
],
[
[
"As usual, you can get the logged metrics from the experiment run when it's finished.",
"_____no_output_____"
]
],
[
[
"# Get logged metrics\nmetrics = run.get_metrics()\nfor key in metrics.keys():\n print(key, metrics.get(key))",
"_____no_output_____"
]
],
[
[
"> **More Information**: To find out more about running experiments, see [this topic](https://docs.microsoft.com/azure/machine-learning/how-to-manage-runs) in the Azure ML documentation. For details of how to log metrics in a run, see [this topic](https://docs.microsoft.com/azure/machine-learning/how-to-track-experiments). For more information about integrating Azure ML experiments with MLflow, see [this topic](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-use-mlflow).",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
4ac54e6ffafde271ca42ec6e0870e752668a7d8c
| 4,211 |
ipynb
|
Jupyter Notebook
|
jupyter/annotation/english/match-pattern-pipeline/Pretrained-MatchPattern-Pipeline.ipynb
|
kbarlow-databricks/JohnSnowLabsTraining
|
f2c9463f0501739d2b5b35670b1d381edbc5267a
|
[
"Apache-2.0"
] | 3 |
2020-04-18T20:21:11.000Z
|
2022-02-08T23:57:46.000Z
|
jupyter/annotation/english/match-pattern-pipeline/Pretrained-MatchPattern-Pipeline.ipynb
|
mhibdr/spark-nlp-workshop
|
21fc6f5a75b77691c1207df190a703bf4ccafc8e
|
[
"Apache-2.0"
] | null | null | null |
jupyter/annotation/english/match-pattern-pipeline/Pretrained-MatchPattern-Pipeline.ipynb
|
mhibdr/spark-nlp-workshop
|
21fc6f5a75b77691c1207df190a703bf4ccafc8e
|
[
"Apache-2.0"
] | null | null | null | 20.441748 | 87 | 0.520066 |
[
[
[
"",
"_____no_output_____"
],
[
"# Use pretrained `match_pattern` Pipeline",
"_____no_output_____"
],
[
"\n* DocumentAssembler\n* SentenceDetector\n* Tokenizer\n* RegexMatcher (match phone numbers)\n",
"_____no_output_____"
]
],
[
[
"import sys\nsys.path.append('../')\n\n#Spark ML and SQL\nfrom pyspark.ml import Pipeline, PipelineModel\nfrom pyspark.sql.functions import array_contains\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.types import StructType, StructField, IntegerType, StringType\n\n#Spark NLP\nimport sparknlp\nfrom sparknlp.pretrained import PretrainedPipeline\nfrom sparknlp.base import LightPipeline\nfrom sparknlp.annotator import *\nfrom sparknlp.common import RegexRule\nfrom sparknlp.base import DocumentAssembler, Finisher",
"_____no_output_____"
]
],
[
[
"### Let's create a Spark Session for our app",
"_____no_output_____"
]
],
[
[
"spark = sparknlp.start()\n\nprint(\"Spark NLP version: \", sparknlp.version())\nprint(\"Apache Spark version: \", spark.version)\n",
"Spark NLP version: 2.4.2\nApache Spark version: 2.4.4\n"
]
],
[
[
"This Pipeline can extract `phone numbers` in these formats:\n```\n0689912549\n+33698912549\n+33 6 79 91 25 49\n+33-6-79-91-25-49\n(555)-555-5555\n555-555-5555\n+1-238 6 79 91 25 49\n+1-555-532-3455\n+15555323455\n+7 06 79 91 25 49\n```",
"_____no_output_____"
]
],
[
[
"pipeline = PretrainedPipeline('match_pattern', lang='en')",
"match_pattern download started this may take some time.\nApprox size to download 19.6 KB\n[OK!]\n"
],
[
"result=pipeline.annotate(\"You should call Mr. Jon Doe at +33 1 79 01 22 89\")",
"_____no_output_____"
],
[
"result['regex']",
"_____no_output_____"
],
[
"result=pipeline.annotate(\"Ring me up dude! +1-334-179-1466\")",
"_____no_output_____"
],
[
"result['regex']",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
4ac5534f0dcb9f44e93a83567573d3bc98d07186
| 6,341 |
ipynb
|
Jupyter Notebook
|
01-quickstart/.ipynb_checkpoints/np-checkpoint.ipynb
|
sachinpr0001/data_science
|
d028233ff7bbcbbb6b26f01806d1c5ccf788df9a
|
[
"MIT"
] | null | null | null |
01-quickstart/.ipynb_checkpoints/np-checkpoint.ipynb
|
sachinpr0001/data_science
|
d028233ff7bbcbbb6b26f01806d1c5ccf788df9a
|
[
"MIT"
] | null | null | null |
01-quickstart/.ipynb_checkpoints/np-checkpoint.ipynb
|
sachinpr0001/data_science
|
d028233ff7bbcbbb6b26f01806d1c5ccf788df9a
|
[
"MIT"
] | null | null | null | 16.385013 | 107 | 0.42375 |
[
[
[
"# Quickstart Numpy",
"_____no_output_____"
]
],
[
[
"!pip install numpy",
"Requirement already satisfied: numpy in c:\\users\\dexter\\anaconda3\\lib\\site-packages (1.18.1)\n"
],
[
"import numpy as np",
"_____no_output_____"
],
[
"a = np.array([1,2,3,4])\nprint(a)",
"[1 2 3 4]\n"
],
[
"print(type(a))",
"<class 'numpy.ndarray'>\n"
],
[
"a.shape",
"_____no_output_____"
],
[
"b = np.array([[1,2,3,4], [5,6,7,8]])\nprint(b)",
"[[1 2 3 4]\n [5 6 7 8]]\n"
],
[
"print(b.shape)",
"(2, 4)\n"
],
[
"b.T",
"_____no_output_____"
],
[
"np.dot(b, b.T)",
"_____no_output_____"
],
[
"np.random.randint?",
"_____no_output_____"
],
[
"np.random.randint(60,100,10)",
"_____no_output_____"
],
[
"matrix = np.random.randint(60,100,(5,5))\nprint(matrix)",
"[[94 88 66 77 74]\n [75 63 96 96 72]\n [73 76 67 63 96]\n [74 60 97 79 99]\n [92 88 66 95 77]]\n"
],
[
"np.min(matrix)",
"_____no_output_____"
],
[
"a = np.array([0,10,10,10,1,2,3,6,6,6,6,-8,10])",
"_____no_output_____"
],
[
"np.argmin(a)",
"_____no_output_____"
],
[
"b = np.unique(a, return_counts=True)",
"_____no_output_____"
],
[
"print(b[0])",
"[-8 0 1 2 3 6 10]\n"
],
[
"print(b[1])",
"[1 1 1 1 1 1 1]\n"
],
[
"b = np.unique(a, return_counts=True)",
"_____no_output_____"
],
[
"print(b)",
"(array([-8, 0, 1, 2, 3, 6, 10]), array([1, 1, 1, 1, 1, 1, 1], dtype=int64))\n"
],
[
"np.argmax(b[1])",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac5597912b7d452686a9b35e13cb64ef982e0fa
| 4,089 |
ipynb
|
Jupyter Notebook
|
notebooks/016. cross validation.ipynb
|
gillouche/exploratory-data-analysis
|
b2e2361ffd2eccbdbcfe72b9f223a7f06cc9d064
|
[
"MIT"
] | null | null | null |
notebooks/016. cross validation.ipynb
|
gillouche/exploratory-data-analysis
|
b2e2361ffd2eccbdbcfe72b9f223a7f06cc9d064
|
[
"MIT"
] | 2 |
2021-06-08T21:43:25.000Z
|
2021-12-13T20:41:55.000Z
|
notebooks/016. cross validation.ipynb
|
gillouche/exploratory-data-analysis
|
b2e2361ffd2eccbdbcfe72b9f223a7f06cc9d064
|
[
"MIT"
] | null | null | null | 22.344262 | 112 | 0.511127 |
[
[
[
"# Cross validation with KFold\n\nSplit the train set in k folds and use each fold as a validation set with the other folds as train set.\n\nThe result is then averaged.\n\nEvery observations will be in the testing set at least once.",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import KFold, cross_val_score\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets\nfrom sklearn import svm",
"_____no_output_____"
],
[
"X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])\ny = np.array([1, 2, 3, 4])",
"_____no_output_____"
],
[
"for train_index, test_index in KFold(n_splits=2).split(X):\n print(\"Train:\", train_index, \"Test:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]",
"Train: [2 3] Test: [0 1]\nTrain: [0 1] Test: [2 3]\n"
],
[
"for train_index, test_index in KFold(n_splits=4).split(X):\n print(\"Train:\", train_index, \"Test:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]",
"Train: [1 2 3] Test: [0]\nTrain: [0 2 3] Test: [1]\nTrain: [0 1 3] Test: [2]\nTrain: [0 1 2] Test: [3]\n"
]
],
[
[
"## Using K-Fold cross validation with a classifier",
"_____no_output_____"
]
],
[
[
"X, y = datasets.load_iris(return_X_y=True)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0)",
"_____no_output_____"
],
[
"clf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train)\nclf.score(X_test, y_test)",
"_____no_output_____"
],
[
"clf = svm.SVC(kernel='linear', C=1)\nscores = cross_val_score(clf, X, y, cv=5)\nscores",
"_____no_output_____"
],
[
"print(\"Accuracy: %0.2f (+/- %0.2f)\" % (scores.mean(), scores.std() * 2))",
"Accuracy: 0.98 (+/- 0.03)\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4ac55d4f2c2cf646231d4f2dff9906772a72ec7e
| 110,870 |
ipynb
|
Jupyter Notebook
|
notebooks/findkeywords.ipynb
|
myra-ink/model_fkeywords
|
7f6166453ebf3250aad968fcadac0c403585c6d9
|
[
"Apache-2.0"
] | null | null | null |
notebooks/findkeywords.ipynb
|
myra-ink/model_fkeywords
|
7f6166453ebf3250aad968fcadac0c403585c6d9
|
[
"Apache-2.0"
] | null | null | null |
notebooks/findkeywords.ipynb
|
myra-ink/model_fkeywords
|
7f6166453ebf3250aad968fcadac0c403585c6d9
|
[
"Apache-2.0"
] | null | null | null | 52.845567 | 739 | 0.443637 |
[
[
[
"## Install Lib API",
"_____no_output_____"
]
],
[
[
"! pip install https://dnaink.jfrog.io/artifactory/dna-ink-pypi/model-fkeywords/0.1.0/model_fkeywords-0.1.0-py3-none-any.whl",
"Collecting model-fkeywords==0.1.0\n Downloading https://dnaink.jfrog.io/artifactory/dna-ink-pypi/model-fkeywords/0.1.0/model_fkeywords-0.1.0-py3-none-any.whl (8.6 kB)\nCollecting django-rss-plugin==0.0.9\n Downloading django-rss-plugin-0.0.9.tar.gz (5.5 kB)\nCollecting requests==2.26.0\n Downloading requests-2.26.0-py2.py3-none-any.whl (62 kB)\n\u001b[K |████████████████████████████████| 62 kB 645 kB/s \n\u001b[?25hCollecting PyYAML==5.1\n Downloading PyYAML-5.1.tar.gz (274 kB)\n\u001b[K |████████████████████████████████| 274 kB 8.9 MB/s \n\u001b[?25hCollecting spacy==3.0.3\n Downloading spacy-3.0.3-cp37-cp37m-manylinux2014_x86_64.whl (12.7 MB)\n\u001b[K |████████████████████████████████| 12.7 MB 27.9 MB/s \n\u001b[?25hCollecting pygments>=2.7.4\n Downloading Pygments-2.11.2-py3-none-any.whl (1.1 MB)\n\u001b[K |████████████████████████████████| 1.1 MB 63.1 MB/s \n\u001b[?25hRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from model-fkeywords==0.1.0) (1.1.5)\nRequirement already satisfied: cython in /usr/local/lib/python3.7/dist-packages (from model-fkeywords==0.1.0) (0.29.26)\nCollecting pyspark==3.1.1\n Downloading pyspark-3.1.1.tar.gz (212.3 MB)\n\u001b[K |████████████████████████████████| 212.3 MB 14 kB/s \n\u001b[?25hRequirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (from model-fkeywords==0.1.0) (2019.12.20)\nCollecting seaborn==0.11.1\n Downloading seaborn-0.11.1-py3-none-any.whl (285 kB)\n\u001b[K |████████████████████████████████| 285 kB 49.9 MB/s \n\u001b[?25hCollecting twine\n Downloading twine-3.7.1-py3-none-any.whl (35 kB)\nRequirement already satisfied: pytest in /usr/local/lib/python3.7/dist-packages (from model-fkeywords==0.1.0) (3.6.4)\nCollecting nltk==3.6.5\n Downloading nltk-3.6.5-py3-none-any.whl (1.5 MB)\n\u001b[K |████████████████████████████████| 1.5 MB 55.8 MB/s \n\u001b[?25hCollecting pendulum==2.0.5\n Downloading pendulum-2.0.5-cp37-cp37m-manylinux1_x86_64.whl (141 kB)\n\u001b[K |████████████████████████████████| 141 kB 54.4 MB/s \n\u001b[?25hCollecting wordcloud>=1.8.1\n Downloading wordcloud-1.8.1-cp37-cp37m-manylinux1_x86_64.whl (366 kB)\n\u001b[K |████████████████████████████████| 366 kB 66.2 MB/s \n\u001b[?25hCollecting kneebow\n Downloading kneebow-0.1.1.tar.gz (3.4 kB)\nCollecting gensim>=4.0.0\n Downloading gensim-4.1.2-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (24.1 MB)\n\u001b[K |████████████████████████████████| 24.1 MB 1.4 MB/s \n\u001b[?25hCollecting feedparser\n Downloading feedparser-6.0.8-py3-none-any.whl (81 kB)\n\u001b[K |████████████████████████████████| 81 kB 8.6 MB/s \n\u001b[?25hCollecting Django>=1.4\n Downloading Django-3.2.11-py3-none-any.whl (7.9 MB)\n\u001b[K |████████████████████████████████| 7.9 MB 29.2 MB/s \n\u001b[?25hCollecting django-cms>=2.3\n Downloading django_cms-3.9.0-py2.py3-none-any.whl (2.1 MB)\n\u001b[K |████████████████████████████████| 2.1 MB 39.2 MB/s \n\u001b[?25hRequirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from nltk==3.6.5->model-fkeywords==0.1.0) (1.1.0)\nRequirement already satisfied: click in /usr/local/lib/python3.7/dist-packages (from nltk==3.6.5->model-fkeywords==0.1.0) (7.1.2)\nCollecting regex\n Downloading regex-2022.1.18-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (748 kB)\n\u001b[K |████████████████████████████████| 748 kB 61.8 MB/s \n\u001b[?25hRequirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from nltk==3.6.5->model-fkeywords==0.1.0) (4.62.3)\nRequirement already satisfied: python-dateutil<3.0,>=2.6 in /usr/local/lib/python3.7/dist-packages (from pendulum==2.0.5->model-fkeywords==0.1.0) (2.8.2)\nCollecting pytzdata>=2018.3\n Downloading pytzdata-2020.1-py2.py3-none-any.whl (489 kB)\n\u001b[K |████████████████████████████████| 489 kB 75.1 MB/s \n\u001b[?25hCollecting py4j==0.10.9\n Downloading py4j-0.10.9-py2.py3-none-any.whl (198 kB)\n\u001b[K |████████████████████████████████| 198 kB 75.0 MB/s \n\u001b[?25hRequirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests==2.26.0->model-fkeywords==0.1.0) (1.24.3)\nRequirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests==2.26.0->model-fkeywords==0.1.0) (2.10)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests==2.26.0->model-fkeywords==0.1.0) (2021.10.8)\nRequirement already satisfied: charset-normalizer~=2.0.0 in /usr/local/lib/python3.7/dist-packages (from requests==2.26.0->model-fkeywords==0.1.0) (2.0.10)\nRequirement already satisfied: numpy>=1.15 in /usr/local/lib/python3.7/dist-packages (from seaborn==0.11.1->model-fkeywords==0.1.0) (1.19.5)\nRequirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from seaborn==0.11.1->model-fkeywords==0.1.0) (1.4.1)\nRequirement already satisfied: matplotlib>=2.2 in /usr/local/lib/python3.7/dist-packages (from seaborn==0.11.1->model-fkeywords==0.1.0) (3.2.2)\nRequirement already satisfied: wasabi<1.1.0,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from spacy==3.0.3->model-fkeywords==0.1.0) (0.9.0)\nCollecting pathy\n Downloading pathy-0.6.1-py3-none-any.whl (42 kB)\n\u001b[K |████████████████████████████████| 42 kB 1.1 MB/s \n\u001b[?25hCollecting typer<0.4.0,>=0.3.0\n Downloading typer-0.3.2-py3-none-any.whl (21 kB)\nCollecting catalogue<2.1.0,>=2.0.1\n Downloading catalogue-2.0.6-py3-none-any.whl (17 kB)\nRequirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy==3.0.3->model-fkeywords==0.1.0) (2.0.6)\nRequirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from spacy==3.0.3->model-fkeywords==0.1.0) (21.3)\nRequirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.7/dist-packages (from spacy==3.0.3->model-fkeywords==0.1.0) (1.0.6)\nRequirement already satisfied: typing-extensions>=3.7.4 in /usr/local/lib/python3.7/dist-packages (from spacy==3.0.3->model-fkeywords==0.1.0) (3.10.0.2)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from spacy==3.0.3->model-fkeywords==0.1.0) (57.4.0)\nCollecting thinc<8.1.0,>=8.0.0\n Downloading thinc-8.0.13-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (628 kB)\n\u001b[K |████████████████████████████████| 628 kB 73.0 MB/s \n\u001b[?25hCollecting spacy-legacy<3.1.0,>=3.0.0\n Downloading spacy_legacy-3.0.8-py2.py3-none-any.whl (14 kB)\nRequirement already satisfied: blis<0.8.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy==3.0.3->model-fkeywords==0.1.0) (0.4.1)\nCollecting pydantic<1.8.0,>=1.7.1\n Downloading pydantic-1.7.4-cp37-cp37m-manylinux2014_x86_64.whl (9.1 MB)\n\u001b[K |████████████████████████████████| 9.1 MB 31.8 MB/s \n\u001b[?25hCollecting srsly<3.0.0,>=2.4.0\n Downloading srsly-2.4.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (451 kB)\n\u001b[K |████████████████████████████████| 451 kB 39.8 MB/s \n\u001b[?25hRequirement already satisfied: importlib-metadata>=0.20 in /usr/local/lib/python3.7/dist-packages (from spacy==3.0.3->model-fkeywords==0.1.0) (4.10.0)\nRequirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy==3.0.3->model-fkeywords==0.1.0) (3.0.6)\nRequirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from spacy==3.0.3->model-fkeywords==0.1.0) (2.11.3)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from catalogue<2.1.0,>=2.0.1->spacy==3.0.3->model-fkeywords==0.1.0) (3.7.0)\nRequirement already satisfied: pytz in /usr/local/lib/python3.7/dist-packages (from Django>=1.4->django-rss-plugin==0.0.9->model-fkeywords==0.1.0) (2018.9)\nCollecting asgiref<4,>=3.3.2\n Downloading asgiref-3.4.1-py3-none-any.whl (25 kB)\nRequirement already satisfied: sqlparse>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from Django>=1.4->django-rss-plugin==0.0.9->model-fkeywords==0.1.0) (0.4.2)\nCollecting djangocms-admin-style>=1.2\n Downloading djangocms_admin_style-2.0.2-py3-none-any.whl (404 kB)\n\u001b[K |████████████████████████████████| 404 kB 54.3 MB/s \n\u001b[?25hCollecting django-formtools>=2.1\n Downloading django_formtools-2.3-py3-none-any.whl (148 kB)\n\u001b[K |████████████████████████████████| 148 kB 53.5 MB/s \n\u001b[?25hCollecting django-classy-tags>=0.7.2\n Downloading django_classy_tags-2.0.0-py3-none-any.whl (23 kB)\nCollecting django-sekizai>=0.7\n Downloading django_sekizai-2.0.0-py3-none-any.whl (12 kB)\nCollecting django-treebeard>=4.3\n Downloading django_treebeard-4.5.1-py3-none-any.whl (103 kB)\n\u001b[K |████████████████████████████████| 103 kB 64.8 MB/s \n\u001b[?25hRequirement already satisfied: smart-open>=1.8.1 in /usr/local/lib/python3.7/dist-packages (from gensim>=4.0.0->model-fkeywords==0.1.0) (5.2.1)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.2->seaborn==0.11.1->model-fkeywords==0.1.0) (1.3.2)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.2->seaborn==0.11.1->model-fkeywords==0.1.0) (3.0.6)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib>=2.2->seaborn==0.11.1->model-fkeywords==0.1.0) (0.11.0)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil<3.0,>=2.6->pendulum==2.0.5->model-fkeywords==0.1.0) (1.15.0)\nRequirement already satisfied: pillow in /usr/local/lib/python3.7/dist-packages (from wordcloud>=1.8.1->model-fkeywords==0.1.0) (7.1.2)\nCollecting sgmllib3k\n Downloading sgmllib3k-1.0.0.tar.gz (5.8 kB)\nRequirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->spacy==3.0.3->model-fkeywords==0.1.0) (2.0.1)\nRequirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from kneebow->model-fkeywords==0.1.0) (1.0.2)\nRequirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.7/dist-packages (from pytest->model-fkeywords==0.1.0) (0.7.1)\nRequirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.7/dist-packages (from pytest->model-fkeywords==0.1.0) (21.4.0)\nRequirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pytest->model-fkeywords==0.1.0) (1.11.0)\nRequirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from pytest->model-fkeywords==0.1.0) (8.12.0)\nRequirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.7/dist-packages (from pytest->model-fkeywords==0.1.0) (1.4.0)\nRequirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->kneebow->model-fkeywords==0.1.0) (3.0.0)\nCollecting keyring>=15.1\n Downloading keyring-23.5.0-py3-none-any.whl (33 kB)\nCollecting readme-renderer>=21.0\n Downloading readme_renderer-32.0-py3-none-any.whl (16 kB)\nCollecting requests-toolbelt!=0.9.0,>=0.8.0\n Downloading requests_toolbelt-0.9.1-py2.py3-none-any.whl (54 kB)\n\u001b[K |████████████████████████████████| 54 kB 2.2 MB/s \n\u001b[?25hCollecting colorama>=0.4.3\n Downloading colorama-0.4.4-py2.py3-none-any.whl (16 kB)\nCollecting pkginfo>=1.8.1\n Downloading pkginfo-1.8.2-py2.py3-none-any.whl (26 kB)\nCollecting rfc3986>=1.4.0\n Downloading rfc3986-2.0.0-py2.py3-none-any.whl (31 kB)\nCollecting jeepney>=0.4.2\n Downloading jeepney-0.7.1-py3-none-any.whl (54 kB)\n\u001b[K |████████████████████████████████| 54 kB 2.1 MB/s \n\u001b[?25hCollecting SecretStorage>=3.2\n Downloading SecretStorage-3.3.1-py3-none-any.whl (15 kB)\nRequirement already satisfied: docutils>=0.13.1 in /usr/local/lib/python3.7/dist-packages (from readme-renderer>=21.0->twine->model-fkeywords==0.1.0) (0.17.1)\nRequirement already satisfied: bleach>=2.1.0 in /usr/local/lib/python3.7/dist-packages (from readme-renderer>=21.0->twine->model-fkeywords==0.1.0) (4.1.0)\nRequirement already satisfied: webencodings in /usr/local/lib/python3.7/dist-packages (from bleach>=2.1.0->readme-renderer>=21.0->twine->model-fkeywords==0.1.0) (0.5.1)\nCollecting cryptography>=2.0\n Downloading cryptography-36.0.1-cp36-abi3-manylinux_2_24_x86_64.whl (3.6 MB)\n\u001b[K |████████████████████████████████| 3.6 MB 41.6 MB/s \n\u001b[?25hRequirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=2.0->SecretStorage>=3.2->keyring>=15.1->twine->model-fkeywords==0.1.0) (1.15.0)\nRequirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=2.0->SecretStorage>=3.2->keyring>=15.1->twine->model-fkeywords==0.1.0) (2.21)\nBuilding wheels for collected packages: django-rss-plugin, pyspark, PyYAML, kneebow, sgmllib3k\n Building wheel for django-rss-plugin (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for django-rss-plugin: filename=django_rss_plugin-0.0.9-py3-none-any.whl size=7869 sha256=b43edeb13e91071698fa3c2ffbc3b3d396cbc22e2f61587a1f92b41ee3c25f30\n Stored in directory: /root/.cache/pip/wheels/b9/50/4a/54ef95c386ece9d6f25e81eaee1d0b106e536a2eb35e45335b\n Building wheel for pyspark (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for pyspark: filename=pyspark-3.1.1-py2.py3-none-any.whl size=212767605 sha256=3a3c68c67f3f4c39369f93992cef8e6c439a83a4d9397f1d957bc4b7c6c63dc0\n Stored in directory: /root/.cache/pip/wheels/43/47/42/bc413c760cf9d3f7b46ab7cd6590e8c47ebfd19a7386cd4a57\n Building wheel for PyYAML (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for PyYAML: filename=PyYAML-5.1-cp37-cp37m-linux_x86_64.whl size=44092 sha256=83dd208397266d420e7e13e1ab13ebb10ccd1015845a29ce21e017b863b62d68\n Stored in directory: /root/.cache/pip/wheels/77/f5/10/d00a2bd30928b972790053b5de0c703ca87324f3fead0f2fd9\n Building wheel for kneebow (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for kneebow: filename=kneebow-0.1.1-py3-none-any.whl size=3591 sha256=27c3f94e3bfabd8bd3126b0a7bc30ed1a2e5ed9bb626b54eb4da07c46abccd2a\n Stored in directory: /root/.cache/pip/wheels/df/c8/26/01654920ba2a566c78a34582bb013ba47e0eb8ce358008954c\n Building wheel for sgmllib3k (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for sgmllib3k: filename=sgmllib3k-1.0.0-py3-none-any.whl size=6066 sha256=dafa2b9a12e5fb2d0b1818fce2d26d7cd7701b63315f97baf269185ef1b97846\n Stored in directory: /root/.cache/pip/wheels/73/ad/a4/0dff4a6ef231fc0dfa12ffbac2a36cebfdddfe059f50e019aa\nSuccessfully built django-rss-plugin pyspark PyYAML kneebow sgmllib3k\nInstalling collected packages: asgiref, Django, jeepney, django-classy-tags, cryptography, catalogue, typer, srsly, sgmllib3k, SecretStorage, requests, pygments, pydantic, djangocms-admin-style, django-treebeard, django-sekizai, django-formtools, thinc, spacy-legacy, rfc3986, requests-toolbelt, regex, readme-renderer, pytzdata, py4j, pkginfo, pathy, keyring, feedparser, django-cms, colorama, wordcloud, twine, spacy, seaborn, PyYAML, pyspark, pendulum, nltk, kneebow, gensim, django-rss-plugin, model-fkeywords\n Attempting uninstall: catalogue\n Found existing installation: catalogue 1.0.0\n Uninstalling catalogue-1.0.0:\n Successfully uninstalled catalogue-1.0.0\n Attempting uninstall: srsly\n Found existing installation: srsly 1.0.5\n Uninstalling srsly-1.0.5:\n Successfully uninstalled srsly-1.0.5\n Attempting uninstall: requests\n Found existing installation: requests 2.23.0\n Uninstalling requests-2.23.0:\n Successfully uninstalled requests-2.23.0\n Attempting uninstall: pygments\n Found existing installation: Pygments 2.6.1\n Uninstalling Pygments-2.6.1:\n Successfully uninstalled Pygments-2.6.1\n Attempting uninstall: thinc\n Found existing installation: thinc 7.4.0\n Uninstalling thinc-7.4.0:\n Successfully uninstalled thinc-7.4.0\n Attempting uninstall: regex\n Found existing installation: regex 2019.12.20\n Uninstalling regex-2019.12.20:\n Successfully uninstalled regex-2019.12.20\n Attempting uninstall: wordcloud\n Found existing installation: wordcloud 1.5.0\n Uninstalling wordcloud-1.5.0:\n Successfully uninstalled wordcloud-1.5.0\n Attempting uninstall: spacy\n Found existing installation: spacy 2.2.4\n Uninstalling spacy-2.2.4:\n Successfully uninstalled spacy-2.2.4\n Attempting uninstall: seaborn\n Found existing installation: seaborn 0.11.2\n Uninstalling seaborn-0.11.2:\n Successfully uninstalled seaborn-0.11.2\n Attempting uninstall: PyYAML\n Found existing installation: PyYAML 3.13\n Uninstalling PyYAML-3.13:\n Successfully uninstalled PyYAML-3.13\n Attempting uninstall: nltk\n Found existing installation: nltk 3.2.5\n Uninstalling nltk-3.2.5:\n Successfully uninstalled nltk-3.2.5\n Attempting uninstall: gensim\n Found existing installation: gensim 3.6.0\n Uninstalling gensim-3.6.0:\n Successfully uninstalled gensim-3.6.0\n\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\ngoogle-colab 1.0.0 requires requests~=2.23.0, but you have requests 2.26.0 which is incompatible.\ndatascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.\u001b[0m\nSuccessfully installed Django-3.2.11 PyYAML-5.1 SecretStorage-3.3.1 asgiref-3.4.1 catalogue-2.0.6 colorama-0.4.4 cryptography-36.0.1 django-classy-tags-2.0.0 django-cms-3.9.0 django-formtools-2.3 django-rss-plugin-0.0.9 django-sekizai-2.0.0 django-treebeard-4.5.1 djangocms-admin-style-2.0.2 feedparser-6.0.8 gensim-4.1.2 jeepney-0.7.1 keyring-23.5.0 kneebow-0.1.1 model-fkeywords-0.1.0 nltk-3.6.5 pathy-0.6.1 pendulum-2.0.5 pkginfo-1.8.2 py4j-0.10.9 pydantic-1.7.4 pygments-2.11.2 pyspark-3.1.1 pytzdata-2020.1 readme-renderer-32.0 regex-2022.1.18 requests-2.26.0 requests-toolbelt-0.9.1 rfc3986-2.0.0 seaborn-0.11.1 sgmllib3k-1.0.0 spacy-3.0.3 spacy-legacy-3.0.8 srsly-2.4.2 thinc-8.0.13 twine-3.7.1 typer-0.3.2 wordcloud-1.8.1\n"
],
[
"! python -m spacy download pt_core_news_sm",
"Collecting pt-core-news-sm==3.0.0\n Downloading https://github.com/explosion/spacy-models/releases/download/pt_core_news_sm-3.0.0/pt_core_news_sm-3.0.0-py3-none-any.whl (22.1 MB)\n\u001b[K |████████████████████████████████| 22.1 MB 311 kB/s \n\u001b[?25hRequirement already satisfied: spacy<3.1.0,>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from pt-core-news-sm==3.0.0) (3.0.3)\nRequirement already satisfied: numpy>=1.15.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (1.19.5)\nRequirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.0.6)\nRequirement already satisfied: pydantic<1.8.0,>=1.7.1 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (1.7.4)\nRequirement already satisfied: catalogue<2.1.0,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.0.6)\nRequirement already satisfied: typing-extensions>=3.7.4 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (3.10.0.2)\nRequirement already satisfied: pathy in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (0.6.1)\nRequirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (21.3)\nRequirement already satisfied: tqdm<5.0.0,>=4.38.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (4.62.3)\nRequirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.11.3)\nRequirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (1.0.6)\nRequirement already satisfied: requests<3.0.0,>=2.13.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.26.0)\nRequirement already satisfied: thinc<8.1.0,>=8.0.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (8.0.13)\nRequirement already satisfied: spacy-legacy<3.1.0,>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (3.0.8)\nRequirement already satisfied: typer<0.4.0,>=0.3.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (0.3.2)\nRequirement already satisfied: importlib-metadata>=0.20 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (4.10.0)\nRequirement already satisfied: wasabi<1.1.0,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (0.9.0)\nRequirement already satisfied: blis<0.8.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (0.4.1)\nRequirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (3.0.6)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (57.4.0)\nRequirement already satisfied: srsly<3.0.0,>=2.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.4.2)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from catalogue<2.1.0,>=2.0.1->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (3.7.0)\nRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging>=20.0->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (3.0.6)\nRequirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.13.0->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (1.24.3)\nRequirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.13.0->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.10)\nRequirement already satisfied: charset-normalizer~=2.0.0 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.13.0->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.0.10)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3.0.0,>=2.13.0->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2021.10.8)\nRequirement already satisfied: click<7.2.0,>=7.1.1 in /usr/local/lib/python3.7/dist-packages (from typer<0.4.0,>=0.3.0->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (7.1.2)\nRequirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (2.0.1)\nRequirement already satisfied: smart-open<6.0.0,>=5.0.0 in /usr/local/lib/python3.7/dist-packages (from pathy->spacy<3.1.0,>=3.0.0->pt-core-news-sm==3.0.0) (5.2.1)\nInstalling collected packages: pt-core-news-sm\nSuccessfully installed pt-core-news-sm-3.0.0\n\u001b[38;5;2m✔ Download and installation successful\u001b[0m\nYou can now load the package via spacy.load('pt_core_news_sm')\n"
]
],
[
[
"## Import libs",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport spacy\nimport nltk\nnltk.download('stopwords')\nfrom api_model import nlextract\n\npd.set_option('display.max_colwidth', -1)\npd.set_option('display.max_rows', None)",
"[nltk_data] Downloading package stopwords to /root/nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:7: FutureWarning: Passing a negative integer is deprecated in version 1.0 and will not be supported in future version. Instead, use None to not limit the column width.\n import sys\n"
],
[
"extractor = nlextract.NLExtractor()",
"[nltk_data] Downloading package stopwords to /root/nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n"
]
],
[
[
"## Read Excel file",
"_____no_output_____"
]
],
[
[
"df = pd.read_excel(\"/content/Conversas Sodexo.xlsx\", engine='openpyxl')\ndf.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 179685 entries, 0 to 179684\nData columns (total 35 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Codigo 179685 non-null int64 \n 1 CHAT_Protocolo 179685 non-null int64 \n 2 TEM 179685 non-null int64 \n 3 ChatID 179685 non-null int64 \n 4 ExpertID 179685 non-null int64 \n 5 ExpertFullName 179685 non-null object \n 6 CategoryName 179685 non-null object \n 7 ClosedBy 179614 non-null object \n 8 DateAnswered 179685 non-null float64 \n 9 DateFinished 179541 non-null float64 \n 10 CustomerID 179685 non-null int64 \n 11 CustomerName 179644 non-null object \n 12 CustomerEmail 179685 non-null object \n 13 DataInsercao 179685 non-null float64 \n 14 Status 179685 non-null int64 \n 15 Resolution 173979 non-null float64 \n 16 CustomerFieldA 179685 non-null int64 \n 17 CustomerFieldC 45 non-null object \n 18 CustomerFieldD 0 non-null float64 \n 19 CustomerFieldE 2634 non-null object \n 20 CustomerFieldG 2380 non-null object \n 21 CustomerFieldH 4099 non-null object \n 22 CustomerFieldU 0 non-null float64 \n 23 Link 179685 non-null object \n 24 UniqueID 177585 non-null float64 \n 25 Type 179685 non-null int64 \n 26 MsgTipo 179685 non-null int64 \n 27 ClassificacaoTags 0 non-null float64 \n 28 ClassificacaoTreeName 0 non-null float64 \n 29 CustomerName_1 97583 non-null object \n 30 ExpertFullName_2 81227 non-null object \n 31 Date 179685 non-null datetime64[ns]\n 32 MÊS 179685 non-null object \n 33 Message 179685 non-null object \n 34 Column1 2234 non-null object \ndtypes: datetime64[ns](1), float64(9), int64(10), object(15)\nmemory usage: 48.0+ MB\n"
]
],
[
[
"#### See the first line of dataset",
"_____no_output_____"
]
],
[
[
"df.head(1)",
"_____no_output_____"
]
],
[
[
"### Limpeza de acentuações",
"_____no_output_____"
],
[
"#### Atribuir o nome original da coluna de texto para uma variavel (pode se usar qualquer coluna que tenha texto)",
"_____no_output_____"
]
],
[
[
"coluna_texto = 'Message'",
"_____no_output_____"
],
[
"df[f'{coluna_texto}_clean'] = df[coluna_texto].apply(extractor.udf_clean_text) ## limpa toda a acentuação, caracteres especiais,\n # pontuações do texto.",
"_____no_output_____"
],
[
"df[[f'{coluna_texto}_clean', coluna_texto]].head(10)",
"_____no_output_____"
]
],
[
[
"### Call the functions inside of wheels file",
"_____no_output_____"
],
[
"#### Lista de Palavras Procuradas",
"_____no_output_____"
],
[
"#### Formato Exemplo:\n variavel = {coluna_nome : [lista de palavras procuradas],\n coluna_nome : [lista de palavras procuradas]}",
"_____no_output_____"
]
],
[
[
"mydict = {\n 'alto_atrito': ['ainda não', 'não chegou', 'até agora', 'até o momento', 'atraso', 'reclamação', 'pelo amor de Deus', 'procon', \\\n 'péssimo', 'cansado', 'incompetente', 'ouvidoria', 'frustração', 'absurdo', 'porra', 'PQP', 'poxa vida', 'horrível',\\\n 'ridículo', 'decepção', 'humilhação', 'FDP', 'merda', 'triste', 'bosta', 'protocolo','so um miniuto'],\n 'cancelamento': ['cancelar minha viagem', 'quero cancelar', 'cancelamento', 'desejo cancelar', 'quero desativar', 'verificado'],\n 'callback': ['me liga de novo', 'está me ligado']\n }",
"_____no_output_____"
]
],
[
[
"#### Colocar coluna original para lowercase (minusculo)",
"_____no_output_____"
]
],
[
[
"df[coluna_texto] = df[coluna_texto].str.lower()",
"_____no_output_____"
]
],
[
[
"#### Aplicar função de Caça Palavras no Texto",
"_____no_output_____"
]
],
[
[
"coluna_texto = f'{coluna_texto}_clean'",
"_____no_output_____"
],
[
"try:\n for key in mydict:\n df[key] = df[coluna_texto].apply(lambda x: extractor.pattern_matcher(x,mydict[key],mode=\"dictionary\", anonymizer=False,custom_anonymizer=f'<{key}>'))\nexcept IOError as e:\n print(f'não tem mais listas para rodar dados {e}')\n pass",
"_____no_output_____"
],
[
"df[['Message','Message_clean','alto_atrito','cancelamento','callback']].head(20)",
"_____no_output_____"
]
],
[
[
"## Caça Palavras com palavras exatas do texto",
"_____no_output_____"
]
],
[
[
"mydict = {\n 'alto_atrito_2': ['ainda não', 'não chegou', 'até agora', 'até o momento', 'atraso', 'reclamação', 'pelo amor de Deus', 'procon', \\\n 'péssimo', 'cansado', 'incompetente', 'ouvidoria', 'frustração', 'absurdo', 'porra', 'PQP', 'poxa vida', 'horrível',\\\n 'ridículo', 'decepção', 'humilhação', 'FDP', 'merda', 'triste', 'bosta', 'protocolo'],\n 'cancelamento_2': ['cancelar minha viagem', 'quero cancelar', 'cancelamento', 'desejo cancelar', 'quero desativar', 'verificado']\n }",
"_____no_output_____"
],
[
"try:\n for key in mydict:\n df[key] = df[coluna_texto].apply(lambda x: extractor.udf_type_keywords(x,mydict[key],mode=\"dictionary\"))\nexcept IOError as e:\n print(f'não tem mais listas para rodar dados {e}')\n pass",
"_____no_output_____"
]
],
[
[
"#### Avaliação das colunas do Caça Palavras geradas",
"_____no_output_____"
]
],
[
[
"df[['Message','Message_clean','alto_atrito','cancelamento','alto_atrito_2', 'cancelamento_2']].head(50)",
"_____no_output_____"
]
],
[
[
"## Salvar o Resultado em um CSV",
"_____no_output_____"
]
],
[
[
"filename = 'sodexo_tratado'\nfile_save = f'{filename}.csv'\ndf.to_csv(file_save, sep=';',encoding='utf-8',index=False)",
"_____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",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac56cde02b0ae60ec947062f9464a5ee47a7bf5
| 12,306 |
ipynb
|
Jupyter Notebook
|
learning_per_machine.ipynb
|
shuuchen/data_analysis
|
8982765eaac05128c5bd1b90c9356a95b032493a
|
[
"MIT"
] | null | null | null |
learning_per_machine.ipynb
|
shuuchen/data_analysis
|
8982765eaac05128c5bd1b90c9356a95b032493a
|
[
"MIT"
] | null | null | null |
learning_per_machine.ipynb
|
shuuchen/data_analysis
|
8982765eaac05128c5bd1b90c9356a95b032493a
|
[
"MIT"
] | null | null | null | 38.099071 | 175 | 0.493743 |
[
[
[
"import pandas as pd\nimport os\nimport numpy as np\nfrom datetime import timedelta\n\nfrom sklearn.ensemble import RandomForestRegressor\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline",
"_____no_output_____"
],
[
"in_dir = 'D:\\\\Toppan\\\\2017-11-20 全データ\\\\処理済(機械ごと)\\\\vectorized'\nout_dir = in_dir",
"_____no_output_____"
],
[
"holiday_path = 'D:\\\\Toppan\\\\2017-11-20 全データ\\\\データ\\\\切り離し全休日\\\\全休日.xlsx'\n\ndef mask_out(X, y, month):\n \n try:\n df_filter = pd.read_excel(holiday_path, sheet_name=month, index_col=0).iloc[2:]\n except Exception as e:\n print(e, month)\n return X, y\n \n seisan = True if '生産\\n有無' in df_filter else False\n \n def isBusy(idx):\n row = df_filter.loc[idx]\n if row.loc['切離\\n有無'] == '切離' or row.loc['全休\\n判定'] == '全休' \\\n or row.loc['異常判定'] == '※異常稼動' or (seisan and row.loc['生産\\n有無'] == '無'):\n return False\n else:\n return True\n \n x_busy_idx = []\n y_busy_idx = []\n for x_idx, y_idx in zip (X.index, y.index):\n if isBusy(x_idx) and isBusy(y_idx):\n x_busy_idx.append(x_idx)\n y_busy_idx.append(y_idx)\n \n return X.loc[x_busy_idx], y.loc[y_busy_idx]",
"_____no_output_____"
],
[
"def get_importance_figure(model, name, features):\n \n indices = np.argsort(model.feature_importances_)[::-1]\n \n # save csv\n s = pd.Series(data=model.feature_importances_[indices], \n index=features[indices])\n \n s.to_csv(os.path.join(out_dir, name + '_寄与度.csv'), \n encoding='shift-jis')",
"_____no_output_____"
],
[
"def parse_data(exl, sheet):\n \n df = exl.parse(sheet_name=sheet, index_col=0)\n\n return df\n",
"_____no_output_____"
],
[
"def split_day_night(acc_abs):\n acc_abs_days, acc_abs_nights = [], []\n for i, acc in acc_abs.iteritems():\n if 7 < i.hour < 22:\n acc_abs_days.append(acc)\n else:\n acc_abs_nights.append(acc)\n\n return acc_abs_days, acc_abs_nights\n\ndef get_output(res, output, sname):\n res = res[res['target'] != 0]\n \n if len(res) == 0:\n return None\n \n y_pred, y_true = res['preds'], res['target']\n '''calculate abs accuracy'''\n acc_abs = abs(y_pred - y_true) / y_true\n '''aplit days and nights'''\n acc_abs_days, acc_abs_nights = split_day_night(acc_abs)\n len_days, len_nights = len(acc_abs_days), len(acc_abs_nights)\n\n #sname2acc = {'蒸気': [0.2, 0.15], '電力': [0.09, 0.15], '冷水': [0.15, 0.1]}\n\n '''acc stats'''\n len_acc_days = len(list(filter(lambda x: x <= 0.2, acc_abs_days)))\n len_acc_nights = len(list(filter(lambda x: x <= 0.15, acc_abs_nights)))\n acc_stats_days = len_acc_days / len_days\n acc_stats_nights = len_acc_nights / len_nights\n\n output['設備名'].append(sname)\n output['平日昼・総'].append(len_days)\n output['平日夜・総'].append(len_nights)\n output['平日昼・基準内'].append(len_acc_days)\n output['平日夜・基準内'].append(len_acc_nights)\n output['平日昼基準率'].append(acc_stats_days)\n output['平日夜基準率'].append(acc_stats_nights)\n\n return output",
"_____no_output_____"
]
],
[
[
"### Learning",
"_____no_output_____"
]
],
[
[
"exl_learn = pd.ExcelFile(os.path.join(in_dir, '201709010800_vapor_per_machine.xlsx'))\nexl_test = pd.ExcelFile(os.path.join(in_dir, '201710010800_vapor_per_machine.xlsx'))\n\naccs = []\nfor sheet in exl_learn.sheet_names:\n \n if sheet == 'GDNA': continue\n \n # data\n df_learn = parse_data(exl_learn, sheet)\n df_test = parse_data(exl_test, sheet)\n\n # filter out holidays\n X_learn, y_learn = mask_out(df_learn.iloc[:-1, :-1], df_learn.iloc[1:, -1], '17年9月')\n X_test, y_test = mask_out(df_test.iloc[:-1, :-1], df_test.iloc[1:, -1], '17年10月')\n \n # base learner\n model = RandomForestRegressor(n_estimators=700, \n n_jobs=-1, \n max_depth=11, \n max_features='auto', \n criterion='mae', \n random_state=700, \n warm_start=True)\n \n # learn 1 hour later target\n model.fit(X_learn.values, y_learn.values)\n \n # get feature importance figures\n #get_importance_figure(model, sheet)\n \n # test with online learning\n preds = []\n for idx, row in X_test.iterrows():\n \n # predict\n preds.append(model.predict(row.values.reshape(1, -1))[0])\n \n # online learning\n model.n_estimators += 50\n \n X_learn = X_learn.append(row)\n y_learn = y_learn.append(pd.Series(data=y_test.loc[idx + timedelta(hours=1)], \n index=[idx + timedelta(hours=1)]))\n \n model.fit(X_learn, y_learn)\n \n # save preds and test\n preds = pd.Series(data=preds, index=y_test.index, name='preds')\n result = pd.concat([preds, y_test], axis=1)\n result.to_csv(os.path.join(out_dir, sheet + '.csv'))\n \n # accuracy\n output = {'設備名': [], \n '平日昼・総': [], '平日夜・総': [], \n '平日昼・基準内': [], '平日夜・基準内': [], \n '平日昼基準率': [], '平日夜基準率': []}\n output = get_output(result, output, sheet)\n \n print(sheet, output)\n \n if output:\n accs.append(pd.DataFrame(output))\n \n# save accuracy\naccs = pd.concat(accs)\naccs.to_csv(os.path.join(out_dir, 'acc.csv'), index=False, encoding='shift-jis')\n ",
"GDNB {'設備名': ['GDNB'], '平日昼・総': [290], '平日夜・総': [202], '平日昼・基準内': [107], '平日夜・基準内': [56], '平日昼基準率': [0.3689655172413793], '平日夜基準率': [0.27722772277227725]}\nGE07 {'設備名': ['GE07'], '平日昼・総': [292], '平日夜・総': [227], '平日昼・基準内': [125], '平日夜・基準内': [53], '平日昼基準率': [0.4280821917808219], '平日夜基準率': [0.23348017621145375]}\nGE51 {'設備名': ['GE51'], '平日昼・総': [299], '平日夜・総': [234], '平日昼・基準内': [125], '平日夜・基準内': [67], '平日昼基準率': [0.4180602006688963], '平日夜基準率': [0.2863247863247863]}\nGE52 {'設備名': ['GE52'], '平日昼・総': [124], '平日夜・総': [124], '平日昼・基準内': [56], '平日夜・基準内': [42], '平日昼基準率': [0.45161290322580644], '平日夜基準率': [0.3387096774193548]}\nGE53 {'設備名': ['GE53'], '平日昼・総': [294], '平日夜・総': [215], '平日昼・基準内': [189], '平日夜・基準内': [137], '平日昼基準率': [0.6428571428571429], '平日夜基準率': [0.6372093023255814]}\nGL15 {'設備名': ['GL15'], '平日昼・総': [341], '平日夜・総': [266], '平日昼・基準内': [304], '平日夜・基準内': [242], '平日昼基準率': [0.8914956011730205], '平日夜基準率': [0.9097744360902256]}\nGL51 {'設備名': ['GL51'], '平日昼・総': [340], '平日夜・総': [266], '平日昼・基準内': [328], '平日夜・基準内': [214], '平日昼基準率': [0.9647058823529412], '平日夜基準率': [0.8045112781954887]}\nGL52 {'設備名': ['GL52'], '平日昼・総': [344], '平日夜・総': [267], '平日昼・基準内': [323], '平日夜・基準内': [250], '平日昼基準率': [0.938953488372093], '平日夜基準率': [0.9363295880149812]}\nGP22 {'設備名': ['GP22'], '平日昼・総': [322], '平日夜・総': [247], '平日昼・基準内': [150], '平日夜・基準内': [63], '平日昼基準率': [0.4658385093167702], '平日夜基準率': [0.2550607287449393]}\nGP25 {'設備名': ['GP25'], '平日昼・総': [283], '平日夜・総': [215], '平日昼・基準内': [70], '平日夜・基準内': [40], '平日昼基準率': [0.24734982332155478], '平日夜基準率': [0.18604651162790697]}\nGP26 {'設備名': ['GP26'], '平日昼・総': [201], '平日夜・総': [90], '平日昼・基準内': [37], '平日夜・基準内': [18], '平日昼基準率': [0.18407960199004975], '平日夜基準率': [0.2]}\nGP27 {'設備名': ['GP27'], '平日昼・総': [299], '平日夜・総': [232], '平日昼・基準内': [68], '平日夜・基準内': [40], '平日昼基準率': [0.22742474916387959], '平日夜基準率': [0.1724137931034483]}\nGP28 {'設備名': ['GP28'], '平日昼・総': [285], '平日夜・総': [199], '平日昼・基準内': [54], '平日夜・基準内': [27], '平日昼基準率': [0.18947368421052632], '平日夜基準率': [0.135678391959799]}\nGP29 {'設備名': ['GP29'], '平日昼・総': [348], '平日夜・総': [266], '平日昼・基準内': [156], '平日夜・基準内': [84], '平日昼基準率': [0.4482758620689655], '平日夜基準率': [0.3157894736842105]}\nGP30 {'設備名': ['GP30'], '平日昼・総': [330], '平日夜・総': [252], '平日昼・基準内': [112], '平日夜・基準内': [41], '平日昼基準率': [0.3393939393939394], '平日夜基準率': [0.1626984126984127]}\nGP31 {'設備名': ['GP31'], '平日昼・総': [324], '平日夜・総': [256], '平日昼・基準内': [106], '平日夜・基準内': [49], '平日昼基準率': [0.3271604938271605], '平日夜基準率': [0.19140625]}\nGP51 {'設備名': ['GP51'], '平日昼・総': [343], '平日夜・総': [264], '平日昼・基準内': [135], '平日夜・基準内': [65], '平日昼基準率': [0.3935860058309038], '平日夜基準率': [0.24621212121212122]}\nGP52 {'設備名': ['GP52'], '平日昼・総': [316], '平日夜・総': [242], '平日昼・基準内': [81], '平日夜・基準内': [37], '平日昼基準率': [0.2563291139240506], '平日夜基準率': [0.15289256198347106]}\nGP53 {'設備名': ['GP53'], '平日昼・総': [304], '平日夜・総': [228], '平日昼・基準内': [72], '平日夜・基準内': [36], '平日昼基準率': [0.23684210526315788], '平日夜基準率': [0.15789473684210525]}\nGT1A_GT1B {'設備名': ['GT1A_GT1B'], '平日昼・総': [339], '平日夜・総': [267], '平日昼・基準内': [262], '平日夜・基準内': [172], '平日昼基準率': [0.7728613569321534], '平日夜基準率': [0.6441947565543071]}\n空調 {'設備名': ['空調'], '平日昼・総': [350], '平日夜・総': [267], '平日昼・基準内': [301], '平日夜・基準内': [201], '平日昼基準率': [0.86], '平日夜基準率': [0.7528089887640449]}\n溶剤回収 {'設備名': ['溶剤回収'], '平日昼・総': [350], '平日夜・総': [267], '平日昼・基準内': [299], '平日夜・基準内': [199], '平日昼基準率': [0.8542857142857143], '平日夜基準率': [0.7453183520599251]}\n"
],
[
"print('-------------over-----------')",
"-------------over-----------\n"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4ac56d7a921f5296113ae93abe7f220f1dc338de
| 37,970 |
ipynb
|
Jupyter Notebook
|
Neural Networks and Deep Learning/Week 2/Python Basics with Numpy/.ipynb_checkpoints/Python Basics With Numpy v3-checkpoint.ipynb
|
zatang007/Deep-Learning-Coursera
|
2b4f26f4e97a27df06ebcdfbeb19028fa2e9c1d4
|
[
"MIT"
] | 127 |
2018-08-17T03:36:58.000Z
|
2022-03-17T13:00:57.000Z
|
Neural Networks and Deep Learning/Week 2/Python Basics with Numpy/.ipynb_checkpoints/Python Basics With Numpy v3-checkpoint.ipynb
|
zatang007/Deep-Learning-Coursera
|
2b4f26f4e97a27df06ebcdfbeb19028fa2e9c1d4
|
[
"MIT"
] | null | null | null |
Neural Networks and Deep Learning/Week 2/Python Basics with Numpy/.ipynb_checkpoints/Python Basics With Numpy v3-checkpoint.ipynb
|
zatang007/Deep-Learning-Coursera
|
2b4f26f4e97a27df06ebcdfbeb19028fa2e9c1d4
|
[
"MIT"
] | 73 |
2018-08-17T10:30:05.000Z
|
2021-02-07T12:03:06.000Z
| 34.207207 | 916 | 0.527574 |
[
[
[
"# Python Basics with Numpy (optional assignment)\n\nWelcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will help familiarize you with functions we'll need. \n\n**Instructions:**\n- You will be using Python 3.\n- Avoid using for-loops and while-loops, unless you are explicitly told to do so.\n- Do not modify the (# GRADED FUNCTION [function name]) comment in some cells. Your work would not be graded if you change this. Each cell containing that comment should only contain one function.\n- After coding your function, run the cell right below it to check if your result is correct.\n\n**After this assignment you will:**\n- Be able to use iPython Notebooks\n- Be able to use numpy functions and numpy matrix/vector operations\n- Understand the concept of \"broadcasting\"\n- Be able to vectorize code\n\nLet's get started!",
"_____no_output_____"
],
[
"## About iPython Notebooks ##\n\niPython Notebooks are interactive coding environments embedded in a webpage. You will be using iPython notebooks in this class. You only need to write code between the ### START CODE HERE ### and ### END CODE HERE ### comments. After writing your code, you can run the cell by either pressing \"SHIFT\"+\"ENTER\" or by clicking on \"Run Cell\" (denoted by a play symbol) in the upper bar of the notebook. \n\nWe will often specify \"(≈ X lines of code)\" in the comments to tell you about how much code you need to write. It is just a rough estimate, so don't feel bad if your code is longer or shorter.\n\n**Exercise**: Set test to `\"Hello World\"` in the cell below to print \"Hello World\" and run the two cells below.",
"_____no_output_____"
]
],
[
[
"### START CODE HERE ### (≈ 1 line of code)\ntest = \"Hello World\"\n### END CODE HERE ###",
"_____no_output_____"
],
[
"print (\"test: \" + test)",
"test: Hello World\n"
]
],
[
[
"**Expected output**:\ntest: Hello World",
"_____no_output_____"
],
[
"<font color='blue'>\n**What you need to remember**:\n- Run your cells using SHIFT+ENTER (or \"Run cell\")\n- Write code in the designated areas using Python 3 only\n- Do not modify the code outside of the designated areas",
"_____no_output_____"
],
[
"## 1 - Building basic functions with numpy ##\n\nNumpy is the main package for scientific computing in Python. It is maintained by a large community (www.numpy.org). In this exercise you will learn several key numpy functions such as np.exp, np.log, and np.reshape. You will need to know how to use these functions for future assignments.\n\n### 1.1 - sigmoid function, np.exp() ###\n\nBefore using np.exp(), you will use math.exp() to implement the sigmoid function. You will then see why np.exp() is preferable to math.exp().\n\n**Exercise**: Build a function that returns the sigmoid of a real number x. Use math.exp(x) for the exponential function.\n\n**Reminder**:\n$sigmoid(x) = \\frac{1}{1+e^{-x}}$ is sometimes also known as the logistic function. It is a non-linear function used not only in Machine Learning (Logistic Regression), but also in Deep Learning.\n\n<img src=\"images/Sigmoid.png\" style=\"width:500px;height:228px;\">\n\nTo refer to a function belonging to a specific package you could call it using package_name.function(). Run the code below to see an example with math.exp().",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: basic_sigmoid\n\nimport math\n\ndef basic_sigmoid(x):\n \"\"\"\n Compute sigmoid of x.\n\n Arguments:\n x -- A scalar\n\n Return:\n s -- sigmoid(x)\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n s = 1/(1+math.exp(-x))\n ### END CODE HERE ###\n \n return s",
"_____no_output_____"
],
[
"basic_sigmoid(3)",
"_____no_output_____"
]
],
[
[
"**Expected Output**: \n<table style = \"width:40%\">\n <tr>\n <td>** basic_sigmoid(3) **</td> \n <td>0.9525741268224334 </td> \n </tr>\n\n</table>",
"_____no_output_____"
],
[
"Actually, we rarely use the \"math\" library in deep learning because the inputs of the functions are real numbers. In deep learning we mostly use matrices and vectors. This is why numpy is more useful. ",
"_____no_output_____"
]
],
[
[
"### One reason why we use \"numpy\" instead of \"math\" in Deep Learning ###\nx = [1, 2, 3]\nbasic_sigmoid(x) # you will see this give an error when you run it, because x is a vector.",
"_____no_output_____"
]
],
[
[
"In fact, if $ x = (x_1, x_2, ..., x_n)$ is a row vector then $np.exp(x)$ will apply the exponential function to every element of x. The output will thus be: $np.exp(x) = (e^{x_1}, e^{x_2}, ..., e^{x_n})$",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\n# example of np.exp\nx = np.array([1, 2, 3])\nprint(np.exp(x)) # result is (exp(1), exp(2), exp(3))",
"[ 2.71828183 7.3890561 20.08553692]\n"
]
],
[
[
"Furthermore, if x is a vector, then a Python operation such as $s = x + 3$ or $s = \\frac{1}{x}$ will output s as a vector of the same size as x.",
"_____no_output_____"
]
],
[
[
"# example of vector operation\nx = np.array([1, 2, 3])\nprint (x + 3)",
"[4 5 6]\n"
]
],
[
[
"Any time you need more info on a numpy function, we encourage you to look at [the official documentation](https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.exp.html). \n\nYou can also create a new cell in the notebook and write `np.exp?` (for example) to get quick access to the documentation.\n\n**Exercise**: Implement the sigmoid function using numpy. \n\n**Instructions**: x could now be either a real number, a vector, or a matrix. The data structures we use in numpy to represent these shapes (vectors, matrices...) are called numpy arrays. You don't need to know more for now.\n$$ \\text{For } x \\in \\mathbb{R}^n \\text{, } sigmoid(x) = sigmoid\\begin{pmatrix}\n x_1 \\\\\n x_2 \\\\\n ... \\\\\n x_n \\\\\n\\end{pmatrix} = \\begin{pmatrix}\n \\frac{1}{1+e^{-x_1}} \\\\\n \\frac{1}{1+e^{-x_2}} \\\\\n ... \\\\\n \\frac{1}{1+e^{-x_n}} \\\\\n\\end{pmatrix}\\tag{1} $$",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: sigmoid\n\nimport numpy as np # this means you can access numpy functions by writing np.function() instead of numpy.function()\n\ndef sigmoid(x):\n \"\"\"\n Compute the sigmoid of x\n\n Arguments:\n x -- A scalar or numpy array of any size\n\n Return:\n s -- sigmoid(x)\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n s = 1/(1+np.exp(-x))\n ### END CODE HERE ###\n \n return s",
"_____no_output_____"
],
[
"x = np.array([1, 2, 3])\nsigmoid(x)",
"_____no_output_____"
]
],
[
[
"**Expected Output**: \n<table>\n <tr> \n <td> **sigmoid([1,2,3])**</td> \n <td> array([ 0.73105858, 0.88079708, 0.95257413]) </td> \n </tr>\n</table> \n",
"_____no_output_____"
],
[
"### 1.2 - Sigmoid gradient\n\nAs you've seen in lecture, you will need to compute gradients to optimize loss functions using backpropagation. Let's code your first gradient function.\n\n**Exercise**: Implement the function sigmoid_grad() to compute the gradient of the sigmoid function with respect to its input x. The formula is: $$sigmoid\\_derivative(x) = \\sigma'(x) = \\sigma(x) (1 - \\sigma(x))\\tag{2}$$\nYou often code this function in two steps:\n1. Set s to be the sigmoid of x. You might find your sigmoid(x) function useful.\n2. Compute $\\sigma'(x) = s(1-s)$",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: sigmoid_derivative\n\ndef sigmoid_derivative(x):\n \"\"\"\n Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x.\n You can store the output of the sigmoid function into variables and then use it to calculate the gradient.\n \n Arguments:\n x -- A scalar or numpy array\n\n Return:\n ds -- Your computed gradient.\n \"\"\"\n \n ### START CODE HERE ### (≈ 2 lines of code)\n s = sigmoid(x)\n ds = s*(1-s)\n ### END CODE HERE ###\n \n return ds",
"_____no_output_____"
],
[
"x = np.array([1, 2, 3])\nprint (\"sigmoid_derivative(x) = \" + str(sigmoid_derivative(x)))",
"sigmoid_derivative(x) = [ 0.19661193 0.10499359 0.04517666]\n"
]
],
[
[
"**Expected Output**: \n\n\n<table>\n <tr> \n <td> **sigmoid_derivative([1,2,3])**</td> \n <td> [ 0.19661193 0.10499359 0.04517666] </td> \n </tr>\n</table> \n\n",
"_____no_output_____"
],
[
"### 1.3 - Reshaping arrays ###\n\nTwo common numpy functions used in deep learning are [np.shape](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html) and [np.reshape()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html). \n- X.shape is used to get the shape (dimension) of a matrix/vector X. \n- X.reshape(...) is used to reshape X into some other dimension. \n\nFor example, in computer science, an image is represented by a 3D array of shape $(length, height, depth = 3)$. However, when you read an image as the input of an algorithm you convert it to a vector of shape $(length*height*3, 1)$. In other words, you \"unroll\", or reshape, the 3D array into a 1D vector.\n\n<img src=\"images/image2vector_kiank.png\" style=\"width:500px;height:300;\">\n\n**Exercise**: Implement `image2vector()` that takes an input of shape (length, height, 3) and returns a vector of shape (length\\*height\\*3, 1). For example, if you would like to reshape an array v of shape (a, b, c) into a vector of shape (a*b,c) you would do:\n``` python\nv = v.reshape((v.shape[0]*v.shape[1], v.shape[2])) # v.shape[0] = a ; v.shape[1] = b ; v.shape[2] = c\n```\n- Please don't hardcode the dimensions of image as a constant. Instead look up the quantities you need with `image.shape[0]`, etc. ",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: image2vector\ndef image2vector(image):\n \"\"\"\n Argument:\n image -- a numpy array of shape (length, height, depth)\n \n Returns:\n v -- a vector of shape (length*height*depth, 1)\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n v = image.reshape((image.shape[0]*image.shape[1]*image.shape[2], 1))\n ### END CODE HERE ###\n \n return v",
"_____no_output_____"
],
[
"# This is a 3 by 3 by 2 array, typically images will be (num_px_x, num_px_y,3) where 3 represents the RGB values\nimage = np.array([[[ 0.67826139, 0.29380381],\n [ 0.90714982, 0.52835647],\n [ 0.4215251 , 0.45017551]],\n\n [[ 0.92814219, 0.96677647],\n [ 0.85304703, 0.52351845],\n [ 0.19981397, 0.27417313]],\n\n [[ 0.60659855, 0.00533165],\n [ 0.10820313, 0.49978937],\n [ 0.34144279, 0.94630077]]])\n\nprint (\"image2vector(image) = \" + str(image2vector(image)))",
"image2vector(image) = [[ 0.67826139]\n [ 0.29380381]\n [ 0.90714982]\n [ 0.52835647]\n [ 0.4215251 ]\n [ 0.45017551]\n [ 0.92814219]\n [ 0.96677647]\n [ 0.85304703]\n [ 0.52351845]\n [ 0.19981397]\n [ 0.27417313]\n [ 0.60659855]\n [ 0.00533165]\n [ 0.10820313]\n [ 0.49978937]\n [ 0.34144279]\n [ 0.94630077]]\n"
]
],
[
[
"**Expected Output**: \n\n\n<table style=\"width:100%\">\n <tr> \n <td> **image2vector(image)** </td> \n <td> [[ 0.67826139]\n [ 0.29380381]\n [ 0.90714982]\n [ 0.52835647]\n [ 0.4215251 ]\n [ 0.45017551]\n [ 0.92814219]\n [ 0.96677647]\n [ 0.85304703]\n [ 0.52351845]\n [ 0.19981397]\n [ 0.27417313]\n [ 0.60659855]\n [ 0.00533165]\n [ 0.10820313]\n [ 0.49978937]\n [ 0.34144279]\n [ 0.94630077]]</td> \n </tr>\n \n \n</table>",
"_____no_output_____"
],
[
"### 1.4 - Normalizing rows\n\nAnother common technique we use in Machine Learning and Deep Learning is to normalize our data. It often leads to a better performance because gradient descent converges faster after normalization. Here, by normalization we mean changing x to $ \\frac{x}{\\| x\\|} $ (dividing each row vector of x by its norm).\n\nFor example, if $$x = \n\\begin{bmatrix}\n 0 & 3 & 4 \\\\\n 2 & 6 & 4 \\\\\n\\end{bmatrix}\\tag{3}$$ then $$\\| x\\| = np.linalg.norm(x, axis = 1, keepdims = True) = \\begin{bmatrix}\n 5 \\\\\n \\sqrt{56} \\\\\n\\end{bmatrix}\\tag{4} $$and $$ x\\_normalized = \\frac{x}{\\| x\\|} = \\begin{bmatrix}\n 0 & \\frac{3}{5} & \\frac{4}{5} \\\\\n \\frac{2}{\\sqrt{56}} & \\frac{6}{\\sqrt{56}} & \\frac{4}{\\sqrt{56}} \\\\\n\\end{bmatrix}\\tag{5}$$ Note that you can divide matrices of different sizes and it works fine: this is called broadcasting and you're going to learn about it in part 5.\n\n\n**Exercise**: Implement normalizeRows() to normalize the rows of a matrix. After applying this function to an input matrix x, each row of x should be a vector of unit length (meaning length 1).",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: normalizeRows\n\ndef normalizeRows(x):\n \"\"\"\n Implement a function that normalizes each row of the matrix x (to have unit length).\n \n Argument:\n x -- A numpy matrix of shape (n, m)\n \n Returns:\n x -- The normalized (by row) numpy matrix. You are allowed to modify x.\n \"\"\"\n \n ### START CODE HERE ### (≈ 2 lines of code)\n # Compute x_norm as the norm 2 of x. Use np.linalg.norm(..., ord = 2, axis = ..., keepdims = True)\n x_norm = np.linalg.norm(x,ord=2,axis=1,keepdims = True)\n \n # Divide x by its norm.\n x = x/x_norm\n ### END CODE HERE ###\n\n return x",
"_____no_output_____"
],
[
"x = np.array([\n [0, 3, 4],\n [1, 6, 4]])\nprint(\"normalizeRows(x) = \" + str(normalizeRows(x)))",
"normalizeRows(x) = [[ 0. 0.6 0.8 ]\n [ 0.13736056 0.82416338 0.54944226]]\n"
]
],
[
[
"**Expected Output**: \n\n<table style=\"width:60%\">\n\n <tr> \n <td> **normalizeRows(x)** </td> \n <td> [[ 0. 0.6 0.8 ]\n [ 0.13736056 0.82416338 0.54944226]]</td> \n </tr>\n \n \n</table>",
"_____no_output_____"
],
[
"**Note**:\nIn normalizeRows(), you can try to print the shapes of x_norm and x, and then rerun the assessment. You'll find out that they have different shapes. This is normal given that x_norm takes the norm of each row of x. So x_norm has the same number of rows but only 1 column. So how did it work when you divided x by x_norm? This is called broadcasting and we'll talk about it now! ",
"_____no_output_____"
],
[
"### 1.5 - Broadcasting and the softmax function ####\nA very important concept to understand in numpy is \"broadcasting\". It is very useful for performing mathematical operations between arrays of different shapes. For the full details on broadcasting, you can read the official [broadcasting documentation](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).",
"_____no_output_____"
],
[
"**Exercise**: Implement a softmax function using numpy. You can think of softmax as a normalizing function used when your algorithm needs to classify two or more classes. You will learn more about softmax in the second course of this specialization.\n\n**Instructions**:\n- $ \\text{for } x \\in \\mathbb{R}^{1\\times n} \\text{, } softmax(x) = softmax(\\begin{bmatrix}\n x_1 &&\n x_2 &&\n ... &&\n x_n \n\\end{bmatrix}) = \\begin{bmatrix}\n \\frac{e^{x_1}}{\\sum_{j}e^{x_j}} &&\n \\frac{e^{x_2}}{\\sum_{j}e^{x_j}} &&\n ... &&\n \\frac{e^{x_n}}{\\sum_{j}e^{x_j}} \n\\end{bmatrix} $ \n\n- $\\text{for a matrix } x \\in \\mathbb{R}^{m \\times n} \\text{, $x_{ij}$ maps to the element in the $i^{th}$ row and $j^{th}$ column of $x$, thus we have: }$ $$softmax(x) = softmax\\begin{bmatrix}\n x_{11} & x_{12} & x_{13} & \\dots & x_{1n} \\\\\n x_{21} & x_{22} & x_{23} & \\dots & x_{2n} \\\\\n \\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n x_{m1} & x_{m2} & x_{m3} & \\dots & x_{mn}\n\\end{bmatrix} = \\begin{bmatrix}\n \\frac{e^{x_{11}}}{\\sum_{j}e^{x_{1j}}} & \\frac{e^{x_{12}}}{\\sum_{j}e^{x_{1j}}} & \\frac{e^{x_{13}}}{\\sum_{j}e^{x_{1j}}} & \\dots & \\frac{e^{x_{1n}}}{\\sum_{j}e^{x_{1j}}} \\\\\n \\frac{e^{x_{21}}}{\\sum_{j}e^{x_{2j}}} & \\frac{e^{x_{22}}}{\\sum_{j}e^{x_{2j}}} & \\frac{e^{x_{23}}}{\\sum_{j}e^{x_{2j}}} & \\dots & \\frac{e^{x_{2n}}}{\\sum_{j}e^{x_{2j}}} \\\\\n \\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n \\frac{e^{x_{m1}}}{\\sum_{j}e^{x_{mj}}} & \\frac{e^{x_{m2}}}{\\sum_{j}e^{x_{mj}}} & \\frac{e^{x_{m3}}}{\\sum_{j}e^{x_{mj}}} & \\dots & \\frac{e^{x_{mn}}}{\\sum_{j}e^{x_{mj}}}\n\\end{bmatrix} = \\begin{pmatrix}\n softmax\\text{(first row of x)} \\\\\n softmax\\text{(second row of x)} \\\\\n ... \\\\\n softmax\\text{(last row of x)} \\\\\n\\end{pmatrix} $$",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: softmax\n\ndef softmax(x):\n \"\"\"Calculates the softmax for each row of the input x.\n\n Your code should work for a row vector and also for matrices of shape (n, m).\n\n Argument:\n x -- A numpy matrix of shape (n,m)\n\n Returns:\n s -- A numpy matrix equal to the softmax of x, of shape (n,m)\n \"\"\"\n \n ### START CODE HERE ### (≈ 3 lines of code)\n # Apply exp() element-wise to x. Use np.exp(...).\n x_exp = np.exp(x)\n\n # Create a vector x_sum that sums each row of x_exp. Use np.sum(..., axis = 1, keepdims = True).\n x_sum = np.sum(x,axis=1,keepdims=True)\n \n # Compute softmax(x) by dividing x_exp by x_sum. It should automatically use numpy broadcasting.\n s = np.divide(x_exp,x_sum)\n\n ### END CODE HERE ###\n \n return s",
"_____no_output_____"
],
[
"x = np.array([\n [9, 2, 5, 0, 0],\n [7, 5, 0, 0 ,0]])\nprint(\"softmax(x) = \" + str(softmax(x)))",
"softmax(x) = [[ 1.97455687e-03 2.16536453e+00 1.07807152e-01 1.60000000e+01\n 1.60000000e+01]\n [ 1.09425836e-02 8.08553640e-02 1.20000000e+01 1.20000000e+01\n 1.20000000e+01]]\n"
]
],
[
[
"**Expected Output**:\n\n<table style=\"width:60%\">\n\n <tr> \n <td> **softmax(x)** </td> \n <td> [[ 9.80897665e-01 8.94462891e-04 1.79657674e-02 1.21052389e-04\n 1.21052389e-04]\n [ 8.78679856e-01 1.18916387e-01 8.01252314e-04 8.01252314e-04\n 8.01252314e-04]]</td> \n </tr>\n</table>\n",
"_____no_output_____"
],
[
"**Note**:\n- If you print the shapes of x_exp, x_sum and s above and rerun the assessment cell, you will see that x_sum is of shape (2,1) while x_exp and s are of shape (2,5). **x_exp/x_sum** works due to python broadcasting.\n\nCongratulations! You now have a pretty good understanding of python numpy and have implemented a few useful functions that you will be using in deep learning.",
"_____no_output_____"
],
[
"<font color='blue'>\n**What you need to remember:**\n- np.exp(x) works for any np.array x and applies the exponential function to every coordinate\n- the sigmoid function and its gradient\n- image2vector is commonly used in deep learning\n- np.reshape is widely used. In the future, you'll see that keeping your matrix/vector dimensions straight will go toward eliminating a lot of bugs. \n- numpy has efficient built-in functions\n- broadcasting is extremely useful",
"_____no_output_____"
],
[
"## 2) Vectorization",
"_____no_output_____"
],
[
"\nIn deep learning, you deal with very large datasets. Hence, a non-computationally-optimal function can become a huge bottleneck in your algorithm and can result in a model that takes ages to run. To make sure that your code is computationally efficient, you will use vectorization. For example, try to tell the difference between the following implementations of the dot/outer/elementwise product.",
"_____no_output_____"
]
],
[
[
"import time\n\nx1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]\nx2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]\n\n### CLASSIC DOT PRODUCT OF VECTORS IMPLEMENTATION ###\ntic = time.process_time()\ndot = 0\nfor i in range(len(x1)):\n dot+= x1[i]*x2[i]\ntoc = time.process_time()\nprint (\"dot = \" + str(dot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### CLASSIC OUTER PRODUCT IMPLEMENTATION ###\ntic = time.process_time()\nouter = np.zeros((len(x1),len(x2))) # we create a len(x1)*len(x2) matrix with only zeros\nfor i in range(len(x1)):\n for j in range(len(x2)):\n outer[i,j] = x1[i]*x2[j]\ntoc = time.process_time()\nprint (\"outer = \" + str(outer) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### CLASSIC ELEMENTWISE IMPLEMENTATION ###\ntic = time.process_time()\nmul = np.zeros(len(x1))\nfor i in range(len(x1)):\n mul[i] = x1[i]*x2[i]\ntoc = time.process_time()\nprint (\"elementwise multiplication = \" + str(mul) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### CLASSIC GENERAL DOT PRODUCT IMPLEMENTATION ###\nW = np.random.rand(3,len(x1)) # Random 3*len(x1) numpy array\ntic = time.process_time()\ngdot = np.zeros(W.shape[0])\nfor i in range(W.shape[0]):\n for j in range(len(x1)):\n gdot[i] += W[i,j]*x1[j]\ntoc = time.process_time()\nprint (\"gdot = \" + str(gdot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")",
"_____no_output_____"
],
[
"x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]\nx2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]\n\n### VECTORIZED DOT PRODUCT OF VECTORS ###\ntic = time.process_time()\ndot = np.dot(x1,x2)\ntoc = time.process_time()\nprint (\"dot = \" + str(dot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### VECTORIZED OUTER PRODUCT ###\ntic = time.process_time()\nouter = np.outer(x1,x2)\ntoc = time.process_time()\nprint (\"outer = \" + str(outer) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### VECTORIZED ELEMENTWISE MULTIPLICATION ###\ntic = time.process_time()\nmul = np.multiply(x1,x2)\ntoc = time.process_time()\nprint (\"elementwise multiplication = \" + str(mul) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### VECTORIZED GENERAL DOT PRODUCT ###\ntic = time.process_time()\ndot = np.dot(W,x1)\ntoc = time.process_time()\nprint (\"gdot = \" + str(dot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")",
"_____no_output_____"
]
],
[
[
"As you may have noticed, the vectorized implementation is much cleaner and more efficient. For bigger vectors/matrices, the differences in running time become even bigger. \n\n**Note** that `np.dot()` performs a matrix-matrix or matrix-vector multiplication. This is different from `np.multiply()` and the `*` operator (which is equivalent to `.*` in Matlab/Octave), which performs an element-wise multiplication.",
"_____no_output_____"
],
[
"### 2.1 Implement the L1 and L2 loss functions\n\n**Exercise**: Implement the numpy vectorized version of the L1 loss. You may find the function abs(x) (absolute value of x) useful.\n\n**Reminder**:\n- The loss is used to evaluate the performance of your model. The bigger your loss is, the more different your predictions ($ \\hat{y} $) are from the true values ($y$). In deep learning, you use optimization algorithms like Gradient Descent to train your model and to minimize the cost.\n- L1 loss is defined as:\n$$\\begin{align*} & L_1(\\hat{y}, y) = \\sum_{i=0}^m|y^{(i)} - \\hat{y}^{(i)}| \\end{align*}\\tag{6}$$",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: L1\n\ndef L1(yhat, y):\n \"\"\"\n Arguments:\n yhat -- vector of size m (predicted labels)\n y -- vector of size m (true labels)\n \n Returns:\n loss -- the value of the L1 loss function defined above\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n loss = None\n ### END CODE HERE ###\n \n return loss",
"_____no_output_____"
],
[
"yhat = np.array([.9, 0.2, 0.1, .4, .9])\ny = np.array([1, 0, 0, 1, 1])\nprint(\"L1 = \" + str(L1(yhat,y)))",
"_____no_output_____"
]
],
[
[
"**Expected Output**:\n\n<table style=\"width:20%\">\n\n <tr> \n <td> **L1** </td> \n <td> 1.1 </td> \n </tr>\n</table>\n",
"_____no_output_____"
],
[
"**Exercise**: Implement the numpy vectorized version of the L2 loss. There are several way of implementing the L2 loss but you may find the function np.dot() useful. As a reminder, if $x = [x_1, x_2, ..., x_n]$, then `np.dot(x,x)` = $\\sum_{j=0}^n x_j^{2}$. \n\n- L2 loss is defined as $$\\begin{align*} & L_2(\\hat{y},y) = \\sum_{i=0}^m(y^{(i)} - \\hat{y}^{(i)})^2 \\end{align*}\\tag{7}$$",
"_____no_output_____"
]
],
[
[
"# GRADED FUNCTION: L2\n\ndef L2(yhat, y):\n \"\"\"\n Arguments:\n yhat -- vector of size m (predicted labels)\n y -- vector of size m (true labels)\n \n Returns:\n loss -- the value of the L2 loss function defined above\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n loss = None\n ### END CODE HERE ###\n \n return loss",
"_____no_output_____"
],
[
"yhat = np.array([.9, 0.2, 0.1, .4, .9])\ny = np.array([1, 0, 0, 1, 1])\nprint(\"L2 = \" + str(L2(yhat,y)))",
"_____no_output_____"
]
],
[
[
"**Expected Output**: \n<table style=\"width:20%\">\n <tr> \n <td> **L2** </td> \n <td> 0.43 </td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"Congratulations on completing this assignment. We hope that this little warm-up exercise helps you in the future assignments, which will be more exciting and interesting!",
"_____no_output_____"
],
[
"<font color='blue'>\n**What to remember:**\n- Vectorization is very important in deep learning. It provides computational efficiency and clarity.\n- You have reviewed the L1 and L2 loss.\n- You are familiar with many numpy functions such as np.sum, np.dot, np.multiply, np.maximum, etc...",
"_____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",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
4ac57911b69925221c8d63a23ea9147896671f7e
| 1,647 |
ipynb
|
Jupyter Notebook
|
Autoencoder Variacional.ipynb
|
dimagela29/Formacao_cientista_de_dados
|
bd891e18037da61da2fd373dd39d7710cbbf4a4c
|
[
"MIT"
] | null | null | null |
Autoencoder Variacional.ipynb
|
dimagela29/Formacao_cientista_de_dados
|
bd891e18037da61da2fd373dd39d7710cbbf4a4c
|
[
"MIT"
] | null | null | null |
Autoencoder Variacional.ipynb
|
dimagela29/Formacao_cientista_de_dados
|
bd891e18037da61da2fd373dd39d7710cbbf4a4c
|
[
"MIT"
] | null | null | null | 26.142857 | 241 | 0.625987 |
[
[
[
"Autoencoders variacionais ",
"_____no_output_____"
],
[
"Quando fazemos para um autoencoder usual, estamos pegando toda a informação que há no input e a comprimindo para que ela fique do tamanho do código.",
"_____no_output_____"
],
[
"Forçamos que o código seja de um tamanho k, e que todos os nossos dados sejam suficientemente bem representadis através de k valores.",
"_____no_output_____"
],
[
"A idéia de um auto encoder variacional é um pouco diferente: ao invés de aprender uma nova representação fixa de tamanho k, cada k vai ser modelado por uma distribuição Normal. Então cada variável vai ser modelada por uma distribuição.",
"_____no_output_____"
],
[
"A função custo vai depender de duas coisas:\n1. A qualidade da restauração feita pelo autoencoder('reconstruction error')\n2. A divergência de KL entre a distribuição sendo estimada no espaço latente e uma distribuição Normal padrão.",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4ac57993d8b5245a7c51c055233a354a0ab1ce4e
| 6,078 |
ipynb
|
Jupyter Notebook
|
math_probability/generate_primes/check_prime_solution.ipynb
|
benkeesey/interactive-coding-challenges
|
4994452a729f4bcfab5c8a4225f2b5e004b79075
|
[
"Apache-2.0"
] | 27,173 |
2015-07-06T12:36:05.000Z
|
2022-03-31T23:56:41.000Z
|
math_probability/generate_primes/check_prime_solution.ipynb
|
benkeesey/interactive-coding-challenges
|
4994452a729f4bcfab5c8a4225f2b5e004b79075
|
[
"Apache-2.0"
] | 143 |
2015-07-07T05:13:11.000Z
|
2021-12-07T17:05:54.000Z
|
math_probability/generate_primes/check_prime_solution.ipynb
|
benkeesey/interactive-coding-challenges
|
4994452a729f4bcfab5c8a4225f2b5e004b79075
|
[
"Apache-2.0"
] | 4,657 |
2015-07-06T13:28:02.000Z
|
2022-03-31T10:11:28.000Z
| 28.269767 | 185 | 0.489306 |
[
[
[
"This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).",
"_____no_output_____"
],
[
"# Solution Notebook",
"_____no_output_____"
],
[
"## Problem: Generate a list of primes.\n\n* [Constraints](#Constraints)\n* [Test Cases](#Test-Cases)\n* [Algorithm](#Algorithm)\n* [Code](#Code)\n* [Unit Test](#Unit-Test)",
"_____no_output_____"
],
[
"## Constraints\n\n* Is it correct that 1 is not considered a prime number?\n * Yes\n* Can we assume the inputs are valid?\n * No\n* Can we assume this fits memory?\n * Yes",
"_____no_output_____"
],
[
"## Test Cases\n\n* None -> Exception\n* Not an int -> Exception\n* 20 -> [False, False, True, True, False, True, False, True, False, False, False, True, False, True, False, False, False, True, False, True]",
"_____no_output_____"
],
[
"## Algorithm\n\nFor a number to be prime, it must be 2 or greater and cannot be divisible by another number other than itself (and 1).\n\nWe'll use the Sieve of Eratosthenes. All non-prime numbers are divisible by a prime number.\n\n* Use an array (or bit array, bit vector) to keep track of each integer up to the max\n* Start at 2, end at sqrt(max)\n * We can use sqrt(max) instead of max because:\n * For each value that divides the input number evenly, there is a complement b where a * b = n\n * If a > sqrt(n) then b < sqrt(n) because sqrt(n^2) = n\n * \"Cross off\" all numbers divisible by 2, 3, 5, 7, ... by setting array[index] to False\n\nComplexity:\n* Time: O(n log log n)\n* Space: O(n)\n\nWikipedia's animation:\n\n",
"_____no_output_____"
],
[
"## Code",
"_____no_output_____"
]
],
[
[
"import math\n\n\nclass PrimeGenerator(object):\n\n def generate_primes(self, max_num):\n if max_num is None:\n raise TypeError('max_num cannot be None')\n array = [True] * max_num\n array[0] = False\n array[1] = False\n prime = 2\n while prime <= math.sqrt(max_num):\n self._cross_off(array, prime)\n prime = self._next_prime(array, prime)\n return array\n\n def _cross_off(self, array, prime):\n for index in range(prime*prime, len(array), prime):\n # Start with prime*prime because if we have a k*prime\n # where k < prime, this value would have already been\n # previously crossed off\n array[index] = False\n\n def _next_prime(self, array, prime):\n next = prime + 1\n while next < len(array) and not array[next]:\n next += 1\n return next",
"_____no_output_____"
]
],
[
[
"## Unit Test",
"_____no_output_____"
]
],
[
[
"%%writefile test_generate_primes.py\nimport unittest\n\n\nclass TestMath(unittest.TestCase):\n\n def test_generate_primes(self):\n prime_generator = PrimeGenerator()\n self.assertRaises(TypeError, prime_generator.generate_primes, None)\n self.assertRaises(TypeError, prime_generator.generate_primes, 98.6)\n self.assertEqual(prime_generator.generate_primes(20), [False, False, True, \n True, False, True, \n False, True, False, \n False, False, True, \n False, True, False, \n False, False, True, \n False, True])\n print('Success: generate_primes')\n\n\ndef main():\n test = TestMath()\n test.test_generate_primes()\n\n\nif __name__ == '__main__':\n main()",
"Overwriting test_generate_primes.py\n"
],
[
"%run -i test_generate_primes.py",
"Success: generate_primes\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
4ac57d577575688079b91cc88f717b0a662ff391
| 13,111 |
ipynb
|
Jupyter Notebook
|
examples/notebooks/core/combineExample.ipynb
|
ShaikAsifullah/distributed-tellurium
|
007e9b3842b614edd34908c001119c6da1d41897
|
[
"Apache-2.0"
] | 1 |
2019-06-19T04:40:33.000Z
|
2019-06-19T04:40:33.000Z
|
examples/notebooks/core/combineExample.ipynb
|
ShaikAsifullah/distributed-tellurium
|
007e9b3842b614edd34908c001119c6da1d41897
|
[
"Apache-2.0"
] | null | null | null |
examples/notebooks/core/combineExample.ipynb
|
ShaikAsifullah/distributed-tellurium
|
007e9b3842b614edd34908c001119c6da1d41897
|
[
"Apache-2.0"
] | null | null | null | 46.328622 | 1,156 | 0.562962 |
[
[
[
"Back to the main [Index](../index.ipynb)",
"_____no_output_____"
],
[
"### Combine archives\nThe experiment, i.e. model with the simulation description, can be stored as Combine Archive.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nfrom __future__ import print_function\nimport tellurium as te\n\nantimonyStr = \"\"\"\nmodel test()\n J0: S1 -> S2; k1*S1;\n S1 = 10.0; S2=0.0;\n k1 = 0.1;\nend\n\"\"\"\n\nphrasedmlStr = \"\"\"\n model0 = model \"test\"\n sim0 = simulate uniform(0, 6, 100)\n task0 = run sim0 on model0\n plot \"Timecourse test model\" task0.time vs task0.S1\n\"\"\"\n\n# phrasedml experiment\nexp = te.experiment(antimonyStr, phrasedmlStr)\nexp.execute(phrasedmlStr)\n\n# create Combine Archive\nimport tempfile\nf = tempfile.NamedTemporaryFile()\nexp.exportAsCombine(f.name)\n\n# print the content of the Combine Archive\nimport zipfile\nzip=zipfile.ZipFile(f.name)\nprint(zip.namelist())",
"_____no_output_____"
]
],
[
[
"### Create combine archive\nTODO",
"_____no_output_____"
]
],
[
[
"import tellurium as te\nimport phrasedml\n\nantTest1Str = \"\"\"\nmodel test1()\n J0: S1 -> S2; k1*S1;\n S1 = 10.0; S2=0.0;\n k1 = 0.1;\nend\n\"\"\"\n\nantTest2Str = \"\"\"\nmodel test2()\n v0: X1 -> X2; p1*X1;\n X1 = 5.0; X2 = 20.0;\n k1 = 0.2;\nend\n\"\"\"\n\nphrasedmlStr = \"\"\"\n model1 = model \"test1\"\n model2 = model \"test2\"\n model3 = model model1 with S1=S2+20\n sim1 = simulate uniform(0, 6, 100)\n task1 = run sim1 on model1\n task2 = run sim1 on model2\n plot \"Timecourse test1\" task1.time vs task1.S1, task1.S2\n plot \"Timecourse test2\" task2.time vs task2.X1, task2.X2\n\"\"\"\n\n# phrasedml.setReferencedSBML(\"test1\")\nexp = te.experiment(phrasedmlList=[phrasedmlStr], antimonyList=[antTest1Str])\nprint(exp)\n\n# set first model\nphrasedml.setReferencedSBML(\"test1\", te.antimonyToSBML(antTest1Str))\nphrasedml.setReferencedSBML(\"test2\", te.antimonyToSBML(antTest2Str))\n\nsedmlstr = phrasedml.convertString(phrasedmlStr)\nif sedmlstr is None:\n raise Exception(phrasedml.getLastError())\nprint(sedmlstr)",
"<tellurium.sedml.tephrasedml.experiment object at 0x7ff6f0755e90>\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- Created by phraSED-ML version v1.0.1 on 2016-03-08 10:29 with libSBML version 5.12.1. -->\n<sedML xmlns=\"http://sed-ml.org/sed-ml/level1/version2\" level=\"1\" version=\"2\">\n <listOfSimulations>\n <uniformTimeCourse id=\"sim1\" initialTime=\"0\" outputStartTime=\"0\" outputEndTime=\"6\" numberOfPoints=\"100\">\n <algorithm kisaoID=\"KISAO:0000019\"/>\n </uniformTimeCourse>\n </listOfSimulations>\n <listOfModels>\n <model id=\"model1\" language=\"urn:sedml:language:sbml.level-3.version-1\" source=\"test1\"/>\n <model id=\"model2\" language=\"urn:sedml:language:sbml.level-3.version-1\" source=\"test2\"/>\n <model id=\"model3\" language=\"urn:sedml:language:sbml.level-3.version-1\" source=\"model1\">\n <listOfChanges>\n <computeChange target=\"/sbml:sbml/sbml:model/descendant::*[@id='S1']\">\n <listOfVariables>\n <variable id=\"S2\" target=\"/sbml:sbml/sbml:model/descendant::*[@id='S2']\" modelReference=\"model3\"/>\n </listOfVariables>\n <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n <apply>\n <plus/>\n <ci> S2 </ci>\n <cn type=\"integer\"> 20 </cn>\n </apply>\n </math>\n </computeChange>\n </listOfChanges>\n </model>\n </listOfModels>\n <listOfTasks>\n <task id=\"task1\" modelReference=\"model1\" simulationReference=\"sim1\"/>\n <task id=\"task2\" modelReference=\"model2\" simulationReference=\"sim1\"/>\n </listOfTasks>\n <listOfDataGenerators>\n <dataGenerator id=\"plot_0_0_0\" name=\"task1.time\">\n <listOfVariables>\n <variable id=\"task1_____time\" symbol=\"urn:sedml:symbol:time\" taskReference=\"task1\"/>\n </listOfVariables>\n <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n <ci> task1_____time </ci>\n </math>\n </dataGenerator>\n <dataGenerator id=\"plot_0_0_1\" name=\"task1.S1\">\n <listOfVariables>\n <variable id=\"task1_____S1\" target=\"/sbml:sbml/sbml:model/descendant::*[@id='S1']\" taskReference=\"task1\" modelReference=\"model1\"/>\n </listOfVariables>\n <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n <ci> task1_____S1 </ci>\n </math>\n </dataGenerator>\n <dataGenerator id=\"plot_0_1_1\" name=\"task1.S2\">\n <listOfVariables>\n <variable id=\"task1_____S2\" target=\"/sbml:sbml/sbml:model/descendant::*[@id='S2']\" taskReference=\"task1\" modelReference=\"model1\"/>\n </listOfVariables>\n <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n <ci> task1_____S2 </ci>\n </math>\n </dataGenerator>\n <dataGenerator id=\"plot_1_0_0\" name=\"task2.time\">\n <listOfVariables>\n <variable id=\"task2_____time\" symbol=\"urn:sedml:symbol:time\" taskReference=\"task2\"/>\n </listOfVariables>\n <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n <ci> task2_____time </ci>\n </math>\n </dataGenerator>\n <dataGenerator id=\"plot_1_0_1\" name=\"task2.X1\">\n <listOfVariables>\n <variable id=\"task2_____X1\" target=\"/sbml:sbml/sbml:model/descendant::*[@id='X1']\" taskReference=\"task2\" modelReference=\"model2\"/>\n </listOfVariables>\n <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n <ci> task2_____X1 </ci>\n </math>\n </dataGenerator>\n <dataGenerator id=\"plot_1_1_1\" name=\"task2.X2\">\n <listOfVariables>\n <variable id=\"task2_____X2\" target=\"/sbml:sbml/sbml:model/descendant::*[@id='X2']\" taskReference=\"task2\" modelReference=\"model2\"/>\n </listOfVariables>\n <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n <ci> task2_____X2 </ci>\n </math>\n </dataGenerator>\n </listOfDataGenerators>\n <listOfOutputs>\n <plot2D id=\"plot_0\" name=\"Timecourse test1\">\n <listOfCurves>\n <curve logX=\"false\" logY=\"false\" xDataReference=\"plot_0_0_0\" yDataReference=\"plot_0_0_1\"/>\n <curve logX=\"false\" logY=\"false\" xDataReference=\"plot_0_0_0\" yDataReference=\"plot_0_1_1\"/>\n </listOfCurves>\n </plot2D>\n <plot2D id=\"plot_1\" name=\"Timecourse test2\">\n <listOfCurves>\n <curve logX=\"false\" logY=\"false\" xDataReference=\"plot_1_0_0\" yDataReference=\"plot_1_0_1\"/>\n <curve logX=\"false\" logY=\"false\" xDataReference=\"plot_1_0_0\" yDataReference=\"plot_1_1_1\"/>\n </listOfCurves>\n </plot2D>\n </listOfOutputs>\n</sedML>\n\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
4ac586d4f2c39ca30408b7d9b2f5641f40458302
| 20,324 |
ipynb
|
Jupyter Notebook
|
UltimateMovieRankings.ipynb
|
tgadf/movies
|
28ae1a0798029d3d3f1034aba456390d06e7e0dc
|
[
"MIT"
] | null | null | null |
UltimateMovieRankings.ipynb
|
tgadf/movies
|
28ae1a0798029d3d3f1034aba456390d06e7e0dc
|
[
"MIT"
] | null | null | null |
UltimateMovieRankings.ipynb
|
tgadf/movies
|
28ae1a0798029d3d3f1034aba456390d06e7e0dc
|
[
"MIT"
] | null | null | null | 30.700906 | 155 | 0.431952 |
[
[
[
"## Basic stuff\n%load_ext autoreload\n%autoreload\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:100% !important; }</style>\"))\ndisplay(HTML(\"\"\"<style>div.output_area{max-height:10000px;overflow:scroll;}</style>\"\"\"))\n\n## Python Version\nimport sys\nprint(\"Python: {0}\".format(sys.version))\n\n#from rottentomatoes import rottentomatoes\nfrom ultimatemovierankings import ultimatemovierankings\n\nimport datetime as dt\nstart = dt.datetime.now()\nprint(\"Notebook Last Run Initiated: \"+str(start))",
"_____no_output_____"
],
[
"umr = ultimatemovierankings()",
"_____no_output_____"
],
[
"umr.getUltimateMovieRankingsYearlyData(startYear = 2018, endYear = 2018, debug=True)",
"Data Directory: /Users/tgadfort/Documents/code/movies/ultimatemovierankings/data\nDownloading/Saving /Users/tgadfort/Documents/code/movies/ultimatemovierankings/data/2018.p\n"
],
[
"umr.parseUltimateMovieRankingsYearlyData()",
"----> 1928 (Top 5/10 Movies) <----\n('The Circus ', 98.0)\n('In Old Arizona', 94.9)\n('Lilac Time ', 93.1)\n('The Singing Fool ', 92.3)\n('The Last Command ', 91.2)\n\n\n----> 1929 (Top 5/10 Movies) <----\n('The Broadway Melody', 97.7)\n('The Love Parade', 95.9)\n('The Virginian ', 93.5)\n('Gold Diggers of Broadway ', 92.9)\n('The Cocoanuts ', 91.3)\n\n\n----> 1930 (Top 5/10 Movies) <----\n('All Quiet on the Western Front', 99.7)\n('The Big House', 98.2)\n('Whoopee ', 96.5)\n(\"Hell's Angels \", 95.0)\n('Animal Crackers ', 94.0)\n\n\n----> 1931 (Top 5/10 Movies) <----\n('The Champ', 98.5)\n('City Lights ', 97.8)\n('Trader Horn', 97.5)\n('Cimarron', 97.4)\n('Morocco ', 97.1)\n\n\n----> 1932 (Top 5/10 Movies) <----\n('Shanghai Express', 98.9)\n('Grand Hotel', 98.5)\n('A Farewell To Arms', 98.3)\n('The Kid From Spain ', 96.0)\n('One Hour with You', 95.8)\n\n\n----> 1933 (Top 5/10 Movies) <----\n('Cavalcade', 99.1)\n('She Done Him Wrong', 98.4)\n('Little Women', 98.1)\n('King Kong ', 98.0)\n('State Fair', 97.9)\n\n\n----> 1934 (Top 5/10 Movies) <----\n('It Happened One Night', 99.9)\n('Cleopatra', 98.5)\n('The Gay Divorcee', 96.8)\n('The Thin Man', 96.0)\n('Imitation of Life', 95.5)\n\n\n----> 1935 (Top 5/10 Movies) <----\n('Mutiny on the Bounty', 99.8)\n('Top Hat', 99.0)\n('The Lives of a Bengal Lancer', 98.5)\n('Broadway Melody of 1936', 98.0)\n('David Copperfield', 97.9)\n\n\n----> 1936 (Top 5/10 Movies) <----\n('Mr. Deeds Goes to Town', 99.2)\n('San Francisco', 99.2)\n('Dodsworth', 99.1)\n('The Great Ziegfeld', 99.0)\n('Libeled Lady', 98.4)\n\n\n----> 1937 (Top 5/10 Movies) <----\n('The Life of Emile Zola', 99.4)\n('The Good Earth', 99.2)\n('Captains Courageous', 99.1)\n('Stage Door', 98.8)\n('Lost Horizon', 98.7)\n\n\n----> 1938 (Top 5/0 Movies) <----\n\n\n----> 1939 (Top 5/10 Movies) <----\n('Gone with the Wind', 100.0)\n('Mr. Smith Goes to Washington', 99.5)\n('The Wizard of Oz', 99.5)\n('Wuthering Heights', 99.3)\n('Goodbye Mr. Chips', 99.0)\n\n\n----> 1940 (Top 5/10 Movies) <----\n('Rebecca', 99.9)\n('The Philadelphia Story', 99.5)\n('The Grapes of Wrath', 99.4)\n('The Great Dictator', 99.3)\n('Pinocchio ', 98.4)\n\n\n----> 1941 (Top 5/10 Movies) <----\n('How Green Was My Valley', 99.8)\n('Sergeant York', 99.2)\n('The Maltese Falcon', 99.0)\n('Suspicion', 98.6)\n('The Little Foxes', 98.3)\n\n\n----> 1942 (Top 5/10 Movies) <----\n('Casablanca', 100.0)\n('Mrs. Miniver', 99.8)\n('Yankee Doodle Dandy', 99.4)\n('The Pride of the Yankees', 99.3)\n('Random Harvest', 99.1)\n\n\n----> 1943 (Top 5/10 Movies) <----\n('The Song of Bernadette', 99.3)\n('For Whom the Bell Tolls', 98.8)\n('Heaven Can Wait', 98.4)\n('The Human Comedy', 98.3)\n('Madame Curie', 98.3)\n\n\n----> 1944 (Top 5/10 Movies) <----\n('Going My Way', 99.7)\n('Double Indemnity', 99.4)\n('Gaslight', 99.0)\n('Since You Went Away', 98.5)\n('Wilson', 98.2)\n\n\n----> 1945 (Top 5/10 Movies) <----\n('The Lost Weekend', 99.8)\n(\"The Bells of St. Mary's\", 99.2)\n('Mildred Pierce', 98.9)\n('Spellbound', 98.7)\n('A Tree Grows in Brooklyn ', 97.9)\n\n\n----> 1946 (Top 5/10 Movies) <----\n('The Best Years of Our Lives', 99.9)\n(\"It's a Wonderful Life\", 99.3)\n('The Yearling', 98.9)\n(\"The Razor's Edge\", 98.6)\n('Notorious ', 98.2)\n\n\n----> 1947 (Top 5/10 Movies) <----\n(\"Gentleman's Agreement\", 99.5)\n('Miracle on 34th Street', 98.8)\n(\"The Bishop's Wife\", 98.6)\n('Great Expectations (1946)', 97.5)\n('Life with Father ', 97.3)\n\n\n----> 1948 (Top 5/10 Movies) <----\n('Hamlet', 99.5)\n('The Snake Pit', 99.0)\n('The Treasure of the Sierra Madre', 98.7)\n('Johnny Belinda', 98.0)\n('Key Largo ', 97.8)\n\n\n----> 1949 (Top 5/10 Movies) <----\n(\"All the King's Men\", 99.1)\n(\"Twelve O'Clock High\", 99.0)\n('Battleground', 98.9)\n('The Heiress', 98.3)\n('A Letter to Three Wives', 98.1)\n\n\n----> 1950 (Top 5/10 Movies) <----\n('All About Eve', 99.7)\n('Born Yesterday', 99.0)\n('Sunset Blvd.', 98.8)\n('Father of the Bride', 98.7)\n(\"King Solomon's Mines\", 98.1)\n\n\n----> 1951 (Top 5/10 Movies) <----\n('An American in Paris', 99.7)\n('A Streetcar Named Desire', 99.5)\n('A Place in the Sun', 99.0)\n('Quo Vadis', 98.8)\n('The African Queen ', 98.2)\n\n\n----> 1952 (Top 5/10 Movies) <----\n('High Noon', 99.1)\n('The Greatest Show on Earth', 98.9)\n(\"Singin' in the Rain \", 98.7)\n('The Quiet Man', 98.6)\n('Moulin Rouge', 98.2)\n\n\n----> 1953 (Top 5/10 Movies) <----\n('From Here to Eternity', 99.6)\n('Shane', 99.1)\n('Roman Holiday', 98.4)\n('The Robe', 98.2)\n('Gentlemen Prefer Blondes ', 97.2)\n\n\n----> 1954 (Top 5/10 Movies) <----\n('On the Waterfront', 100.0)\n('The Caine Mutiny', 99.0)\n('The Country Girl', 98.8)\n('Seven Brides for Seven Brothers', 98.7)\n('Rear Window ', 98.6)\n\n\n----> 1955 (Top 5/10 Movies) <----\n('Mister Roberts', 99.0)\n('The Rose Tattoo', 98.8)\n('East of Eden ', 98.6)\n('Love Is a Many-Splendored Thing', 98.3)\n('Rebel without a Cause ', 97.8)\n\n\n----> 1956 (Top 5/10 Movies) <----\n('Around the World in 80 Days', 99.4)\n('Giant', 99.4)\n('The King and I', 99.3)\n('The Ten Commandments', 99.1)\n('Friendly Persuasion', 98.6)\n\n\n----> 1957 (Top 5/10 Movies) <----\n('The Bridge on the River Kwai', 99.9)\n('Sayonara', 99.2)\n('Witness for the Prosecution', 98.8)\n('Peyton Place', 97.7)\n('Old Yeller ', 96.7)\n\n\n----> 1958 (Top 5/10 Movies) <----\n('Gigi', 99.4)\n('Auntie Mame', 99.3)\n('Cat on a Hot Tin Roof', 99.1)\n('Separate Tables', 97.3)\n('The Defiant Ones', 96.9)\n\n\n----> 1959 (Top 5/10 Movies) <----\n('Ben-Hur', 100.0)\n('Anatomy of a Murder', 99.2)\n(\"The Nun's Story\", 99.2)\n('Some Like It Hot ', 99.1)\n('North by Northwest ', 98.4)\n\n\n----> 1960 (Top 5/10 Movies) <----\n('The Apartment', 99.9)\n('Spartacus ', 99.2)\n('Elmer Gantry', 98.9)\n('Psycho ', 98.6)\n('La Dolce Vita ', 98.4)\n\n\n----> 1961 (Top 5/10 Movies) <----\n('West Side Story', 99.8)\n('The Guns of Navarone', 99.0)\n('Judgment at Nuremberg', 98.4)\n('The Hustler', 98.0)\n('El Cid ', 97.8)\n\n\n----> 1962 (Top 5/10 Movies) <----\n('Lawrence of Arabia', 100.0)\n('To Kill a Mockingbird', 99.6)\n('The Music Man', 99.1)\n('How the West Was Won', 98.8)\n('Mutiny on the Bounty', 98.4)\n\n\n----> 1963 (Top 5/10 Movies) <----\n('Tom Jones', 99.4)\n('Charade ', 97.7)\n('From Russia with Love ', 97.7)\n('Irma La Douce ', 97.6)\n(\"It's a Mad Mad Mad Mad World \", 97.6)\n\n\n----> 1964 (Top 5/10 Movies) <----\n('My Fair Lady', 99.8)\n('Mary Poppins', 99.4)\n('Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb', 98.1)\n('Becket', 98.0)\n('Goldfinger', 97.6)\n\n\n----> 1965 (Top 5/10 Movies) <----\n('The Sound of Music', 99.9)\n('Doctor Zhivago', 99.6)\n('Cat Ballou ', 97.6)\n('The Great Race ', 97.2)\n('A Patch of Blue ', 96.4)\n\n\n----> 1966 (Top 5/10 Movies) <----\n('A Man for All Seasons', 99.8)\n(\"Who's Afraid of Virginia Woolf?\", 99.5)\n('The Sand Pebbles', 99.1)\n('Alfie', 98.5)\n('The Good, the Bad and the Ugly ', 98.4)\n\n\n----> 1967 (Top 5/10 Movies) <----\n('In the Heat of the Night', 99.7)\n('Bonnie and Clyde', 99.5)\n('The Graduate', 99.4)\n(\"Guess Who's Coming to Dinner\", 98.8)\n('Thoroughly Modern Millie ', 98.1)\n\n\n----> 1968 (Top 5/10 Movies) <----\n('2001: A Space Odyssey', 99.6)\n('The Lion in Winter', 99.6)\n('Oliver!', 99.5)\n('Funny Girl', 99.4)\n(\"Rosemary's Baby \", 98.2)\n\n\n----> 1969 (Top 5/10 Movies) <----\n('Midnight Cowboy', 99.7)\n('Butch Cassidy and the Sundance Kid', 99.2)\n('Z', 98.7)\n('Hello, Dolly!', 98.4)\n('Easy Rider ', 97.8)\n\n\n----> 1970 (Top 5/10 Movies) <----\n('Patton', 99.9)\n('MASH', 99.3)\n('Woodstock ', 98.4)\n('Airport', 98.1)\n('Love Story', 97.8)\n\n\n----> 1971 (Top 5/10 Movies) <----\n('The French Connection', 99.8)\n('The Last Picture Show', 99.4)\n('Fiddler on the Roof', 99.4)\n('A Clockwork Orange', 99.2)\n('Dirty Harry ', 97.6)\n\n\n----> 1972 (Top 5/10 Movies) <----\n('The Godfather', 100.0)\n('Cabaret', 99.6)\n('Deliverance', 99.1)\n('The Poseidon Adventure ', 97.7)\n('Jeremiah Johnson ', 97.3)\n\n\n----> 1973 (Top 5/10 Movies) <----\n('The Sting', 99.7)\n('American Graffiti', 99.4)\n('The Exorcist', 99.2)\n('Paper Moon', 98.0)\n('Serpico ', 96.3)\n\n\n----> 1974 (Top 5/10 Movies) <----\n('The Godfather: Part II', 99.9)\n('Chinatown', 99.1)\n('The Towering Inferno', 98.3)\n('Lenny', 98.3)\n('Young Frankenstein', 98.0)\n\n\n----> 1975 (Top 5/10 Movies) <----\n(\"One Flew Over the Cuckoo's Nest\", 99.9)\n('Jaws', 99.6)\n('Dog Day Afternoon', 99.3)\n('Barry Lyndon', 98.1)\n('Three Days of the Condor ', 96.7)\n\n\n----> 1976 (Top 5/10 Movies) <----\n('Rocky', 99.7)\n('Network', 99.6)\n(\"All the President's Men\", 99.3)\n('Taxi Driver', 97.1)\n('The Omen ', 96.4)\n\n\n----> 1977 (Top 5/0 Movies) <----\n\n\n----> 1978 (Top 5/10 Movies) <----\n('The Deer Hunter', 99.8)\n('Heaven Can Wait', 98.9)\n('Superman ', 98.1)\n('Midnight Express', 97.2)\n(\"National Lampoon's Animal House\", 97.2)\n\n\n----> 1979 (Top 5/10 Movies) <----\n('Apocalypse Now', 99.7)\n('Kramer vs. Kramer', 99.7)\n('All That Jazz', 98.9)\n('Alien ', 98.4)\n('The China Syndrome ', 96.4)\n\n\n----> 1980 (Top 5/10 Movies) <----\n('Ordinary People', 99.7)\n(\"Coal Miner's Daughter\", 99.2)\n('Star Wars: Episode V - The Empire Strikes Back ', 98.6)\n('Superman II ', 97.3)\n('Airplane! ', 97.1)\n\n\n----> 1981 (Top 5/10 Movies) <----\n('Raiders of the Lost Ark', 99.6)\n('On Golden Pond', 99.3)\n('Chariots of Fire', 99.3)\n('Reds', 98.3)\n('Arthur', 97.3)\n\n\n----> 1982 (Top 5/10 Movies) <----\n('E.T. the Extra-Terrestrial', 99.7)\n('Tootsie', 99.6)\n('Gandhi', 99.2)\n('The Verdict', 99.1)\n('An Officer and a Gentleman', 98.1)\n\n\n----> 1983 (Top 5/10 Movies) <----\n('Terms of Endearment', 99.9)\n('Trading Places ', 97.2)\n('Star Wars: Episode VI - Return of the Jedi ', 96.8)\n('WarGames', 96.7)\n('Scarface ', 95.8)\n\n\n----> 1984 (Top 5/10 Movies) <----\n('Amadeus', 99.8)\n('Ghostbusters ', 97.7)\n('Beverly Hills Cop', 96.7)\n('Indiana Jones and the Temple of Doom ', 96.3)\n('Romancing the Stone ', 96.2)\n\n\n----> 1985 (Top 5/10 Movies) <----\n('The Color Purple', 99.3)\n('Out of Africa', 99.3)\n('Witness', 98.9)\n('Back to the Future', 98.8)\n('Cocoon', 95.2)\n\n\n----> 1986 (Top 5/10 Movies) <----\n('Platoon', 99.9)\n('Aliens ', 98.9)\n('Hannah and Her Sisters', 97.3)\n('Star Trek IV: The Voyage Home', 96.7)\n('Back to School', 95.5)\n\n\n----> 1987 (Top 5/10 Movies) <----\n('Moonstruck', 99.0)\n('Fatal Attraction', 98.6)\n('The Last Emperor', 98.6)\n('Good Morning, Vietnam ', 96.7)\n('Broadcast News', 96.5)\n\n\n----> 2011 (Top 5/10 Movies) <----\n('The Help', 98.3)\n('Harry Potter and the Deathly Hallows: Part 2', 98.1)\n('The Artist', 97.9)\n('Bridesmaids ', 97.4)\n('Mission: Impossible - Ghost Protocol ', 97.4)\n\n\n----> 2012 (Top 5/10 Movies) <----\n('Lincoln', 99.5)\n('Argo', 99.5)\n('Django Unchained', 99.1)\n('Silver Linings Playbook', 98.7)\n('Life of Pi', 98.6)\n\n\n----> 2013 (Top 5/10 Movies) <----\n('Gravity', 99.5)\n('American Hustle', 98.9)\n('12 Years a Slave', 97.8)\n('Frozen ', 97.7)\n('The Hunger Games: Catching Fire ', 97.6)\n\n\n----> 2014 (Top 5/10 Movies) <----\n('American Sniper', 98.8)\n('Guardians of the Galaxy ', 97.9)\n('Dawn of the Planet of The Apes ', 97.8)\n('The LEGO Movie ', 97.8)\n('Big Hero 6 ', 97.6)\n\n\n----> 2015 (Top 5/10 Movies) <----\n('The Martian', 99.5)\n('The Revenant', 99.4)\n('Mad Max: Fury Road', 99.3)\n('Inside Out ', 98.6)\n('Star Wars: The Force Awakens ', 98.4)\n\n\n----> 2016 (Top 5/10 Movies) <----\n('La La Land', 99.4)\n('Hidden Figures', 98.2)\n('Zootopia ', 97.9)\n('Moana ', 97.8)\n('The Jungle Book ', 97.7)\n\n\n----> 2017 (Top 5/10 Movies) <----\n('Dunkirk', 99.4)\n('Get Out', 98.7)\n('Coco ', 98.5)\n('The Shape Of Water', 97.9)\n('Logan ', 97.8)\n\n\nSaving 67 Years of Ultimate Movie Rankings data to /Users/tgadfort/Documents/code/movies/ultimatemovierankings/results/ultimatemovierankings.json\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
4ac599def40fa65dd727ddf56b9a0d75081047b9
| 40,621 |
ipynb
|
Jupyter Notebook
|
notebooks/DB Connectivity.ipynb
|
adamw523/simple-flask-app
|
07ba4e796c0f89118dd3beafa3ce46c35f993f66
|
[
"MIT"
] | null | null | null |
notebooks/DB Connectivity.ipynb
|
adamw523/simple-flask-app
|
07ba4e796c0f89118dd3beafa3ce46c35f993f66
|
[
"MIT"
] | null | null | null |
notebooks/DB Connectivity.ipynb
|
adamw523/simple-flask-app
|
07ba4e796c0f89118dd3beafa3ce46c35f993f66
|
[
"MIT"
] | null | null | null | 161.194444 | 1,634 | 0.699417 |
[
[
[
"import sys\napp_path = '/data/app/app'\nif sys.path[0] != app_path:\n sys.path.insert(0, app_path)",
"_____no_output_____"
],
[
"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy",
"_____no_output_____"
],
[
"import app",
"_____no_output_____"
],
[
"print(app.app.config['SQLALCHEMY_DATABASE_URI'])",
"postgresql://postgres:password@db/flask-app\n"
],
[
"db = SQLAlchemy(app.app)",
"_____no_output_____"
],
[
"from sqlalchemy.sql import text",
"_____no_output_____"
],
[
"stmt = text(\"SELECT 1\")\nconn = db.engine.connect()\n",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac59c58fdb82828b39ec28d19d95cec8a28829e
| 17,197 |
ipynb
|
Jupyter Notebook
|
section_robot/ideal_robot11.ipynb
|
harukary/LNPR_BOOK_CODES
|
97752f8c415b6006fcb8e25f919cd821c66101c4
|
[
"MIT"
] | null | null | null |
section_robot/ideal_robot11.ipynb
|
harukary/LNPR_BOOK_CODES
|
97752f8c415b6006fcb8e25f919cd821c66101c4
|
[
"MIT"
] | null | null | null |
section_robot/ideal_robot11.ipynb
|
harukary/LNPR_BOOK_CODES
|
97752f8c415b6006fcb8e25f919cd821c66101c4
|
[
"MIT"
] | null | null | null | 61.417857 | 6,974 | 0.668954 |
[
[
[
"import matplotlib\nmatplotlib.use('nbagg')\nimport matplotlib.animation as anm\nimport matplotlib.pyplot as plt\nimport math\nimport matplotlib.patches as patches\nimport numpy as np\n%matplotlib widget",
"_____no_output_____"
],
[
"class World:\n def __init__(self, time_span, time_interval, debug=False):\n self.objects = [] \n self.debug = debug\n self.time_span = time_span \n self.time_interval = time_interval \n \n def append(self,obj): \n self.objects.append(obj)\n \n def draw(self): \n fig = plt.figure(figsize=(4,4))\n ax = fig.add_subplot(111)\n ax.set_aspect('equal') \n ax.set_xlim(-5,5) \n ax.set_ylim(-5,5) \n ax.set_xlabel(\"X\",fontsize=10) \n ax.set_ylabel(\"Y\",fontsize=10) \n \n elems = []\n \n if self.debug: \n for i in range(int(self.time_span/self.time_interval)): self.one_step(i, elems, ax)\n else:\n self.ani = anm.FuncAnimation(fig, self.one_step, fargs=(elems, ax),\n frames=int(self.time_span/self.time_interval)+1, interval=int(self.time_interval*1000), repeat=False)\n plt.show()\n \n def one_step(self, i, elems, ax):\n while elems: elems.pop().remove()\n time_str = \"t = %.2f[s]\" % (self.time_interval*i)\n elems.append(ax.text(-4.4, 4.5, time_str, fontsize=10))\n for obj in self.objects:\n obj.draw(ax, elems)\n if hasattr(obj, \"one_step\"): obj.one_step(self.time_interval) ",
"_____no_output_____"
],
[
"class IdealRobot: \n def __init__(self, pose, agent=None, sensor=None, color=\"black\"): # 引数を追加\n self.pose = pose\n self.r = 0.2 \n self.color = color \n self.agent = agent\n self.poses = [pose]\n self.sensor = sensor # 追加\n \n def draw(self, ax, elems): ### call_agent_draw\n x, y, theta = self.pose \n xn = x + self.r * math.cos(theta) \n yn = y + self.r * math.sin(theta) \n elems += ax.plot([x,xn], [y,yn], color=self.color)\n c = patches.Circle(xy=(x, y), radius=self.r, fill=False, color=self.color) \n elems.append(ax.add_patch(c))\n self.poses.append(self.pose)\n elems += ax.plot([e[0] for e in self.poses], [e[1] for e in self.poses], linewidth=0.5, color=\"black\")\n if self.sensor and len(self.poses) > 1: \n self.sensor.draw(ax, elems, self.poses[-2])\n if self.agent and hasattr(self.agent, \"draw\"): #以下2行追加 \n self.agent.draw(ax, elems)\n \n @classmethod \n def state_transition(cls, nu, omega, time, pose):\n t0 = pose[2]\n if math.fabs(omega) < 1e-10:\n return pose + np.array( [nu*math.cos(t0), \n nu*math.sin(t0),\n omega ] ) * time\n else:\n return pose + np.array( [nu/omega*(math.sin(t0 + omega*time) - math.sin(t0)), \n nu/omega*(-math.cos(t0 + omega*time) + math.cos(t0)),\n omega*time ] )\n\n def one_step(self, time_interval):\n if not self.agent: return \n obs =self.sensor.data(self.pose) if self.sensor else None #追加\n nu, omega = self.agent.decision(obs) #引数追加\n self.pose = self.state_transition(nu, omega, time_interval, self.pose)\n if self.sensor: self.sensor.data(self.pose) ",
"_____no_output_____"
],
[
"class Agent: \n def __init__(self, nu, omega):\n self.nu = nu\n self.omega = omega\n \n def decision(self, observation=None):\n return self.nu, self.omega",
"_____no_output_____"
],
[
"class Landmark:\n def __init__(self, x, y):\n self.pos = np.array([x, y]).T\n self.id = None\n \n def draw(self, ax, elems):\n c = ax.scatter(self.pos[0], self.pos[1], s=100, marker=\"*\", label=\"landmarks\", color=\"orange\")\n elems.append(c)\n elems.append(ax.text(self.pos[0], self.pos[1], \"id:\" + str(self.id), fontsize=10))",
"_____no_output_____"
],
[
"class Map:\n def __init__(self): # 空のランドマークのリストを準備\n self.landmarks = []\n \n def append_landmark(self, landmark): # ランドマークを追加\n landmark.id = len(self.landmarks) # 追加するランドマークにIDを与える\n self.landmarks.append(landmark)\n\n def draw(self, ax, elems): # 描画(Landmarkのdrawを順に呼び出し)\n for lm in self.landmarks: lm.draw(ax, elems)",
"_____no_output_____"
],
[
"class IdealCamera:\n def __init__(self, env_map, \\\n distance_range=(0.5, 6.0),\n direction_range=(-math.pi/3, math.pi/3)):\n self.map = env_map\n self.lastdata = []\n \n self.distance_range = distance_range\n self.direction_range = direction_range\n \n def visible(self, polarpos): # ランドマークが計測できる条件\n if polarpos is None:\n return False\n \n return self.distance_range[0] <= polarpos[0] <= self.distance_range[1] \\\n and self.direction_range[0] <= polarpos[1] <= self.direction_range[1]\n \n def data(self, cam_pose):\n observed = []\n for lm in self.map.landmarks:\n z = self.observation_function(cam_pose, lm.pos)\n if self.visible(z): # 条件を追加\n observed.append((z, lm.id)) # インデント\n \n self.lastdata = observed \n return observed\n \n @classmethod\n def observation_function(cls, cam_pose, obj_pos):\n diff = obj_pos - cam_pose[0:2]\n phi = math.atan2(diff[1], diff[0]) - cam_pose[2]\n while phi >= np.pi: phi -= 2*np.pi\n while phi < -np.pi: phi += 2*np.pi\n return np.array( [np.hypot(*diff), phi ] ).T\n \n def draw(self, ax, elems, cam_pose): \n for lm in self.lastdata:\n x, y, theta = cam_pose\n distance, direction = lm[0][0], lm[0][1]\n lx = x + distance * math.cos(direction + theta)\n ly = y + distance * math.sin(direction + theta)\n elems += ax.plot([x,lx], [y,ly], color=\"pink\")",
"_____no_output_____"
],
[
"if __name__ == '__main__': ###name_indent\n world = World(30, 0.1) \n\n ### 地図を生成して3つランドマークを追加 ###\n m = Map() \n m.append_landmark(Landmark(2,-2))\n m.append_landmark(Landmark(-1,-3))\n m.append_landmark(Landmark(3,3))\n world.append(m) \n\n ### ロボットを作る ###\n straight = Agent(0.2, 0.0) \n circling = Agent(0.2, 10.0/180*math.pi) \n robot1 = IdealRobot( np.array([ 2, 3, math.pi/6]).T, sensor=IdealCamera(m), agent=straight ) # 引数にcameraを追加、整理\n robot2 = IdealRobot( np.array([-2, -1, math.pi/5*6]).T, sensor=IdealCamera(m), agent=circling, color=\"red\") # robot3は消しました\n world.append(robot1)\n world.append(robot2)\n\n ### アニメーション実行 ###\n world.draw()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac59dd057f597b0abdcaaf7cf1450d1277c476f
| 559,357 |
ipynb
|
Jupyter Notebook
|
Notebooks/Localization/Realistic Model - 4 dets (~10 deg angles).ipynb
|
nkasmanoff/Simulation
|
38d47db79cebe8504a03424c564f2207ae2275ac
|
[
"MIT"
] | null | null | null |
Notebooks/Localization/Realistic Model - 4 dets (~10 deg angles).ipynb
|
nkasmanoff/Simulation
|
38d47db79cebe8504a03424c564f2207ae2275ac
|
[
"MIT"
] | 15 |
2017-04-06T18:52:39.000Z
|
2019-08-15T17:48:40.000Z
|
Notebooks/Localization/Realistic Model - 4 dets (~10 deg angles).ipynb
|
nkasmanoff/Simulation
|
38d47db79cebe8504a03424c564f2207ae2275ac
|
[
"MIT"
] | 3 |
2017-06-13T17:54:29.000Z
|
2018-09-16T15:43:24.000Z
| 828.677037 | 303,936 | 0.944122 |
[
[
[
"## Overview/To-Do\n\nThis one tries a different, more realistic detecor layouout.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap",
"_____no_output_____"
],
[
"from BurstCube.LocSim.GRB import *\nfrom BurstCube.LocSim.Detector import *\nfrom BurstCube.LocSim.Spacecraft import *\nfrom BurstCube.LocSim.Stats import calcNorms, addErrors, calcNormsWithError",
"_____no_output_____"
]
],
[
[
"## Set up\nThese are actually the default pointings but I put it here to show you how to set up various detectors. Just six, smaller detectors this time.",
"_____no_output_____"
]
],
[
[
"#Evenly spaced around azimuth\n#Staggered in zenith\n#Arbitrary type\npointings = {'01': ('90:0:0','8:0:0'),\n '02': ('180:0:0','10:0:0'),\n '03': ('270:0:0','12:0:0'),\n '04': ('360:0:0','14:0:0')}",
"_____no_output_____"
]
],
[
[
"Set up a spacecraft object with the pointings of the detector you've decided on. The spacecraft defaults to a position above DC at an elevation of 550 km (about the orbit of Fermi).",
"_____no_output_____"
]
],
[
[
"spacecraft = Spacecraft(pointings, window = 0.1)",
"_____no_output_____"
]
],
[
[
"Set up some points in RA/Dec to calculate exposures and then access the 'exposure' function of the detector objects within the spacecraft object to plot the exposure.",
"_____no_output_____"
]
],
[
[
"res = 250\nrr,dd = np.meshgrid(np.linspace(0,360,res,endpoint=False),np.linspace(-90,90,res))\nexposure_positions = np.vstack([rr.ravel(),dd.ravel()])",
"_____no_output_____"
],
[
"exposures = np.array([[detector.exposure(position[0],position[1]) for position in exposure_positions.T] \n for detector in spacecraft.detectors])",
"_____no_output_____"
],
[
"plt.figure(figsize=(20,4))\nm = Basemap(projection='moll',lon_0=180.,resolution='c')\nx,y = m(rr,dd)\nfor sp in range(4):\n plt.subplot(2, 2, sp+1)\n m.pcolormesh(x,y,exposures[sp].reshape((res,res)))\nplt.show()",
"/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3413: MatplotlibDeprecationWarning: The ishold function was deprecated in version 2.0.\n b = ax.ishold()\n/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3422: MatplotlibDeprecationWarning: axes.hold is deprecated.\n See the API Changes document (http://matplotlib.org/api/api_changes.html)\n for more details.\n ax.hold(b)\n/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:1623: MatplotlibDeprecationWarning: The get_axis_bgcolor function was deprecated in version 2.0. Use get_facecolor instead.\n fill_color = ax.get_axis_bgcolor()\n"
],
[
"plt.figure(figsize=(8,10))\nm = Basemap(projection='moll',lon_0=180,resolution='c')\nm.drawparallels(np.arange(-90.,120.,30.))\nm.drawmeridians(np.arange(0.,420.,60.))\nx,y = m(rr,dd)\nm.pcolormesh(x,y,exposures.sum(axis=0).reshape((res,res)))\nm.colorbar()\nplt.show()",
"/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:1623: MatplotlibDeprecationWarning: The get_axis_bgcolor function was deprecated in version 2.0. Use get_facecolor instead.\n fill_color = ax.get_axis_bgcolor()\n/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3413: MatplotlibDeprecationWarning: The ishold function was deprecated in version 2.0.\n b = ax.ishold()\n/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3422: MatplotlibDeprecationWarning: axes.hold is deprecated.\n See the API Changes document (http://matplotlib.org/api/api_changes.html)\n for more details.\n ax.hold(b)\n"
],
[
"rr,dd = np.meshgrid(np.linspace(0,360,55,endpoint=False),np.linspace(-90,90,55))\ntraining_positions = np.vstack([rr.ravel(),dd.ravel()])",
"_____no_output_____"
],
[
"exposures = np.array([[detector.exposure(position[0],position[1]) for position in training_positions.T] \n for detector in spacecraft.detectors])",
"_____no_output_____"
],
[
"training_grbs = [GRB(position[0],position[1],binz=.001) for position in training_positions.T[exposures.sum(axis=0) > 0.]]",
"_____no_output_____"
],
[
"pos = np.array([[grb.eph._ra*180./np.pi,grb.eph._dec*180./np.pi] for grb in training_grbs])\nplt.figure(figsize=(8,10))\nm = Basemap(projection='moll',lon_0=180,resolution='c')\nm.drawparallels(np.arange(-90.,120.,30.))\nm.drawmeridians(np.arange(0.,420.,60.))\nx,y = m(pos[:,0],pos[:,1])\nm.scatter(x,y,3,marker='o',color='k')\nplt.show()",
"/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:1623: MatplotlibDeprecationWarning: The get_axis_bgcolor function was deprecated in version 2.0. Use get_facecolor instead.\n fill_color = ax.get_axis_bgcolor()\n/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3222: MatplotlibDeprecationWarning: The ishold function was deprecated in version 2.0.\n b = ax.ishold()\n/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3231: MatplotlibDeprecationWarning: axes.hold is deprecated.\n See the API Changes document (http://matplotlib.org/api/api_changes.html)\n for more details.\n ax.hold(b)\n"
],
[
"training_counts = spacecraft.throw_grbs(training_grbs,scaled=True)",
"/Users/jsperki1/.local/lib/python3.6/site-packages/BurstCube/LocSim/Spacecraft.py:80: RuntimeWarning: invalid value encountered in true_divide\n for idx,rec in enumerate(grb_rec)]\n"
]
],
[
[
"## Setup and throw a random sample of GRBs\n\nNote that I'm only throwing them in the north since the Earth blocks the south.",
"_____no_output_____"
]
],
[
[
"real_positions = np.array(list(zip(360.*np.random.random_sample(2000),180.*np.random.random_sample(2000)-90.)))",
"_____no_output_____"
],
[
"exposures = np.array([[detector.exposure(position[0],position[1]) for position in real_positions]\n for detector in spacecraft.detectors])",
"_____no_output_____"
],
[
"real_grbs = [GRB(position[0],position[1],binz=0.001) for position in real_positions[exposures.sum(axis=0) > 0.]]",
"_____no_output_____"
],
[
"np.shape(real_grbs)",
"_____no_output_____"
],
[
"real_counts = spacecraft.throw_grbs(real_grbs, scaled=True)",
"/Users/jsperki1/.local/lib/python3.6/site-packages/BurstCube/LocSim/Spacecraft.py:80: RuntimeWarning: invalid value encountered in true_divide\n for idx,rec in enumerate(grb_rec)]\n"
],
[
"pos = np.array([[grb.eph._ra*180./np.pi,grb.eph._dec*180./np.pi] for grb in real_grbs])\nplt.figure(figsize=(8,10))\nm = Basemap(projection='moll',lon_0=180,resolution='c')\nm.drawparallels(np.arange(-90.,120.,30.))\nm.drawmeridians(np.arange(0.,420.,60.))\nx,y = m(pos[:,0],pos[:,1])\nm.scatter(x,y,3,marker='o',color='k')\nplt.show()",
"/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:1623: MatplotlibDeprecationWarning: The get_axis_bgcolor function was deprecated in version 2.0. Use get_facecolor instead.\n fill_color = ax.get_axis_bgcolor()\n/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3222: MatplotlibDeprecationWarning: The ishold function was deprecated in version 2.0.\n b = ax.ishold()\n/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3231: MatplotlibDeprecationWarning: axes.hold is deprecated.\n See the API Changes document (http://matplotlib.org/api/api_changes.html)\n for more details.\n ax.hold(b)\n"
],
[
"norms = calcNorms(real_counts,training_counts)",
"_____no_output_____"
],
[
"real_counts_err = addErrors(real_counts,training_counts)",
"_____no_output_____"
],
[
"norms_errp, norms_errm = calcNormsWithError(real_counts,training_counts,real_counts_err)",
"_____no_output_____"
]
],
[
[
"Find the minimum distance of each GRB.",
"_____no_output_____"
]
],
[
[
"loc_mins = [norm.argmin() for norm in norms]\nloc_mins_errm = [norm.argmin() for norm in norms_errm]\nloc_mins_errp = [norm.argmin() for norm in norms_errp]",
"_____no_output_____"
]
],
[
[
"Now, calculate the distance from the real GRB to the training one picked out from the distance measuremnt above.",
"_____no_output_____"
]
],
[
[
"errors = [eph.separation(grb.eph,training_grbs[loc_mins[idx]].eph)*180./np.pi for idx,grb in enumerate(real_grbs)]\nerrors_errm = [eph.separation(grb.eph,training_grbs[loc_mins_errm[idx]].eph)*180./np.pi for idx,grb in enumerate(real_grbs)]\nerrors_errp = [eph.separation(grb.eph,training_grbs[loc_mins_errp[idx]].eph)*180./np.pi for idx,grb in enumerate(real_grbs)]",
"_____no_output_____"
]
],
[
[
"Plot and save the cumulative distribution of this error.",
"_____no_output_____"
]
],
[
[
"hist_data = plt.hist(errors,bins=100,normed=1, histtype='step', cumulative=True)\nhist_data_errm = plt.hist(errors_errm,bins=100,normed=1, histtype='step', cumulative=True)\nhist_data_errp = plt.hist(errors_errp,bins=100,normed=1, histtype='step', cumulative=True)\nplt.plot()",
"_____no_output_____"
]
],
[
[
"The 1-sigma error is around 68%. Quick function to find the distance value that most closely matches 0.68.",
"_____no_output_____"
]
],
[
[
"avg_stat = np.average([hist_data_errm[1][np.abs(hist_data_errm[0] - 0.68).argmin()],\n hist_data_errp[1][np.abs(hist_data_errp[0] - 0.68).argmin()]])",
"_____no_output_____"
],
[
"print('Systematic Error: {:,.2f}'.format(hist_data[1][np.abs(hist_data[0] - 0.68).argmin()]))",
"Systematic Error: 33.76\n"
],
[
"print('Statistical Error: {:,.2f}'.format(avg_stat))",
"Statistical Error: 33.70\n"
],
[
"pos = np.array([[grb.eph._ra*180./np.pi,grb.eph._dec*180./np.pi] for grb in real_grbs])\nplt.figure(figsize=(20,10))\nm = Basemap(projection='moll',lon_0=180,resolution='c')\nm.drawparallels(np.arange(-90.,120.,30.))\nm.drawmeridians(np.arange(0.,420.,60.))\nx,y = m(pos[:,0],pos[:,1])\n#m.scatter(x,y,marker='o',c=errors, s=np.array(errors)*10,cmap=plt.cm.hsv)\nm.scatter(x,y,marker='o',c=errors,s=100.,cmap=plt.cm.hsv)\nplt.colorbar(shrink=0.5)\nplt.savefig('Sky Map with Errors.pdf', transparent = True)\nplt.show()",
"/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:1623: MatplotlibDeprecationWarning: The get_axis_bgcolor function was deprecated in version 2.0. Use get_facecolor instead.\n fill_color = ax.get_axis_bgcolor()\n/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3222: MatplotlibDeprecationWarning: The ishold function was deprecated in version 2.0.\n b = ax.ishold()\n/usr/local/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py:3231: MatplotlibDeprecationWarning: axes.hold is deprecated.\n See the API Changes document (http://matplotlib.org/api/api_changes.html)\n for more details.\n ax.hold(b)\n"
]
]
] |
[
"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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4ac59e950d9d378b09f9fb0e804f08440ab80528
| 4,863 |
ipynb
|
Jupyter Notebook
|
01_pre-requisites/01_python/py03_02 Map, Reduce & Filter.ipynb
|
sujeetkrjaiswal/learn-ml-ai
|
930b72b4963ad14a89e2c3701446999c2f5bdbdf
|
[
"MIT"
] | null | null | null |
01_pre-requisites/01_python/py03_02 Map, Reduce & Filter.ipynb
|
sujeetkrjaiswal/learn-ml-ai
|
930b72b4963ad14a89e2c3701446999c2f5bdbdf
|
[
"MIT"
] | null | null | null |
01_pre-requisites/01_python/py03_02 Map, Reduce & Filter.ipynb
|
sujeetkrjaiswal/learn-ml-ai
|
930b72b4963ad14a89e2c3701446999c2f5bdbdf
|
[
"MIT"
] | null | null | null | 22.410138 | 631 | 0.494962 |
[
[
[
"first_list = [2, 4, 5]\nprint(first_list**2)",
"_____no_output_____"
],
[
"first_list = [2, 4, 5]",
"_____no_output_____"
],
[
"print(map(lambda x: x**2, first_list))",
"<map object at 0x108262be0>\n"
],
[
"first_list = [2,4,5]\nprint(list(map(lambda x: x**2, first_list)))",
"[4, 16, 25]\n"
],
[
"def squareit(n):\n return n**2\nprint(list(map(squareit, first_list)))\n",
"[4, 16, 25]\n"
],
[
"sums_list = [3,5,9,7]\nsums_list2 = (4,5,6,7)\nprint(list(map(lambda x,y : x+y, sums_list,sums_list2)))",
"[7, 10, 15, 14]\n"
],
[
"list_of_names = ['nikola', 'james', 'albert']\nlist_of_names2 = ['tesla','watt','einstein']\nproper = lambda x, y: x[0].upper()+x[1:] +' '+ y[0].upper()+y[1:]\nprint(list(map(proper, list_of_names,list_of_names2)))",
"['Nikola Tesla', 'James Watt', 'Albert Einstein']\n"
],
[
"#Filter\ndivby3 = lambda x: x % 3 == 0\nmy_list = [3,4,5,6,7,8,9]\ndiv = filter(divby3, my_list)\nprint(list(div))",
"[3, 6, 9]\n"
],
[
"#Reduce\nfrom functools import reduce\nq = reduce(lambda x, y: x+y, range(1,4))\nprint(q)",
"6\n"
],
[
"list_of_nums = [22,45,32,20,87,94,30]\nprint(reduce(lambda x,y: x if x>y else y,list_of_nums))",
"94\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac5c84105b64cd62163e5010c7e43e66ce57370
| 4,050 |
ipynb
|
Jupyter Notebook
|
examples/JCG14e61.ipynb
|
blegat/SwitchOnSafety.jl
|
c5461c0d9fbdf63ed0fb284962808b963d218070
|
[
"MIT"
] | 13 |
2017-11-24T10:29:56.000Z
|
2022-01-23T15:10:52.000Z
|
examples/JCG14e61.ipynb
|
blegat/SwitchedSystems.jl
|
88c6c64f7499de1fc8b039cfc2da393778f1e4c4
|
[
"MIT"
] | 22 |
2017-10-02T09:26:21.000Z
|
2022-03-28T15:14:00.000Z
|
examples/JCG14e61.ipynb
|
blegat/SwitchedSystems.jl
|
88c6c64f7499de1fc8b039cfc2da393778f1e4c4
|
[
"MIT"
] | 6 |
2017-11-29T13:44:09.000Z
|
2021-09-15T11:08:56.000Z
| 19.756098 | 84 | 0.488148 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4ac5d6e3252730a345f5b7ba6ce8f815541fa0d8
| 7,987 |
ipynb
|
Jupyter Notebook
|
Python/56_VH_Registration1.ipynb
|
Seojin24/SimpleITK-Cardiac-
|
24a17320528ea7c07bb463ddcad253c74decc560
|
[
"Apache-2.0"
] | 1 |
2018-01-12T08:03:53.000Z
|
2018-01-12T08:03:53.000Z
|
Python/56_VH_Registration1.ipynb
|
Seojin24/SimpleITK-Cardiac-
|
24a17320528ea7c07bb463ddcad253c74decc560
|
[
"Apache-2.0"
] | null | null | null |
Python/56_VH_Registration1.ipynb
|
Seojin24/SimpleITK-Cardiac-
|
24a17320528ea7c07bb463ddcad253c74decc560
|
[
"Apache-2.0"
] | 2 |
2018-12-24T06:43:52.000Z
|
2020-01-13T08:31:19.000Z
| 26.623333 | 234 | 0.598723 |
[
[
[
"from __future__ import print_function\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport SimpleITK as sitk\nprint(sitk.Version())\nfrom myshow import myshow\n# Download data to work on\n%run update_path_to_download_script\nfrom downloaddata import fetch_data as fdata\n\nOUTPUT_DIR = \"Output\"",
"_____no_output_____"
]
],
[
[
"This section of the Visible Human Male is about 1.5GB. To expedite processing and registration we crop the region of interest, and reduce the resolution. Take note that the physical space is maintained through these operations. ",
"_____no_output_____"
]
],
[
[
"fixed_rgb = sitk.ReadImage(fdata(\"vm_head_rgb.mha\"))\nfixed_rgb = fixed_rgb[735:1330,204:975,:]\nfixed_rgb = sitk.BinShrink(fixed_rgb,[3,3,1])",
"_____no_output_____"
],
[
"moving = sitk.ReadImage(fdata(\"vm_head_mri.mha\"))\n",
"_____no_output_____"
],
[
"myshow(moving)",
"_____no_output_____"
],
[
"# Segment blue ice\nseeds = [[10,10,10]]\nfixed_mask = sitk.VectorConfidenceConnected(fixed_rgb, seedList=seeds, initialNeighborhoodRadius=5, numberOfIterations=4, multiplier=8)",
"_____no_output_____"
],
[
"# Invert the segment and choose largest component\nfixed_mask = sitk.RelabelComponent(sitk.ConnectedComponent(fixed_mask==0))==1",
"_____no_output_____"
],
[
"myshow(sitk.Mask(fixed_rgb, fixed_mask));",
"_____no_output_____"
],
[
"# pick red channel\nfixed = sitk.VectorIndexSelectionCast(fixed_rgb,0)\n\nfixed = sitk.Cast(fixed,sitk.sitkFloat32)\nmoving = sitk.Cast(moving,sitk.sitkFloat32)",
"_____no_output_____"
],
[
"initialTransform = sitk.Euler3DTransform()\ninitialTransform = sitk.CenteredTransformInitializer(sitk.Cast(fixed_mask,moving.GetPixelID()), moving, initialTransform, sitk.CenteredTransformInitializerFilter.MOMENTS)\nprint(initialTransform)",
"_____no_output_____"
],
[
"def command_iteration(method) :\n print(\"{0} = {1} : {2}\".format(method.GetOptimizerIteration(),\n method.GetMetricValue(),\n method.GetOptimizerPosition()),\n end='\\n');\n sys.stdout.flush();",
"_____no_output_____"
],
[
"tx = initialTransform\nR = sitk.ImageRegistrationMethod()\nR.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)\nR.SetOptimizerAsGradientDescentLineSearch(learningRate=1,numberOfIterations=100)\nR.SetOptimizerScalesFromIndexShift()\nR.SetShrinkFactorsPerLevel([4,2,1])\nR.SetSmoothingSigmasPerLevel([8,4,2])\nR.SmoothingSigmasAreSpecifiedInPhysicalUnitsOn()\nR.SetMetricSamplingStrategy(R.RANDOM)\nR.SetMetricSamplingPercentage(0.1)\nR.SetInitialTransform(tx)\nR.SetInterpolator(sitk.sitkLinear)",
"_____no_output_____"
],
[
"import sys\nR.RemoveAllCommands()\nR.AddCommand( sitk.sitkIterationEvent, lambda: command_iteration(R) )\noutTx = R.Execute(sitk.Cast(fixed,sitk.sitkFloat32), sitk.Cast(moving,sitk.sitkFloat32))\n\nprint(\"-------\")\nprint(tx)\nprint(\"Optimizer stop condition: {0}\".format(R.GetOptimizerStopConditionDescription()))\nprint(\" Iteration: {0}\".format(R.GetOptimizerIteration()))\nprint(\" Metric value: {0}\".format(R.GetMetricValue()))",
"_____no_output_____"
],
[
"tx.AddTransform(sitk.Transform(3,sitk.sitkAffine))\n\nR.SetOptimizerAsGradientDescentLineSearch(learningRate=1,numberOfIterations=100)\nR.SetOptimizerScalesFromIndexShift()\nR.SetShrinkFactorsPerLevel([2,1])\nR.SetSmoothingSigmasPerLevel([4,1])\nR.SmoothingSigmasAreSpecifiedInPhysicalUnitsOn()\nR.SetInitialTransform(tx)",
"_____no_output_____"
],
[
"outTx = R.Execute(sitk.Cast(fixed,sitk.sitkFloat32), sitk.Cast(moving,sitk.sitkFloat32))\nR.GetOptimizerStopConditionDescription()",
"_____no_output_____"
],
[
"resample = sitk.ResampleImageFilter()\nresample.SetReferenceImage(fixed_rgb)\nresample.SetInterpolator(sitk.sitkBSpline)\nresample.SetTransform(outTx)\nresample.AddCommand(sitk.sitkProgressEvent, lambda: print(\"\\rProgress: {0:03.1f}%...\".format(100*resample.GetProgress()),end=''))\nresample.AddCommand(sitk.sitkProgressEvent, lambda: sys.stdout.flush())\nresample.AddCommand(sitk.sitkEndEvent, lambda: print(\"Done\"))\nout = resample.Execute(moving)",
"_____no_output_____"
],
[
"out_rgb = sitk.Cast( sitk.Compose( [sitk.RescaleIntensity(out)]*3), sitk.sitkVectorUInt8)\nvis_xy = sitk.CheckerBoard(fixed_rgb, out_rgb, checkerPattern=[8,8,1])\nvis_xz = sitk.CheckerBoard(fixed_rgb, out_rgb, checkerPattern=[8,1,8])\nvis_xz = sitk.PermuteAxes(vis_xz, [0,2,1])",
"_____no_output_____"
],
[
"myshow(vis_xz,dpi=30)",
"_____no_output_____"
],
[
"import os\n\nsitk.WriteImage(out, os.path.join(OUTPUT_DIR, \"example_registration.mha\"))\nsitk.WriteImage(vis_xy, os.path.join(OUTPUT_DIR, \"example_registration_xy.mha\"))\nsitk.WriteImage(vis_xz, os.path.join(OUTPUT_DIR, \"example_registration_xz.mha\"))",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac5ded517d55429c46e21a0c9bbc062e1ed048f
| 14,145 |
ipynb
|
Jupyter Notebook
|
docs/fs.ipynb
|
eschmidt42/Molly.jl
|
d2b3375bd231bfbdf2546e7d7beb5503183d76df
|
[
"MIT"
] | null | null | null |
docs/fs.ipynb
|
eschmidt42/Molly.jl
|
d2b3375bd231bfbdf2546e7d7beb5503183d76df
|
[
"MIT"
] | null | null | null |
docs/fs.ipynb
|
eschmidt42/Molly.jl
|
d2b3375bd231bfbdf2546e7d7beb5503183d76df
|
[
"MIT"
] | null | null | null | 25.765027 | 307 | 0.518911 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4ac611e2451bd7fba6639507406d62a5eeac73ca
| 652,605 |
ipynb
|
Jupyter Notebook
|
Task 5/TSF Task 5.ipynb
|
ps1899/TheSparksFoundation
|
190244d95ba7a8b2989d1213380df437a2200e80
|
[
"Apache-2.0"
] | 2 |
2020-09-12T07:15:59.000Z
|
2020-09-27T16:57:34.000Z
|
Task 5/TSF Task 5.ipynb
|
ps1899/TheSparksFoundation
|
190244d95ba7a8b2989d1213380df437a2200e80
|
[
"Apache-2.0"
] | null | null | null |
Task 5/TSF Task 5.ipynb
|
ps1899/TheSparksFoundation
|
190244d95ba7a8b2989d1213380df437a2200e80
|
[
"Apache-2.0"
] | null | null | null | 663.89115 | 201,176 | 0.945342 |
[
[
[
"# BUSINESS ANALYTICS\nYou are the business owner of the retail firm and want to see how your company is performing. You are interested in finding out the weak areas where you can work to make more profit. What all business problems you can derive by looking into the data?",
"_____no_output_____"
]
],
[
[
"# Importing certain libraries\nimport pandas as pd\nimport numpy as np\nimport seaborn as sb\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"## Understanding the data",
"_____no_output_____"
]
],
[
[
"# Importing the dataset\ndata = pd.read_csv(r\"D:/TSF/Task 5/SampleSuperstore.csv\")\n\n# Displaying the Dataset\ndata.head()",
"_____no_output_____"
],
[
"# Gathering the basic Information\ndata.describe()",
"_____no_output_____"
],
[
"# Learning about differnet datatypes present in the dataset\ndata.dtypes",
"_____no_output_____"
],
[
"# Checking for any null or misssing values\ndata.isnull().sum()",
"_____no_output_____"
]
],
[
[
"Since, there are no null or missing values present, therefore we can move further for data exploration",
"_____no_output_____"
],
[
"## Exploratory Data Analysis",
"_____no_output_____"
]
],
[
[
"# First, using seaborn pairplot for data visualisation\nsb.set(style = \"whitegrid\")\nplt.figure(figsize = (20, 10))\nsb.pairplot(data, hue = \"Quantity\")",
"_____no_output_____"
]
],
[
[
"We can clearly see that in our dataset, there are total of 14 different quantities in which our business deals.",
"_____no_output_____"
]
],
[
[
"# Second, using seaborn heatmap for data visualization\nplt.figure(figsize = (7, 5))\nsb.heatmap(data.corr(), annot = True, fmt = \".2g\", linewidth = 0.5, linecolor = \"Black\", cmap = \"YlOrRd\")",
"_____no_output_____"
]
],
[
[
"Here, We can see that Sales and Profit are highly corelated as obvious.",
"_____no_output_____"
]
],
[
[
"# Third, using seaborn countplot for data visualization\nsb.countplot(x = data[\"Country\"])\nplt.show()",
"_____no_output_____"
]
],
[
[
"Our dataset only contains data from United States only.",
"_____no_output_____"
]
],
[
[
"sb.countplot(x = data[\"Segment\"])\nplt.show()",
"_____no_output_____"
]
],
[
[
"Maximum Segment is of Consumer & Minimum segment is of Home Office",
"_____no_output_____"
]
],
[
[
"sb.countplot(x = data[\"Region\"])\nplt.show()",
"_____no_output_____"
]
],
[
[
"Maximum entries are from West region of United States, followed by East, Central & South respectively.",
"_____no_output_____"
]
],
[
[
"sb.countplot(x = data[\"Ship Mode\"])\nplt.show()",
"_____no_output_____"
]
],
[
[
"This shows that the mostly our business uses Standard class for shipping as compared to other classes.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize = (8, 8))\nsb.countplot(x = data[\"Quantity\"])\nplt.show()",
"_____no_output_____"
]
],
[
[
"Out of total 14 quantites present, Maximum are number 2 and 3 respectively.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize = (10, 8))\nsb.countplot(x = data[\"State\"])\nplt.xticks(rotation = 90)\nplt.show()",
"_____no_output_____"
]
],
[
[
"If we watch carefully, we can clearly see that maximum sales happened in California, followed by New York & the Texas.\nLowest sales happened North Dakota, West Virginea.",
"_____no_output_____"
]
],
[
[
"sb.countplot(x = data[\"Category\"])\nplt.show()",
"_____no_output_____"
]
],
[
[
"So, Our business deals maximum in Office Supplies category, followed by Furniture & then Tech products.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize = (10, 8))\nsb.countplot(x = data['Sub-Category'])\nplt.xticks(rotation = 90)\nplt.show()",
"_____no_output_____"
]
],
[
[
"If we define Sub Categories section, maximum profit is earned through Binders, followed by Paper & Furnishing. Minimum Profit is earned through Copiers, Machines etc.",
"_____no_output_____"
]
],
[
[
"# Forth, using Seaborn barplot for data visualization\nplt.figure(figsize = (12, 10))\nsb.barplot(x = data[\"Sub-Category\"], y = data[\"Profit\"], capsize = .1, saturation = .5)\nplt.xticks(rotation = 90)\nplt.show()",
"_____no_output_____"
]
],
[
[
"In this Sub-categories, Bookcases, Tables and Supplies are facing losses on the business level as compared to ther categories. So, Business owner needs to pay attention towards these 3 categories. ",
"_____no_output_____"
],
[
"### Now, to compare specific features of Business, We have to use certain different Exploration operations",
"_____no_output_____"
]
],
[
[
"# Fifth, using regression plot for data visualization\nplt.figure(figsize = (10, 8))\nsb.regplot(data[\"Sales\"], data[\"Profit\"], marker = \"X\", color = \"r\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"This Relationship does not seem to be Linear. So, this relationship doesn't help much.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize = (10, 8))\nsb.regplot(data[\"Quantity\"], data[\"Profit\"], color = \"black\", y_jitter=.1)\nplt.show()",
"_____no_output_____"
]
],
[
[
"This Relationship happens to be linear. The quantity '5' has the maximum profit as compared to others.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize = (10, 8))\nsb.regplot(data[\"Quantity\"], data[\"Sales\"], color = \"m\", marker = \"+\", y_jitter=.1)\nplt.show()",
"_____no_output_____"
]
],
[
[
"This Relationship is also linear. The quantity '6' has the maximum sales as compared to others.",
"_____no_output_____"
]
],
[
[
"# Sixth, using seaborn lineplot for data visualisation\nplt.figure(figsize = (10, 8))\nsb.lineplot(data[\"Discount\"], data[\"Profit\"], color = \"orange\", label = \"Discount\")\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"As expected, we can see at 50% discount, the profit is very much negligible or we can say that there are losses. But, on the other hand, at 10% discount, there is a profit at a very good level.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize = (10, 8))\nsb.lineplot(data[\"Sub-Category\"], data[\"Profit\"], color = \"blue\", label = \"Sales\")\nplt.xticks(rotation = 90)\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"With Copiers, Business makes the largest Profit.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize = (10, 8))\nsb.lineplot(data[\"Quantity\"], data[\"Profit\"], color = \"red\", label = \"Quantity\")\nplt.legend()\nplt.show()",
"_____no_output_____"
]
],
[
[
"Quantity '13' has the maximum profit.",
"_____no_output_____"
],
[
"### WHAT CAN BE DERIVED FROM ABOVE VISUALIZATIONS :\n* Improvements should be made for same day shipment mode.\n* We have to work more in the Southern region of USA for better business.\n* Office Supplies are good. We have to work more on Technology and Furniture Category of business.\n* There are very less people working as Copiers.\n* Maximum number of people are from California and New York. It should expand in other parts of USA as well.\n* Company is facing losses in sales of bookcases and tables products.\n* Company have a lots of profit in the sale of copier but the number of sales is very less so there is a need of increase innumber of sales of copier.\n* When the profits of a state are compared with the discount provided in each state, the states which has allowed more discount, went into loss.\n* Profit and discount show very weak and negative relationship. This should be kept in mind that before taking any other decision related to business.",
"_____no_output_____"
],
[
"# ASSIGNMENT COMPLETED !!",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code",
"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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
4ac6156c97283cbf9a02771d981b58c40f19330e
| 23,765 |
ipynb
|
Jupyter Notebook
|
.ipynb_checkpoints/Generator_BehaviourInvestigations-checkpoint.ipynb
|
nutmas/CarND-Behavioral-Cloning-P3
|
04e6e2de53ce85693637ccb4dd06b8b56c1a70a4
|
[
"MIT"
] | null | null | null |
.ipynb_checkpoints/Generator_BehaviourInvestigations-checkpoint.ipynb
|
nutmas/CarND-Behavioral-Cloning-P3
|
04e6e2de53ce85693637ccb4dd06b8b56c1a70a4
|
[
"MIT"
] | null | null | null |
.ipynb_checkpoints/Generator_BehaviourInvestigations-checkpoint.ipynb
|
nutmas/CarND-Behavioral-Cloning-P3
|
04e6e2de53ce85693637ccb4dd06b8b56c1a70a4
|
[
"MIT"
] | null | null | null | 60.780051 | 1,669 | 0.615527 |
[
[
[
"### LOAD DATA",
"_____no_output_____"
]
],
[
[
"import csv # for csv file import\nimport numpy as np\nimport os\nimport cv2\nimport math\n#from keras import optimizers\nfrom sklearn.utils import shuffle # to shuffle data in generator\nfrom sklearn.model_selection import train_test_split # to split data into Training + Validation",
"_____no_output_____"
],
[
"def get_file_data(file_path, header=False):\n # function to read in data from driving_log.csv\n \n samples = []\n with open(file_path + '/driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n # if header is set to true then skip first line of csv\n if header:\n # if header exists iterate to next item in list, returns -1 if exhausted\n next(reader, -1)\n for line in reader:\n # loop through reader appending each line to samples array\n samples.append(line)\n return samples\n\n",
"_____no_output_____"
],
[
"def stats_print(X_train,y_train):\n\n\n instance_count = len(y_train)\n image_count = len(X_train)\n num_zeros = ((y_train == 0.0) & (y_train == -0.0)).sum()\n num_near_zero = ((y_train < 0.0174) & (y_train > -0.0174)).sum()\n num_left = (y_train < 0.0).sum()\n num_right = (y_train > 0.0).sum()\n\n deg = math.degrees(0.0174)\n rad = math.radians(1)\n\n print(\"Total number of steering instances: {0}\".format(instance_count))\n print(\"Total number of image instances: {0}\".format(image_count))\n print(\"Number of instances with 0 as steering Angle: {0} ({1:.2f}%)\".format(num_zeros, (num_zeros/instance_count)*100))\n print(\"Number of instances < +/-1 degree as steering Angle: {0} ({1:.2f}%)\".format(num_near_zero, (num_near_zero/instance_count)*100))\n print(\"Number of instances with left steering Angle: {0} ({1:.2f}%)\".format(num_left, (num_left/instance_count)*100))\n print(\"Number of instances with right steering Angle: {0} ({1:.2f}%)\".format(num_right, (num_right/instance_count)*100))",
"_____no_output_____"
],
[
"def generator(samples, batch_size=32):\n \"\"\"\n Generate the required images and measurments for training/\n `samples` is a list of pairs (`imagePath`, `measurement`).\n \"\"\"\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n samples = sklearn.utils.shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset+batch_size]\n\n images = []\n angles = []\n for imagePath, measurement in batch_samples:\n originalImage = cv2.imread(imagePath)\n image = cv2.cvtColor(originalImage, cv2.COLOR_BGR2RGB)\n images.append(image)\n angles.append(measurement)\n # Flipping\n images.append(cv2.flip(image,1))\n angles.append(measurement*-1.0)\n\n # trim image to only see section with road\n inputs = np.array(images)\n outputs = np.array(angles)\n yield sklearn.utils.shuffle(inputs, outputs)",
"_____no_output_____"
]
],
[
[
"### NVIDIA NET FUNCTION",
"_____no_output_____"
]
],
[
[
"from keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Lambda, Cropping2D, Dropout\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.pooling import MaxPooling2D\n\n\ndef createPreProcessingLayers():\n \"\"\"\n Creates a model with the initial pre-processing layers.\n \"\"\"\n model = Sequential()\n model.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(160,320,3)))\n model.add(Cropping2D(cropping=((50,20), (0,0))))\n return model\n\ndef net_NVIDIA():\n # NVIDIA Convolutional Network function\n \n # create a sequential model\n #model = Sequential()\n\n\n # add pre-processing steps - normalising the data and mean centre the data\n # add a lambda layer for normalisation\n # normalise image by divide each element by 255 (max value of an image pixel)\n #model.add(Lambda(lambda x: x / 255.0 - 0.5, input_shape=(160, 320, 3)))\n # after image is normalised in a range 0 to 1 - mean centre it by subtracting 0.5 from each element - shifts mean from 0.5 to 0\n # training loss and validation loss should be much smaller\n\n # crop the image to remove pixels that are not adding value - top 70, and bottom 25 rows\n #model.add(Cropping2D(cropping=((70, 25), (0, 0))))\n model = createPreProcessingLayers()\n # keras auto infer shape of all layers after 1st layer\n # 1st layer\n #model.add(Conv2D(24, (5, 5), subsample=(2, 2), activation=\"relu\"))\n model.add(Conv2D(24, (5, 5), activation=\"elu\", strides=(2, 2)))\n # 2nd layer\n #model.add(Conv2D(36, (5, 5), subsample=(2, 2), activation=\"relu\"))\n model.add(Conv2D(36, (5, 5), activation=\"elu\", strides=(2, 2)))\n # 3rd layer\n #model.add(Conv2D(48, (5, 5), subsample=(2, 2), activation=\"relu\"))\n model.add(Conv2D(48, (5, 5), activation=\"elu\", strides=(2, 2)))\n # 4th layer\n model.add(Conv2D(64, (3, 3), activation=\"elu\"))\n # 5th layer\n model.add(Conv2D(64, (3, 3), activation=\"elu\"))\n # 6th layer\n model.add(Flatten())\n # 7th layer - add fully connected layer ouput of 100\n model.add(Dense(100))\n # 8th layer - add fully connected layer ouput of 50\n model.add(Dense(50))\n # 9th layer - add fully connected layer ouput of 10\n model.add(Dense(10))\n # 0th layer - add fully connected layer ouput of 1\n model.add(Dense(1))\n \n # summarise neural net and display on screen\n model.summary()\n \n return model\n\n\n",
"_____no_output_____"
],
[
"def train_model(model, train_samples, validation_samples, model_path, set_epochs= 3):\n\n #model.compile(loss='mse', optimizer='adam')\n \n #adam = optimizers.Adam(lr=0.001)\n model.compile(loss='mse', optimizer='Adam', metrics=['mse', 'mae', 'mape', 'cosine', 'acc'])\n \n \n #model.compile(loss='mse', optimizer='adam'(lr=0.001), metrics=['mse', 'mae', 'mape', 'cosine', 'acc'])\n #history_object = model.fit(inputs, outputs, validation_split=0.2, shuffle=True, epochs=set_epochs, verbose=1)\n \n train_generator = generator(train_samples)\n #print (train_generator[0])\n validation_generator = generator(validation_samples)\n \n \n \n history_object=model.fit_generator(train_generator, steps_per_epoch= len(train_samples), validation_data=validation_generator, validation_steps=len(validation_samples), epochs=set_epochs, verbose = 1)\n \n model_path\n \n model_object = 'Final_' + model_path + str(set_epochs) + '.h5'\n model.save(model_object)\n print(\"Model saved at \" + model_object)\n \n return history_object",
"_____no_output_____"
],
[
"## main program\n\nimport sklearn\n\n\n#samples = get_file_data('./my_driving')\ndata_samples = get_file_data('./data')\n#print(data_samples[0])\n\n# Split dataset: 80% training; 20% validation\ntrain_samples, validation_samples = train_test_split(data_samples, test_size=0.2)\n\n\n#X_train_gen, y_train_gen = generator(data_samples)\n\nprint(train_samples[0])\n\n\n# Create Model\nmodel = net_NVIDIA() #input_shape=(160, 320, 3)\nnum_epoch = 1\n\nmodel.compile(loss='mse', optimizer='adam', metrics=['mse', 'mae', 'mape', 'cosine', 'acc'])\n\ntrain_generator = generator(train_samples, batch_size=32)\nvalidation_generator = generator(validation_samples, batch_size=32)\n\nhistory_object = model.fit_generator(train_generator, samples_per_epoch= \\\n len(train_samples), validation_data=validation_generator, \\\n nb_val_samples=len(validation_samples), nb_epoch=1, verbose=1)\n\n# train the model and save the model\n#history_object = train_model(model, train_samples, validation_samples, './Gen_NVidia_', num_epoch)\n",
"['IMG/center_2016_12_01_13_35_31_535.jpg', ' IMG/left_2016_12_01_13_35_31_535.jpg', ' IMG/right_2016_12_01_13_35_31_535.jpg', ' 0.2626991', ' 0.9855326', ' 0', ' 30.18174']\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nlambda_10 (Lambda) (None, 160, 320, 3) 0 \n_________________________________________________________________\ncropping2d_10 (Cropping2D) (None, 90, 320, 3) 0 \n_________________________________________________________________\nconv2d_46 (Conv2D) (None, 43, 158, 24) 1824 \n_________________________________________________________________\nconv2d_47 (Conv2D) (None, 20, 77, 36) 21636 \n_________________________________________________________________\nconv2d_48 (Conv2D) (None, 8, 37, 48) 43248 \n_________________________________________________________________\nconv2d_49 (Conv2D) (None, 6, 35, 64) 27712 \n_________________________________________________________________\nconv2d_50 (Conv2D) (None, 4, 33, 64) 36928 \n_________________________________________________________________\nflatten_10 (Flatten) (None, 8448) 0 \n_________________________________________________________________\ndense_37 (Dense) (None, 100) 844900 \n_________________________________________________________________\ndense_38 (Dense) (None, 50) 5050 \n_________________________________________________________________\ndense_39 (Dense) (None, 10) 510 \n_________________________________________________________________\ndense_40 (Dense) (None, 1) 11 \n=================================================================\nTotal params: 981,819\nTrainable params: 981,819\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"\n\n### print the keys contained in the history object\nprint(history_object.history.keys())\n\n### plot the training and validation loss for each epoch\nplt.plot(history_object.history['loss'])\nplt.plot(history_object.history['val_loss'])\n\nplt.title('model mean squared error loss')\nplt.ylabel('mean squared error loss')\nplt.xlabel('epoch')\nplt.legend(['training set', 'validation set'], loc='upper right')\n\n#plt.savefig(\"Loss_NVidia_6.png\")\nplt.savefig(\"Final_Loss_NVidia_{0}.png\".format(num_epochs))\nplt.show()\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4ac6196cd9a1ef52c349bd1a7c361efd69f440c7
| 250,313 |
ipynb
|
Jupyter Notebook
|
experiments/tl_1v2/wisig-oracle.run1/trials/26/trial.ipynb
|
stevester94/csc500-notebooks
|
4c1b04c537fe233a75bed82913d9d84985a89177
|
[
"MIT"
] | null | null | null |
experiments/tl_1v2/wisig-oracle.run1/trials/26/trial.ipynb
|
stevester94/csc500-notebooks
|
4c1b04c537fe233a75bed82913d9d84985a89177
|
[
"MIT"
] | null | null | null |
experiments/tl_1v2/wisig-oracle.run1/trials/26/trial.ipynb
|
stevester94/csc500-notebooks
|
4c1b04c537fe233a75bed82913d9d84985a89177
|
[
"MIT"
] | null | null | null | 107.384384 | 73,904 | 0.707702 |
[
[
[
"# Transfer Learning Template",
"_____no_output_____"
]
],
[
[
"%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n\n \nimport os, json, sys, time, random\nimport numpy as np\nimport torch\nfrom torch.optim import Adam\nfrom easydict import EasyDict\nimport matplotlib.pyplot as plt\n\nfrom steves_models.steves_ptn import Steves_Prototypical_Network\n\nfrom steves_utils.lazy_iterable_wrapper import Lazy_Iterable_Wrapper\nfrom steves_utils.iterable_aggregator import Iterable_Aggregator\nfrom steves_utils.ptn_train_eval_test_jig import PTN_Train_Eval_Test_Jig\nfrom steves_utils.torch_sequential_builder import build_sequential\nfrom steves_utils.torch_utils import get_dataset_metrics, ptn_confusion_by_domain_over_dataloader\nfrom steves_utils.utils_v2 import (per_domain_accuracy_from_confusion, get_datasets_base_path)\nfrom steves_utils.PTN.utils import independent_accuracy_assesment\n\nfrom torch.utils.data import DataLoader\n\nfrom steves_utils.stratified_dataset.episodic_accessor import Episodic_Accessor_Factory\n\nfrom steves_utils.ptn_do_report import (\n get_loss_curve,\n get_results_table,\n get_parameters_table,\n get_domain_accuracies,\n)\n\nfrom steves_utils.transforms import get_chained_transform",
"_____no_output_____"
]
],
[
[
"# Allowed Parameters\nThese are allowed parameters, not defaults\nEach of these values need to be present in the injected parameters (the notebook will raise an exception if they are not present)\n\nPapermill uses the cell tag \"parameters\" to inject the real parameters below this cell.\nEnable tags to see what I mean",
"_____no_output_____"
]
],
[
[
"required_parameters = {\n \"experiment_name\",\n \"lr\",\n \"device\",\n \"seed\",\n \"dataset_seed\",\n \"n_shot\",\n \"n_query\",\n \"n_way\",\n \"train_k_factor\",\n \"val_k_factor\",\n \"test_k_factor\",\n \"n_epoch\",\n \"patience\",\n \"criteria_for_best\",\n \"x_net\",\n \"datasets\",\n \"torch_default_dtype\",\n \"NUM_LOGS_PER_EPOCH\",\n \"BEST_MODEL_PATH\",\n \"x_shape\",\n}",
"_____no_output_____"
],
[
"from steves_utils.CORES.utils import (\n ALL_NODES,\n ALL_NODES_MINIMUM_1000_EXAMPLES,\n ALL_DAYS\n)\n\nfrom steves_utils.ORACLE.utils_v2 import (\n ALL_DISTANCES_FEET_NARROWED,\n ALL_RUNS,\n ALL_SERIAL_NUMBERS,\n)\n\nstandalone_parameters = {}\nstandalone_parameters[\"experiment_name\"] = \"STANDALONE PTN\"\nstandalone_parameters[\"lr\"] = 0.001\nstandalone_parameters[\"device\"] = \"cuda\"\n\nstandalone_parameters[\"seed\"] = 1337\nstandalone_parameters[\"dataset_seed\"] = 1337\n\nstandalone_parameters[\"n_way\"] = 8\nstandalone_parameters[\"n_shot\"] = 3\nstandalone_parameters[\"n_query\"] = 2\nstandalone_parameters[\"train_k_factor\"] = 1\nstandalone_parameters[\"val_k_factor\"] = 2\nstandalone_parameters[\"test_k_factor\"] = 2\n\n\nstandalone_parameters[\"n_epoch\"] = 50\n\nstandalone_parameters[\"patience\"] = 10\nstandalone_parameters[\"criteria_for_best\"] = \"source_loss\"\n\nstandalone_parameters[\"datasets\"] = [\n {\n \"labels\": ALL_SERIAL_NUMBERS,\n \"domains\": ALL_DISTANCES_FEET_NARROWED,\n \"num_examples_per_domain_per_label\": 100,\n \"pickle_path\": os.path.join(get_datasets_base_path(), \"oracle.Run1_framed_2000Examples_stratified_ds.2022A.pkl\"),\n \"source_or_target_dataset\": \"source\",\n \"x_transforms\": [\"unit_mag\", \"minus_two\"],\n \"episode_transforms\": [],\n \"domain_prefix\": \"ORACLE_\"\n },\n {\n \"labels\": ALL_NODES,\n \"domains\": ALL_DAYS,\n \"num_examples_per_domain_per_label\": 100,\n \"pickle_path\": os.path.join(get_datasets_base_path(), \"cores.stratified_ds.2022A.pkl\"),\n \"source_or_target_dataset\": \"target\",\n \"x_transforms\": [\"unit_power\", \"times_zero\"],\n \"episode_transforms\": [],\n \"domain_prefix\": \"CORES_\"\n } \n]\n\nstandalone_parameters[\"torch_default_dtype\"] = \"torch.float32\" \n\n\n\nstandalone_parameters[\"x_net\"] = [\n {\"class\": \"nnReshape\", \"kargs\": {\"shape\":[-1, 1, 2, 256]}},\n {\"class\": \"Conv2d\", \"kargs\": { \"in_channels\":1, \"out_channels\":256, \"kernel_size\":(1,7), \"bias\":False, \"padding\":(0,3), },},\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\":256}},\n\n {\"class\": \"Conv2d\", \"kargs\": { \"in_channels\":256, \"out_channels\":80, \"kernel_size\":(2,7), \"bias\":True, \"padding\":(0,3), },},\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\":80}},\n {\"class\": \"Flatten\", \"kargs\": {}},\n\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 80*256, \"out_features\": 256}}, # 80 units per IQ pair\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm1d\", \"kargs\": {\"num_features\":256}},\n\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 256, \"out_features\": 256}},\n]\n\n# Parameters relevant to results\n# These parameters will basically never need to change\nstandalone_parameters[\"NUM_LOGS_PER_EPOCH\"] = 10\nstandalone_parameters[\"BEST_MODEL_PATH\"] = \"./best_model.pth\"\n\n\n\n\n",
"_____no_output_____"
],
[
"# Parameters\nparameters = {\n \"experiment_name\": \"tl_1v2:wisig-oracle.run1\",\n \"device\": \"cuda\",\n \"lr\": 0.0001,\n \"n_shot\": 3,\n \"n_query\": 2,\n \"train_k_factor\": 3,\n \"val_k_factor\": 2,\n \"test_k_factor\": 2,\n \"torch_default_dtype\": \"torch.float32\",\n \"n_epoch\": 50,\n \"patience\": 3,\n \"criteria_for_best\": \"target_accuracy\",\n \"x_net\": [\n {\"class\": \"nnReshape\", \"kargs\": {\"shape\": [-1, 1, 2, 256]}},\n {\n \"class\": \"Conv2d\",\n \"kargs\": {\n \"in_channels\": 1,\n \"out_channels\": 256,\n \"kernel_size\": [1, 7],\n \"bias\": False,\n \"padding\": [0, 3],\n },\n },\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\": 256}},\n {\n \"class\": \"Conv2d\",\n \"kargs\": {\n \"in_channels\": 256,\n \"out_channels\": 80,\n \"kernel_size\": [2, 7],\n \"bias\": True,\n \"padding\": [0, 3],\n },\n },\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\": 80}},\n {\"class\": \"Flatten\", \"kargs\": {}},\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 20480, \"out_features\": 256}},\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm1d\", \"kargs\": {\"num_features\": 256}},\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 256, \"out_features\": 256}},\n ],\n \"NUM_LOGS_PER_EPOCH\": 10,\n \"BEST_MODEL_PATH\": \"./best_model.pth\",\n \"n_way\": 16,\n \"datasets\": [\n {\n \"labels\": [\n \"1-10\",\n \"1-12\",\n \"1-14\",\n \"1-16\",\n \"1-18\",\n \"1-19\",\n \"1-8\",\n \"10-11\",\n \"10-17\",\n \"10-4\",\n \"10-7\",\n \"11-1\",\n \"11-10\",\n \"11-19\",\n \"11-20\",\n \"11-4\",\n \"11-7\",\n \"12-19\",\n \"12-20\",\n \"12-7\",\n \"13-14\",\n \"13-18\",\n \"13-19\",\n \"13-20\",\n \"13-3\",\n \"13-7\",\n \"14-10\",\n \"14-11\",\n \"14-12\",\n \"14-13\",\n \"14-14\",\n \"14-19\",\n \"14-20\",\n \"14-7\",\n \"14-8\",\n \"14-9\",\n \"15-1\",\n \"15-19\",\n \"15-6\",\n \"16-1\",\n \"16-16\",\n \"16-19\",\n \"16-20\",\n \"17-10\",\n \"17-11\",\n \"18-1\",\n \"18-10\",\n \"18-11\",\n \"18-12\",\n \"18-13\",\n \"18-14\",\n \"18-15\",\n \"18-16\",\n \"18-17\",\n \"18-19\",\n \"18-2\",\n \"18-20\",\n \"18-4\",\n \"18-5\",\n \"18-7\",\n \"18-8\",\n \"18-9\",\n \"19-1\",\n \"19-10\",\n \"19-11\",\n \"19-12\",\n \"19-13\",\n \"19-14\",\n \"19-15\",\n \"19-19\",\n \"19-2\",\n \"19-20\",\n \"19-3\",\n \"19-4\",\n \"19-6\",\n \"19-7\",\n \"19-8\",\n \"19-9\",\n \"2-1\",\n \"2-13\",\n \"2-15\",\n \"2-3\",\n \"2-4\",\n \"2-5\",\n \"2-6\",\n \"2-7\",\n \"2-8\",\n \"20-1\",\n \"20-12\",\n \"20-14\",\n \"20-15\",\n \"20-16\",\n \"20-18\",\n \"20-19\",\n \"20-20\",\n \"20-3\",\n \"20-4\",\n \"20-5\",\n \"20-7\",\n \"20-8\",\n \"3-1\",\n \"3-13\",\n \"3-18\",\n \"3-2\",\n \"3-8\",\n \"4-1\",\n \"4-10\",\n \"4-11\",\n \"5-1\",\n \"5-5\",\n \"6-1\",\n \"6-15\",\n \"6-6\",\n \"7-10\",\n \"7-11\",\n \"7-12\",\n \"7-13\",\n \"7-14\",\n \"7-7\",\n \"7-8\",\n \"7-9\",\n \"8-1\",\n \"8-13\",\n \"8-14\",\n \"8-18\",\n \"8-20\",\n \"8-3\",\n \"8-8\",\n \"9-1\",\n \"9-7\",\n ],\n \"domains\": [1, 2, 3, 4],\n \"num_examples_per_domain_per_label\": -1,\n \"pickle_path\": \"/root/csc500-main/datasets/wisig.node3-19.stratified_ds.2022A.pkl\",\n \"source_or_target_dataset\": \"source\",\n \"x_transforms\": [],\n \"episode_transforms\": [],\n \"domain_prefix\": \"Wisig_\",\n },\n {\n \"labels\": [\n \"3123D52\",\n \"3123D65\",\n \"3123D79\",\n \"3123D80\",\n \"3123D54\",\n \"3123D70\",\n \"3123D7B\",\n \"3123D89\",\n \"3123D58\",\n \"3123D76\",\n \"3123D7D\",\n \"3123EFE\",\n \"3123D64\",\n \"3123D78\",\n \"3123D7E\",\n \"3124E4A\",\n ],\n \"domains\": [32, 38, 8, 44, 14, 50, 20, 26],\n \"num_examples_per_domain_per_label\": 10000,\n \"pickle_path\": \"/root/csc500-main/datasets/oracle.Run1_10kExamples_stratified_ds.2022A.pkl\",\n \"source_or_target_dataset\": \"target\",\n \"x_transforms\": [],\n \"episode_transforms\": [],\n \"domain_prefix\": \"ORACLE.run1\",\n },\n ],\n \"dataset_seed\": 500,\n \"seed\": 500,\n}\n",
"_____no_output_____"
],
[
"# Set this to True if you want to run this template directly\nSTANDALONE = False\nif STANDALONE:\n print(\"parameters not injected, running with standalone_parameters\")\n parameters = standalone_parameters\n\nif not 'parameters' in locals() and not 'parameters' in globals():\n raise Exception(\"Parameter injection failed\")\n\n#Use an easy dict for all the parameters\np = EasyDict(parameters)\n\nif \"x_shape\" not in p:\n p.x_shape = [2,256] # Default to this if we dont supply x_shape\n\n\nsupplied_keys = set(p.keys())\n\nif supplied_keys != required_parameters:\n print(\"Parameters are incorrect\")\n if len(supplied_keys - required_parameters)>0: print(\"Shouldn't have:\", str(supplied_keys - required_parameters))\n if len(required_parameters - supplied_keys)>0: print(\"Need to have:\", str(required_parameters - supplied_keys))\n raise RuntimeError(\"Parameters are incorrect\")",
"_____no_output_____"
],
[
"###################################\n# Set the RNGs and make it all deterministic\n###################################\nnp.random.seed(p.seed)\nrandom.seed(p.seed)\ntorch.manual_seed(p.seed)\n\ntorch.use_deterministic_algorithms(True) ",
"_____no_output_____"
],
[
"###########################################\n# The stratified datasets honor this\n###########################################\ntorch.set_default_dtype(eval(p.torch_default_dtype))",
"_____no_output_____"
],
[
"###################################\n# Build the network(s)\n# Note: It's critical to do this AFTER setting the RNG\n###################################\nx_net = build_sequential(p.x_net)",
"_____no_output_____"
],
[
"start_time_secs = time.time()",
"_____no_output_____"
],
[
"p.domains_source = []\np.domains_target = []\n\n\ntrain_original_source = []\nval_original_source = []\ntest_original_source = []\n\ntrain_original_target = []\nval_original_target = []\ntest_original_target = []",
"_____no_output_____"
],
[
"# global_x_transform_func = lambda x: normalize(x.to(torch.get_default_dtype()), \"unit_power\") # unit_power, unit_mag\n# global_x_transform_func = lambda x: normalize(x, \"unit_power\") # unit_power, unit_mag",
"_____no_output_____"
],
[
"def add_dataset(\n labels,\n domains,\n pickle_path,\n x_transforms,\n episode_transforms,\n domain_prefix,\n num_examples_per_domain_per_label,\n source_or_target_dataset:str,\n iterator_seed=p.seed,\n dataset_seed=p.dataset_seed,\n n_shot=p.n_shot,\n n_way=p.n_way,\n n_query=p.n_query,\n train_val_test_k_factors=(p.train_k_factor,p.val_k_factor,p.test_k_factor),\n):\n \n if x_transforms == []: x_transform = None\n else: x_transform = get_chained_transform(x_transforms)\n \n if episode_transforms == []: episode_transform = None\n else: raise Exception(\"episode_transforms not implemented\")\n \n episode_transform = lambda tup, _prefix=domain_prefix: (_prefix + str(tup[0]), tup[1])\n\n\n eaf = Episodic_Accessor_Factory(\n labels=labels,\n domains=domains,\n num_examples_per_domain_per_label=num_examples_per_domain_per_label,\n iterator_seed=iterator_seed,\n dataset_seed=dataset_seed,\n n_shot=n_shot,\n n_way=n_way,\n n_query=n_query,\n train_val_test_k_factors=train_val_test_k_factors,\n pickle_path=pickle_path,\n x_transform_func=x_transform,\n )\n\n train, val, test = eaf.get_train(), eaf.get_val(), eaf.get_test()\n train = Lazy_Iterable_Wrapper(train, episode_transform)\n val = Lazy_Iterable_Wrapper(val, episode_transform)\n test = Lazy_Iterable_Wrapper(test, episode_transform)\n\n if source_or_target_dataset==\"source\":\n train_original_source.append(train)\n val_original_source.append(val)\n test_original_source.append(test)\n\n p.domains_source.extend(\n [domain_prefix + str(u) for u in domains]\n )\n elif source_or_target_dataset==\"target\":\n train_original_target.append(train)\n val_original_target.append(val)\n test_original_target.append(test)\n p.domains_target.extend(\n [domain_prefix + str(u) for u in domains]\n )\n else:\n raise Exception(f\"invalid source_or_target_dataset: {source_or_target_dataset}\")\n ",
"_____no_output_____"
],
[
"for ds in p.datasets:\n add_dataset(**ds)",
"_____no_output_____"
],
[
"# from steves_utils.CORES.utils import (\n# ALL_NODES,\n# ALL_NODES_MINIMUM_1000_EXAMPLES,\n# ALL_DAYS\n# )\n\n# add_dataset(\n# labels=ALL_NODES,\n# domains = ALL_DAYS,\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"cores.stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"target\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"cores_{u}\"\n# )",
"_____no_output_____"
],
[
"# from steves_utils.ORACLE.utils_v2 import (\n# ALL_DISTANCES_FEET,\n# ALL_RUNS,\n# ALL_SERIAL_NUMBERS,\n# )\n\n\n# add_dataset(\n# labels=ALL_SERIAL_NUMBERS,\n# domains = list(set(ALL_DISTANCES_FEET) - {2,62}),\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"oracle.Run2_framed_2000Examples_stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"source\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"oracle1_{u}\"\n# )\n",
"_____no_output_____"
],
[
"# from steves_utils.ORACLE.utils_v2 import (\n# ALL_DISTANCES_FEET,\n# ALL_RUNS,\n# ALL_SERIAL_NUMBERS,\n# )\n\n\n# add_dataset(\n# labels=ALL_SERIAL_NUMBERS,\n# domains = list(set(ALL_DISTANCES_FEET) - {2,62,56}),\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"oracle.Run2_framed_2000Examples_stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"source\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"oracle2_{u}\"\n# )",
"_____no_output_____"
],
[
"# add_dataset(\n# labels=list(range(19)),\n# domains = [0,1,2],\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"metehan.stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"target\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"met_{u}\"\n# )",
"_____no_output_____"
],
[
"# # from steves_utils.wisig.utils import (\n# # ALL_NODES_MINIMUM_100_EXAMPLES,\n# # ALL_NODES_MINIMUM_500_EXAMPLES,\n# # ALL_NODES_MINIMUM_1000_EXAMPLES,\n# # ALL_DAYS\n# # )\n\n# import steves_utils.wisig.utils as wisig\n\n\n# add_dataset(\n# labels=wisig.ALL_NODES_MINIMUM_100_EXAMPLES,\n# domains = wisig.ALL_DAYS,\n# num_examples_per_domain_per_label=100,\n# pickle_path=os.path.join(get_datasets_base_path(), \"wisig.node3-19.stratified_ds.2022A.pkl\"),\n# source_or_target_dataset=\"target\",\n# x_transform_func=global_x_transform_func,\n# domain_modifier=lambda u: f\"wisig_{u}\"\n# )",
"_____no_output_____"
],
[
"###################################\n# Build the dataset\n###################################\ntrain_original_source = Iterable_Aggregator(train_original_source, p.seed)\nval_original_source = Iterable_Aggregator(val_original_source, p.seed)\ntest_original_source = Iterable_Aggregator(test_original_source, p.seed)\n\n\ntrain_original_target = Iterable_Aggregator(train_original_target, p.seed)\nval_original_target = Iterable_Aggregator(val_original_target, p.seed)\ntest_original_target = Iterable_Aggregator(test_original_target, p.seed)\n\n# For CNN We only use X and Y. And we only train on the source.\n# Properly form the data using a transform lambda and Lazy_Iterable_Wrapper. Finally wrap them in a dataloader\n\ntransform_lambda = lambda ex: ex[1] # Original is (<domain>, <episode>) so we strip down to episode only\n\ntrain_processed_source = Lazy_Iterable_Wrapper(train_original_source, transform_lambda)\nval_processed_source = Lazy_Iterable_Wrapper(val_original_source, transform_lambda)\ntest_processed_source = Lazy_Iterable_Wrapper(test_original_source, transform_lambda)\n\ntrain_processed_target = Lazy_Iterable_Wrapper(train_original_target, transform_lambda)\nval_processed_target = Lazy_Iterable_Wrapper(val_original_target, transform_lambda)\ntest_processed_target = Lazy_Iterable_Wrapper(test_original_target, transform_lambda)\n\ndatasets = EasyDict({\n \"source\": {\n \"original\": {\"train\":train_original_source, \"val\":val_original_source, \"test\":test_original_source},\n \"processed\": {\"train\":train_processed_source, \"val\":val_processed_source, \"test\":test_processed_source}\n },\n \"target\": {\n \"original\": {\"train\":train_original_target, \"val\":val_original_target, \"test\":test_original_target},\n \"processed\": {\"train\":train_processed_target, \"val\":val_processed_target, \"test\":test_processed_target}\n },\n})",
"_____no_output_____"
],
[
"from steves_utils.transforms import get_average_magnitude, get_average_power\n\nprint(set([u for u,_ in val_original_source]))\nprint(set([u for u,_ in val_original_target]))\n\ns_x, s_y, q_x, q_y, _ = next(iter(train_processed_source))\nprint(s_x)\n\n# for ds in [\n# train_processed_source,\n# val_processed_source,\n# test_processed_source,\n# train_processed_target,\n# val_processed_target,\n# test_processed_target\n# ]:\n# for s_x, s_y, q_x, q_y, _ in ds:\n# for X in (s_x, q_x):\n# for x in X:\n# assert np.isclose(get_average_magnitude(x.numpy()), 1.0)\n# assert np.isclose(get_average_power(x.numpy()), 1.0)\n ",
"{'Wisig_1', 'Wisig_2', 'Wisig_3', 'Wisig_4'}\n"
],
[
"###################################\n# Build the model\n###################################\n# easfsl only wants a tuple for the shape\nmodel = Steves_Prototypical_Network(x_net, device=p.device, x_shape=tuple(p.x_shape))\noptimizer = Adam(params=model.parameters(), lr=p.lr)",
"(2, 256)\n"
],
[
"###################################\n# train\n###################################\njig = PTN_Train_Eval_Test_Jig(model, p.BEST_MODEL_PATH, p.device)\n\njig.train(\n train_iterable=datasets.source.processed.train,\n source_val_iterable=datasets.source.processed.val,\n target_val_iterable=datasets.target.processed.val,\n num_epochs=p.n_epoch,\n num_logs_per_epoch=p.NUM_LOGS_PER_EPOCH,\n patience=p.patience,\n optimizer=optimizer,\n criteria_for_best=p.criteria_for_best,\n)",
"epoch: 1, [batch: 1 / 6843], examples_per_second: 31.5017, train_label_loss: 2.1935, \n"
],
[
"total_experiment_time_secs = time.time() - start_time_secs",
"_____no_output_____"
],
[
"###################################\n# Evaluate the model\n###################################\nsource_test_label_accuracy, source_test_label_loss = jig.test(datasets.source.processed.test)\ntarget_test_label_accuracy, target_test_label_loss = jig.test(datasets.target.processed.test)\n\nsource_val_label_accuracy, source_val_label_loss = jig.test(datasets.source.processed.val)\ntarget_val_label_accuracy, target_val_label_loss = jig.test(datasets.target.processed.val)\n\nhistory = jig.get_history()\n\ntotal_epochs_trained = len(history[\"epoch_indices\"])\n\nval_dl = Iterable_Aggregator((datasets.source.original.val,datasets.target.original.val))\n\nconfusion = ptn_confusion_by_domain_over_dataloader(model, p.device, val_dl)\nper_domain_accuracy = per_domain_accuracy_from_confusion(confusion)\n\n# Add a key to per_domain_accuracy for if it was a source domain\nfor domain, accuracy in per_domain_accuracy.items():\n per_domain_accuracy[domain] = {\n \"accuracy\": accuracy,\n \"source?\": domain in p.domains_source\n }\n\n# Do an independent accuracy assesment JUST TO BE SURE!\n# _source_test_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.test, p.device)\n# _target_test_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.test, p.device)\n# _source_val_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.val, p.device)\n# _target_val_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.val, p.device)\n\n# assert(_source_test_label_accuracy == source_test_label_accuracy)\n# assert(_target_test_label_accuracy == target_test_label_accuracy)\n# assert(_source_val_label_accuracy == source_val_label_accuracy)\n# assert(_target_val_label_accuracy == target_val_label_accuracy)\n\nexperiment = {\n \"experiment_name\": p.experiment_name,\n \"parameters\": dict(p),\n \"results\": {\n \"source_test_label_accuracy\": source_test_label_accuracy,\n \"source_test_label_loss\": source_test_label_loss,\n \"target_test_label_accuracy\": target_test_label_accuracy,\n \"target_test_label_loss\": target_test_label_loss,\n \"source_val_label_accuracy\": source_val_label_accuracy,\n \"source_val_label_loss\": source_val_label_loss,\n \"target_val_label_accuracy\": target_val_label_accuracy,\n \"target_val_label_loss\": target_val_label_loss,\n \"total_epochs_trained\": total_epochs_trained,\n \"total_experiment_time_secs\": total_experiment_time_secs,\n \"confusion\": confusion,\n \"per_domain_accuracy\": per_domain_accuracy,\n },\n \"history\": history,\n \"dataset_metrics\": get_dataset_metrics(datasets, \"ptn\"),\n}",
"_____no_output_____"
],
[
"ax = get_loss_curve(experiment)\nplt.show()",
"_____no_output_____"
],
[
"get_results_table(experiment)",
"_____no_output_____"
],
[
"get_domain_accuracies(experiment)",
"_____no_output_____"
],
[
"print(\"Source Test Label Accuracy:\", experiment[\"results\"][\"source_test_label_accuracy\"], \"Target Test Label Accuracy:\", experiment[\"results\"][\"target_test_label_accuracy\"])\nprint(\"Source Val Label Accuracy:\", experiment[\"results\"][\"source_val_label_accuracy\"], \"Target Val Label Accuracy:\", experiment[\"results\"][\"target_val_label_accuracy\"])",
"Source Test Label Accuracy: 0.9611556359875905 Target Test Label Accuracy: 0.26580729166666667\nSource Val Label Accuracy: 0.9622890295358649 Target Val Label Accuracy: 0.26572265625\n"
],
[
"json.dumps(experiment)",
"_____no_output_____"
]
]
] |
[
"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"
]
] |
4ac61a39f3f223ee44fac8f4314afe2b34ac83c8
| 10,079 |
ipynb
|
Jupyter Notebook
|
lectures/.ipynb_checkpoints/Week4-checkpoint.ipynb
|
christianpoulsen/socialdata2021
|
eee14811f59b68dabf56115b2e46d885b270a4d0
|
[
"MIT"
] | null | null | null |
lectures/.ipynb_checkpoints/Week4-checkpoint.ipynb
|
christianpoulsen/socialdata2021
|
eee14811f59b68dabf56115b2e46d885b270a4d0
|
[
"MIT"
] | null | null | null |
lectures/.ipynb_checkpoints/Week4-checkpoint.ipynb
|
christianpoulsen/socialdata2021
|
eee14811f59b68dabf56115b2e46d885b270a4d0
|
[
"MIT"
] | null | null | null | 70.978873 | 491 | 0.70126 |
[
[
[
"# Week 4\n\n## Overview\n\nYay! It's week 4. Today's we'll keep things light. \n\nI've noticed that many of you are struggling a bit to keep up and still working on exercises from the previous week. Thus, this week we only have two components with no lectures and very little reading. \n\n## Informal intro\n\n[](https://www.youtube.com/watch?v=YX0kCReIZzk)\n\n\n## Overview\n\n* An exercise on visualizing geodata using a different set of tools from the ones we played with during Lecture 2.\n* Thinking about visualization, data quality, and binning. Why ***looking at the details of the data before applying fancy methods*** is often important.",
"_____no_output_____"
],
[
"## Part 1: Visualizing geo-data\n\nIt turns out that `plotly` (which we used during Week 2) is not the only way of working with geo-data. There are many different ways to go about it. (The hard-core PhD and PostDoc researchers in my group simply use matplotlib, since that provides more control. For an example of that kind of thing, check out [this one](https://towardsdatascience.com/visualizing-geospatial-data-in-python-e070374fe621).)\n\nToday, we'll try another library for geodata called \"[Folium](https://github.com/python-visualization/folium)\". It's good for you all to try out a few different libraries - remember that data visualization and analysis Python is all about the ability to use many different tools. \n\nThe exercise below is based code illustrated in this nice [tutorial](https://www.kaggle.com/daveianhickey/how-to-folium-for-maps-heatmaps-time-data)), so let us start by taking a look at that one.",
"_____no_output_____"
],
[
"*Reading*. Read through the following tutorial\n * \"How to: Folium for maps, heatmaps & time data\". Get it here: https://www.kaggle.com/daveianhickey/how-to-folium-for-maps-heatmaps-time-data\n * (Optional) There are also some nice tricks in \"Spatial Visualizations and Analysis in Python with Folium\". Read it here: https://towardsdatascience.com/data-101s-spatial-visualizations-and-analysis-in-python-with-folium-39730da2adf",
"_____no_output_____"
],
[
"> *Exercise*: A new take on geospatial data. \n>\n>A couple of weeks ago (Part 4 of Week 2), we worked with spacial data by using color-intensity of shapefiles to show the counts of certain crimes within those individual areas. Today we look at studying geospatial data by plotting raw data points as well as heatmaps on top of actual maps.\n> \n> * First start by plotting a map of San Francisco with a nice tight zoom. Simply use the command `folium.Map([lat, lon], zoom_start=13)`, where you'll have to look up San Francisco's longitude and latitude.\n> * Next, use the the coordinates for SF City Hall `37.77919, -122.41914` to indicate its location on the map with a nice, pop-up enabled maker. (In the screenshot below, I used the black & white Stamen tiles, because they look cool).\n> \n> * Now, let's plot some more data (no need for popups this time). Select a couple of months of data for `'DRUG/NARCOTIC'` and draw a little dot for each arrest for those two months. You could, for example, choose June-July 2016, but you can choose anything you like - the main concern is to not have too many points as this uses a lot of memory and makes Folium behave non-optimally. \n> We can call this a kind of visualization a *point scatter plot*.\n\nOk. Time for a little break. Note that a nice thing about Folium is that you can zoom in and out of the maps.\n\n> * Now, let's play with **heatmaps**. You can figure out the appropriate commands by grabbing code from the main [tutorial](https://www.kaggle.com/daveianhickey/how-to-folium-for-maps-heatmaps-time-data)) and modifying to suit your needs.\n> * To create your first heatmap, grab all arrests for the category `'SEX OFFENSES, NON FORCIBLE'` across all time. Play with parameters to get plots you like.\n> * Now, comment on the differences between scatter plots and heatmaps. \n>. - What can you see using the scatter-plots that you can't see using the heatmaps? \n>. - And *vice versa*: what does the heatmaps help you see that's difficult to distinguish in the scatter-plots?\n> * Play around with the various parameter for heatmaps. You can find a list here: https://python-visualization.github.io/folium/plugins.html\n> * Comment on the effect on the various parameters for the heatmaps. How do they change the picture? (at least talk about the `radius` and `max_zoom`).\n> For one combination of settings, my heatmap plot looks like this.\n> \n> * In that screenshot, I've (manually) highlighted a specific hotspot for this type of crime. Use your detective skills to find out what's going on in that building on the 800 block of Bryant street ... and explain in your own words. \n\n(*Fun fact*: I remembered the concentration of crime-counts discussed at the end of this exercise from when I did the course back in 2016. It popped up when I used a completely different framework for visualizing geodata called [`geoplotlib`](https://github.com/andrea-cuttone/geoplotlib). You can spot it if you go to that year's [lecture 2](https://nbviewer.jupyter.org/github/suneman/socialdataanalysis2016/blob/master/lectures/Week3.ipynb), exercise 4.)",
"_____no_output_____"
],
[
"For the final element of working with heatmaps, let's now use the cool Folium functionality `HeatMapWithTime` to create a visualization of how the patterns of your favorite crime-type changes over time.\n\n> *Exercise*: Heat map movies. This exercise is a bit more independent than above - you get to make all the choices.\n> * Start by choosing your favorite crimetype. Prefereably one with spatial patterns that change over time (use your data-exploration from the previous lectures to choose a good one).\n> * Now, choose a time-resolution. You could plot daily, weekly, monthly datasets to plot in your movie. Again the goal is to find interesting temporal patterns to display. We want at least 20 frames though.\n> * Create the movie using `HeatMapWithTime`.\n> * Comment on your results: \n> - What patterns does your movie reveal?\n> - Motivate/explain the reasoning behind your choice of crimetype and time-resolution. ",
"_____no_output_____"
],
[
"## Part 2: Errors in the data. The importance of looking at raw (or close to raw) data.\n\nWe started the course by plotting simple histogram plots that showed a lot of cool patterns. But sometimes the binning can hide imprecision, irregularity, and simple errors in the data that could be misleading. In the work we've done so far, we've already come across at least three examples of this in the SF data. \n\n1. In the hourly activity for `PROSTITUTION` something surprising is going on on Wednesday. Remind yourself [**here**](https://raw.githubusercontent.com/suneman/socialdata2021/master/files/prostitution_hourly.png), where I've highlighted the phenomenon I'm talking about.\n1. When we investigated the details of how the timestamps are recorded using jitter-plots, we saw that many more crimes were recorded e.g. on the hour, 15 minutes past the hour, and to a lesser in whole increments of 10 minutes. Crimes didn't appear to be recorded as frequently in between those round numbers. Remind yourself [**here**](https://raw.githubusercontent.com/suneman/socialdata2021/master/files/jitter_plot.png), where I've highlighted the phenomenon I'm talking about.\n1. And finally, today we saw that the Hall of Justice seemed to be an unlikely hotspot for sex offences. Remind yourself [**here**](https://raw.githubusercontent.com/suneman/socialdata2021/master/files/crime_hot_spot.png).\n\n> *Exercise*: Data errors. The data errors we discovered above become difficult to notice when we aggregate data (and when we calculate mean values, as well as statistics more generally). Thus, when we visualize, errors become difficult to notice when when we bin the data. We explore this process in the exercise below.\n>\n>This last exercise for today has two parts.\n> * In each of the three examples above, describe in your own words how the data-errors I call attention to above can bias the binned versions of the data. Also briefly mention how not noticing these errors can result in misconceptions about the underlying patterns of what's going on in San Francisco (and our modeling).\n> * Find your own example of human noise in the data and visualize it.",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4ac61b0ceb18475105043d0d27fc03d687b31fe4
| 5,492 |
ipynb
|
Jupyter Notebook
|
introductory-tutorials/intro-to-julia/07. Packages.ipynb
|
rajsardhara/Julia_Lang_Tutoria
|
69c2fedb72751493f0f101f348c888133ff08830
|
[
"MIT"
] | 535 |
2020-07-15T14:56:11.000Z
|
2022-03-25T12:50:32.000Z
|
introductory-tutorials/intro-to-julia/07. Packages.ipynb
|
rajsardhara/Julia_Lang_Tutoria
|
69c2fedb72751493f0f101f348c888133ff08830
|
[
"MIT"
] | 42 |
2018-02-25T22:53:47.000Z
|
2020-05-14T02:15:50.000Z
|
introductory-tutorials/intro-to-julia/07. Packages.ipynb
|
rajsardhara/Julia_Lang_Tutoria
|
69c2fedb72751493f0f101f348c888133ff08830
|
[
"MIT"
] | 394 |
2020-07-14T23:22:24.000Z
|
2022-03-28T20:12:57.000Z
| 22.234818 | 259 | 0.553714 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
4ac61e97249fb9890bd49c73a55e4c57ccca1fd7
| 160,422 |
ipynb
|
Jupyter Notebook
|
IBM_AI_Engineering/Course-4-deep-neural-networks-with-pytorch/Week-5-Deep-Networks/8.2.1dropoutPredictin_v2.ipynb
|
fengjings/Coursera
|
54098a9732faa4b37afe69d196e27805b1ac73aa
|
[
"MIT"
] | null | null | null |
IBM_AI_Engineering/Course-4-deep-neural-networks-with-pytorch/Week-5-Deep-Networks/8.2.1dropoutPredictin_v2.ipynb
|
fengjings/Coursera
|
54098a9732faa4b37afe69d196e27805b1ac73aa
|
[
"MIT"
] | null | null | null |
IBM_AI_Engineering/Course-4-deep-neural-networks-with-pytorch/Week-5-Deep-Networks/8.2.1dropoutPredictin_v2.ipynb
|
fengjings/Coursera
|
54098a9732faa4b37afe69d196e27805b1ac73aa
|
[
"MIT"
] | 1 |
2021-06-09T08:59:48.000Z
|
2021-06-09T08:59:48.000Z
| 194.215496 | 52,600 | 0.902314 |
[
[
[
"<a href=\"http://cocl.us/pytorch_link_top\">\n <img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/Pytochtop.png\" width=\"750\" alt=\"IBM Product \" />\n</a> \n",
"_____no_output_____"
],
[
"<img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/cc-logo-square.png\" width=\"200\" alt=\"cognitiveclass.ai logo\" />",
"_____no_output_____"
],
[
"<h1>Using Dropout for Classification </h1>",
"_____no_output_____"
],
[
"<h2>Table of Contents</h2>\n<p>In this lab, you will see how adding dropout to your model will decrease overfitting.</p>\n\n<ul>\n<li><a href=\"#Makeup_Data\">Make Some Data</a></li>\n<li><a href=\"#Model_Cost\">Create the Model and Cost Function the PyTorch way</a></li>\n<li><a href=\"#BGD\">Batch Gradient Descent</a></li>\n</ul>\n<p>Estimated Time Needed: <strong>20 min</strong></p>\n\n<hr>",
"_____no_output_____"
],
[
"<h2>Preparation</h2>",
"_____no_output_____"
],
[
"We'll need the following libraries",
"_____no_output_____"
]
],
[
[
"# Import the libraries we need for this lab\n\nimport torch\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom matplotlib.colors import ListedColormap\nfrom torch.utils.data import Dataset, DataLoader",
"_____no_output_____"
]
],
[
[
"Use this function only for plotting:",
"_____no_output_____"
]
],
[
[
"# The function for plotting the diagram\n\ndef plot_decision_regions_3class(data_set, model=None):\n cmap_light = ListedColormap([ '#0000FF','#FF0000'])\n cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#00AAFF'])\n X = data_set.x.numpy()\n y = data_set.y.numpy()\n h = .02\n x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1 \n y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1 \n xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n newdata = np.c_[xx.ravel(), yy.ravel()]\n \n Z = data_set.multi_dim_poly(newdata).flatten()\n f = np.zeros(Z.shape)\n f[Z > 0] = 1\n f = f.reshape(xx.shape)\n if model != None:\n model.eval()\n XX = torch.Tensor(newdata)\n _, yhat = torch.max(model(XX), 1)\n yhat = yhat.numpy().reshape(xx.shape)\n plt.pcolormesh(xx, yy, yhat, cmap=cmap_light)\n plt.contour(xx, yy, f, cmap=plt.cm.Paired)\n else:\n plt.contour(xx, yy, f, cmap=plt.cm.Paired)\n plt.pcolormesh(xx, yy, f, cmap=cmap_light) \n\n plt.title(\"decision region vs True decision boundary\")",
"_____no_output_____"
]
],
[
[
"Use this function to calculate accuracy: ",
"_____no_output_____"
]
],
[
[
"# The function for calculating accuracy\n\ndef accuracy(model, data_set):\n _, yhat = torch.max(model(data_set.x), 1)\n return (yhat == data_set.y).numpy().mean()",
"_____no_output_____"
]
],
[
[
"<!--Empty Space for separating topics-->",
"_____no_output_____"
],
[
"<h2 id=\"Makeup_Data\">Make Some Data</h2>",
"_____no_output_____"
],
[
"Create a nonlinearly separable dataset: ",
"_____no_output_____"
]
],
[
[
"# Create data class for creating dataset object\n\nclass Data(Dataset):\n \n # Constructor\n def __init__(self, N_SAMPLES=1000, noise_std=0.15, train=True):\n a = np.matrix([-1, 1, 2, 1, 1, -3, 1]).T\n self.x = np.matrix(np.random.rand(N_SAMPLES, 2))\n self.f = np.array(a[0] + (self.x) * a[1:3] + np.multiply(self.x[:, 0], self.x[:, 1]) * a[4] + np.multiply(self.x, self.x) * a[5:7]).flatten()\n self.a = a\n \n self.y = np.zeros(N_SAMPLES)\n self.y[self.f > 0] = 1\n self.y = torch.from_numpy(self.y).type(torch.LongTensor)\n self.x = torch.from_numpy(self.x).type(torch.FloatTensor)\n self.x = self.x + noise_std * torch.randn(self.x.size())\n self.f = torch.from_numpy(self.f)\n self.a = a\n if train == True:\n torch.manual_seed(1)\n self.x = self.x + noise_std * torch.randn(self.x.size())\n torch.manual_seed(0)\n \n # Getter \n def __getitem__(self, index): \n return self.x[index], self.y[index]\n \n # Get Length\n def __len__(self):\n return self.len\n \n # Plot the diagram\n def plot(self):\n X = data_set.x.numpy()\n y = data_set.y.numpy()\n h = .02\n x_min, x_max = X[:, 0].min(), X[:, 0].max()\n y_min, y_max = X[:, 1].min(), X[:, 1].max() \n xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n Z = data_set.multi_dim_poly(np.c_[xx.ravel(), yy.ravel()]).flatten()\n f = np.zeros(Z.shape)\n f[Z > 0] = 1\n f = f.reshape(xx.shape)\n \n plt.title('True decision boundary and sample points with noise ')\n plt.plot(self.x[self.y == 0, 0].numpy(), self.x[self.y == 0,1].numpy(), 'bo', label='y=0') \n plt.plot(self.x[self.y == 1, 0].numpy(), self.x[self.y == 1,1].numpy(), 'ro', label='y=1')\n plt.contour(xx, yy, f,cmap=plt.cm.Paired)\n plt.xlim(0,1)\n plt.ylim(0,1)\n plt.legend()\n \n # Make a multidimension ploynomial function\n def multi_dim_poly(self, x):\n x = np.matrix(x)\n out = np.array(self.a[0] + (x) * self.a[1:3] + np.multiply(x[:, 0], x[:, 1]) * self.a[4] + np.multiply(x, x) * self.a[5:7])\n out = np.array(out)\n return out",
"_____no_output_____"
]
],
[
[
"Create a dataset object:",
"_____no_output_____"
]
],
[
[
"# Create a dataset object\n\ndata_set = Data(noise_std=0.2)\ndata_set.plot()",
"_____no_output_____"
]
],
[
[
"Validation data: ",
"_____no_output_____"
]
],
[
[
"# Get some validation data\n\ntorch.manual_seed(0) \nvalidation_set = Data(train=False)",
"_____no_output_____"
]
],
[
[
"<!--Empty Space for separating topics-->",
"_____no_output_____"
],
[
"<h2 id=\"Model_Cost\">Create the Model, Optimizer, and Total Loss Function (Cost)</h2>",
"_____no_output_____"
],
[
"Create a custom module with three layers. <code>in_size</code> is the size of the input features, <code>n_hidden</code> is the size of the layers, and <code>out_size</code> is the size. <code>p</code> is the dropout probability. The default is 0, that is, no dropout.\n",
"_____no_output_____"
]
],
[
[
"# Create Net Class\n\nclass Net(nn.Module):\n \n # Constructor\n # p denotes probability\n def __init__(self, in_size, n_hidden, out_size, p=0):\n super(Net, self).__init__()\n self.drop = nn.Dropout(p=p)\n self.linear1 = nn.Linear(in_size, n_hidden)\n self.linear2 = nn.Linear(n_hidden, n_hidden)\n self.linear3 = nn.Linear(n_hidden, out_size)\n \n # Prediction function\n def forward(self, x):\n x = F.relu(self.drop(self.linear1(x)))\n x = F.relu(self.drop(self.linear2(x)))\n x = self.linear3(x)\n return x",
"_____no_output_____"
]
],
[
[
"Create two model objects: <code>model</code> had no dropout and <code>model_drop</code> has a dropout probability of 0.5:",
"_____no_output_____"
]
],
[
[
"# Create two model objects: model without dropout and model with dropout\n\nmodel = Net(2, 300, 2)\nmodel_drop = Net(2, 300, 2, p=0.5)\n",
"_____no_output_____"
]
],
[
[
"<!--Empty Space for separating topics-->",
"_____no_output_____"
]
],
[
[
"model1 = torch.nn.Sequential(\ntorch.nn.Linear(in_features=3,out_features=3), torch.nn.Dropout(0.5),torch.nn.Sigmoid(),\ntorch.nn.Linear(in_features=3,out_features=4), torch.nn.Dropout(0.3),torch.nn.Sigmoid(), \ntorch.nn.Linear(in_features=4,out_features=3)\n)\nmodel1.parameters",
"_____no_output_____"
]
],
[
[
"<h2 id=\"BGD\">Train the Model via Mini-Batch Gradient Descent</h2>",
"_____no_output_____"
],
[
"Set the model using dropout to training mode; this is the default mode, but it's good practice to write this in your code : ",
"_____no_output_____"
]
],
[
[
"# Set the model to training mode\n\nmodel_drop.train()",
"_____no_output_____"
]
],
[
[
"Train the model by using the Adam optimizer. See the unit on other optimizers. Use the Cross Entropy Loss:",
"_____no_output_____"
]
],
[
[
"# Set optimizer functions and criterion functions\n# In this lab we will use the ADAM optimizer, this optimizer gives more consistent performance. You can try with SGD. \noptimizer_ofit = torch.optim.Adam(model.parameters(), lr=0.01)\noptimizer_drop = torch.optim.Adam(model_drop.parameters(), lr=0.01)\ncriterion = torch.nn.CrossEntropyLoss()",
"_____no_output_____"
]
],
[
[
"Initialize a dictionary that stores the training and validation loss for each model:",
"_____no_output_____"
]
],
[
[
"# Initialize the LOSS dictionary to store the loss\n\nLOSS = {}\nLOSS['training data no dropout'] = []\nLOSS['validation data no dropout'] = []\nLOSS['training data dropout'] = []\nLOSS['validation data dropout'] = []",
"_____no_output_____"
]
],
[
[
"Run 500 iterations of batch gradient gradient descent: ",
"_____no_output_____"
]
],
[
[
"# Train the model\n\nepochs = 500\n\ndef train_model(epochs):\n \n for epoch in range(epochs):\n #all the samples are used for training \n yhat = model(data_set.x)\n # batch gradient descent as we can store all data in memory\n yhat_drop = model_drop(data_set.x)\n loss = criterion(yhat, data_set.y)\n loss_drop = criterion(yhat_drop, data_set.y)\n\n #store the loss for both the training and validation data for both models \n LOSS['training data no dropout'].append(loss.item())\n LOSS['validation data no dropout'].append(criterion(model(validation_set.x), validation_set.y).item())\n LOSS['training data dropout'].append(loss_drop.item())\n model_drop.eval()# make a prediction on val data will turn off the dropout\n LOSS['validation data dropout'].append(criterion(model_drop(validation_set.x), validation_set.y).item())\n model_drop.train()# set back to train when we continue training\n\n optimizer_ofit.zero_grad()\n optimizer_drop.zero_grad()\n loss.backward()\n loss_drop.backward()\n optimizer_ofit.step()\n optimizer_drop.step()\n \ntrain_model(epochs)",
"_____no_output_____"
]
],
[
[
"Set the model with dropout to evaluation mode: ",
"_____no_output_____"
]
],
[
[
"# Set the model to evaluation model\n\nmodel_drop.eval()",
"_____no_output_____"
]
],
[
[
"Test the model without dropout on the validation data: ",
"_____no_output_____"
]
],
[
[
"# Print out the accuracy of the model without dropout\n\nprint(\"The accuracy of the model without dropout: \", accuracy(model, validation_set))",
"The accuracy of the model without dropout: 0.812\n"
]
],
[
[
"Test the model with dropout on the validation data: ",
"_____no_output_____"
]
],
[
[
"# Print out the accuracy of the model with dropout\n\nprint(\"The accuracy of the model with dropout: \", accuracy(model_drop, validation_set))",
"The accuracy of the model with dropout: 0.798\n"
]
],
[
[
"You see that the model with dropout performs better on the validation data.",
"_____no_output_____"
],
[
"<h3>True Function</h3>",
"_____no_output_____"
],
[
"Plot the decision boundary and the prediction of the networks in different colors.",
"_____no_output_____"
]
],
[
[
"# Plot the decision boundary and the prediction\n\nplot_decision_regions_3class(data_set)",
"_____no_output_____"
]
],
[
[
"Model without Dropout:",
"_____no_output_____"
]
],
[
[
"# The model without dropout\n\nplot_decision_regions_3class(data_set, model)",
"_____no_output_____"
]
],
[
[
"Model with Dropout:",
"_____no_output_____"
]
],
[
[
"# The model with dropout\n\nplot_decision_regions_3class(data_set, model_drop)",
"_____no_output_____"
]
],
[
[
"You can see that the model using dropout does better at tracking the function that generated the data. ",
"_____no_output_____"
],
[
"Plot out the loss for the training and validation data on both models, we use the log to make the difference more apparent",
"_____no_output_____"
]
],
[
[
"# Plot the LOSS\n\nplt.figure(figsize=(6.1, 10))\ndef plot_LOSS():\n for key, value in LOSS.items():\n plt.plot(np.log(np.array(value)), label=key)\n plt.legend()\n plt.xlabel(\"iterations\")\n plt.ylabel(\"Log of cost or total loss\")\n\nplot_LOSS()",
"_____no_output_____"
]
],
[
[
"You see that the model without dropout performs better on the training data, but it performs worse on the validation data. This suggests overfitting. However, the model using dropout performed better on the validation data, but worse on the training data. ",
"_____no_output_____"
],
[
"<!--Empty Space for separating topics-->",
"_____no_output_____"
],
[
"<a href=\"http://cocl.us/pytorch_link_bottom\">\n <img src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/notebook_bottom%20.png\" width=\"750\" alt=\"PyTorch Bottom\" />\n</a>",
"_____no_output_____"
],
[
"<h2>About the Authors:</h2> \n\n<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\">Joseph Santarcangelo</a> has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD. ",
"_____no_output_____"
],
[
"Other contributors: <a href=\"https://www.linkedin.com/in/michelleccarey/\">Michelle Carey</a>, <a href=\"www.linkedin.com/in/jiahui-mavis-zhou-a4537814a\">Mavis Zhou</a>",
"_____no_output_____"
],
[
"<hr>",
"_____no_output_____"
],
[
"Copyright © 2018 <a href=\"cognitiveclass.ai?utm_source=bducopyrightlink&utm_medium=dswb&utm_campaign=bdu\">cognitiveclass.ai</a>. This notebook and its source code are released under the terms of the <a href=\"https://bigdatauniversity.com/mit-license/\">MIT License</a>.",
"_____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"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4ac62934066b6225230a36179e61b4b952641e8b
| 118,952 |
ipynb
|
Jupyter Notebook
|
python/notebooks/image_representation/01_connected_components.ipynb
|
evarol/ot_tracking
|
cddf27558fa5679ef06aad6a0945c34db0209ee7
|
[
"MIT"
] | 1 |
2020-04-05T17:01:39.000Z
|
2020-04-05T17:01:39.000Z
|
python/notebooks/image_representation/01_connected_components.ipynb
|
evarol/ot_tracking
|
cddf27558fa5679ef06aad6a0945c34db0209ee7
|
[
"MIT"
] | null | null | null |
python/notebooks/image_representation/01_connected_components.ipynb
|
evarol/ot_tracking
|
cddf27558fa5679ef06aad6a0945c34db0209ee7
|
[
"MIT"
] | 1 |
2021-06-03T16:48:45.000Z
|
2021-06-03T16:48:45.000Z
| 489.514403 | 52,468 | 0.948937 |
[
[
[
"# Compute connected components of 3D image\n\nThis notebook uses the `skimage` library's `measure.label()` function to compute connected components in a 3D worm image.",
"_____no_output_____"
]
],
[
[
"%load_ext autoreload\n%autoreload\n%matplotlib inline",
"_____no_output_____"
],
[
"import numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nfrom skimage import measure\nfrom skimage import filters\n\nfrom otimage import io ",
"_____no_output_____"
]
],
[
[
"### Load single video frame from file",
"_____no_output_____"
]
],
[
[
"# Path to HDF5 file\nin_fpath = '/home/mn2822/Desktop/WormOT/data/zimmer/mCherry_v00065-01581.hdf5'\n\n# Index of frame to use\nt_frame = 500\n\nwith io.ZimmerReader(in_fpath) as reader:\n frame = reader.get_frame(t_frame)",
"_____no_output_____"
]
],
[
[
"### Select head region from frame as test image ",
"_____no_output_____"
]
],
[
[
"# Section of XY plane where head is found\nhead_x = (500, 650)\nhead_y = (250, 525)\nhead_z = (0, 33)\n\nimg = frame[head_x[0]:head_x[1], head_y[0]:head_y[1], head_z[0]:head_z[1]]\n\n# Display max projection\nplt.imshow(np.max(img, 2).T);\nplt.xticks([])\nplt.yticks([]);",
"_____no_output_____"
]
],
[
[
"### Binarize image using threshold\n\nRight now, this threshold is set by hand.\n\n**TODO: Find a way to automatically set this (maybe using Oatsu's algorithm?)**",
"_____no_output_____"
]
],
[
[
"# Threshold applied to pixel values in image\nthreshold = 0.007\n\n# Create binary th\nimg_th = (img >= threshold)\n\n# Display max projection\nplt.imshow(np.max(img_th, 2).T);",
"_____no_output_____"
]
],
[
[
"### Compute connected components in image",
"_____no_output_____"
]
],
[
[
"img_labels = measure.label(img_th)\nplt.imshow(np.max(img_labels, 2).T, cmap='nipy_spectral');",
"_____no_output_____"
]
],
[
[
"### Display results",
"_____no_output_____"
]
],
[
[
"img_mp = np.max(img, 2)\nimg_th_mp = np.max(img_th, 2)\nimg_labels_mp = np.max(img_labels, 2)\n\nplt.figure(figsize=(9, 3.5))\n\nplt.subplot(131)\nplt.imshow(img_mp.T, cmap='gray')\nplt.axis('off')\nplt.title('image')\n\nplt.subplot(132)\nplt.imshow(img_th_mp.T, cmap='gray')\nplt.axis('off')\nplt.title('thresholded image')\n\nplt.subplot(133)\nplt.imshow(img_labels_mp.T, cmap='nipy_spectral')\nplt.axis('off')\nplt.title('connected components')\n\nplt.tight_layout()\n\n#plt.savefig('components_mp.png')",
"_____no_output_____"
]
]
] |
[
"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"
]
] |
4ac629dfb9697b69dbb91b225e82b3b3700d98db
| 57,949 |
ipynb
|
Jupyter Notebook
|
examples/Periodic_Domain_Example.ipynb
|
ProfDema/CMGDB
|
0390d306871469392c0be2a2dd0785eda80d996d
|
[
"MIT"
] | 1 |
2022-01-11T21:07:58.000Z
|
2022-01-11T21:07:58.000Z
|
examples/Periodic_Domain_Example.ipynb
|
ProfDema/CMGDB
|
0390d306871469392c0be2a2dd0785eda80d996d
|
[
"MIT"
] | null | null | null |
examples/Periodic_Domain_Example.ipynb
|
ProfDema/CMGDB
|
0390d306871469392c0be2a2dd0785eda80d996d
|
[
"MIT"
] | 2 |
2021-03-25T21:13:26.000Z
|
2021-05-04T18:47:00.000Z
| 157.899183 | 15,640 | 0.8747 |
[
[
[
"import CMGDB\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport matplotlib\nimport numpy as np\nimport time\nimport csv",
"_____no_output_____"
]
],
[
[
"# A silly example of a torus map",
"_____no_output_____"
]
],
[
[
"# Define the torus map\n# f(x, y) = (2 x + 3 y, 0.5 x + 0.3 y) mod 1\ndef f(x):\n return [(2.0 * x[0] + 3.0 * x[1]) % 1, (0.5 * x[0] + 0.3 * x[1]) % 1]\n\n# Define box map for f\ndef F(rect):\n return CMGDB.BoxMap(f, rect, padding=True)",
"_____no_output_____"
],
[
"subdiv_min = 20\nsubdiv_max = 30\nlower_bounds = [0.0, 0.0]\nupper_bounds = [1.0, 1.0]\nphase_periodic = [True, True]\n\nmodel = CMGDB.Model(subdiv_min, subdiv_max, lower_bounds, upper_bounds, phase_periodic, F)",
"_____no_output_____"
],
[
"%%time\nmorse_graph, map_graph = CMGDB.ComputeMorseGraph(model)",
"CPU times: user 1min 27s, sys: 996 ms, total: 1min 28s\nWall time: 1min 39s\n"
],
[
"CMGDB.PlotMorseGraph(morse_graph)",
"_____no_output_____"
],
[
"CMGDB.PlotMorseSets(morse_graph)",
"_____no_output_____"
],
[
"# Save Morse sets to a file\nmorse_fname = 'morse_sets.csv'\n\nCMGDB.SaveMorseSets(morse_graph, morse_fname)",
"_____no_output_____"
],
[
"# Plot Morse sets from file\nCMGDB.PlotMorseSets(morse_fname)",
"_____no_output_____"
]
],
[
[
"# The same example on a fixed grid",
"_____no_output_____"
]
],
[
[
"phase_subdiv = 20\nlower_bounds = [0.0, 0.0]\nupper_bounds = [1.0, 1.0]\nphase_periodic = [True, True]\n\nmodel = CMGDB.Model(phase_subdiv, lower_bounds, upper_bounds, phase_periodic, F)",
"_____no_output_____"
],
[
"%%time\nmorse_graph, map_graph = CMGDB.ComputeMorseGraph(model)",
"CPU times: user 1min 13s, sys: 678 ms, total: 1min 13s\nWall time: 1min 18s\n"
],
[
"CMGDB.PlotMorseGraph(morse_graph)",
"_____no_output_____"
],
[
"CMGDB.PlotMorseSets(morse_graph)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
4ac650878ac3ff8933c73c19c3471219febd6fc1
| 8,475 |
ipynb
|
Jupyter Notebook
|
tutorials/working_with_distributed_graph_engine.ipynb
|
HeMingKai/PGL
|
9640469c9709f3703e9a189354d1c083ee83ca61
|
[
"ECL-2.0",
"Apache-2.0"
] | 1,389 |
2019-06-11T03:29:20.000Z
|
2022-03-29T18:25:43.000Z
|
tutorials/working_with_distributed_graph_engine.ipynb
|
HeMingKai/PGL
|
9640469c9709f3703e9a189354d1c083ee83ca61
|
[
"ECL-2.0",
"Apache-2.0"
] | 232 |
2019-06-21T06:52:10.000Z
|
2022-03-29T08:20:31.000Z
|
tutorials/working_with_distributed_graph_engine.ipynb
|
HeMingKai/PGL
|
9640469c9709f3703e9a189354d1c083ee83ca61
|
[
"ECL-2.0",
"Apache-2.0"
] | 229 |
2019-06-20T12:13:58.000Z
|
2022-03-25T12:04:48.000Z
| 26.904762 | 208 | 0.557994 |
[
[
[
"## Introduction\n\nIn real world, there exists many huge graphs that can not be loaded in one machine, \nsuch as social networks and citation networks.\n\nTo deal with such graphs, PGL develops a Distributed Graph Engine Framework to \nsupport graph sampling on large scale graph networks for distributed GNN training.\n\nIn this tutorial, we will walk through the steps of performing distributed Graph Engine for graph sampling. \n\nWe also develop a launch script for launch a distributed Graph Engine. To see more examples of distributed GNN training, please refer to [here](https://github.com/PaddlePaddle/PGL/tree/main/examples).\n",
"_____no_output_____"
],
[
"## Requirements\n\npaddlepaddle>=2.1.0\n\npgl>=2.1.4",
"_____no_output_____"
],
[
"## example of how to start a distributed graph engine service\n\nSupose we have a following graph that has two type of nodes (u and t).\n\nFirstly, We should create a configuration file and specify the ip address of each machine. \nHere we use two ports to simulate two machines.\n\nAfter creating the configuration file and ip adress file, we can now start two graph servers.\n\nThen we can use the client to sample neighbors or sample nodes from graph servers.",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\nimport re\nimport time\nimport tqdm\nimport argparse\nimport unittest\nimport shutil\nimport numpy as np\n\nfrom pgl.utils.logger import log\n\nfrom pgl.distributed import DistGraphClient, DistGraphServer\n",
"/ssd2/liweibin02/projects/pgl_dygraph/pgl/distributed/__init__.py:26: UserWarning: The Distributed Graph Engine is experimental, we will officially release it soon\n \"The Distributed Graph Engine is experimental, we will officially release it soon\"\n"
],
[
"edges_file = \"\"\"37\t45\t0.34\n37\t145\t0.31\n37\t112\t0.21\n96\t48\t1.4\n96\t247\t0.31\n96\t111\t1.21\n59\t45\t0.34\n59\t145\t0.31\n59\t122\t0.21\n97\t48\t0.34\n98\t247\t0.31\n7\t222\t0.91\n7\t234\t0.09\n37\t333\t0.21\n47\t211\t0.21\n47\t113\t0.21\n47\t191\t0.21\n34\t131\t0.21\n34\t121\t0.21\n39\t131\t0.21\"\"\"\n\nnode_file = \"\"\"u\t98\nu\t97\nu\t96\nu\t7\nu\t59\nt\t48\nu\t47\nt\t45\nu\t39\nu\t37\nu\t34\nt\t333\nt\t247\nt\t234\nt\t222\nt\t211\nt\t191\nt\t145\nt\t131\nt\t122\nt\t121\nt\t113\nt\t112\nt\t111\"\"\"\n\n\ntmp_path = \"./tmp_distgraph_test\"\nif not os.path.exists(tmp_path):\n os.makedirs(tmp_path)\n\nwith open(os.path.join(tmp_path, \"edges.txt\"), 'w') as f:\n f.write(edges_file)\n\nwith open(os.path.join(tmp_path, \"node_types.txt\"), 'w') as f:\n f.write(node_file)",
"_____no_output_____"
],
[
"# configuration file\nconfig = \"\"\"\netype2files: \"u2e2t:./tmp_distgraph_test/edges.txt\"\nsymmetry: True\n\nntype2files: \"u:./tmp_distgraph_test/node_types.txt,t:./tmp_distgraph_test/node_types.txt\"\n\n\"\"\"\n\nip_addr = \"\"\"127.0.0.1:8342\n127.0.0.1:8343\"\"\"\n\n\nwith open(os.path.join(tmp_path, \"config.yaml\"), 'w') as f:\n f.write(config)\n \nwith open(os.path.join(tmp_path, \"ip_addr.txt\"), 'w') as f:\n f.write(ip_addr)",
"_____no_output_____"
],
[
"\nconfig = os.path.join(tmp_path, \"config.yaml\")\n\nip_addr = os.path.join(tmp_path, \"ip_addr.txt\")\nshard_num = 10\ngserver1 = DistGraphServer(config, shard_num, ip_addr, server_id=0)\ngserver2 = DistGraphServer(config, shard_num, ip_addr, server_id=1)",
"/ssd2/liweibin02/projects/pgl_dygraph/pgl/distributed/helper.py:60: UserWarning: nfeat_info attribute is not existed, return None\n warnings.warn(\"%s attribute is not existed, return None\" % attr)\n"
],
[
"client1 = DistGraphClient(config, shard_num=shard_num, ip_config=ip_addr, client_id=0)\n\nclient1.load_edges()\nclient1.load_node_types()\nprint(\"data loading finished\")",
"/ssd2/liweibin02/projects/pgl_dygraph/pgl/distributed/helper.py:60: UserWarning: node_batch_stream_shuffle_size attribute is not existed, return None\n warnings.warn(\"%s attribute is not existed, return None\" % attr)\n/ssd2/liweibin02/projects/pgl_dygraph/pgl/distributed/dist_graph.py:172: UserWarning: node_batch_stream_shuffle_size is not specified, default value is 20000\n warnings.warn(\"node_batch_stream_shuffle_size is not specified, \"\n[INFO] 2021-06-18 18:56:30,655 [dist_graph.py: 200]:\tload edges of type u2e2t from ./tmp_distgraph_test/edges.txt\n[INFO] 2021-06-18 18:56:30,658 [dist_graph.py: 210]:\tload nodes of type u from ./tmp_distgraph_test/node_types.txt\n[INFO] 2021-06-18 18:56:30,658 [dist_graph.py: 210]:\tload nodes of type t from ./tmp_distgraph_test/node_types.txt\n"
],
[
"# random sample nodes by node type\nclient1.random_sample_nodes(node_type=\"u\", size=3)",
"_____no_output_____"
],
[
"# traverse all nodes from each server\nnode_generator = client1.node_batch_iter(batch_size=3, node_type=\"t\", shuffle=True)\nfor nodes in node_generator:\n print(nodes)",
"[333, 111, 121]\n[234, 113, 191]\n[131, 122, 222]\n[211, 112]\n[45, 145, 247]\n[48]\n"
],
[
"# sample neighbors\n# note that the edge_type \"u2eut\" is defined in config.yaml file\nnodes = [98, 7]\nneighs = client1.sample_successor(nodes, max_degree=10, edge_type=\"u2e2t\")\nprint(neighs)",
"[[247], [222, 234]]\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
4ac66226f08b3e57201624d6a2832e99220fa9f4
| 4,270 |
ipynb
|
Jupyter Notebook
|
_notebooks/2020-12-06-What's the difference between a metric and a loss?.ipynb
|
peiyiHung/mywebsite
|
4f6bb8dab272960d39e84c04b545f5417278a081
|
[
"Apache-2.0"
] | 1 |
2020-12-16T13:40:27.000Z
|
2020-12-16T13:40:27.000Z
|
_notebooks/2020-12-06-What's the difference between a metric and a loss?.ipynb
|
peiyiHung/mywebsite
|
4f6bb8dab272960d39e84c04b545f5417278a081
|
[
"Apache-2.0"
] | 1 |
2021-07-03T06:24:55.000Z
|
2021-07-03T06:24:56.000Z
|
_notebooks/2020-12-06-What's the difference between a metric and a loss?.ipynb
|
peiyiHung/mywebsite
|
4f6bb8dab272960d39e84c04b545f5417278a081
|
[
"Apache-2.0"
] | null | null | null | 51.445783 | 795 | 0.699063 |
[
[
[
"# \"[ML] What's the difference between a metric and a loss?\"\n\n- toc:true\n- branch: master\n- badges: false\n- comments: true\n- author: Peiyi Hung\n- categories: [learning, machine learning]",
"_____no_output_____"
],
[
"In machine learning, we usually use two values to evaluate our model: a metric and a loss. For instance, if we are doing a binary classification task, our metric may be the accuracy and our loss would be the cross-entroy. They both show how good our model \nperforms. However, why do we need both rather than just use one of them? Also, what's the difference between them?",
"_____no_output_____"
],
[
"The short answer is that **the metric is for human while the loss is for your model.**",
"_____no_output_____"
],
[
"Based on the metric, machine learning practitioners such as data scientists and researchers assess a machine learning model. On the assessment, ML practitioners make decisions to address their problems or achieve their business goals. For example , say a data scientist aims to build a spam classifier to distinguish normal email from spam with 95% accuracy. First, the data scientist build a model with 90% accuracy. Apparently, this result doesn't meet his business goal, so he tries to build a better one. After implementing some techniques, he might get a classifier with 97% accuracy, which goes beyond his goal. Since the goal is met, the data scientist decides to integrate this model into his data product. ML partitioners use the metric to tell whether their model is good enough.",
"_____no_output_____"
],
[
"On the other hand, a loss indicates in what direction your model should improve. The difference between machine learning and traditional programming is how they get the ability to solve a problem. Traditional programs solve problems by following exact instructions given by programmers. In contrast, machine learning models learn how to solve a problem by taking into some examples (data) and discovering the underlying patterns of the problem. How does a machine learning model learn? Most ML models learn using a gradient-based method. Here's how a gradient-based method (be specifically, a gradient descent method in supervised learning context) works:\n\n1. A model takes into data and makes predictions.\n1. Compute the loss based on the predictions and the true data.\n1. Compute the gradients of the loss with respect to parameters of the model.\n1. Updating these parameters based on these gradients.\n\nThe gradient of the loss helps our model to get better and better. The reason why we need a loss is that a loss is **sensitive** enough to small changes so our model can improve based on it. More precisely, the gradient of the loss should vary if our parameters change slightly. In our spam classification example, accuracy is obviously not suitable for being a loss since it only changes when some examples are classified differently. The cross-entrpy is relatively smoother and so it is a good candidate for a loss. However, a metric do not have to be different from a loss. A metric can be a loss as long as it is sensitive enough. For instance, in a regression setting, MSE (mean squared error) can be both a metric and a loss.",
"_____no_output_____"
],
[
"In summary, a metric helps ML partitioners to evaluate their models and a loss facilitates the learning process of a ML model. ",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
4ac67ed0a258306e7b03d0ddb1e56ad2f9235f26
| 252,407 |
ipynb
|
Jupyter Notebook
|
lecture-07/.ipynb_checkpoints/lab-checkpoint.ipynb
|
fralvarezz/modern-ai-course
|
6d5666789ba09728c4f5b0fcc48f511e60d99395
|
[
"MIT"
] | null | null | null |
lecture-07/.ipynb_checkpoints/lab-checkpoint.ipynb
|
fralvarezz/modern-ai-course
|
6d5666789ba09728c4f5b0fcc48f511e60d99395
|
[
"MIT"
] | null | null | null |
lecture-07/.ipynb_checkpoints/lab-checkpoint.ipynb
|
fralvarezz/modern-ai-course
|
6d5666789ba09728c4f5b0fcc48f511e60d99395
|
[
"MIT"
] | null | null | null | 98.905564 | 94,376 | 0.834232 |
[
[
[
"# Convolutional Neural Networks\nA CNN is made up of basic building blocks defined as tensor, neurons, layers and kernel weights and biases. In this lab, we use PyTorch to build a image classifier using CNN. The objective is to learn CNN using PyTorch framework.\nPlease refer to the link below for know more about CNN\nhttps://poloclub.github.io/cnn-explainer/\n\n\n## Import necessary libraries",
"_____no_output_____"
]
],
[
[
"import torch\nimport torchvision\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.datasets import MNIST\nfrom torchvision.transforms import ToTensor\nfrom torchvision import datasets, transforms\nfrom torchvision.utils import make_grid\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.optim.lr_scheduler import StepLR\nfrom torch.utils.data import random_split\nfrom torch.utils.data.sampler import SubsetRandomSampler\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"### Download the MNIST dataset. ",
"_____no_output_____"
]
],
[
[
"# choose the training and test datasets\ntrain_data = datasets.MNIST(root='data', train=True,download=True, transform=ToTensor())\ntest_data = datasets.MNIST(root='data', train=False,download=True, transform=ToTensor())",
"_____no_output_____"
]
],
[
[
"##Chopping training datasets in train set and validation set. This is done to avoid overfitting on the test set.\n\nUse simple algorithm to create validation set:\nFirst, create a list of indices of the training data. Then randomly shuffle those indices. Lastly,split the indices in 80-20.\n\n",
"_____no_output_____"
]
],
[
[
"indices = np.arange(len(train_data))\nnp.random.shuffle(indices)\ntrain_indices = indices[:int(len(indices)*0.8)]\ntest_indices = indices[len(train_indices):]",
"_____no_output_____"
]
],
[
[
"## Print data size",
"_____no_output_____"
]
],
[
[
"print(train_data)\nprint(test_data)",
"Dataset MNIST\n Number of datapoints: 60000\n Root location: data\n Split: Train\n StandardTransform\nTransform: ToTensor()\nDataset MNIST\n Number of datapoints: 10000\n Root location: data\n Split: Test\n StandardTransform\nTransform: ToTensor()\n"
]
],
[
[
"## Data Visualization",
"_____no_output_____"
]
],
[
[
"figure = plt.figure(figsize=(10, 8))\ncols, rows = 5, 5\nfor i in range(1, cols * rows + 1):\n sample_idx = torch.randint(len(train_data), size=(1,)).item()\n img, label = train_data[sample_idx]\n figure.add_subplot(rows, cols, i)\n plt.title(label)\n plt.axis(\"off\")\n plt.imshow(img.squeeze(), cmap=\"gray\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Data preparation for training with PyTorch DataLoaders ",
"_____no_output_____"
]
],
[
[
"# Obtaining training and validation batches\ntrain_batch = SubsetRandomSampler(train_indices)\nval_batch = SubsetRandomSampler(test_indices)\n\n# Samples per batch to load\nbatch_size = 256\n\n# Training Set \ntrain_loader = torch.utils.data.DataLoader(dataset=train_data, batch_size=batch_size,sampler=train_batch,num_workers=4,pin_memory=True)\n# Validation Set \nval_loader = torch.utils.data.DataLoader(dataset=train_data,batch_size=batch_size, sampler=val_batch, num_workers=4,pin_memory=True)\n# Test Set \ntest_loader = torch.utils.data.DataLoader(dataset=test_data,batch_size=batch_size,num_workers=4,pin_memory=True)",
"_____no_output_____"
]
],
[
[
"## Data normalization step: Calculate Mean and Std",
"_____no_output_____"
]
],
[
[
"train_mean = 0.\ntrain_std = 0.\nfor images, _ in train_loader:\n batch_samples = images.size(0) # batch size (the last batch can have smaller size!)\n images = images.view(batch_samples, images.size(1), -1)\n\n train_mean += images.mean(2).sum(0)\n train_std += images.std(2).sum(0)\n\ntrain_mean /= len(train_loader.dataset)\ntrain_std /= len(train_loader.dataset)\n\nprint('Mean: ', train_mean)\nprint('Std: ', train_std)",
"Mean: tensor([0.1044])\nStd: tensor([0.2411])\n"
]
],
[
[
"## Data Augmentation: \nIt is usually done to increase the performance of the CNN based classifiers. Consider this is preprocess of the data. PyTorch inculdes lots of pre-built data augumentation and data transformation features such as Below are the list of transformations that come pre-built with PyTorch: ToTensor, Normalize, Scale, RandomCrop, LinearTransformation, RandomGrayscale, etc. Try to use atleaset one the data.",
"_____no_output_____"
]
],
[
[
"# Your code\n\n# Check the data and see weither suggested augumenation is done. Also check for normalization transformation.",
"_____no_output_____"
]
],
[
[
"## Evaluation Metrics\nprediction acuracy",
"_____no_output_____"
]
],
[
[
"def accuracy(outputs, labels):\n _, preds = torch.max(outputs, dim=1)\n return torch.tensor(torch.sum(preds == labels).item() / len(preds))\n\n## Use different form of evaluation meterics ",
"_____no_output_____"
]
],
[
[
"## Loss Function: Cross Entropy\nFor each output row, pick the predicted probability for the correct label. E.g. if the predicted probabilities for an image are [0.1, 0.3, 0.2, ...] and the correct label is 1, we pick the corresponding element 0.3 and ignore the rest.\n\nThen, take the logarithm of the picked probability. If the probability is high i.e. close to 1, then its logarithm is a very small negative value, close to 0. And if the probability is low (close to 0), then the logarithm is a very large negative value. We also multiply the result by -1, which results is a large postive value of the loss for poor predictions.\n\nFinally, take the average of the cross entropy across all the output rows to get the overall loss for a batch of data.\n",
"_____no_output_____"
]
],
[
[
"class MnistModelBase(nn.Module):\n def training_step(self, batch):\n pass\n # your code\n \n def validation_step(self, batch):\n pass\n # your code\n def validation_epoch_end(self, outputs):\n pass\n #your code\n \n def epoch_end(self, epoch, result,LR):\n pass \n #your code",
"_____no_output_____"
]
],
[
[
"## Convolutional Neural Network model\nwe will use a convolutional neural network, using the nn.Conv2d class from PyTorch. The activation function we'll use here is called a Rectified Linear Unit or ReLU, and it has a really simple formula: relu(x) = max(0,x) i.e. if an element is negative, we replace it by 0, otherwise we leave it unchanged. To define the model, we extend the nn.Module class",
"_____no_output_____"
]
],
[
[
"class MnistModel(MnistModelBase):\n \"\"\"Feedfoward neural network with 2 hidden layer\"\"\"\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Sequential(\n nn.Conv2d(in_channels = 1, out_channels = 16, kernel_size=3), #RF - 3x3 # 26x26\n nn.ReLU(),\n nn.BatchNorm2d(16),\n nn.Dropout2d(0.1),\n\n nn.Conv2d(16, 16, 3), #RF - 5x5 # 24x24\n nn.ReLU(),\n nn.BatchNorm2d(16),\n nn.Dropout2d(0.1),\n\n nn.Conv2d(16, 32, 3), #RF - 7x7 # 22x22\n nn.ReLU(),\n nn.BatchNorm2d(32),\n nn.Dropout2d(0.1),\n )\n\n # translation layer\n # input - 22x22x64; output - 11x11x32\n self.trans1 = nn.Sequential(\n # RF - 7x7\n nn.Conv2d(32, 20, 1), # 22x22\n nn.ReLU(),\n nn.BatchNorm2d(20),\n\n\n # RF - 14x14\n nn.MaxPool2d(2, 2), # 11x11\n )\n\n self.conv2 = nn.Sequential(\n \n nn.Conv2d(20,20,3,padding=1), #RF - 16x16 #output- 9x9\n nn.ReLU(),\n nn.BatchNorm2d(20),\n nn.Dropout2d(0.1),\n\n nn.Conv2d(20,16,3), #RF - 16x16 #output- 9x9\n nn.ReLU(),\n nn.BatchNorm2d(16),\n nn.Dropout2d(0.1),\n\n nn.Conv2d(16, 16, 3), #RF - 18x18 #output- 7x7\n nn.ReLU(),\n nn.BatchNorm2d(16),\n nn.Dropout2d(0.1),\n ) \n\n \n self.conv3 = nn.Sequential(\n nn.Conv2d(16,16,3), #RF - 20x20 #output- 5x5\n nn.ReLU(),\n nn.BatchNorm2d(16),\n nn.Dropout2d(0.1),\n\n #nn.Conv2d(16,10,1), #RF - 20x20 #output- 7x7\n\n ) \n\n # GAP Layer\n self.avg_pool = nn.Sequential(\n # # RF - 22x22\n nn.AvgPool2d(5)\n ) ## output_size=1 \n\n self.conv4 = nn.Sequential(\n \n nn.Conv2d(16,10,1), #RF - 20x20 #output- 7x7\n\n ) \n\n \n def forward(self, xb):\n x = self.conv1(xb)\n x = self.trans1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.avg_pool(x)\n x = self.conv4(x)\n\n x = x.view(-1, 10)\n return x",
"_____no_output_____"
]
],
[
[
"### Using a GPU\n",
"_____no_output_____"
]
],
[
[
"#function to ensure that our code uses the GPU if available, and defaults to using the CPU if it isn't.\ndef get_default_device():\n \"\"\"Pick GPU if available, else CPU\"\"\"\n if torch.cuda.is_available():\n return torch.device('cuda')\n else:\n return torch.device('cpu')\n \n# a function that can move data and model to a chosen device. \ndef to_device(data, device):\n \"\"\"Move tensor(s) to chosen device\"\"\"\n if isinstance(data, (list,tuple)):\n return [to_device(x, device) for x in data]\n return data.to(device, non_blocking=True)\n\n\n#Finally, we define a DeviceDataLoader class to wrap our existing data loaders and move data to the selected device, \n#as a batches are accessed. Interestingly, we don't need to extend an existing class to create a PyTorch dataloader. \n#All we need is an __iter__ method to retrieve batches of data, and an __len__ method to get the number of batches.\n\nclass DeviceDataLoader():\n \"\"\"Wrap a dataloader to move data to a device\"\"\"\n def __init__(self, dl, device):\n self.dl = dl\n self.device = device\n \n def __iter__(self):\n \"\"\"Yield a batch of data after moving it to device\"\"\"\n for b in self.dl: \n yield to_device(b, self.device)\n\n def __len__(self):\n \"\"\"Number of batches\"\"\"\n return len(self.dl)",
"_____no_output_____"
]
],
[
[
"We can now wrap our data loaders using DeviceDataLoader.",
"_____no_output_____"
]
],
[
[
"device = get_default_device()\ntrain_loader = DeviceDataLoader(train_loader, device)\nval_loader = DeviceDataLoader(val_loader, device)\ntest_loader = DeviceDataLoader(test_loader, device)",
"_____no_output_____"
]
],
[
[
"### Model Training\n\n\n",
"_____no_output_____"
]
],
[
[
"from torch.optim.lr_scheduler import OneCycleLR\[email protected]_grad()\ndef evaluate(model, val_loader):\n model.eval()\n outputs = [model.validation_step(batch) for batch in val_loader]\n return model.validation_epoch_end(outputs)\n\ndef fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD):\n torch.cuda.empty_cache()\n history = []\n optimizer = opt_func(model.parameters(), lr)\n scheduler = OneCycleLR(optimizer, lr, epochs=epochs,steps_per_epoch=len(train_loader))\n\n for epoch in range(epochs):\n # Training Phase \n model.train()\n train_losses = []\n for batch in train_loader:\n loss = model.training_step(batch)\n train_losses.append(loss)\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n\n scheduler.step()\n # Validation phase\n result = evaluate(model, val_loader)\n result['train_loss'] = torch.stack(train_losses).mean().item()\n model.epoch_end(epoch, result,scheduler.get_lr())\n history.append(result)\n return history",
"_____no_output_____"
]
],
[
[
"Before we train the model, we need to ensure that the data and the model's parameters (weights and biases) are on the same device (CPU or GPU). We can reuse the to_device function to move the model's parameters to the right device.",
"_____no_output_____"
]
],
[
[
"# Model (on GPU)\nmodel = MnistModel()\nto_device(model, device)",
"_____no_output_____"
]
],
[
[
"Print Summary of the model",
"_____no_output_____"
]
],
[
[
"from torchsummary import summary\n# print the summary of the model\nsummary(model, input_size=(1, 28, 28), batch_size=-1)",
"----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n Conv2d-1 [-1, 16, 26, 26] 160\n ReLU-2 [-1, 16, 26, 26] 0\n BatchNorm2d-3 [-1, 16, 26, 26] 32\n Dropout2d-4 [-1, 16, 26, 26] 0\n Conv2d-5 [-1, 16, 24, 24] 2,320\n ReLU-6 [-1, 16, 24, 24] 0\n BatchNorm2d-7 [-1, 16, 24, 24] 32\n Dropout2d-8 [-1, 16, 24, 24] 0\n Conv2d-9 [-1, 32, 22, 22] 4,640\n ReLU-10 [-1, 32, 22, 22] 0\n BatchNorm2d-11 [-1, 32, 22, 22] 64\n Dropout2d-12 [-1, 32, 22, 22] 0\n Conv2d-13 [-1, 20, 22, 22] 660\n ReLU-14 [-1, 20, 22, 22] 0\n BatchNorm2d-15 [-1, 20, 22, 22] 40\n MaxPool2d-16 [-1, 20, 11, 11] 0\n Conv2d-17 [-1, 20, 11, 11] 3,620\n ReLU-18 [-1, 20, 11, 11] 0\n BatchNorm2d-19 [-1, 20, 11, 11] 40\n Dropout2d-20 [-1, 20, 11, 11] 0\n Conv2d-21 [-1, 16, 9, 9] 2,896\n ReLU-22 [-1, 16, 9, 9] 0\n BatchNorm2d-23 [-1, 16, 9, 9] 32\n Dropout2d-24 [-1, 16, 9, 9] 0\n Conv2d-25 [-1, 16, 7, 7] 2,320\n ReLU-26 [-1, 16, 7, 7] 0\n BatchNorm2d-27 [-1, 16, 7, 7] 32\n Dropout2d-28 [-1, 16, 7, 7] 0\n Conv2d-29 [-1, 16, 5, 5] 2,320\n ReLU-30 [-1, 16, 5, 5] 0\n BatchNorm2d-31 [-1, 16, 5, 5] 32\n Dropout2d-32 [-1, 16, 5, 5] 0\n AvgPool2d-33 [-1, 16, 1, 1] 0\n Conv2d-34 [-1, 10, 1, 1] 170\n================================================================\nTotal params: 19,410\nTrainable params: 19,410\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.00\nForward/backward pass size (MB): 1.47\nParams size (MB): 0.07\nEstimated Total Size (MB): 1.55\n----------------------------------------------------------------\n"
]
],
[
[
"Let's see how the model performs on the validation set with the initial set of weights and biases.",
"_____no_output_____"
]
],
[
[
"history = [evaluate(model, val_loader)]\nhistory",
"/usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:481: UserWarning: This DataLoader will create 4 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n cpuset_checked))\n"
]
],
[
[
"The initial accuracy is around 10%, which is what one might expect from a randomly intialized model (since it has a 1 in 10 chance of getting a label right by guessing randomly).\n\nWe are now ready to train the model. Let's train for 5 epochs and look at the results. We can use a relatively higher learning of 0.01.",
"_____no_output_____"
]
],
[
[
"history += fit(10, 0.01, model, train_loader, val_loader)\n",
"/usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:481: UserWarning: This DataLoader will create 4 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n cpuset_checked))\n"
]
],
[
[
"## Plot Metrics",
"_____no_output_____"
]
],
[
[
"def plot_scores(history):\n# scores = [x['val_score'] for x in history]\n acc = [x['val_acc'] for x in history]\n plt.plot(acc, '-x')\n plt.xlabel('epoch')\n plt.ylabel('acc')\n plt.title('acc vs. No. of epochs');",
"_____no_output_____"
],
[
"def plot_losses(history):\n train_losses = [x.get('train_loss') for x in history]\n val_losses = [x['val_loss'] for x in history]\n plt.plot(train_losses, '-bx')\n plt.plot(val_losses, '-rx')\n plt.xlabel('epoch')\n plt.ylabel('loss')\n plt.legend(['Training', 'Validation'])\n plt.title('Loss vs. No. of epochs');",
"_____no_output_____"
],
[
"plot_losses(history)\n",
"_____no_output_____"
],
[
"plot_scores(history)\n",
"_____no_output_____"
],
[
"def get_misclassified(model, test_loader):\n misclassified = []\n misclassified_pred = []\n misclassified_target = []\n # put the model to evaluation mode\n model.eval()\n # turn off gradients\n\n with torch.no_grad():\n for data, target in test_loader:\n\n # do inferencing\n output = model(data)\n # get the predicted output\n pred = output.argmax(dim=1, keepdim=True)\n\n # get the current misclassified in this batch\n list_misclassified = (pred.eq(target.view_as(pred)) == False)\n batch_misclassified = data[list_misclassified]\n batch_mis_pred = pred[list_misclassified]\n batch_mis_target = target.view_as(pred)[list_misclassified]\n\n # batch_misclassified =\n\n misclassified.append(batch_misclassified)\n misclassified_pred.append(batch_mis_pred)\n misclassified_target.append(batch_mis_target)\n # group all the batches together\n misclassified = torch.cat(misclassified)\n misclassified_pred = torch.cat(misclassified_pred)\n misclassified_target = torch.cat(misclassified_target)\n\n return list(map(lambda x, y, z: (x, y, z), misclassified, misclassified_pred, misclassified_target))",
"_____no_output_____"
],
[
"misclassified = get_misclassified(model, test_loader)\n",
"/usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:481: UserWarning: This DataLoader will create 4 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n cpuset_checked))\n"
],
[
"import random\n\nnum_images = 25\nfig = plt.figure(figsize=(12, 12))\nfor idx, (image, pred, target) in enumerate(random.choices(misclassified, k=num_images)):\n image, pred, target = image.cpu().numpy(), pred.cpu(), target.cpu()\n ax = fig.add_subplot(5, 5, idx+1)\n ax.axis('off')\n ax.set_title('target {}\\npred {}'.format(target.item(), pred.item()), fontsize=12)\n ax.imshow(image.squeeze())\nplt.tight_layout()\nplt.show()\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"
],
[
"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"
]
] |
4ac67f0b1fa1b4250a79a3bfd781aad66ece9907
| 2,269 |
ipynb
|
Jupyter Notebook
|
testing-security-temporary.ipynb
|
freyam/my-dask
|
98f2532fa372e611a29ea6a23462cbab09e6e5b1
|
[
"BSD-3-Clause"
] | null | null | null |
testing-security-temporary.ipynb
|
freyam/my-dask
|
98f2532fa372e611a29ea6a23462cbab09e6e5b1
|
[
"BSD-3-Clause"
] | 1 |
2021-06-27T19:21:49.000Z
|
2021-06-29T13:21:22.000Z
|
testing-security-temporary.ipynb
|
freyam/my-dask
|
98f2532fa372e611a29ea6a23462cbab09e6e5b1
|
[
"BSD-3-Clause"
] | null | null | null | 21.009259 | 188 | 0.5487 |
[
[
[
"%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"from dask.distributed import Security",
"_____no_output_____"
],
[
"Security.temporary()",
"_____no_output_____"
],
[
"Security(tls_ca_file=\"ca.pem\", tls_scheduler_cert=\"scert.pem\")",
"_____no_output_____"
],
[
"Security(require_encryption=False, tls_ca_file=\"ca.pem\", tls_scheduler_cert=\"scert.pem\")",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code"
]
] |
4ac6986dec644bfc3c3a5e5df7d668ba7259e76f
| 208,669 |
ipynb
|
Jupyter Notebook
|
cca_notebook.ipynb
|
htwangtw/cca_primer
|
74012f209b9165ee4b994ccec70bde5174839dea
|
[
"MIT"
] | 4 |
2020-03-17T14:41:55.000Z
|
2020-06-22T19:49:44.000Z
|
cca_notebook.ipynb
|
htwangtw/cca_primer
|
74012f209b9165ee4b994ccec70bde5174839dea
|
[
"MIT"
] | null | null | null |
cca_notebook.ipynb
|
htwangtw/cca_primer
|
74012f209b9165ee4b994ccec70bde5174839dea
|
[
"MIT"
] | 2 |
2020-06-17T10:11:01.000Z
|
2020-06-17T15:08:34.000Z
| 383.582721 | 33,068 | 0.94141 |
[
[
[
"# Canonical correlation analysis in python\n\nIn this notebook, we will walk through the solution to the basic algrithm of canonical correlation analysis and compare that to the output of implementations in existing python libraries `statsmodels` and `scikit-learn`. \n\n",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom scipy.linalg import sqrtm\n\nfrom statsmodels.multivariate.cancorr import CanCorr as smCCA\nfrom sklearn.cross_decomposition import CCA as skCCA\n\nimport matplotlib.pyplot as plt\nfrom seaborn import heatmap",
"_____no_output_____"
]
],
[
[
"Let's define a plotting functon for the output first.",
"_____no_output_____"
]
],
[
[
"def plot_cca(a, b, U, V, s):\n # plotting\n plt.figure()\n heatmap(a, square=True, center=0)\n plt.title(\"Canonical vector - x\")\n plt.figure()\n heatmap(b, square=True, center=0)\n plt.title(\"Canonical vector - y\")\n\n plt.figure(figsize=(9, 6))\n for i in range(N):\n\n plt.subplot(221 + i)\n plt.scatter(np.array(X_score[:, i]).reshape(100), \n np.array(Y_score[:, i]).reshape(100), \n marker=\"o\", c=\"b\", s=25)\n plt.xlabel(\"Canonical variate of X\")\n plt.ylabel(\"Canonical variate of Y\")\n plt.title('Mode %i (corr = %.2f)' %(i + 1, s[i]))\n plt.xticks(())\n plt.yticks(())",
"_____no_output_____"
]
],
[
[
"## Create data based on some latent variables\n\nFirst generate some test data.\nThe code below is modified based on the scikit learn example of CCA. \nThe aim of using simulated data is that we can have complete control over the structure of the data and help us see the utility of CCA.\n\nLet's create a dataset with 100 observations with two hidden variables:",
"_____no_output_____"
]
],
[
[
"n = 100\n# fix the random seed so this tutorial will always create the same results\nnp.random.seed(42)\nl1 = np.random.normal(size=n)\nl2 = np.random.normal(size=n)",
"_____no_output_____"
]
],
[
[
"For each observation, there are two domains of data. \nSix and four variables are measured in each of the domain. \nIn domain 1 (x), the first latent structure 1 is underneath the first 3 variables and latent strucutre 2 for the rest.\nIn domain 2 (y), the first latent structure 1 is underneath every other variable and for latent strucutre 2 as well.",
"_____no_output_____"
]
],
[
[
"latents_x = np.array([l1, l1, l1, l2, l2, l2]).T\nlatents_y = np.array([l1, l2, l1, l2]).T",
"_____no_output_____"
]
],
[
[
"Now let's add some random noise on this latent structure.",
"_____no_output_____"
]
],
[
[
"X = latents_x + np.random.normal(size=6 * n).reshape((n, 6))\nY = latents_y + np.random.normal(size=4 * n).reshape((n, 4))",
"_____no_output_____"
]
],
[
[
"The aim of CCA is finding the correlated latent features in the two domains of data. \nTherefore, we would expect to find the hidden strucure is laid out in the latent components. ",
"_____no_output_____"
],
[
"## SVD algebra solution\nSVD solution is the most implemented way of CCA solution. For the proof of standard eigenvalue solution and the proof SVD solution demonstrated below, see [Uurtio wt. al, (2018)](https://dl.acm.org/citation.cfm?id=3136624). ",
"_____no_output_____"
],
[
"The first step is getting the covariance matrixes of X and Y.",
"_____no_output_____"
]
],
[
[
"Cx, Cy = np.corrcoef(X.T), np.corrcoef(Y.T)\nCxy = np.corrcoef(X.T, Y.T)[:X.shape[1], X.shape[1]:]\nCyx = Cxy.T",
"_____no_output_____"
]
],
[
[
"We first retrieve the identity form of the covariance matix of X and Y.",
"_____no_output_____"
]
],
[
[
"sqrt_x, sqrt_y = np.matrix(sqrtm(Cx)), np.matrix(sqrtm(Cy))\nisqrt_x, isqrt_y = sqrt_x.I, sqrt_y.I",
"_____no_output_____"
]
],
[
[
"According to the proof, we leared that the canonical correlation can be retrieved from SVD on Cx^-1/2 Cxy Cy^-1/2.",
"_____no_output_____"
]
],
[
[
"W = isqrt_x * Cxy * isqrt_y\nu, s, v = np.linalg.svd(W)",
"_____no_output_____"
]
],
[
[
"The columns of the matrices U and V correspond to the sets of orthonormal left and right singular vectors respectively. The singular values of matrix S correspond to\nthe canonical correlations. The positions w a and w b are obtained from:",
"_____no_output_____"
]
],
[
[
"N = np.min([X.shape[1], Y.shape[1]])\na = np.dot(u, isqrt_x.T[:, :N]) / np.std(X) # scaling because we didn't standardise the input\nb = np.dot(v, isqrt_y).T / np.std(Y)",
"_____no_output_____"
]
],
[
[
"Now compute the score.",
"_____no_output_____"
]
],
[
[
"X_score, Y_score = X.dot(a), Y.dot(b)",
"_____no_output_____"
],
[
"plot_cca(a, b, X_score, Y_score, s) # predefined plotting function",
"_____no_output_____"
]
],
[
[
"## Solution Using SVD Only\n\nThe solution above can be further simplified by conducting SVD on the two domains. \nThe algorithm SVD X and Y. This step is similar to doing principle component analysis on the two domains. ",
"_____no_output_____"
]
],
[
[
"ux, sx, vx = np.linalg.svd(X, 0)\nuy, sy, vy = np.linalg.svd(Y, 0)",
"_____no_output_____"
]
],
[
[
"Then take the unitary bases and form UxUy^T and SVD it. S would be the canonical correlation of the two domanins of features. ",
"_____no_output_____"
]
],
[
[
"u, s, v = np.linalg.svd(ux.T.dot(uy), 0)",
"_____no_output_____"
]
],
[
[
"We can yield the canonical vectors by transforming the unitary basis in the hidden space back to the original space.",
"_____no_output_____"
]
],
[
[
"a = (vx.T).dot(u) # no scaling here as SVD handled it.\nb = (vy.T).dot(v.T)\n\nX_score, Y_score = X.dot(a), Y.dot(b)",
"_____no_output_____"
]
],
[
[
"Now we can plot the results. It shows very similar results to solution 1.",
"_____no_output_____"
]
],
[
[
"plot_cca(a, b, X_score, Y_score, s) # predefined plotting function",
"_____no_output_____"
]
],
[
[
"The method above has been implemented in `Statsmodels`. The results are almost identical:",
"_____no_output_____"
]
],
[
[
"sm_cca = smCCA(Y, X)\nsm_s = sm_cca.cancorr\nsm_a = sm_cca.x_cancoef\nsm_b = sm_cca.y_cancoef\nsm_X_score = X.dot(a)\nsm_Y_score = Y.dot(b)\n\nplot_cca(a, b, X_score, Y_score, s)",
"_____no_output_____"
]
],
[
[
"## Scikit learn\n\nScikit learn implemented [a different algorithm](https://www.stat.washington.edu/sites/default/files/files/reports/2000/tr371.pdf). \nThe outcome of the Scikit learn implementation yield very similar results.\nThe first mode capture the hidden structure in the simulated data. ",
"_____no_output_____"
]
],
[
[
"cca = skCCA(n_components=4)\ncca.fit(X, Y)",
"_____no_output_____"
],
[
"s = np.corrcoef(cca.x_scores_.T, cca.y_scores_.T).diagonal(offset=cca.n_components)\na = cca.x_weights_\nb = cca.y_weights_\n\nX_score, Y_score = cca.x_scores_, cca.y_scores_\n\nplot_cca(a, b, X_score, Y_score, s) # predefined plotting function",
"_____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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.