markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Numpy arrays use numpy arrays whenever possible (efficiency) Any numpy arrays that are part of the serialized object will not be copied out of the object store. They will remain in the object store and the resulting deserialized object will simply have a pointer to the relevant place in the object store’s memory. Since...
x_id = ray.put(1) ray.get(x_id) # 1
Archive/The Ray API.ipynb
Bowenislandsong/Distributivecom
gpl-3.0
The main reason to use ray.put is that you want to pass the same large object into a number of tasks. By first doing ray.put and then passing the resulting object ID into each of the tasks, the large object is copied into the object store only once, whereas when we directly pass the object in, it is copied multiple tim...
import numpy as np @ray.remote def f(x): pass x = np.zeros(10 ** 6) # Alternative 1: Here, x is copied into the object store 10 times. [f.remote(x) for _ in range(10)] # Alternative 2: Here, x is copied into the object store once. x_id = ray.put(x) [f.remote(x_id) for _ in range(10)]
Archive/The Ray API.ipynb
Bowenislandsong/Distributivecom
gpl-3.0
Note that ray.put is called under the hood in a couple situations. It is called on the values returned by a task. It is called on the arguments to a task, unless the arguments are Python primitives like integers or short strings, lists, tuples, or dictionaries. ray.put(value, worker= < ray.worker.Worker object >) Sto...
import time import numpy as np @ray.remote def f(n): time.sleep(n) return n # # Start 3 tasks with different durations. # results = [f.remote(i) for i in range(3)] # # Block until 2 of them have finished. # ready_ids, remaining_ids = ray.wait(results, num_returns=2) # Start 5 tasks with different durations. ...
Archive/The Ray API.ipynb
Bowenislandsong/Distributivecom
gpl-3.0
It is easy to use this construct to create an infinite loop in which multiple tasks are executing, and whenever one task finishes, a new one is launched.
@ray.remote def f(): return 10 # Start 5 tasks. remaining_ids = [f.remote() for i in range(5)] #print(ray.get(remaining_ids)) ''' The following few lines is for testing the behavior of the wait method without specifying the number of returning object IDs. Comment it before running the for loop in the original docu...
Archive/The Ray API.ipynb
Bowenislandsong/Distributivecom
gpl-3.0
ray.wait (object_ids, num_returns=1, timeout=None, worker= < ray.worker.Worker object > ) Return a list of IDs that are ready and a list of IDs that are not. If timeout is set, the function returns either when the requested number of IDs are ready or when the timeout is reached, whichever occurs first. If it is not se...
@ray.remote def f(): raise Exception("This task failed!!") f.remote() # An error message will be printed in the background. # Wait for the error to propagate to Redis. import time time.sleep(1) ray.error_info() # This returns a list containing the error message.
Archive/The Ray API.ipynb
Bowenislandsong/Distributivecom
gpl-3.0
Edit-run-repeat: Stopping the cycle of pain 1. No more docs-guessing
df = pd.read_csv("../data/water-pumps.csv", index=0) df.head(1) pd.read_csv? df = pd.read_csv("../data/water-pumps.csv", index_col=0, parse_dates="date_recorded") df.head(1)
notebooks/edit-run-repeat.ipynb
pjbull/data-science-is-software
mit
2. No more copy pasta Don't repeat yourself.
plot_data = df['construction_year'] plot_data = plot_data[plot_data != 0] sns.kdeplot(plot_data, bw=0.1) plt.show() plot_data = df['longitude'] plot_data = plot_data[plot_data != 0] sns.kdeplot(plot_data, bw=0.1) plt.show() plot_data = df['amount_tsh'] plot_data = plot_data[plot_data > 20000] sns.kdeplot(plot_data, b...
notebooks/edit-run-repeat.ipynb
pjbull/data-science-is-software
mit
3. No more guess-and-check Use pdb the Python debugger to debug inside a notebook. Key commands are: p: Evaluate and print Python code w: Where in the stack trace am I? u: Go up a frame in the stack trace. d: Go down a frame in the stack trace. c: Continue execution q: Stop execution There are two ways to ac...
kde_plot(df, 'date_recorded') # "1" turns pdb on, "0" turns pdb off %pdb 1 kde_plot(df, 'date_recorded') # turn off debugger %pdb 0
notebooks/edit-run-repeat.ipynb
pjbull/data-science-is-software
mit
4. No more "Restart & Run All" assert is the poor man's unit test: stops execution if condition is False, continues silently if True
def gimme_the_mean(series): return np.mean(series) assert gimme_the_mean([0.0]*10) == 0.0 data = np.random.normal(0.0, 1.0, 1000000) assert gimme_the_mean(data) == 0.0 np.testing.assert_almost_equal(gimme_the_mean(data), 0.0, decimal=1)
notebooks/edit-run-repeat.ipynb
pjbull/data-science-is-software
mit
Download weather data
start_date = date(2012, 7, 1) end_date = date(2016, 2, 29) # data = pd.DataFrame() frames = [] url_template = 'https://www.wunderground.com/history/airport/KNYC/%s/%s/%s/DailyHistory.html?req_city=New+York&req_state=NY&req_statename=New+York&reqdb.zip=10001&reqdb.magic=4&reqdb.wmo=99999&format=1.csv' month = "" for ...
project/Weather Data.ipynb
masve/saav-deliveries
mit
Cleaning the weather dataset Convert weather DateUTC to local time
from datetime import datetime from dateutil import tz weather = pd.read_csv('datasets/weather_data_nyc_clean.csv') def UTCtoActual(utcDate): from_zone = tz.gettz('UTC') to_zone = tz.gettz('America/New_York') utc = datetime.strptime(utcDate.DateUTC, '%m/%d/%Y %H:%M:%S')\ .replace(tzi...
project/Weather Data.ipynb
masve/saav-deliveries
mit
Merge weather and NYPD MVC datasets
incidents = pd.read_csv('datasets/NYPD_Motor_Vehicle_Collisions.csv') weather = pd.read_csv('datasets/weather_data_nyc_clean2.csv') weather.head(1) weather[(weather.Year == 2015) & (weather.Month == 11) & (weather.Day == 27)] features0 = ['Conditions', 'TemperatureC'] features = ['Conditions', 'Precipitationmm',\ ...
project/Weather Data.ipynb
masve/saav-deliveries
mit
Make some nice data analysis
# Read dataset incidents = pd.read_csv('datasets/NYPD_Motor_Vehicle_Collisions_weather3.csv') # Filter 2016 incidents incidents = incidents[(incidents.DATE.str.split('/').str.get(2) != '2016') & (pd.notnull(incidents.Conditions))] # Distribution of incidents by weather conditions ys = [] xs = []...
project/Weather Data.ipynb
masve/saav-deliveries
mit
Now lets try to find out if there are any condition that causes more incidents than others. We do this by plotting out heatmaps to get an idea of the distributions in the NYC area
def plot_zip_weather(condition, data): ys = [] xs = [] for z in data['ZIP CODE'].unique(): mask = (data['ZIP CODE'] == z) filtered_incidents = data[mask] ys.append(len(filtered_incidents.index)) xs.append(z) df = pd.DataFrame(pd.Series(ys, index=xs, name="%s incidents b...
project/Weather Data.ipynb
masve/saav-deliveries
mit
Finding the ratio between conditions that resulted in an incident. Borough level
# What is the probability of an incident based on the weather condition? # Normalize incidents based on the conditions. from collections import Counter ConditionIncidentCounter = Counter(incidents.Conditions.values) p_incident = {} for k,v in ConditionIncidentCounter.most_common(): p_incident[k] = v/len(incidents...
project/Weather Data.ipynb
masve/saav-deliveries
mit
Let's try to look at zip codes in Brooklyn only
# What is the probability of an incident based on the weather condition? # Normalize incidents based on the conditions. from collections import Counter borough = incidents[incidents.BOROUGH == 'MANHATTAN'] ConditionIncidentCounter = Counter(borough.Conditions.values) p_incident = {} for k,v in ConditionIncidentCounte...
project/Weather Data.ipynb
masve/saav-deliveries
mit
Looking at weather based causes
# Read dataset incidents = pd.read_csv('datasets/NYPD_Motor_Vehicle_Collisions_weather4.csv') # Filter 2016 incidents incidents = incidents[(incidents.DATE.str.split('/').str.get(2) != '2016') & (pd.notnull(incidents.Conditions))] def count_contributing(cont): temp = incidents[(incidents['CO...
project/Weather Data.ipynb
masve/saav-deliveries
mit
There seems to be a lot of incidents caused by slippery pavement. Let's look at the weather conditions for those incidents.
weather_incidents = incidents[(incidents['CONTRIBUTING FACTOR VEHICLE 1'] == 'Pavement Slippery') | \ (incidents['CONTRIBUTING FACTOR VEHICLE 2'] == 'Pavement Slippery') | \ (incidents['CONTRIBUTING FACTOR VEHICLE 3'] == 'Pavement Slippery') | \ ...
project/Weather Data.ipynb
masve/saav-deliveries
mit
Okay, the overcast and clear weather still are the top 2. The assumption that the type of incidents are caused by weather conditions might still hold true. It could be that top 2 are caused by pavement conditions independent of the weather, such as water or oil on the roads. In any case, lets try to plot out where thes...
def draw_dot(data, type_color): bbox = BoundingBox(north=incidents.LATITUDE.max()-0.055,\ west=incidents.LONGITUDE.min()+0.055,\ south=incidents.LATITUDE.min()-0.055,\ east=incidents.LONGITUDE.max()+0.055) gridDots = {'lat': data.LATITUDE.values.tolist(), 'lon':...
project/Weather Data.ipynb
masve/saav-deliveries
mit
Looking at the intersections we can find those most dangerous based on the number of incidents happening there which are in some way caused by slippery pavement.
top10 = weather_incidents.LOCATION.value_counts()[:20] top10.to_csv('datasets/top20slippery')
project/Weather Data.ipynb
masve/saav-deliveries
mit
Ignoring incidents happening outside intersections the top 3 looks like this: 40.5732661, -74.1469613 (Google Street View) 40.8726198, -73.9046763 (Google Street View) 40.7460347, -73.9344002 (Google Street View) What we find is - that atleast for top 3 - incidents occouring because of slippery pavement happens becau...
locations = weather_incidents[weather_incidents.LOCATION.isin(top10.index)].drop_duplicates('LOCATION','first')\ [['TIME','BOROUGH','ZIP CODE','LATITUDE','LONGITUDE','LOCATION','ON STREET NAME','CROSS STREET NAME']] loca = locations.copy() def m(r): return top10[top10.index == r.LOCATION].iloc[0] loca['COUNT']...
project/Weather Data.ipynb
masve/saav-deliveries
mit
fin
lightsnow = incidents[incidents['Conditions'] == 'Light Snow'] print "Accidents happening because of light snow: %s" % str(lightsnow.size) print "Injuries: %s" % lightsnow['NUMBER OF PERSONS INJURED'].sum() print "Killed: %s" % lightsnow['NUMBER OF PERSONS KILLED'].sum() print "Top intersections:" lightsnow.LOCATION....
project/Weather Data.ipynb
masve/saav-deliveries
mit
If that looks confusing, don't worry! It's perfectly normal as that's your first example of iteration. Let's take a deeper look: - First, we defined a variable counter and we initialised it with a value of 1. - Then we used the while statement to check if the value of counter was less than or equal to 10. - Since th...
otherCounter = 1 while ??? <= ???: print("This is an odd number: " + str(???)) otherCounter += 2 otherCounter = 1 while otherCounter <= 10: print("This is an odd number: " + str(otherCounter)) otherCounter += 2
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
You can also run while loops decrementally until they meet a certain condition (run the code block to see how):
myThirdCounter = 10 while myThirdCounter >= 0: print("Decrementing counter: " + str(myThirdCounter)) myThirdCounter -= 1
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
Break and Continue To prematurely interrupt the execution of a while loop (before the while condition become false) you can use the break statement
myFourthCounter = 1 while myFourthCounter < 10: print(str(myFourthCounter)) myFourthCounter += 1 if myFourthCounter == 5: print("Time to escape this madness!") break
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
Nesting Conditions That last example shows that you can 'nest' an if (if myFourthCounter) inside of a while loop -- this approach allows us to add much more complex logic to our code than we could before. Here's an example, but see if you can figure out what it will print out (and how) before you run the code block!
i=0 while True: i += 1 if i % 2 != 0: print( str(i) + " is odd.") if i == 9: print("\t i is 9") else: print("\t i is not 9") else: print( str(i) + " is even.") if i % 4 == 0: print("\t i is divisible by 4.") elif i == 8: ...
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
In terms of explanation: Python is going to keep running the code (while True) until it is told to stop by a break (which happens at i == 21). In fact, if you remove the break then you will crash jupyter because the computer will print out every even number to infinity (which the computer can’t handle because it runs...
# So use i and j as counters because # this is a stylistic convention and # helps you to to write more concise code # (and be constructively lazy). i = 0 while True: i += 1 if i % 2 != 0: print(i) else: continue if i % 7 == 0: print("WOOT!") if i == 25...
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
How would you change the code above so that it printed only the odd number or 'WOOT!', but not both? In other words, change the code so that it prints: 1 3 5 WOOT! 9 11 13 15 17 19 WOOT!
i = 0 while True: i += 1 if i % 2 != 0: if i % 7 == 0: print("WOOT!") else: print(i) if i == 25: break print("Done!")
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
A challenge for you! Now, replace the ??? in the code below and use it to print only even numbers less than 22.
i = 0 while True: i += 1 if i % 2 != 0: continue if i == ???: break print(???) print("Done!") i = 0 while True: i += 1 if i % 2 != 0: continue if i == 22: break print(i) print("Done!")
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
Iterating over a List What you just saw with the while statement is a way of iterating: a way of repeating a certain set of instruction until a given condition is met. We can use to our advantage not only to print stuff, but also to 'iterate over' the elements in a list:
# remember our friends, the british computer scientists? britishCompList = ["babbage", "lovelace", "turing"] # this is the condition python is going to check against stoppingCondition = len(britishCompList) counter = 1 while counter < stoppingCondition: print(britishCompList[counter] + " was a british computer sc...
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
Wow, lot of stuff in that chunk of code, eh? Well, once again, take a deep breath and go through it line by line. The important bits are: - notice that this time we used the len of britishCompList as stopping condition, instead of specifying ourselves a number. - we accessed the items in the list with a regular index,...
#your code here counter = 0 # To include Babbage, we need to start counter from 0 while counter < len(britishCompList): print(britishCompList[counter] + " was a british computer scientist") # don't forget to increment the counter!!! counter += 1
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
Other Overlooked Computers If you think that being skipped over in the loop above was tough for old Babbage, then perhaps you might be interested to hear about the history of the NASA 'computers' who helped put a man on the moon and are only getting a film made about them in 2016. A challenge for you! Complete the fol...
counter = ??? nonBritishProgrammers = ["Torvald", "Knuth", "Swartz"] stoppingCondition = len(???) while counter < stoppingCondition : print("This is a computer genius too: " + nonBritishProgrammers[counter]) # always remember to increment the counter!!! counter += 1 counter = 0 nonBritishProgrammers = ["...
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
CAVEAT: An important condition to remember when iterating over a list is thus that lists are zero-indexed! If if you start you counter from 1 you will certainly miss the first item in the list (which has an index of 0). But watch out! There's more: Another challenge for you! Can you guess why I needed to subtract -1 t...
counter = 0 nonBritishProgrammers = ["Torvald", "Knuth", "Swartz"] stoppingCondition = len(nonBritishProgrammers) -1 while counter <= stoppingCondition : print("These are geniuses too! " + nonBritishProgrammers[counter]) # always remember to increment the counter!!! counter +=1
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
We can see that from the code above the while condition is slightly different: while counter &lt; stoppingCondition : versus while counter &lt;= stoppingCondition Because len counts the number of elements, if we use &lt;= we will access the variable counter at each iteration counter with the value of 0, 1, 2, 3. Th...
for programmer in britishCompList: print(programmer)
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
As you can see, the for loop statement is much more concise: you simply tell Python to repeat a certain instruction (print the list item in this example) for EVERY ITEM in A SEQUENCE. The sequence here is the list of British computer scientists britishCompList created in the code block above. Now, Python will stop auto...
# WHILE LOOP whileCounter = 0 myList = [0,1,2,3,4] stoppingCondition = len(myList) while whileCounter < stoppingCondition: print("Element number: " + str(myList[whileCounter])) whileCounter +=1 # FOR LOOP for element in myList: print("Element number: " + str(element))
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
SIDENOTE: See how the value of myList[whileCounter] and that of element in the two loops are the same? That's because Python is doing the indexing job for you behind the scenes. A challenge for you! Print only the odd numbers in the list. HINT: remember the modulo operator?
numbers = [1,2,3,4,5,6,7,8,9,10] for n in numbers: if (???): print(n) numbers = [1,2,3,4,5,6,7,8,9,10] for n in numbers: if (n % 2 != 0): print(n)
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
Now, as we are lazy programmers, let's repeat the above example combining the range function with a for loop. It will save us the hassle of typing all those numbers!
for i in range(10): if (i % 2 != 0): print(i)
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
Cool, we have seen how to iterate over a list, but what about a dictionary? Well, if you remember we said that you might think of a dictionary as a kind of list where each element isn't indexed by an integer, but rather by a unique identifier (key). Hence, as with lists where we iterate over the indexes, with dictionar...
programmers = { "Charles": "Babbage", "Ada": "Lovelace", "Alan":"Turing" } for k in programmers: print(k)
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
NOTE: I've used the variable k. This is simply an arbitrary word that I've choosen and not some kind of special variable. You could have used anyRandomNameForWhatMatters. What if you want to retrieve the values? In that case you should use not only two variables, (the first for the keys and the second for the values) ...
for k,v in programmers.items(): print("this is the value: \'" + v + "\' for the key: \'" + k +"\'")
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
A Challenge for you! Iterate over the GeoJSON marker and print its "properties".
KCL_marker = { "type": "Feature", "properties": { "marker-color": "#7e7e7e", "marker-size": "medium", "marker-symbol": "", "name": "KCL" }, "geometry": { "type": "Point", "coordinates": [ -0.11630058288574219, 51.51135999349117 ...
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
Very good! Let's summarise some facts about loops: you can increment the counter but also decrement it (effectively counting down!) the increment doesn't need to be 1 every the time (you can increment by 2, 50, whatever..) don’t forget to to indent the block of code after the colon! Code (Applied Geo-example) The geo...
# define a new featureCollection: it is basically a very fancy dictionary # to which we are going to add new 'features' (which are points on a map # but represented as *data* by a dictionary). We need to add one feature # at a time when building our transect... # initial coordinate list init_coords = [-0.0200, 51.592] ...
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
This output on its own makes very little sense, but it's actually a real world data structure called JSON. Below we use a handy library (that you might not yet have installed on your computer) to turn that JSON into something easier to read, and then we'll see how you can use it!
import json parsed = json.loads(str(transect).replace("\'", "\"")) print(json.dumps(parsed, indent=4)) from ipyleaflet import Map, GeoJSON, basemaps m = Map(center = (51.51, -0.10), zoom=10, min_zoom=5, max_zoom=20, basemap=basemaps.OpenTopoMap) geo = GeoJSON(data=parsed) m.add_layer(geo) m
notebook-09-iteration.ipynb
kingsgeocomp/code-camp
mit
Run the simulation while storing all its iterations to an HDF file. The first parameter is the path where the HDF file should be stored. The second parameter determines which properties will be stored. When its value is 'input', only Input plasma properties will be stored. The third parameter, hdf_last_only, if True wi...
simulation.legacy_run_simulation(model, '/tmp/full_example.hdf', 'full', hdf_last_only=False)
docs/notebooks/to_hdf.ipynb
orbitfold/tardis
bsd-3-clause
Open the stored HDF file with pandas and print its structure.
import pandas as pd data = pd.HDFStore('/tmp/full_example.hdf') print data
docs/notebooks/to_hdf.ipynb
orbitfold/tardis
bsd-3-clause
Access model.plasma.density of the 9th simulation, which is a one-dimensional array
print data['/simulation9/model/plasma/density']
docs/notebooks/to_hdf.ipynb
orbitfold/tardis
bsd-3-clause
Scalars are stored in a scalars pandas.Series for every module. For example to access model.t_inner of the 9th iteration of the simulation, one would need to do the following. Note: Quantities are always stored as their SI values.
print data['/simulation9/model/scalars']['t_inner']
docs/notebooks/to_hdf.ipynb
orbitfold/tardis
bsd-3-clause
Breakdown of the various to_hdf methods Every module in TARDIS has its own to_hdf method responsible to store its own data to an HDF file. Plasma The following call will store every plasma property to /tmp/plasma_output.hdf under /parent/plasma
model.plasma.to_hdf('/tmp/plasma_output.hdf', path='parent') import pandas with pandas.HDFStore('/tmp/plasma_output.hdf') as data: print data
docs/notebooks/to_hdf.ipynb
orbitfold/tardis
bsd-3-clause
Plasma's to_hdf method can also accept a collection parameter which can specify which types of plasma properties will be stored. For example if we wanted to only store Input plasma properties, we would do the following:
from tardis.plasma.properties.base import Input model.plasma.to_hdf('/tmp/plasma_input_output.hdf', collection=[Input]) import pandas with pandas.HDFStore('/tmp/plasma_input_output.hdf') as data: print data
docs/notebooks/to_hdf.ipynb
orbitfold/tardis
bsd-3-clause
Model The following call will store properties of the Radial1DModel to /tmp/model_output.hdf under /model. Additionally, it will automatically call model.plasma.to_hdf, since plasma is also a property of the model.
model.to_hdf('/tmp/model_output.hdf')
docs/notebooks/to_hdf.ipynb
orbitfold/tardis
bsd-3-clause
MontecarloRunner The following call will store properties of the MontecarloRunner to /tmp/runner_output.hdf under /runner
simulation.runner.to_hdf('/tmp/runner_output.hdf') import pandas with pandas.HDFStore('/tmp/runner_output.hdf') as data: print data
docs/notebooks/to_hdf.ipynb
orbitfold/tardis
bsd-3-clause
ニューラル画風変換 <table class="tfo-notebook-buttons" align="left"> <td> <img src="https://www.tensorflow.org/images/tf_logo_32px.png"><a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ja/tutorials/generative/style_transfer.ipynb">TensorFlow.org で表示</a> </td> <td> <img ...
import os import tensorflow as tf # Load compressed models from tensorflow_hub os.environ['TFHUB_MODEL_LOAD_FORMAT'] = 'COMPRESSED' import IPython.display as display import matplotlib.pyplot as plt import matplotlib as mpl mpl.rcParams['figure.figsize'] = (12, 12) mpl.rcParams['axes.grid'] = False import numpy as np...
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
画像をダウンロードして、画風画像とコンテンツ画像を選択します。
content_path = tf.keras.utils.get_file('YellowLabradorLooking_new.jpg', 'https://storage.googleapis.com/download.tensorflow.org/example_images/YellowLabradorLooking_new.jpg') style_path = tf.keras.utils.get_file('kandinsky5.jpg','https://storage.googleapis.com/download.tensorflow.org/example_images/Vassily_Kandinsky%2C...
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
入力を視覚化する 画像を読み込んで、その最大寸法を 512 ピクセルに制限する関数を定義します。
def load_img(path_to_img): max_dim = 512 img = tf.io.read_file(path_to_img) img = tf.image.decode_image(img, channels=3) img = tf.image.convert_image_dtype(img, tf.float32) shape = tf.cast(tf.shape(img)[:-1], tf.float32) long_dim = max(shape) scale = max_dim / long_dim new_shape = tf.cast(shape * scal...
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
画像を表示する単純な関数を作成します。
def imshow(image, title=None): if len(image.shape) > 3: image = tf.squeeze(image, axis=0) plt.imshow(image) if title: plt.title(title) content_image = load_img(content_path) style_image = load_img(style_path) plt.subplot(1, 2, 1) imshow(content_image, 'Content Image') plt.subplot(1, 2, 2) imshow(style...
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
TF-Hub を使用した高速画風変換 このチュートリアルでは、画像コンテンツを特定の画風に最適化する、元の画風変換アルゴリズムを実演します。詳細に踏み込む前に、TensorFlow Hub が何を行うのかを確認しましょう。
import tensorflow_hub as hub hub_model = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2') stylized_image = hub_model(tf.constant(content_image), tf.constant(style_image))[0] tensor_to_image(stylized_image)
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
コンテンツと画風の表現を定義する モデルの中間レイヤーを使用して、画像のコンテンツと画風の表現を取得します。ネットワークの入力レイヤーから数えて最初のいくつかのレイヤーアクティベーションは、エッジやテクスチャといった低レベルの特徴を表します。ネットワークをさらに深く探ると、最後のいくつかのレイヤーは、車輪や目といった高レベルの特徴を表します。この場合、VGG19 ネットワークアーキテクチャという、事前トレーニング済みの画像分類ネットワークを使用しています。中間レイヤーは、画像からコンテンツと画風の表現を定義するために必要となるレイヤーです。入力画像については、これらの中間レイヤーにある、対応する画風とコンテンツターゲットの表現に一致...
x = tf.keras.applications.vgg19.preprocess_input(content_image*255) x = tf.image.resize(x, (224, 224)) vgg = tf.keras.applications.VGG19(include_top=True, weights='imagenet') prediction_probabilities = vgg(x) prediction_probabilities.shape predicted_top_5 = tf.keras.applications.vgg19.decode_predictions(prediction_pro...
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
分類ヘッドを除く VGG19 を読み込み、レイヤー名をリストします。
vgg = tf.keras.applications.VGG19(include_top=False, weights='imagenet') print() for layer in vgg.layers: print(layer.name)
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
画像の画風とコンテンツを表現する中間レイヤーをネットワークから選択します。
content_layers = ['block5_conv2'] style_layers = ['block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'] num_content_layers = len(content_layers) num_style_layers = len(style_layers)
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
画風とコンテンツ用の中間レイヤー では、事前トレーニング済みの画像分類ネットワーク内のこれらの中間出力によって画風とコンテンツの表現を定義できるのはなぜでしょうか。 大まかに言えば、ネットワークが画像分類を行うには(このネットワークがトレーニングされた目的)、画像を理解している必要があります。これには、生の画像を入力ピクセルとして取り、生の画像ピクセルを、画像内に存在する特徴の複雑な理解への変換する内部表現が必要です。 これが、畳み込みニューラルネットワークがうまく一般化できる理由でもあります。不変性をキャプチャして、バックグラウンドノイズやその他の邪魔なものにとらわれない特徴をクラス内(猫と犬など)定義することができます。そのため...
def vgg_layers(layer_names): """ Creates a vgg model that returns a list of intermediate output values.""" # Load our model. Load pretrained VGG, trained on imagenet data vgg = tf.keras.applications.VGG19(include_top=False, weights='imagenet') vgg.trainable = False outputs = [vgg.get_layer(name).output for...
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
モデルを作成するには、以下のように行います。
style_extractor = vgg_layers(style_layers) style_outputs = style_extractor(style_image*255) #Look at the statistics of each layer's output for name, output in zip(style_layers, style_outputs): print(name) print(" shape: ", output.numpy().shape) print(" min: ", output.numpy().min()) print(" max: ", output.nu...
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
画風を計算する 画像のコンテンツは、中間特徴量マップの値によって表現されます。 これにより、画像の画風は、異なる特徴量マップの平均と相関によって表現できるようになります。各場所での特徴ベクトルの外積を取り、その外積をすべての場所で平均することにより、この情報を含むグラム行列を計算します。特定のレイヤーのグラム行列は以下のように計算できます。 $$G^l_{cd} = \frac{\sum_{ij} F^l_{ijc}(x)F^l_{ijd}(x)}{IJ}$$ これは、tf.linalg.einsum 関数を使用して、明確に実装することができます。
def gram_matrix(input_tensor): result = tf.linalg.einsum('bijc,bijd->bcd', input_tensor, input_tensor) input_shape = tf.shape(input_tensor) num_locations = tf.cast(input_shape[1]*input_shape[2], tf.float32) return result/(num_locations)
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
画風とコンテンツを抽出する 画風とコンテンツのテンソルを返すモデルを構築します。
class StyleContentModel(tf.keras.models.Model): def __init__(self, style_layers, content_layers): super(StyleContentModel, self).__init__() self.vgg = vgg_layers(style_layers + content_layers) self.style_layers = style_layers self.content_layers = content_layers self.num_style_layers = len(style_l...
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
画像に対して呼び出されると、このモデルは style_layers のグラム行列(画風)と content_layers のコンテンツを返します。
extractor = StyleContentModel(style_layers, content_layers) results = extractor(tf.constant(content_image)) print('Styles:') for name, output in sorted(results['style'].items()): print(" ", name) print(" shape: ", output.numpy().shape) print(" min: ", output.numpy().min()) print(" max: ", output.num...
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
勾配下降法を実行する この画風とコンテンツの抽出器を使用して、画風変換アルゴリズムを実装できるようになりました。各ターゲットに相対する画像の出力の平均二乗誤差を計算し、これらの損失の加重和を取って行います。 画風とコンテンツターゲット値を設定します。
style_targets = extractor(style_image)['style'] content_targets = extractor(content_image)['content']
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
最適化する画像を含めて tf.Variable を定義します。これを素早く行うには、コンテンツ画像で初期化します(tf.Variable は、コンテンツ画像を同じ形状である必要があります)。
image = tf.Variable(content_image)
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
これはフローと画像であるため、ピクセル値を 0 から 1 に維持する関数を定義します。
def clip_0_1(image): return tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=1.0)
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
オプティマイザを作成します。論文では、LBFGS が推奨されていますが、Adam も使用できます。
opt = tf.optimizers.Adam(learning_rate=0.02, beta_1=0.99, epsilon=1e-1)
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
これを最適化するために、重みづけされた、2 つの損失の組み合わせを使用して合計損失を取得します。
style_weight=1e-2 content_weight=1e4 def style_content_loss(outputs): style_outputs = outputs['style'] content_outputs = outputs['content'] style_loss = tf.add_n([tf.reduce_mean((style_outputs[name]-style_targets[name])**2) for name in style_outputs.keys()]) style_loss *= st...
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
tf.GradientTape を使用して画像を更新します。
@tf.function() def train_step(image): with tf.GradientTape() as tape: outputs = extractor(image) loss = style_content_loss(outputs) grad = tape.gradient(loss, image) opt.apply_gradients([(grad, image)]) image.assign(clip_0_1(image))
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
いくつかのステップを実行してテストします。
train_step(image) train_step(image) train_step(image) tensor_to_image(image)
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
機能しているので、さらに長い最適化を実行します。
import time start = time.time() epochs = 10 steps_per_epoch = 100 step = 0 for n in range(epochs): for m in range(steps_per_epoch): step += 1 train_step(image) print(".", end='', flush=True) display.clear_output(wait=True) display.display(tensor_to_image(image)) print("Train step: {}".format(step)...
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
総変動損失 この基本実装には、 高周波アーチファクトが多く生成されるという難点があります。これらは、画像の高周波コンポーネントに明示的な正規化項を使用することで低下させることができます。画風変換では、通常これは総変動損失と呼ばれています。
def high_pass_x_y(image): x_var = image[:, :, 1:, :] - image[:, :, :-1, :] y_var = image[:, 1:, :, :] - image[:, :-1, :, :] return x_var, y_var x_deltas, y_deltas = high_pass_x_y(content_image) plt.figure(figsize=(14, 10)) plt.subplot(2, 2, 1) imshow(clip_0_1(2*y_deltas+0.5), "Horizontal Deltas: Original") pl...
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
これは、高周波コンポーネントがどのように高まったのかを示します。 また、この高周波コンポーネントは基本的にエッジ検出器でもあります。似たような出力は、Sobel エッジ検出器でも見られます。以下に例を示します。
plt.figure(figsize=(14, 10)) sobel = tf.image.sobel_edges(content_image) plt.subplot(1, 2, 1) imshow(clip_0_1(sobel[..., 0]/4+0.5), "Horizontal Sobel-edges") plt.subplot(1, 2, 2) imshow(clip_0_1(sobel[..., 1]/4+0.5), "Vertical Sobel-edges")
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
これに伴う正規化損失は、値の二乗の和です。
def total_variation_loss(image): x_deltas, y_deltas = high_pass_x_y(image) return tf.reduce_sum(tf.abs(x_deltas)) + tf.reduce_sum(tf.abs(y_deltas)) total_variation_loss(image).numpy()
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
何を行うかについては実演されましたが、これを自分で実装する必要はありません。TensorFlow には、標準実装が含まれています。
tf.image.total_variation(image).numpy()
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
最適化を再実行する total_variation_loss の重みを選択します。
total_variation_weight=30
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
train_step 関数にそれを含めます。
@tf.function() def train_step(image): with tf.GradientTape() as tape: outputs = extractor(image) loss = style_content_loss(outputs) loss += total_variation_weight*tf.image.total_variation(image) grad = tape.gradient(loss, image) opt.apply_gradients([(grad, image)]) image.assign(clip_0_1(image))
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
最適化変数を再初期化します。
image = tf.Variable(content_image)
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
そして、最適化を実行します。
import time start = time.time() epochs = 10 steps_per_epoch = 100 step = 0 for n in range(epochs): for m in range(steps_per_epoch): step += 1 train_step(image) print(".", end='', flush=True) display.clear_output(wait=True) display.display(tensor_to_image(image)) print("Train step: {}".format(step)...
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
最後に、結果を保存します。
file_name = 'stylized-image.png' tensor_to_image(image).save(file_name) try: from google.colab import files except ImportError: pass else: files.download(file_name)
site/ja/tutorials/generative/style_transfer.ipynb
tensorflow/docs-l10n
apache-2.0
Create A Priority Queue Object
# Create a priority queue abstract base class class priority_queue: # Initialize the instance def __init__(self): # Create a list to use as the queue self._queue = [] # Create an index to use as ordering self._index = 0 # Create a function to add a task to the queue def ...
python/priority_queues.ipynb
tpin3694/tpin3694.github.io
mit
Add Items To Queue
# Add an item to the queue task_list.add_task('Clean Dishes', 1) # Add an item to the queue task_list.add_task('Wash Car', 2) # Add an item to the queue task_list.add_task('Walk Dog', 3)
python/priority_queues.ipynb
tpin3694/tpin3694.github.io
mit
Retrieve Items From Queue By Priority
# Retrieve items from the queue task_list.next_task() # Retrieve items from the queue task_list.next_task() # Retrieve items from the queue task_list.next_task()
python/priority_queues.ipynb
tpin3694/tpin3694.github.io
mit
Wind Structure Calculator This Python module provides a number of simple calculators with which the structure of line-driven winds can be determined following different analytic approaches. In the following, we briefly demonstrate the usage of these calculators at the example of the well-studies O-star zeta-Puppis. Set...
mstar = 52.5 # mass; if no astropy units are provided, the calculators will assume units of solar masses lstar = 1e6 # luminosity; if no astropy units are provided, the calculators will assume units of solar luminosities teff = 4.2e4 # effective temperature; if no astropy units are provided, the calculators will ass...
jupyter/wind_tutorial.ipynb
unoebauer/public-astro-tools
mit
CAK force multiplier paramters. Again these are adopted from Noebauer & Sim 2015, table 3
alpha = 0.595 k = 0.381
jupyter/wind_tutorial.ipynb
unoebauer/public-astro-tools
mit
The grid for dimensional radii (i.e. r/Rstar) for which the wind velocity and density will be later determined
x = np.logspace(-3, 3, 1024) + 1.
jupyter/wind_tutorial.ipynb
unoebauer/public-astro-tools
mit
Setting up the calculators WindStructureCak75: wind structure based on the seminal work by Castor, Abbott and Klein 1975; the central star is assumed to be a point source WindStructureFa86: wind structure based on fits to the numerical results obtained by Friend and Abbott 1986; only the influence of the finite extent...
wind_cak75 = ws.WindStructureCak75(mstar=mstar, lstar=lstar, teff=teff, gamma=gamma, sigma=sigma, k=k, alpha=alpha) wind_fa86 = ws.WindStructureFa86(mstar=mstar, lstar=lstar, teff=teff, gamma=gamma, sigma=sigma, k=k, alpha=alpha) wind_kppa89 = ws.WindStructureKppa89(mstar=mstar, lstar=lstar, teff=teff, gamma=gamma, sig...
jupyter/wind_tutorial.ipynb
unoebauer/public-astro-tools
mit
Calculating the mass-loss rates
print(" | vterm [km/s] | Mdot [solMass/yr] ") print("==========================================") for wind, label in zip(winds, labels): print("{:6s} | {:7.2f} | {:.4e}".format(label, wind.vterm.value, wind.mdot.value))
jupyter/wind_tutorial.ipynb
unoebauer/public-astro-tools
mit
Determining and visualizing the wind structure Let's first have a look at the wind velocity in absolute terms as predicted by the different descriptions of the wind structure.
plt.figure() for wind, label, ls in zip(winds, labels, linestyles): plt.plot(x, wind.v(x), ls=ls, label=label) plt.legend(frameon=False, loc="lower right") plt.xlabel(r"$r/R_{\star}$") plt.ylabel(r"$v$ [km/s]") plt.xlim([0.8, 1e1])
jupyter/wind_tutorial.ipynb
unoebauer/public-astro-tools
mit
The following illustration compares how fast the terminal wind speed is reached in the various wind descriptions
plt.figure() for wind, label, ls in zip(winds, labels, linestyles): plt.plot(x - 1., wind.v(x) / wind.vterm, ls=ls, label=label) plt.xscale("log") plt.xlim([1e-3, 1e3]) plt.ylim([0, 1]) plt.legend(loc="upper left", frameon=False) plt.xlabel(r"$r/R_{\star} - 1$") plt.ylabel(r"$v/v_{\infty}$")
jupyter/wind_tutorial.ipynb
unoebauer/public-astro-tools
mit
Finally, we have a look at the predicted wind density:
plt.figure() for wind, label, ls in zip(winds, labels, linestyles): plt.plot(x, wind.rho(x), ls=ls, label=label) plt.yscale("log") plt.ylim([1e-15, 1e-10]) plt.xlim([0.8, 10]) plt.xlabel(r"$r/R_{\star}$") plt.ylabel(r"$\rho$ $[\mathrm{g\,cm^{-3}}]$") plt.legend(loc="upper right", frameon=False)
jupyter/wind_tutorial.ipynb
unoebauer/public-astro-tools
mit
Load additional libraries needed for plotting and profiling.
# Math libraries import numpy as np from math import sqrt # Matplotlib plotting libraries import matplotlib.pyplot as plt %matplotlib inline # Bokeh plotting libraries import bokeh.plotting as blt blt.output_notebook()
juliaplots.ipynb
SParadiso18/juliasets
mit
Extend JuliaSet class with additional functionality.
class JuliaSetPlot(JuliaSet): """Extend JuliaSet to add plotting functionality""" def __init__(self, *args, **kwargs): # Invoke constructor for JuliaSet first, unaltered JuliaSet.__init__(self, *args, **kwargs) # Add another attribute: a rendered image array self.img = np.ar...
juliaplots.ipynb
SParadiso18/juliasets
mit
Visualize a Julia set using matplotlib.
j = JuliaSetPlot(-1.037 + 0.17j) %time j.set_spacing(0.006) %time j.generate() %time j.show()
juliaplots.ipynb
SParadiso18/juliasets
mit
Visualize a different Julia set using Bokeh as an interactive Javascript plot.
j = JuliaSetPlot(-0.624 + 0.435j) %time j.set_spacing(0.006) %time j.generate() %time j.interact() %prun j.generate() %load_ext line_profiler %lprun -f j.generate j.generate()
juliaplots.ipynb
SParadiso18/juliasets
mit
The census api needs a key - you can register for can sign up http://api.census.gov/data/key_signup.html
c = Census(os.environ["CENSUS"])
demos/census_api.ipynb
synthicity/synthpop
bsd-3-clause
Here we get aggregate information on households from ACS - note some variables are associated with block groups and others with tracts
income_columns = ['B19001_0%02dE'%i for i in range(1, 18)] vehicle_columns = ['B08201_0%02dE'%i for i in range(1, 7)] workers_columns = ['B08202_0%02dE'%i for i in range(1, 6)] families_columns = ['B11001_001E', 'B11001_002E'] block_group_columns = income_columns + families_columns tract_columns = vehicle_columns + wor...
demos/census_api.ipynb
synthicity/synthpop
bsd-3-clause
And here is aggregate information on people from ACS
population = ['B01001_001E'] sex = ['B01001_002E', 'B01001_026E'] race = ['B02001_0%02dE'%i for i in range(1,11)] male_age_columns = ['B01001_0%02dE'%i for i in range(3,26)] female_age_columns = ['B01001_0%02dE'%i for i in range(27,50)] all_columns = population + sex + race + male_age_columns + female_age_columns p_acs...
demos/census_api.ipynb
synthicity/synthpop
bsd-3-clause
Get the puma for our test tracts - this actually downloads the mapping file from the census website so it might take a few seconds
puma = c.tract_to_puma("06", "075", "030600") puma puma10 = puma[0] puma00 = puma[1]
demos/census_api.ipynb
synthicity/synthpop
bsd-3-clause
Download PUMS for people records for a PUMA from our server (we processed the large files into smaller ones for you)
p_pums = c.download_population_pums("06", puma10=puma10, puma00=puma00) p_pums.head(5)
demos/census_api.ipynb
synthicity/synthpop
bsd-3-clause