markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Experiment with window size The code below returns the length of the warmup phase, simulated accross several seeds. This can give us a sense of how long the warmup phase is on average for different seeds. Be mindful that when using too many seeds with a lot of chains, the GPU can run out of memory. The motivation is to...
target_rhat = 1.01 warmup_window_size = 30 max_num_steps = 1000 // warmup_window_size iteration_after_warmup = np.array([]) for seed in jax.random.split(jax.random.PRNGKey(0), 10): initial_state = initialize((num_super_chains,), key = seed) initial_state = np.repeat(initial_state, num_chains_short // num_super_ch...
nested_rhat/rhat_locker.ipynb
google-research/google-research
apache-2.0
Results for the Banana problem Applying the code above for the banana problem with target_rhat = 1.01 use_nested_rhat = True use_log_joint = False we estimate the length of the warmup phase for different window sizes: w = 10, length = 62 +/- 16.12 w = 15, length = 72 +/- 17.41 w = 20, length = 86 +/- 18 w = 30, length ...
result_cold, _, final_kernel_args = tfp.mcmc.sample_chain( num_results = 100, current_state = initial_state, kernel = kernel_cold, previous_kernel_results = None, seed = random.PRNGKey(1954), return_final_kernel_results = True) result_warm, _, final_kernel_args = tfp.mcmc.sample_c...
nested_rhat/rhat_locker.ipynb
google-research/google-research
apache-2.0
Otherwise, set your project ID here.
if PROJECT_ID == "" or PROJECT_ID is None: PROJECT_ID = "qwiklabs-gcp-00-f25b80479c89" # @param {type:"string"}
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/solutions/sdk-custom-image-classification-batch.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Create a Cloud Storage bucket The following steps are required, regardless of your notebook environment. When you submit a training job using the Cloud SDK, you upload a Python package containing your training code to a Cloud Storage bucket. Vertex AI runs the code from this package. In this tutorial, Vertex AI also sa...
# Fill in your bucket name and region BUCKET_NAME = "gs://qwiklabs-gcp-00-f25b80479c89" # @param {type:"string"} REGION = "us-central1" # @param {type:"string"} if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://qwiklabs-gcp-00-f25b80479c89": BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTA...
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/solutions/sdk-custom-image-classification-batch.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Train the model Define your custom training job on Vertex AI. Use the CustomTrainingJob class to define the job, which takes the following parameters: display_name: The user-defined name of this training pipeline. script_path: The local path to the training script. container_uri: The URI of the training container imag...
# TODO # Define your custom training job and use the run function to start the training job = aiplatform.CustomTrainingJob( display_name=JOB_NAME, script_path="task.py", container_uri=TRAIN_IMAGE, requirements=["tensorflow_datasets==1.3.0"], model_serving_container_image_uri=DEPLOY_IMAGE, ) MODEL_D...
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/solutions/sdk-custom-image-classification-batch.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Send the prediction request To make a batch prediction request, call the model object's batch_predict method with the following parameters: - instances_format: The format of the batch prediction request file: "jsonl", "csv", "bigquery", "tf-record", "tf-record-gzip" or "file-list" - prediction_format: The format of th...
MIN_NODES = 1 MAX_NODES = 1 # The name of the job BATCH_PREDICTION_JOB_NAME = "cifar10_batch-" + TIMESTAMP # Folder in the bucket to write results to DESTINATION_FOLDER = "batch_prediction_results" # The Cloud Storage bucket to upload results to BATCH_PREDICTION_GCS_DEST_PREFIX = BUCKET_NAME + "/" + DESTINATION_FOLD...
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/solutions/sdk-custom-image-classification-batch.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
Cleaning up To clean up all Google Cloud resources used in this project, you can delete the Google Cloud project you used for the tutorial. Otherwise, you can delete the individual resources you created in this tutorial: Training Job Model Cloud Storage Bucket
delete_training_job = True delete_model = True # Warning: Setting this to true will delete everything in your bucket delete_bucket = False # TODO # Delete the training job job.delete() # TODO # Delete the model model.delete() if delete_bucket and "BUCKET_NAME" in globals(): ! gsutil -m rm -r $BUCKET_NAME
courses/machine_learning/deepdive2/machine_learning_in_the_enterprise/solutions/sdk-custom-image-classification-batch.ipynb
GoogleCloudPlatform/training-data-analyst
apache-2.0
์•„์ฃผ ๋ฉ‹์žˆ์–ด ๋ณด์ด๊ธฐ๋Š” ํ•˜์ง€๋งŒ, ๋”ฑํžˆ ์–ด๋–ค ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜์ง€๋Š” ์•Š๋Š”๋‹ค. ๋‹จ์–ด๊ฐ€ ๊ตฌ์ธ ๊ด‘๊ณ ์— ๋“ฑ์žฅํ•˜๋Š” ๋นˆ๋„๋ฅผ ๊ฐ€๋กœ์ถ•, ๋‹จ์–ด๊ฐ€ ์ด๋ ฅ์„œ์— ๋“ฑ์žฅํ•˜๋Š” ๋นˆ๋„๋ฅผ ์„ธ๋กœ์ถ•
def text_size(total): """equals 8 if total is 0, 28 if total is 200""" return 8 + total / 200 * 20 for word, job_popularity, resume_popularity in data: plt.text(job_popularity, resume_popularity, word, ha='center', va='center', size=text_size(job_popularity + resume_popularity)) p...
notebook/ch20_natural_language_processing.ipynb
rnder/data-science-from-scratch
unlicense
2) n-gram ๋ชจ๋ธ
#์œ ๋‹ˆ์ฝ”๋“œ ๋”ฐ์˜ดํ‘œ๋ฅผ ์ผ๋ฐ˜ ์•„์Šคํ‚ค ๋”ฐ์˜ดํ‘œ๋กœ ๋ณ€ํ™˜ def fix_unicode(text): return text.replace(u"\u2019", "'") def get_document(): url = "http://radar.oreilly.com/2010/06/what-is-data-science.html" html = requests.get(url).text soup = BeautifulSoup(html, 'html5lib') #content = soup.find("div", "entry-content") # Non...
notebook/ch20_natural_language_processing.ipynb
rnder/data-science-from-scratch
unlicense
bigram : ๋‘๊ฐœ์˜ ์—ฐ์†์ ์ธ ๋‹จ์–ด trigram : 3๊ฐœ์˜ ์—ฐ์†์ ์ธ ๋‹จ์–ด๋ฅผ ๋ณด๋Š”..(n-gram๋„ ์žˆ๋””๋งŒ 3๊ฐœ ์ •๋„๋งŒ ๋ด๋„ ์ถฉ๋ถ„..)
###+์ˆœ์ฐจ์ ์œผ๋กœ ๋“ฑ์žฅํ•˜๋Š” ๋‹จ์–ด๋“ค์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ์–ป๊ธฐ ์œ„ํ•จ? a = ["We've",'all','heard', 'it'] b = ["We've",'all','heard', 'it'] b = ["We've",'all','heard', 'it'] list(zip(a,b)) #trigrams : ์ง์ „ ๋‘๊ฐœ์˜ ๋‹จ์–ด์— ์˜ํ•ด ๋‹ค์Œ ๋‹จ์–ด๊ฐ€ ๊ฒฐ์ •๋จ trigrams = list(zip(document, document[1:], document[2:])) trigram_transitions = defaultdict(list) starts = [] for prev, current, ...
notebook/ch20_natural_language_processing.ipynb
rnder/data-science-from-scratch
unlicense
trigram์„ ์‚ฌ์šฉํ•˜๋ฉด ๋‹ค์Œ ๋‹จ์–ด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๊ฐ ๋‹จ๊ณ„์—์„œ ์„ ํƒํ•  ์ˆ˜ ์žˆ๋Š” ๋‹จ์–ด์˜ ์ˆ˜๊ฐ€ bigram์„ ์‚ฌ์šฉํ•  ๋•Œ๋งˆ๋‹ค ํ›จ์”ฌ ์ ์–ด์กŒ๊ณ , ์„ ํƒํ•  ์ˆ˜ ์žˆ๋Š” ๋‹จ์–ด๊ฐ€ ๋”ฑ ํ•˜๋‚˜๋งŒ ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ๋„ ๋งŽ์•˜์„ ๊ฒƒ์ด๋‹ค. ์ฆ‰, ์ด๋ฏธ ์–ด๋–ค ๋ฌธ์„œ์ƒ์— ์กด์žฌํ–ˆ๋˜ ๋ฌธ์žฅ(๋˜๋Š” ๊ธด๋ฌธ๊ตฌ)ํ•˜๋‚˜๋ฅผ ๊ทธ๋Œ€๋กœ ์ƒ์„ฑํ–ˆ์„ ๊ฐ€๋Šฅ์„ฑ๋„ ์žˆ๋‹ค. ์ด๋Š” ๋ฐ์ดํ„ฐ ๊ณผํ•™์— ๋Œ€ํ•œ ๋” ๋งŽ์€ ์—์„ธ์ด๋“ค์„ ๋ชจ์œผ๊ณ , ์ด๋ฅผ ํ† ๋Œ€๋กœ n-gram ๋ชจ๋ธ์„ ๊ตฌ์ถ•ํ•˜๋Š” ๊ฒƒ์„ ์˜๋ฏธ! <p><span style="color:blue">**3) ๋ฌธ๋ฒ•**</span></p> ๋ฌธ๋ฒ•์— ๊ธฐ๋ฐ˜ํ•˜์—ฌ ๋ง์ด ๋˜๋Š” ๋ฌธ์žฅ์„ ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ ํ’ˆ์‚ฌ๋ž€ ๋ฌด์—‡์ด๋ฉฐ, ๊ทธ๊ฒƒ๋“ค์„ ์–ด๋–ป๊ฒŒ ์กฐ...
#ํ•ญ๋ชฉ ์•ž์— ๋ฐ‘์ค„์ด ์žˆ์œผ๋ฉด ๋” ํ™•์žฅํ•  ์ˆ˜ ์žˆ๋Š” ๊ทœ์น™์ด๊ณ , ๋‚˜๋จธ์ง€๋Š” ์ข…๊ฒฐ์–ด ๋ผ๊ณ ํ•˜์ž. # ์˜ˆ, '_s'๋Š” ๋ฌธ์žฅ(sentence) ๊ทœ์น™์„ ์˜๋ฏธ, '_NP'๋Š” ๋ช…์‚ฌ๊ตฌ(noun phrase), '_VP'๋Š” ๋™์‚ฌ๊ตฌ grammar = { "_S" : ["_NP _VP"], "_NP" : ["_N", "_A _NP _P _A _N"], "_VP" : ["_V", "_V _NP"], "_N" : ["data science", "Python", "regression"], "_A" : ["big",...
notebook/ch20_natural_language_processing.ipynb
rnder/data-science-from-scratch
unlicense
~~~ ['_S'] ['_NP','_VP'] ['_N','_VP'] ['Python','_VP'] ['Python','_V','_NP'] ['Python','trains','_NP'] ['Python','trains','_A','_NP','_P','_A','_N'] ['Python','trains','logistic','_NP','_P','_A','_N'] ['Python','trains','logistic','_N','_P','_A','_N'] ['Python','trains','logistic','data science','_P','_A','_N'] ...
# ํŠน์ • ํ•ญ๋ชฉ์ด ์ข…๊ฒฐ์–ด์ธ์ง€ ์•„๋‹Œ์ง€? def is_terminal(token): return token[0] != "_" # ๊ฐ ํ•ญ๋ชฉ์„ ๋Œ€์ฒด ๊ฐ€๋Šฅํ•œ ๋‹ค๋ฅธ ํ•ญ๋ชฉ ๋˜๋Š” ํ•ญ๋ชฉ๋“ค๋กœ ๋ณ€ํ™˜์‹œํ‚ค๋Š” ํ•จ์ˆ˜ def expand(grammar, tokens): for i, token in enumerate(tokens): # ์ข…๊ฒฐ์–ด๋Š” ๊ฑด๋„ˆ๋œ€ if is_terminal(token): continue # ์ข…๊ฒฐ์–ด๊ฐ€ ์•„๋‹Œ ๋‹จ์–ด๋Š” ๋Œ€์ฒดํ•  ์ˆ˜ ์žˆ๋Š” ํ•ญ๋ชฉ์„ ์ž„์˜๋กœ ์„ ํƒ replacement = random.choice(gra...
notebook/ch20_natural_language_processing.ipynb
rnder/data-science-from-scratch
unlicense
<p><span style="color:blue">**5) ํ† ํ”ฝ ๋ชจ๋ธ๋ง**</span></p>
#๋‹จ์–ด์˜ ๋ถ„ํฌ์— ๋”ฐ๋ผ ๊ฐ ํ† ํ”ฝ์— weight๋ฅผ ํ• ๋‹น def sample_from(weights): '''i๋ฅผ weight[i] / sum(weight)์˜ ํ™•๋ฅ ๋กœ ๋ฐ˜ํ™˜''' total = sum(weights) rnd = total * random.random() # 0๊ณผ total ์‚ฌ์ด๋ฅผ ๊ท ์ผํ•˜๊ฒŒ ์„ ํƒ for i, w in enumerate(weights): rnd -= w # return the smallest i such that if rnd <= 0: r...
notebook/ch20_natural_language_processing.ipynb
rnder/data-science-from-scratch
unlicense
~~~ ๊ฒฐ๊ตญ, weight๊ฐ€ [1,1,3] ์ด๋ผ๋ฉด 1/5์˜ ํ™•๋ฃ”๋กœ 0, 1/5์˜ ํ™•๋ฅ ๋กœ 1, 3/5์˜ ํ™•๋ฅ ๋กœ 2๋ฅผ ๋ฐ˜ํ™˜ ~~~
documents = [ ["Hadoop", "Big Data", "HBase", "Java", "Spark", "Storm", "Cassandra"], ["NoSQL", "MongoDB", "Cassandra", "HBase", "Postgres"], ["Python", "scikit-learn", "scipy", "numpy", "statsmodels", "pandas"], ["R", "Python", "statistics", "regression", "probability"], ["machine learning", "regre...
notebook/ch20_natural_language_processing.ipynb
rnder/data-science-from-scratch
unlicense
We will vary the fake root we introduced to obtain the phase-mismatch diagram. That is, the phase mismatch $\delta k$ is going to be some linear function of $z$.
plt.plot(x, [abs(f(z))**2 for z in x])
Testing_make_nonlinear_interaction.ipynb
tabakg/potapov_interpolation
gpl-3.0
What happens when we change the indices of refraction for the different modes? The phase-mismatch will shift depending on where the new $\delta k = 0$ occurs. The width of the peak may also change if the indices of refraction are large.
indices_of_refraction=[3.,5.,10.] f = lambda z: functions.make_nonlinear_interaction(roots_to_use(z), modes_to_use,Ex.delays,0,0,0.1,plus_or_minus_arr,indices_of_refraction=indices_of_refraction) plt.plot(x, [abs(f(z))**2 for z in x])
Testing_make_nonlinear_interaction.ipynb
tabakg/potapov_interpolation
gpl-3.0
Generating a Hamiltonian from a model In this section we will use example 3 to generate a Hamiltonian with nonlinaer coefficients resulting when inserting a nonlinearity in a circuit. We will assume that the nonlinearity is inserting at the delay line of index 0 corresponding to $\tau_1$.
import sympy as sp import itertools from qnet.algebra.circuit_algebra import * Ex = Time_Delay_Network.Example3(r1 = 0.9, r3 = 0.9, max_linewidth=35.,max_freq=25.) Ex.run_Potapov() E = Ex.E roots = Ex.roots M1 = Ex.M1 delays = Ex.delays modes = functions.spatial_modes(roots,M1,E) roots ## nonlinearity information d...
Testing_make_nonlinear_interaction.ipynb
tabakg/potapov_interpolation
gpl-3.0
Let's impose a large 'index of refraction'. In the future we will replaces this by better conditions for phase-mismatch, including realistic values. For now, this will narrow the gain versus $\Delta k$ function so that few interaction terms remain.
def weight(combination,pm_arr): roots_to_use = np.array([roots[i].imag for i in combination]) modes_to_use = [modes[i] for i in combination] return functions.make_nonlinear_interaction(roots_to_use, modes_to_use, delays, delay_indices, start_nonlin,duration_nonlin,pm_arr, ...
Testing_make_nonlinear_interaction.ipynb
tabakg/potapov_interpolation
gpl-3.0
As we see above, most of the interactions are negligible. Let's drop them out.
significant_weight_keys = [key for key in weights if abs(weights[key]) > 1e-4] significant_weights = dict((key,weights[key]) for key in significant_weight_keys) significant_weights = {k:v for k,v in weights.iteritems() if abs(v) > 1e-4} ## more elegant len(significant_weights) H_nonlin_sp = 0 ## with sympy only ...
Testing_make_nonlinear_interaction.ipynb
tabakg/potapov_interpolation
gpl-3.0
When Making the nonlinear terms above zero, we find agreement with the linear equtions of motion. Using the symbolic packages is kind of slow. For classical simulations maybe we can avoid that. We just need to extract the equations of motion, which should end up being sparse in the interaction terms. TODO: implement wi...
roots_to_use = np.array([roots[i] for i in combination]) modes_to_use = [modes[i] for i in combination] def call_make_non_lin(): return functions.make_nonlinear_interaction(roots_to_use, modes_to_use, delays, delay_indices, start_nonlin,duration_nonlin,pm_arr, ...
Testing_make_nonlinear_interaction.ipynb
tabakg/potapov_interpolation
gpl-3.0
Unused methods below
## consolidated weights do not take into account which modes are createad or annihilated. consolidated_weightes = {} for key in significant_weights: if not key[0] in consolidated_weightes: consolidated_weightes[key[0]] = significant_weights[key] else: consolidated_weightes[key[0]] += significan...
Testing_make_nonlinear_interaction.ipynb
tabakg/potapov_interpolation
gpl-3.0
The follow code is same as before, but you can send the commands all in one go. However, there are implicit wait for the driver so it can do AJAX request and render the page for elements also, you can you find_element_by_xpath method
# browser = webdriver.Firefox() #I only tested in firefox # browser.get('http://costcotravel.com/Rental-Cars') # browser.implicitly_wait(5)#wait for webpage download # browser.find_element_by_id('pickupLocationTextWidget').send_keys("PHX"); # browser.implicitly_wait(5) #wait for the airport suggestion box to show # br...
costco-rental.ipynb
scko823/web-scraping-selenium-example
mit
let play with one of the row
row = tr[3] row.find('th',{'class':'tar'}).text.encode('utf-8') row row.contents[4].text #1. this is unicode, 2. the dollar sign is in the way 'Car' in 'Econ Car' #use this string logic to filter out unwanted data rows = [i for i in tr if (('Price' not in i.contents[0].text and 'Fees' not in i.contents[0].text a...
costco-rental.ipynb
scko823/web-scraping-selenium-example
mit
Note when running the above cells that we are actively changing the contents of our data variables. If you try to run these cells multiple times in the same session, an error will occur. Investigating the Data
##################################### # 2 # ##################################### ## Find the total number of rows and the number of unique students (account keys) ## in each table. # Part 1 print( len(enrollments), len(daily_engagement), len(project_submissions) ) #...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Problems in the Data
##################################### # 3 # ##################################### ## Rename the "acct" column in the daily_engagement table to "account_key". for engagement_record in daily_engagement: engagement_record['account_key'] = engagement_record['acct'] del[engagement_re...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Missing Engagement Records
##################################### # 4 # ##################################### ## Find any one student enrollments where the student is missing from the daily engagement table. ## Output that enrollment. for e in enrollments: if e["account_key"] not in u_daily_engagement: ...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Checking for More Problem Records
##################################### # 5 # ##################################### ## Find the number of surprising data points (enrollments missing from ## the engagement table) that remain, if any. for ix, e in enumerate(enrollments): if e["account_key"] not in u_daily_engagement ...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Tracking Down the Remaining Problems
# Create a set of the account keys for all Udacity test accounts udacity_test_accounts = set() for enrollment in enrollments: if enrollment['is_udacity']: udacity_test_accounts.add(enrollment['account_key']) len(udacity_test_accounts) # Given some data with an account_key field, removes any records corresp...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Refining the Question
##################################### # 6 # ##################################### ## Create a dictionary named paid_students containing all students who either ## haven't canceled yet or who remained enrolled for more than 7 days. The keys ## should be account keys, and the values shoul...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Getting Data from First Week
# Takes a student's join date and the date of a specific engagement record, # and returns True if that engagement record happened within one week # of the student joining. def within_one_week(join_date, engagement_date): time_delta = engagement_date - join_date return time_delta.days >= 0 and time_delta.days < ...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Exploring Student Engagement
from collections import defaultdict # Create a dictionary of engagement grouped by student. # The keys are account keys, and the values are lists of engagement records. engagement_by_account = defaultdict(list) for engagement_record in paid_engagement_in_first_week: account_key = engagement_record['account_key'] ...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Debugging Data Analysis Code
##################################### # 8 # ##################################### ## Go through a similar process as before to see if there is a problem. ## Locate at least one surprising piece of data, output it, and take a look at it. for k,v in total_minutes_by_account.items(): ...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Lessons Completed in First Week
##################################### # 9 # ##################################### ## Adapt the code above to find the mean, standard deviation, minimum, and maximum for ## the number of lessons completed by each student during the first week. Try creating ## one or more functions to re-...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Number of Visits in First Week
###################################### # 10 # ###################################### ## Find the mean, standard deviation, minimum, and maximum for the number of ## days each student visits the classroom during the first week. for el in paid_engagement_in_first_week: if el["num_cou...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Splitting out Passing Students
###################################### # 11 # ###################################### ## Create two lists of engagement data for paid students in the first week. ## The first list should contain data for students who eventually pass the ## subway project, and the second list should conta...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Comparing the Two Student Groups
###################################### # 12 # ###################################### ## Compute some metrics you're interested in and see how they differ for ## students who pass the subway project vs. students who don't. A good ## starting point would be the metrics we looked at earlie...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Making Histograms
###################################### # 13 # ###################################### ## Make histograms of the three metrics we looked at earlier for both ## students who passed the subway project and students who didn't. You ## might also want to make histograms of any other metrics yo...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Improving Plots and Sharing Findings
###################################### # 14 # ###################################### ## Make a more polished version of at least one of your visualizations ## from earlier. Try importing the seaborn library to make the visualization ## look better, adding axis labels and a title, and ch...
p2/L1_Starter_Code.ipynb
stefanbuenten/nanodegree
mit
Problem 1 The convolutional model above uses convolutions with stride 2 to reduce the dimensionality. Replace the strides by a max pooling operation (nn.max_pool()) of stride 2 and kernel size 2. With adding the max_pool of stride 2 and kernel size 2 and increasing num_of_steps, the performance has improved from 89.8 ...
batch_size = 16 patch_size = 5 depth = 16 num_hidden = 64 graph = tf.Graph() with graph.as_default(): # Input data. tf_train_dataset = tf.placeholder( tf.float32, shape=(batch_size, image_size, image_size, num_channels)) tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels)) tf_vali...
machine-learning/deep-learning/udacity/ud730/4_convolutions.ipynb
pk-ai/training
mit
Variables can be defined freely and change type. There is a very handy print function (this is very different from Python2!). The format function can be used to customize the output. More at https://pyformat.info/
a = 42 b = 256 z = 2 + 3j w = 5 - 6j print("I multiply", a, "and", b, "and I get", a * b) print("Compex numbers!", z + w) print("Real:", z.real) # Variables as objects (in Python everything is an object) print("Abs:", abs(z)) almost_pi = 3.14 better_pi = 3.14159265358979323846264338327950288419716939937510 c = 299792...
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
Note that Python does not require semicolons to terminate an instruction (but they don't harm) but require the indendation to be respected. (After for, if, while, def, class, ...)
for i in range(5): if (not i%2 == 0 or i == 0): print(i)
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
Strucutred Data It's easy to work with variables of different nature. There are three kinds of structured variable: tuple (), lists [], and dicts {}. Tuples are immutable (ofter output of functions is given as a tuple). Lists are the usual arrays (multidimensional). Dictionaries are associative arrays with keywords.
a = 5 a = "Hello, World" # Multiple assignation b, c = "Hello", "World" print(a) print(b, c) tuple_example = (1,2,3) print("Tuple", tuple_example[0]) # tuple_example[1] = 3 list_example = [1,2,3] print("List 1", list_example[0]) list_example[1] = 4 print("List 2", list_example[1]) dict_example = {'one' : 1, ...
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
Lists are very useful as most of the methods are build it, like for sorting, reversing, inserting, deleting, slicing, ...
random_numbers = [1,64,78,13,54,34, "Ravioli"] print("Length:", len(random_numbers)) true_random = random_numbers[0:5] print("Sliced:", true_random) print("Sorted:", sorted(true_random)) print("Max:", max(true_random)) random_numbers.remove("Ravioli") print("Removed:", random_numbers) multi_list = ["A string", ["a", ...
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
CAVEAT: List can be dangerous and have unexpected behavior due to the default copy method (like pointers pointing to the same area of memory)
cool_numbers = [0, 11, 42] other_numbers = cool_numbers print(other_numbers) cool_numbers.append(300) print(other_numbers)
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
To avoid this problem usually slicing is used.
cool_numbers = [0, 11, 42] other_numbers = cool_numbers[:] print(other_numbers) cool_numbers.append(300) print(other_numbers)
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
String are considered list and slicing can be applied on strings, with a sleek behavior with respect to indeces:
s = "GNU Emacs" # No problem with "wrong" index print(s[4:100]) # Backwards! print(s[-9:-6])
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
With a for loop it is possible to iterate over lists. (But attention not to modify the list over which for is iterating!)
for num in cool_numbers: print("I like the number", num)
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
List can generate other list via list comprehension which is a functional way to operate on a list or a subset defined by if statements.
numbers = [0, 1, 2, 3, 4, 5, 6, 7] # Numbers via list comprehension numbers = [i for i in range(0,8)] print("Numbers:", numbers) even = [x for x in numbers if x%2 == 0] odd = [x for x in numbers if not x in even] print("Even:", even) print("Odd:", odd)
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
Functions Python can have user-defined functions. There are some details about passing by reference or passing by value (what Python actually does is passing by assignment, details here: https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference). There are no retu...
def say_hello(to = "Gabriele"): print("Hello", to) say_hello() say_hello("Albert") def sum_and_difference(a, b): return (a + b, a - b) (sum, diff) = sum_and_difference(10, 15) print("Sum: {}, Diff: {}".format(sum, diff)) def usless_box(a,b,c,d,e,f): return a,b,c,d,e,f first, _, _, _, _, _ = usless...
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
A very useful construct is try-except that can be used to handle errors.
hey = "String" ohi = 6 try: print(hey/3) except: print("Error in hey!") try: print(ohi/3) except: print("Error in ohi!")
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
NOTE: Prefer this name convenction (no CamelCase) and space over tabs There is full support to OOP with Ineheritance, Encapsulation and Polymorphism. (https://docs.python.org/3/tutorial/classes.html) Shipped with battery included For Python there exist a huge number of modules that extend the potentiality of Python. He...
# Modules have to be imported # In this way I import thw whole module import os # To access an object inside the module I have to prepend the name # In this way I import only a function but I don't have to prepend the # module's name from os import getcwd print(os.getcwd()) print(getcwd())
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
os with Python's capability for manipulating string is a very simple way to interact with files and dir
dir = "test" files = os.listdir(dir) print(files) # Sorting files.sort() print(files) # I take the subset starting with d and not ending with 10 and that are not directories dfiles = [f for f in files if f.startswith("d") and not f.endswith("10") and not os.path.isdir(f)] print(dfiles) for f in dfiles: data = ...
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
Sys (and argparse) sys is another module for interactive with the system or to obtain information about it, in particular by means of the command line. argparse is a module for defining flags and arguments.
import sys # sys provides the simplest way to pass command line arguments to a python script print(sys.argv[0]) # argparse is more flexible but requires also more setup
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
NumPy Numpy is a module that provides a framework for numerical application. It defines new type of data highly optimized (NumPy is written in C) and provides simple interfaces for importing data from files and manipulate them. It is well integrated with the other scientific libraries for Python as it serves as base in...
# Standard import import numpy as np # Array from list num = [0,1,2] print("List:", num) x = np.array(num) print("Array:", x) y = np.random.randint(3, size = (3)) print("Random", y) z = np.array([x,y]) print("z:", z) print("Shape", z.shape) zres = z.reshape(3,2) print("z reshaped:", zres) # Attention: numpy does no...
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
NumPy offers tools for: - Linear algebra - Logic functions - Datatypes - Constant of nature - Matematical functions (also special, as Hermite, Legendre...) - Polynomials - Statistics - Sorting, searching and counting - Fourier Transform - Random generation - Integration with C/C++ and Fortran code
# Example: Polynomail x^2 + 2 x + 1 p = np.poly1d([1, 2, 1]) print(p) # Evaluate it at 1 print("p(1):", p(1)) # Find the roots print("Roots:", p.r) # Take derivative print("Deriv:", np.polyder(p))
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
Interaction with files is really simple
arr = np.random.random(10) # Prints a single column file, for arrays print many columns np.savetxt("array.dat", arr) files = os.listdir(".") print([f for f in files if f == "array.dat"]) data = np.loadtxt("array.dat") print(data)
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
It is possible to save data compressed in a gzip by appending tar.gz to the name of the file (in this case array.dat.tar.gz). REMEMBER: - To create: tar cvzf archive.tar.gz folder - To extract: tar xvzf archive.tar.gz Matplotlib Matplotlib is the tool for plotting and graphics
import matplotlib.pyplot as plt plt.plot(arr) plt.ylabel('Some numbers') plt.xlabel('An index') plt.title("The title!") plt.show()
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
Matplotlib has a seamless integration with NumPy
x = np.linspace(0,2 * np.pi, 100) y = np.sin(x) z = np.cos(x) plt.plot(x, y, "r-", x, z, "g-") plt.show()
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
Matplotlib has a great library of examples (https://matplotlib.org/examples/) that in particular contains many of the most common plots (histograms, contour, scatter, pie, ...)
# Plot of the Lorenz Attractor based on Edward Lorenz's 1963 "Deterministic # Nonperiodic Flow" publication. # http://journals.ametsoc.org/doi/abs/10.1175/1520-0469%281963%29020%3C0130%3ADNF%3E2.0.CO%3B2 # # Note: Because this is a simple non-linear ODE, it would be more easily # done using SciPy's ode solver, bu...
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
SciPy SciPy is a module that relies on NumPy and provides many ready-made tools used in science. Examples: - Optimization - Integration - Interpolation - Signal processing - Statistics Example, minimize: $f\left(\mathbf{x}\right)=\sum_{i=1}^{N-1}100\left(x_{i}-x_{i-1}^{2}\right)^{2}+\left(1-x_{i-1}\right)^{2}.$
import numpy as np from scipy.optimize import minimize def rosen(x): """The Rosenbrock function""" return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0) x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2]) res = minimize(rosen, x0, method='nelder-mead', options={'xtol': 1e-8, 'disp': True}) print(res.x)
seminar_3/Introduction to Python.ipynb
Sbozzolo/Open-Source-Tools-for-Physics
gpl-3.0
True Values The "true" values can be computed analytically in this case, so we did so. We can also compute the distribution for weighting the errors.
def compute_value_dct(theta_lst, features): return [{s: np.dot(theta, x) for s, x in features.items()} for theta in theta_lst] def compute_values(theta_lst, X): return [np.dot(X, theta) for theta in theta_lst] def compute_errors(value_lst, error_func): return [error_func(v) for v in value_lst] def rmse_f...
rlbench/off_policy_comparison-short.ipynb
rldotai/rlbench
gpl-3.0
Comparing the Errors For each algorithm, we get the associated experiment, and calculate the errors at each timestep, averaged over the runs performed with that algorithm.
# define the experiment num_states = 8 num_features = 6 num_active = 3 num_runs = 10 max_steps = 10000 # set up environment env = chicken.Chicken(num_states) # Define the target policy pol_pi = policy.FixedPolicy({s: {0: 1} for s in env.states}) # Define the behavior policy pol_mu = policy.FixedPolicy({s: {0: 1} if ...
rlbench/off_policy_comparison-short.ipynb
rldotai/rlbench
gpl-3.0
Ejercicio Weigthed Netwroks Cree una red no direccionada con los siguientes pesos. (a, b) = 0.3 (a, c) = 1.0 (a, d) = 0.9 (a, e) = 1.0 (a, f) = 0.4 (c, f) = 0.2 (b, h) = 0.2 (f, j) = 0.8 (f, g) = 0.9 (j, g) = 0.6 (g, k) = 0.4 (g, h) = 0.2 (k, h) = 1.0
# To create a weighted, undirected graph, the edges must be provided in the form: (node1, node2, weight) edges = [('a', 'b', 0.3), ('a', 'c', 1.0), ('a', 'd', 0.9), ('a', 'e', 1.0), ('a', 'f', 0.4), ('c', 'f', 0.2), ('b', 'h', 0.2), ('f', 'j', 0.8), ('f', 'g', 0.9), ('j', 'g', 0.6), ('g', 'k'...
santiagoangee/Ejercicios 1.2 Weak Ties & Random Networks.ipynb
spulido99/NetworksAnalysis
mit
Imprima la matriz de adyasencia
def adjacency_matrix(graph): keys = list(graph.keys()) keys.sort() adj_matrix = np.zeros((len(keys),len(keys))) for node, edges in graph.items(): for edge in edges: adj_matrix[keys.index(node)][keys.index(edge[0])] = edge[1] return (adj_matrix, keys) print (adjace...
santiagoangee/Ejercicios 1.2 Weak Ties & Random Networks.ipynb
spulido99/NetworksAnalysis
mit
Ejercicio Weak & Strong ties Con la misma red anterior asuma que un link debil es inferior a 0.5, cree un cรณdigo que calcule si se cumple la propiedad "strong triadic closure"
def weighted_element_neighbours(tuple_graph, element): for index, item in enumerate(tuple_graph): if element[0] == item[0]: neighbours = [i[0] for i in item[1]] return neighbours raise IndexNotFoundError('Error: the requested element was not found') def weighted_g...
santiagoangee/Ejercicios 1.2 Weak Ties & Random Networks.ipynb
spulido99/NetworksAnalysis
mit
Cambie un peso de los links anteriores para que se deje de cumplir la propiedad y calcule si es cierto. Explique. Escriba un cรณdigo que detecte puntes locales y que calcule el span de cada puente local
import copy """ The following code is thought for unweighted graphs """ edges3 = [(1,2),(1,3),(1,5),(5,6),(2,6),(2,1),(2,4)] edges4 = [('a','b'),('a','c'),('a','d'),('a','e'),('a','f'), ('b','h'),('c','d'),('c','e'),('c','f'),('d','e'), ('f','j'),('f','g'),('j','g'),('g','k'),('g','h'), ('k'...
santiagoangee/Ejercicios 1.2 Weak Ties & Random Networks.ipynb
spulido99/NetworksAnalysis
mit
Ejercicio Random Networks genere 1000 redes aleatorias N = 12, p = 1/6 y grafique la distribuciรณn del nรบmero de enlaces
import random import seaborn as sns %matplotlib inline N = 12 p = float(1)/6 def random_network_links(N, p): edges = [] for i in range(0, N-1): for j in range(i+1, N): rand = random.random() if rand <= p: edges.append((i+1,j+1)) return edges def...
santiagoangee/Ejercicios 1.2 Weak Ties & Random Networks.ipynb
spulido99/NetworksAnalysis
mit
Grafique la distribuciรณn del promedio de grados en cada una de las redes generadas del ejercicio anterior
% matplotlib inline # Transform the list of lists of edges to a list of dicts, this is done to # calculate the average degree distribution in the next methods networks1_graph = [edges_to_graph(edges) for edges in networks1] def degrees(graph): degrees = {} for node, links in graph.items(): degrees[nod...
santiagoangee/Ejercicios 1.2 Weak Ties & Random Networks.ipynb
spulido99/NetworksAnalysis
mit
Haga lo mismo para redes con 100 nodos
% matplotlib inline networks100_1 = random_networks(1000, 100, p) networks100_2 = random_networks_nx(1000,100,p) len_edges100_1 = [len_edges(i) for i in networks100_1] ax = sns.distplot(len_edges100_1) len_edges100_2 = [len(G.edges()) for G in networks100_2] sns.distplot(len_edges100_2) networks100_1_graph = [edge...
santiagoangee/Ejercicios 1.2 Weak Ties & Random Networks.ipynb
spulido99/NetworksAnalysis
mit
Ejercicio Random Networks - Componente Gigante Grafique como crece el tamaรฑo del componente mรกs grande de una red aleatoria con N=100 nodos y diferentes valores de p (grafique con promedio de grado entre 0 y 4 cada 0.05)
""" The following code snippet was taken from Mann, Edd. Depth-First Search and Breadth-First Search in Python. http://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/ """ graph5 = copy.deepcopy(graph4) graph5['m'] = {'n'} graph5['n'] = {'m'} def bfs(graph, start): visited, queue = se...
santiagoangee/Ejercicios 1.2 Weak Ties & Random Networks.ipynb
spulido99/NetworksAnalysis
mit
Grafique cuรกl es el porcentaje de nodos del componente mรกs grande para diferentes valores de p
def plot_giant_component_growth_nodes(N): p_vector = [] node_percentages = [] p = 0.0 while p <= 1: p_vector.append(p) network = random_network_links2(N,p) network = edges_to_graph(network) component = biggest_component(network) component_percentage ...
santiagoangee/Ejercicios 1.2 Weak Ties & Random Networks.ipynb
spulido99/NetworksAnalysis
mit
Identifique para que valores de p el componente mas grande esta totalmente interconectado
def identify_p_value_for_total_connection(N): p = 0.0 while p <= 1: network = random_network_links2(N,p) network = edges_to_graph(network) component = biggest_component(network) component_percentage = float(len(component))/len(network) if component_perce...
santiagoangee/Ejercicios 1.2 Weak Ties & Random Networks.ipynb
spulido99/NetworksAnalysis
mit
This problem originated from a blog post I wrote for DataCamp on graph optimization here. The algorithm I sketched out there for solving the Chinese Problem on the Sleeping Giant state park trail network has since been formalized into the postman_problems python library. I've also added the Rural Postman solver that ...
import mplleaflet import networkx as nx import pandas as pd import matplotlib.pyplot as plt from collections import Counter # can be found in https://github.com/brooksandrew/postman_problems_examples from osm2nx import read_osm, haversine from graph import contract_edges, create_rpp_edgelist from postman_problems.tes...
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Create Graph from OSM
# load OSM to a directed NX g_d = read_osm('sleepinggiant.osm') # create an undirected graph g = g_d.to_undirected()
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Adding edges that don't exist on OSM, but should
g.add_edge('2318082790', '2318082832', id='white_horseshoe_fix_1')
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Adding distance to OSM graph Using the haversine formula to calculate distance between each edge.
for e in g.edges(data=True): e[2]['distance'] = haversine(g.node[e[0]]['lon'], g.node[e[0]]['lat'], g.node[e[1]]['lon'], g.node[e[1]]['lat'])
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Create graph of required trails only A simple heuristic with a couple tweaks is all we need to create the graph with required edges: Keep any edge with 'Trail' in the name attribute. Manually remove the handful of trails that are not part of the required Giant Master route.
g_t = g.copy() for e in g.edges(data=True): # remove non trails name = e[2]['name'] if 'name' in e[2] else '' if ('Trail' not in name.split()) or (name is None): g_t.remove_edge(e[0], e[1]) # remove non Sleeping Giant trails elif name in [ 'Farmington Canal Linear Trai...
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Viz Sleeping Giant Trails All trails required for the Giant Master:
fig, ax = plt.subplots(figsize=(1,8)) pos = {k: (g_t.node[k]['lon'], g_t.node[k]['lat']) for k in g_t.nodes()} nx.draw_networkx_edges(g_t, pos, width=2.5, edge_color='black', alpha=0.7) mplleaflet.save_html(fig, 'maps/sleepinggiant_trails_only.html')
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
<iframe src="https://cdn.rawgit.com/brooksandrew/postman_problems_examples/master/sleepinggiant/maps/sleepinggiant_trails_only.html" height="400" width="750"></iframe> Connect Edges In order to run the RPP algorithm from postman_problems, the required edges of the graph must form a single connected component. We're a...
edge_ids_to_add = [ '223082783', '223077827', '40636272', '223082785', '222868698', '223083721', '222947116', '222711152', '222711155', '222860964', '223083718', '222867540', 'white_horseshoe_fix_1' ] edge_ids_to_remove = [ '17220599' ]
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Add attributes for supplementary edges
for e in g.edges(data=True): way_id = e[2].get('id').split('-')[0] if way_id in edge_ids_to_add: g_t.add_edge(e[0], e[1], **e[2]) g_t.add_node(e[0], lat=g.node[e[0]]['lat'], lon=g.node[e[0]]['lon']) g_t.add_node(e[1], lat=g.node[e[1]]['lat'], lon=g.node[e[1]]['lon']) if way_id in edg...
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Ensuring that we're left with one single connected component:
len(list(nx.connected_components(g_t)))
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Viz Connected Component The map below visualizes the required edges and nodes of interest (intersections and dead-ends where degree != 2):
fig, ax = plt.subplots(figsize=(1,12)) # edges pos = {k: (g_t.node[k].get('lon'), g_t.node[k].get('lat')) for k in g_t.nodes()} nx.draw_networkx_edges(g_t, pos, width=3.0, edge_color='black', alpha=0.6) # nodes (intersections and dead-ends) pos_x = {k: (g_t.node[k]['lon'], g_t.node[k]['lat']) for k in g_t.nodes()...
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
<iframe src="https://cdn.rawgit.com/brooksandrew/postman_problems_examples/master/sleepinggiant/maps/trails_only_intersections.html" height="400" width="750"></iframe> Viz Trail Color Because we can and it's pretty.
name2color = { 'Green Trail': 'green', 'Quinnipiac Trail': 'blue', 'Tower Trail': 'black', 'Yellow Trail': 'yellow', 'Red Square Trail': 'red', 'White/Blue Trail Link': 'lightblue', 'Orange Trail': 'orange', 'Mount Carmel Avenue': 'black', 'Violet Trail': 'violet', 'blue Trail': ...
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
<iframe src="https://cdn.rawgit.com/brooksandrew/postman_problems_examples/master/sleepinggiant/maps/trails_only_color.html" height="400" width="750"></iframe> Check distance This is strikingly close (within 0.25 miles) to what I calculated manually with some guess work from the SG trail map on the first pass at this ...
print('{:0.2f} miles of required trail.'.format(sum([e[2]['distance']/1609.34 for e in g_t.edges(data=True)])))
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Contract Edges We could run the RPP algorithm on the graph as-is with >5000 edges. However, we can simplify computation by contracting edges into logical trail segments first. More details on the intuition and methodology in the 50 states post.
print('Number of edges in trail graph: {}'.format(len(g_t.edges()))) # intialize contracted graph g_tc = nx.MultiGraph() # add contracted edges to graph for ce in contract_edges(g_t, 'distance'): start_node, end_node, distance, path = ce contracted_edge = { 'start_node': start_node, ...
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Edge contraction reduces the number of edges fed to the RPP algorithm by a factor of ~40.
print('Number of edges in contracted trail graoh: {}'.format(len(g_tc.edges())))
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Solve CPP First, let's see how well the Chinese Postman solution works. Create CPP edgelist
# create list with edge attributes and "from" & "to" nodes tmp = [] for e in g_tc.edges(data=True): tmpi = e[2].copy() # so we don't mess w original graph tmpi['start_node'] = e[0] tmpi['end_node'] = e[1] tmp.append(tmpi) # create dataframe w node1 and node2 in order eldf = pd.DataFrame(tmp) el...
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Start node The route is designed to start at the far east end of the park on the Blue trail (node '735393342'). While the CPP and RPP solutions will return a Eulerian circuit (loop back to the starting node), we could truncate this last long doublebacking segment when actually running the route <img src="https://githu...
circuit_cpp, gcpp = cpp(elfn, start_node='735393342')
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
CPP Stats (distances in meters)
cpp_stats = calculate_postman_solution_stats(circuit_cpp) cpp_stats print('Miles in CPP solution: {:0.2f}'.format(cpp_stats['distance_walked']/1609.34))
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Solve RPP With the CPP as benchmark, let's see how well we do when we allow for optional edges in the route.
%%time dfrpp = create_rpp_edgelist(g_tc, graph_full=g, edge_weight='distance', max_distance=2500)
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Required vs optional edge counts (1=required and 0=optional)
Counter( dfrpp['required'])
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Solve RPP
# create mockfilename elfn = create_mock_csv_from_dataframe(dfrpp) %%time # solve circuit_rpp, grpp = rpp(elfn, start_node='735393342')
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
RPP Stats (distances in meters)
rpp_stats = calculate_postman_solution_stats(circuit_rpp) rpp_stats
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Leveraging the optional roads and trails, we're able to shave a about 3 miles off the CPP route. Total mileage checks in at 30.71, just under a 50K (30.1 miles).
print('Miles in RPP solution: {:0.2f}'.format(rpp_stats['distance_walked']/1609.34))
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Viz RPP Solution
# hack to convert 'path' from str back to list. Caused by `create_mock_csv_from_dataframe` for e in circuit_rpp: if type(e[3]['path']) == str: exec('e[3]["path"]=' + e[3]["path"])
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Create graph from RPP solution
g_tcg = g_tc.copy() # calc shortest path between optional nodes and add to graph for e in circuit_rpp: granular_type = 'trail' if e[3]['required'] else 'optional' # add granular optional edges to g_tcg path = e[3]['path'] for pair in list(zip(path[:-1], path[1:])): if (g_tcg.has_edge(pair[...
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Viz: RPP optional edges The RPP algorithm picks up some logical shortcuts using the optional trails and a couple short stretches of road. <font color='black'>black</font>: required trails <font color='blue'>blue</font>: optional trails and roads
fig, ax = plt.subplots(figsize=(1,8)) pos = {k: (g_tcg.node[k].get('lon'), g_tcg.node[k].get('lat')) for k in g_tcg.nodes()} el_opt = [e for e in g_tcg.edges(data=True) if e[2].get('granular_type') == 'optional'] nx.draw_networkx_edges(g_tcg, pos, edgelist=el_opt, width=6.0, edge_color='blue', alpha=1.0) el_tr ...
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
<iframe src="https://cdn.rawgit.com/brooksandrew/postman_problems_examples/master/sleepinggiant/maps/rpp_solution_opt_edges.html" height="400" width="750"></iframe> Viz: RPP edges counts
## Create graph directly from rpp_circuit and original graph w lat/lon (g) color_seq = [None, 'black', 'magenta', 'orange', 'yellow'] grppviz = nx.MultiGraph() for e in circuit_rpp: for n1, n2 in zip(e[3]['path'][:-1], e[3]['path'][1:]): if grppviz.has_edge(n1, n2): grppviz[n1][n2][0]['linewidt...
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
Edge walks per color: <font color='black'>black</font>: 1 <br> <font color='magenta'>magenta</font>: 2 <br>
fig, ax = plt.subplots(figsize=(1,10)) pos = {k: (grppviz.node[k]['lon'], grppviz.node[k]['lat']) for k in grppviz.nodes()} e_width = [e[2]['linewidth'] for e in grppviz.edges(data=True)] e_color = [e[2]['color_cnt'] for e in grppviz.edges(data=True)] nx.draw_networkx_edges(grppviz, pos, width=e_width, edge_color=...
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit
<iframe src="https://cdn.rawgit.com/brooksandrew/postman_problems_examples/master/sleepinggiant/maps/rpp_solution_edge_cnts.html" height="400" width="750"></iframe> Create geojson solution Used for the forthcoming D3 route animation.
geojson = {'features':[], 'type': 'FeatureCollection'} time = 0 path = list(reversed(circuit_rpp[0][3]['path'])) for e in circuit_rpp: if e[3]['path'][0] != path[-1]: path = list(reversed(e[3]['path'])) else: path = e[3]['path'] for n in path: time += 1 doc = {'type': ...
_ipynb/2017-12-01-sleeping-giant-rural-postman-problem.ipynb
brooksandrew/simpleblog
mit