markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
The fourth way to run Python, which is fairly complex-looking at first but becomes much more useful the more you program, is through an IDE. When you installed Anaconda you got an IDE called "Spyder" along with it. Go ahead and start it up and have a look around. Open the Python file you ran at the command line a while... | import os | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
We can list the contents of any directory by using the os.listdir() method. Without any arguments, it gives us the contents of the directory we are standing in. | os.listdir() | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
We can also list the contents of any other directory. For example, the Downloads folder on my Mac is in the folder with my short name (tla), which is in a folder called Users, which is right on the Macintosh HD. So I say
/Users/tla/Downloads
to get at it. That is: Starting at the root (/), look in Users; starting at U... | for f in os.listdir("/Users/tla/Downloads"):
print(f) | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
Python (or any program running on your computer for that matter) always runs from some specific place in this filesystem - that is, some specific directory on your drive. To see where you are running now, you can ask for the current working directory, like so. Try this command in Python at the command line, in IPython,... | os.getcwd() | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
This will look a little different on Mac vs. Windows, because they use different notations (called the path) for their directory structure.
C:\Users\Tara L Andrews\Documents\IPython Notebooks
vs.
/Users/tla/Documents/2014 FS
The two important lessons to take from this are:
If you are not sure where you are, then os... | os.chdir("/Users/tla") # go to the directory tla in the directory Users at the base of the drive
os.chdir("..") # go one directory down
print(os.getcwd()) # see where we are
os.chdir("./tla/Downloads") # go to the directory Downloads in the directory tla that is here where we are
print(os.getcwd()) ... | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
You will remember that there are a few special names when you look at files and directories:
. - the directory I'm standing in
.. - the directory that holds the directory I'm standing in
/ - (all by itself) the base ("root") directory
IF YOU ARE ON WINDOWS: The / is a little more complicated than that if you are on ... | print(os.getenv("HOME", "I don't have a HOME variable, so I must be on Windows"))
print(os.getenv("USERPROFILE", "I don't have a USERPROFILE variable, so I must be on Mac or Linux" )) | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
Once you know which variable contains your home directory, you can save it into a variable and use it. | my_home = os.getenv("HOME")
for f in os.listdir( my_home ):
print(f) | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
Now, if I want to, I can look to see what we have in my Projects folder - this is where I usually keep the code I've worked on. I can do this by joining the directory name ('Projects') to my home directory (which I've saved in my_home.) | doc_path = os.path.join( my_home, "Projects" )
print( "The join operation has given me the path", doc_path )
os.listdir( doc_path ) | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
Using the os.path.join command is a very good idea when you don't know what kind of computer might be running your script - it means that you are letting Python deal with the question of whether the path separator is / or \ or : or % or whatever. But you don't have to use the os.path.join command if you know that / wil... | os.listdir( "/Users/tla/Dropbox/book" ) # Look at the 'book' folder in the Dropbox folder in my home directory | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
So to sum up, here are some equivalences between the command line and Python:
cd DIRECTORY ==> os.chdir("DIRECTORY")
ls DIRECTORY ==> os.listdir("DIRECTORY")
pwd ==> os.getcwd()
echo $VAR ==> os.getenv("VAR")
Reading files
Now that we know how to navigate around our directory, we might also wan... | fh = open(my_home + "/Dropbox/beef_stew.txt") # Open the file
contents = fh.read() # Read its contents
fh.close() # Close the file
print(contents) # Do something with the contents | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
There are three steps to dealing with files from Python:
Open it
Read (or write) whatever you need
Close it
When you open a file, you make something called a filehandle. The filehandle, well, handles the file - does the reading, writing, closing, etc. that you need to be done.
When you read a file, you have two choic... | os.chdir(my_home)
fh = open( "Dropbox/beef_stew.txt" )
counter = 1
for line in fh:
print("%d: %s" % ( counter, line ))
counter += 1
fh.close() | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
Huh, great, but why did that double-space all of a sudden?
Here's what happened: every line in the file ends with a line break where I pressed Return. The print function adds a line break after everything it prints, by default. Since the lines in the file already have one, if we are not careful we will also be double-s... | fh = open( "Dropbox/beef_stew.txt" )
counter = 1
for line in fh:
print("%d: %s" % ( counter, line ), end="")
counter += 1
fh.close() | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
Writing to files
When we open a filehandle on a particular file, that filehandle can either be reading from the file or writing to it (but not both, at least not until we understand the mechanics and the dangers of doing that.)
When we write to a file that already exists, there are two options: either we will replace w... | old_recipe = open( "Dropbox/beef_stew.txt" )
new_recipe = open( "Dropbox/numbered_beef_stew.txt", "w" )
counter = 1
for line in old_recipe:
new_recipe.write( "%d: %s" % ( counter, line ) )
counter += 1 # this is the same as counter = counter + 1
old_recipe.close()
new_recipe.close() | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
So let's look at the new recipe! We open it for reading this time, instead of writing. And instead of reading it line by line, we will read it all in one go, so that we don't have to worry about what print does with line endings. | new_recipe = open( "Dropbox/numbered_beef_stew.txt" )
contents = new_recipe.read()
new_recipe.close()
print(contents) | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
Let's say we forgot a step at the end, and want to add it.
When we write a new line to the file, since we are using .write() and not print(), we have to make sure to add the carriage return at the end of the line. In Python this can usually be done with the term "\n", no matter which sort of computer you are on. (This ... | new_recipe = open( "Dropbox/numbered_beef_stew.txt", "a" )
new_recipe.write( "18: give the leftovers to the cat\n" )
new_recipe.close() | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
And let's see if that worked. This time, instead of using .read() to put the file into a single variable, we will use .readlines() to put the file line by line into an array. This is useful if you want to read the file all in one go, but are going to want to do something with its contents line by line. | new_recipe = open( "Dropbox/numbered_beef_stew.txt" )
contents = new_recipe.readlines()
new_recipe.close()
for line in contents:
print("-", line, end='') | unit1/Running_Python.ipynb | DiXiT-eu/collatex-tutorial | gpl-3.0 |
<li>How much time has passed? | d1 - d2 | BAMM.101x/datetime_objects.ipynb | KECB/learn | mit |
<h4>Obviously that's not going to work. </h4>
<h4>We can't do date operations on strings</h4>
<h4>Let's see what happens with datetime</h4> | import datetime
d1 = datetime.date(2016,11,24)
d2 = datetime.date(2017,10,24)
max(d1,d2)
print(d2 - d1) | BAMM.101x/datetime_objects.ipynb | KECB/learn | mit |
<li>datetime objects understand time
<h3>The datetime library contains several useful types</h3>
<li>date: stores the date (month,day,year)
<li>time: stores the time (hours,minutes,seconds)
<li>datetime: stores the date as well as the time (month,day,year,hours,minutes,seconds)
<li>timedelta: duration between two date... | import datetime
century_start = datetime.date(2000,1,1)
today = datetime.date.today()
print(century_start,today)
print("We are",today-century_start,"days into this century")
print(type(century_start))
print(type(today)) | BAMM.101x/datetime_objects.ipynb | KECB/learn | mit |
<h3>For a cleaner output</h3> | print("We are",(today-century_start).days,"days into this century") | BAMM.101x/datetime_objects.ipynb | KECB/learn | mit |
<h3>datetime.datetime</h3> | century_start = datetime.datetime(2000,1,1,0,0,0)
time_now = datetime.datetime.now()
print(century_start,time_now)
print("we are",time_now - century_start,"days, hour, minutes and seconds into this century") | BAMM.101x/datetime_objects.ipynb | KECB/learn | mit |
<h4>datetime objects can check validity</h4>
<li>A ValueError exception is raised if the object is invalid</li> | some_date=datetime.date(2015,2,29)
#some_date =datetime.date(2016,2,29)
#some_time=datetime.datetime(2015,2,28,23,60,0) | BAMM.101x/datetime_objects.ipynb | KECB/learn | mit |
<h3>datetime.timedelta</h3>
<h4>Used to store the duration between two points in time</h4> | century_start = datetime.datetime(2050,1,1,0,0,0)
time_now = datetime.datetime.now()
time_since_century_start = time_now - century_start
print("days since century start",time_since_century_start.days)
print("seconds since century start",time_since_century_start.total_seconds())
print("minutes since century start",time_... | BAMM.101x/datetime_objects.ipynb | KECB/learn | mit |
<h3>datetime.time</h3> | date_and_time_now = datetime.datetime.now()
time_now = date_and_time_now.time()
print(time_now) | BAMM.101x/datetime_objects.ipynb | KECB/learn | mit |
<h4>You can do arithmetic operations on datetime objects</h4>
<li>You can use timedelta objects to calculate new dates or times from a given date |
today=datetime.date.today()
five_days_later=today+datetime.timedelta(days=5)
print(five_days_later)
now=datetime.datetime.today()
five_minutes_and_five_seconds_later = now + datetime.timedelta(minutes=5,seconds=5)
print(five_minutes_and_five_seconds_later)
now=datetime.datetime.today()
five_minutes_and_five_seconds... | BAMM.101x/datetime_objects.ipynb | KECB/learn | mit |
<li>But you can't use timedelta on time objects. If you do, you'll get a TypeError exception | time_now=datetime.datetime.now().time() #Returns the time component (drops the day)
print(time_now)
thirty_seconds=datetime.timedelta(seconds=30)
time_later=time_now+thirty_seconds
#Bug or feature?
#But this is Python
#And we can always get around something by writing a new function!
#Let's write a small function to g... | BAMM.101x/datetime_objects.ipynb | KECB/learn | mit |
<h2>datetime and strings</h2>
<h4>datetime.strptime</h4>
<li>datetime.strptime(): grabs time from a string and creates a date or datetime or time object
<li>The programmer needs to tell the function what format the string is using
<li> See http://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html for how ... | date='01-Apr-03'
date_object=datetime.datetime.strptime(date,'%d-%b-%y')
print(date_object)
#Unfortunately, there is no similar thing for time delta
#So we have to be creative!
bus_travel_time='2:15:30'
hours,minutes,seconds=bus_travel_time.split(':')
x=datetime.timedelta(hours=int(hours),minutes=int(minutes),seconds=... | BAMM.101x/datetime_objects.ipynb | KECB/learn | mit |
<h4>datetime.strftime</h4>
<li>The strftime function flips the strptime function. It converts a datetime object to a string
<li>with the specified format | now = datetime.datetime.now()
string_now = datetime.datetime.strftime(now,'%m/%d/%y %H:%M:%S')
print(now,string_now)
print(str(now)) #Or you can use the default conversion
| BAMM.101x/datetime_objects.ipynb | KECB/learn | mit |
Showing and Saving
NOTE: in IPython notebooks calling plot will display directly below the call to plot. When not in IPython you have several options for viewing the figure:
call b.show or b.savefig after calling plot
use the returned autofig and matplotlib figures however you'd like
pass show=True to the plot method... | afig, mplfig = b.plot(show=True) | 2.1/tutorials/plotting.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
For more information on each of the available arrays, see the relevant tutorial on that dataset method:
ORB dataset
MESH dataset
LC dataset
RV dataset
LP dataset
Selecting Phase
And to plot in phase we just send x='phases' or x='phases:binary'.
Setting x='phases' will use the ephemeris from the top-level of the hiera... | afig, mplfig = b['lc01@dataset'].plot(x='phases', z=0, show=True) | 2.1/tutorials/plotting.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Basic training loops
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/basic_training_loops"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.... | import tensorflow as tf
import matplotlib.pyplot as plt
colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] | site/en/guide/basic_training_loops.ipynb | tensorflow/docs | apache-2.0 |
Solving machine learning problems
Solving a machine learning problem usually consists of the following steps:
Obtain training data.
Define the model.
Define a loss function.
Run through the training data, calculating loss from the ideal value
Calculate gradients for that loss and use an optimizer to adjust the variabl... | # The actual line
TRUE_W = 3.0
TRUE_B = 2.0
NUM_EXAMPLES = 201
# A vector of random x values
x = tf.linspace(-2,2, NUM_EXAMPLES)
x = tf.cast(x, tf.float32)
def f(x):
return x * TRUE_W + TRUE_B
# Generate some noise
noise = tf.random.normal(shape=[NUM_EXAMPLES])
# Calculate y
y = f(x) + noise
# Plot all the data... | site/en/guide/basic_training_loops.ipynb | tensorflow/docs | apache-2.0 |
Tensors are usually gathered together in batches, or groups of inputs and outputs stacked together. Batching can confer some training benefits and works well with accelerators and vectorized computation. Given how small this dataset is, you can treat the entire dataset as a single batch.
Define the model
Use tf.Varia... | class MyModel(tf.Module):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Initialize the weights to `5.0` and the bias to `0.0`
# In practice, these should be randomly initialized
self.w = tf.Variable(5.0)
self.b = tf.Variable(0.0)
def __call__(self, x):
return self.w * x + self.... | site/en/guide/basic_training_loops.ipynb | tensorflow/docs | apache-2.0 |
The initial variables are set here in a fixed way, but Keras comes with any of a number of initializers you could use, with or without the rest of Keras.
Define a loss function
A loss function measures how well the output of a model for a given input matches the target output. The goal is to minimize this difference du... | # This computes a single loss value for an entire batch
def loss(target_y, predicted_y):
return tf.reduce_mean(tf.square(target_y - predicted_y)) | site/en/guide/basic_training_loops.ipynb | tensorflow/docs | apache-2.0 |
Before training the model, you can visualize the loss value by plotting the model's predictions in red and the training data in blue: | plt.plot(x, y, '.', label="Data")
plt.plot(x, f(x), label="Ground truth")
plt.plot(x, model(x), label="Predictions")
plt.legend()
plt.show()
print("Current loss: %1.6f" % loss(y, model(x)).numpy()) | site/en/guide/basic_training_loops.ipynb | tensorflow/docs | apache-2.0 |
Define a training loop
The training loop consists of repeatedly doing three tasks in order:
Sending a batch of inputs through the model to generate outputs
Calculating the loss by comparing the outputs to the output (or label)
Using gradient tape to find the gradients
Optimizing the variables with those gradients
For... | # Given a callable model, inputs, outputs, and a learning rate...
def train(model, x, y, learning_rate):
with tf.GradientTape() as t:
# Trainable variables are automatically tracked by GradientTape
current_loss = loss(y, model(x))
# Use GradientTape to calculate the gradients with respect to W and b
dw,... | site/en/guide/basic_training_loops.ipynb | tensorflow/docs | apache-2.0 |
For a look at training, you can send the same batch of x and y through the training loop, and see how W and b evolve. | model = MyModel()
# Collect the history of W-values and b-values to plot later
weights = []
biases = []
epochs = range(10)
# Define a training loop
def report(model, loss):
return f"W = {model.w.numpy():1.2f}, b = {model.b.numpy():1.2f}, loss={loss:2.5f}"
def training_loop(model, x, y):
for epoch in epochs:
... | site/en/guide/basic_training_loops.ipynb | tensorflow/docs | apache-2.0 |
Do the training | current_loss = loss(y, model(x))
print(f"Starting:")
print(" ", report(model, current_loss))
training_loop(model, x, y) | site/en/guide/basic_training_loops.ipynb | tensorflow/docs | apache-2.0 |
Plot the evolution of the weights over time: | plt.plot(epochs, weights, label='Weights', color=colors[0])
plt.plot(epochs, [TRUE_W] * len(epochs), '--',
label = "True weight", color=colors[0])
plt.plot(epochs, biases, label='bias', color=colors[1])
plt.plot(epochs, [TRUE_B] * len(epochs), "--",
label="True bias", color=colors[1])
plt.legend()
p... | site/en/guide/basic_training_loops.ipynb | tensorflow/docs | apache-2.0 |
Visualize how the trained model performs | plt.plot(x, y, '.', label="Data")
plt.plot(x, f(x), label="Ground truth")
plt.plot(x, model(x), label="Predictions")
plt.legend()
plt.show()
print("Current loss: %1.6f" % loss(model(x), y).numpy()) | site/en/guide/basic_training_loops.ipynb | tensorflow/docs | apache-2.0 |
The same solution, but with Keras
It's useful to contrast the code above with the equivalent in Keras.
Defining the model looks exactly the same if you subclass tf.keras.Model. Remember that Keras models inherit ultimately from module. | class MyModelKeras(tf.keras.Model):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Initialize the weights to `5.0` and the bias to `0.0`
# In practice, these should be randomly initialized
self.w = tf.Variable(5.0)
self.b = tf.Variable(0.0)
def call(self, x):
return self.w * x +... | site/en/guide/basic_training_loops.ipynb | tensorflow/docs | apache-2.0 |
Rather than write new training loops each time you create a model, you can use the built-in features of Keras as a shortcut. This can be useful when you do not want to write or debug Python training loops.
If you do, you will need to use model.compile() to set the parameters, and model.fit() to train. It can be less ... | keras_model = MyModelKeras()
# compile sets the training parameters
keras_model.compile(
# By default, fit() uses tf.function(). You can
# turn that off for debugging, but it is on now.
run_eagerly=False,
# Using a built-in optimizer, configuring as an object
optimizer=tf.keras.optimizers.SGD(lea... | site/en/guide/basic_training_loops.ipynb | tensorflow/docs | apache-2.0 |
Keras fit expects batched data or a complete dataset as a NumPy array. NumPy arrays are chopped into batches and default to a batch size of 32.
In this case, to match the behavior of the hand-written loop, you should pass x in as a single batch of size 1000. | print(x.shape[0])
keras_model.fit(x, y, epochs=10, batch_size=1000) | site/en/guide/basic_training_loops.ipynb | tensorflow/docs | apache-2.0 |
Let's show the symbols data, to see how good the recommender has to be. | print('Sharpe ratio: {}\nCum. Ret.: {}\nAVG_DRET: {}\nSTD_DRET: {}\nFinal value: {}'.format(*value_eval(pd.DataFrame(data_in_df['Close'].iloc[STARTING_DAYS_AHEAD:]))))
# Simulate (with new envs, each time)
n_epochs = 25
for i in range(n_epochs):
tic = time()
env.reset(STARTING_DAYS_AHEAD)
results_list = s... | notebooks/prod/n08_simple_q_learner_1000_states_full_training_25_epochs.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
Ok, let's save that | import pickle
with open('../../data/simple_q_learner_1000_states_full_training_25_epochs.pkl', 'wb') as best_agent:
pickle.dump(agents[0], best_agent) | notebooks/prod/n08_simple_q_learner_1000_states_full_training_25_epochs.ipynb | mtasende/Machine-Learning-Nanodegree-Capstone | mit |
Firstly we will calculate the features required to characterise the pointcloud.
These are calculated on 3 scales which by default are k=10, 20 & 30 nearest-neighbours.
If wish to alter this go ahead!
The features are:
- anisotropy
- curvature
- eigenentropy
- eigen_sum
- linearity
- omnivariance
- planarity
- spheri... | ln.ply_features(incloud) | example_notebooks/PointCloudClassification.ipynb | Ciaran1981/geospatial-learn | gpl-3.0 |
This snippet is used to create the column names for the 128 attributes (16 sensors and 8 attributes measured by each sensor), the target label and batch number for the corresponding row.
We add '\n' to the 'Batch_no' label to signify EOL. If we use 'csv' package then we don't need to add that, the 'writer' method will ... | col_names = ['Label']
for x in map(chr,range(65,81)):
for y in map(str,range(1,9)):
col_names.append('Sensor_'+x+y)
col_names.append('Batch_No\n')
print 'Number of columns -',len(col_names) | data_formatting.ipynb | aamirg/athena-hacks-honeywell | apache-2.0 |
Open a csv file and write the column names to it | out=open('formatted_data.csv','w')
out.write(','.join(col_names)) | data_formatting.ipynb | aamirg/athena-hacks-honeywell | apache-2.0 |
Get the file names for all the files from the 'raw_data' directory | raw_files = [f for f in listdir('./raw_data') if isfile(join('./raw_data', f))] | data_formatting.ipynb | aamirg/athena-hacks-honeywell | apache-2.0 |
Read the data in from each file, format it by -
Strip extra whitespaces and split on whitespace
Add the batch number from file name, the target label
Split the key value pairs on ':' and retrieve the values | for file_name in raw_files:
with open('./raw_data/'+file_name,'r') as f:
for i in f:
j=i.strip().split(' ')
out.write(','.join([j[0]]+[k.split(':')[1] for k in j[1:]]+[file_name.strip('batch').split('.')[0],'\n']))
out.close() | data_formatting.ipynb | aamirg/athena-hacks-honeywell | apache-2.0 |
The above snippet can be rewritten in the long form as | #for file_name in raw_files:
# with open('./raw_data/'+file_name,'r') as f:
# for i in f:
# j=i.strip().split(' ')
# target_label = [j[0]]
# attributes = [k.split(':')[1] for k in j[1:]]
# batch_no = [file_name.strip('batch').split('.')[0],'\n']
# out.wri... | data_formatting.ipynb | aamirg/athena-hacks-honeywell | apache-2.0 |
Initialisation | # Do a SYGMA run for each NuGrid metallicity
s_02 = s.sygma(iniZ=0.02, imf_type='salpeter')
s_01 = s.sygma(iniZ=0.01, imf_type='salpeter')
s_006 = s.sygma(iniZ=0.006, imf_type='salpeter')
s_001 = s.sygma(iniZ=0.001, imf_type='salpeter')
s_0001 = s.sygma(iniZ=0.0001, imf_type='salpeter')
# Show the number of neutron s... | NSM_test_suite.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
IMF check
The Salpeter allows one to calculate the number of stars $N_{12}$ in the mass interval [m1, m2] with
(I) $N_{12} = k_N \int _{m1}^{m2} m^{-2.35} dm$
Where $k_{N}$ is the normalization constant, which can be derived from the total amount of mass in the system $M_{tot}$.
Since the total mass $M_{12}$ in the ma... | # Name the relevant quantities
mtot = s_001.mgal
nsm_l = s_001.transitionmass
imf0 = s_001.imf_bdys[0]
imf1 = s_001.imf_bdys[1]
# Compute the normalization constant as defined above
k_N = (mtot*0.35) / (imf0**-0.35 - imf1**-0.35) #(I) | NSM_test_suite.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
The total number of NS merger progenitors $N_{12}$ is then:
$N_{12} = \frac{k_N}{1.35}(8^{-1.35} - 100^{-1.35})$ | # Compute the total number of neutron star merger progenitors as defined above
N_nsm = (k_N/1.35) * (nsm_l**-1.35 - imf1**-1.35) | NSM_test_suite.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Compared to a SYGMA run: | # Compute the number of NS merger progenitors in one of the SYGMA runs (normalize to mgal)
A_imf = mtot / s_001._imf(imf0, imf1, 2)
N_sim = A_imf * s_001._imf(nsm_l, imf1, 1)
print 'Theoretical number of neutron star progenitors: ', N_nsm
print 'Number of neutron star progenitors in SYGMA run: ', N_sim
print 'Ratio (s... | NSM_test_suite.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Ensure r-process yields are being read in properly | # Obtain the fractional isotope yields from a SYGMA run
l = len(s_01.history.ism_iso_yield_nsm)
y = s_01.history.ism_iso_yield_nsm[l-1]
n = np.sum(y)
yields = y / n
# Exclude isotopes for which there are no r-process yields in the yield table
nonzero = np.nonzero(yields)
yields = yields[nonzero]
# Obtain the mass num... | NSM_test_suite.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Check DTD fits | # Define the three functions which are fit to the DTD (Power law, 5th and 6th degree polynomials)
def quintic(t, a, b, c, d, e, f):
y = (a*(t**5))+(b*(t**4))+(c*(t**3))+(d*(t**2))+(e*t)+f
return y
def sextic(t, a, b, c, d, e, f, g):
y = a*(t**6) + b*(t**5) + c*(t**4) + d*(t**3) + e*(t**2) + f*t + g
r... | NSM_test_suite.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Utility functions
A number of utility callback functions for image display and for ploting the similarity metric during registration. | import matplotlib.pyplot as plt
%matplotlib inline
from ipywidgets import interact, fixed
from IPython.display import clear_output
# Callback invoked by the interact ipython method for scrolling through the image stacks of
# the two images (moving and fixed).
def display_images(fixed_image_z, moving_image_z, fixed_np... | 60_Registration_Introduction.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Read images
We first read the images, casting the pixel type to that required for registration (Float32 or Float64) and look at them. | fixed_image = sitk.ReadImage(fdata("training_001_ct.mha"), sitk.sitkFloat32)
moving_image = sitk.ReadImage(fdata("training_001_mr_T1.mha"), sitk.sitkFloat32)
interact(display_images, fixed_image_z=(0,fixed_image.GetSize()[2]-1), moving_image_z=(0,moving_image.GetSize()[2]-1), fixed_npa = fixed(sitk.GetArrayFromImage... | 60_Registration_Introduction.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Initial Alignment
Use the CenteredTransformInitializer to align the centers of the two volumes and set the center of rotation to the center of the fixed image. | initial_transform = sitk.CenteredTransformInitializer(fixed_image,
moving_image,
sitk.Euler3DTransform(),
sitk.CenteredTransformInitializerFilter.GEOMETRY)... | 60_Registration_Introduction.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Registration
The specific registration task at hand estimates a 3D rigid transformation between images of different modalities. There are multiple components from each group (optimizers, similarity metrics, interpolators) that are appropriate for the task. Note that each component selection requires setting some parame... | registration_method = sitk.ImageRegistrationMethod()
# Similarity metric settings.
registration_method.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)
registration_method.SetMetricSamplingStrategy(registration_method.RANDOM)
registration_method.SetMetricSamplingPercentage(0.01)
registration_method.SetInt... | 60_Registration_Introduction.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Post registration analysis
Query the registration method to see the metric value and the reason the optimization terminated.
The metric value allows us to compare multiple registration runs as there is a probabilistic aspect to our registration, we are using random sampling to estimate the similarity metric.
Always re... | print('Final metric value: {0}'.format(registration_method.GetMetricValue()))
print('Optimizer\'s stopping condition, {0}'.format(registration_method.GetOptimizerStopConditionDescription())) | 60_Registration_Introduction.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Now visually inspect the results. | moving_resampled = sitk.Resample(moving_image, fixed_image, final_transform, sitk.sitkLinear, 0.0, moving_image.GetPixelIDValue())
interact(display_images_with_alpha, image_z=(0,fixed_image.GetSize()[2]), alpha=(0.0,1.0,0.05), fixed = fixed(fixed_image), moving=fixed(moving_resampled)); | 60_Registration_Introduction.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
If we are satisfied with the results, save them to file. | sitk.WriteImage(moving_resampled, os.path.join(OUTPUT_DIR, 'RIRE_training_001_mr_T1_resampled.mha'))
sitk.WriteTransform(final_transform, os.path.join(OUTPUT_DIR, 'RIRE_training_001_CT_2_mr_T1.tfm')) | 60_Registration_Introduction.ipynb | thewtex/SimpleITK-Notebooks | apache-2.0 |
Linking Widgets
Often, you may want to simply link widget attributes together. Synchronization of attributes can be done in a simpler way than by using bare traitlets events.
The first method is to use the link and directional_link functions from the traitlets module.
Linking traitlets attributes from the server side | from IPython.utils import traitlets
caption = widgets.Latex(value = 'The values of slider1, slider2 and slider3 are synchronized')
sliders1, slider2, slider3 = widgets.IntSlider(description='Slider 1'),\
widgets.IntSlider(description='Slider 2'),\
widgets.IntSl... | python/demo1/scipy-advanced-tutorial-master/Part2/Widget Events.ipynb | masterfish2015/my_project | mit |
Function traitlets.link returns a Link object. The link can be broken by calling the unlink method. | l2.unlink() | python/demo1/scipy-advanced-tutorial-master/Part2/Widget Events.ipynb | masterfish2015/my_project | mit |
Linking widgets attributes from the client side
When synchronizing traitlets attributes, you may experience a lag because of the latency dues to the rountrip to the server side. You can also directly link widgets attributes, either in a unidirectional or a bidirectional fashion using the link widgets. | caption = widgets.Latex(value = 'The values of range1, range2 and range3 are synchronized')
range1, range2, range3 = widgets.IntSlider(description='Range 1'),\
widgets.IntSlider(description='Range 2'),\
widgets.IntSlider(description='Range 3')
l2 = widgets.jslink((range... | python/demo1/scipy-advanced-tutorial-master/Part2/Widget Events.ipynb | masterfish2015/my_project | mit |
Function widgets.jslink returns a Link widget. The link can be broken by calling the unlink method. | l2.unlink() | python/demo1/scipy-advanced-tutorial-master/Part2/Widget Events.ipynb | masterfish2015/my_project | mit |
Full model | def optimize(m, lr=5e-3, it=50):
opt = torch.optim.LBFGS(m.parameters(), lr=lr, max_iter=40)
def eval_model():
obj = m()
opt.zero_grad()
obj.backward()
return obj
for i in range(it):
obj = m()
opt.zero_grad()
obj.backward()
opt.step(eval_model... | notebooks/upper_bound.ipynb | t-vi/candlegp | apache-2.0 |
Upper bounds for sparse variational models
As a first investigation, we compute the upper bound for models trained using the sparse variational GP approximation. | Ms = numpy.arange(4, 20, 2)
vfe_lml = []
vupper_lml = []
vfe_hyps = []
for M in Ms:
Zinit = X[:M, :].clone()
k = candlegp.kernels.RBF(1, lengthscales=torch.DoubleTensor([1.0]),variance=torch.DoubleTensor([1.0]))
m = candlegp.models.SGPR(Variable(X), Variable(Y.unsqueeze(1)), k, Zinit)
m.likelihood.varia... | notebooks/upper_bound.ipynb | t-vi/candlegp | apache-2.0 |
We see that the lower bound increases as more inducing points are added. Note that the upper bound does not monotonically decrease! This is because as we train the sparse model, we also get better estimates of the hyperparameters. The upper bound will be different for this different setting of the hyperparameters, and ... | fMs = numpy.arange(3, 20, 1)
fvfe_lml = [] # Fixed vfe lml
fvupper_lml = [] # Fixed upper lml
for M in fMs:
Zinit = vfe.Z.value[:M, :].copy()
Zinit = np.vstack((Zinit, X[np.random.permutation(len(X))[:(M - len(Zinit))], :].copy()))
init_params = vfe.get_parameter_dict()
init_params['model.Z'] = Zinit
... | notebooks/upper_bound.ipynb | t-vi/candlegp | apache-2.0 |
Now, as the hyperparameters are fixed, the bound does monotonically decrease. We chose the optimal hyperparameters here, but the picture should be the same for any hyperparameter setting. This shows that we increasingly get a better estimate of the marginal likelihood as we add more inducing points.
A tight estimate bo... | vfe = gpflow.models.SGPR(X, Y, gpflow.kernels.RBF(1), X[None, 0, :].copy())
vfe.optimize()
print("Lower bound: %f" % -vfe._objective(vfe.get_free_state())[0])
print("Upper bound: %f" % vfe.compute_upper_bound()) | notebooks/upper_bound.ipynb | t-vi/candlegp | apache-2.0 |
In this case we show that for the hyperparameter setting, the bound is very tight. However, this does not imply that we have enough inducing points, but simply that we have correctly identified the marginal likelihood for this particular hyperparameter setting. In this specific case, where we used a single inducing poi... | vfe | notebooks/upper_bound.ipynb | t-vi/candlegp | apache-2.0 |
3. Semantic Analysis
The dictionary D and the Bag of Words in corpus_bow are the key inputs to the topic model algorithms. The topic model algorithms in gensim assume that input documents are parameterized using the tf-idf model. | tfidf = gensim.models.TfidfModel(corpus_bow) | 3_TopicModeling/TM2_Topic_Modeling_student.ipynb | jeroarenas/MLBigData | mit |
Or to apply a transformation to a whole corpus | corpus_tfidf = tfidf[corpus_bow] | 3_TopicModeling/TM2_Topic_Modeling_student.ipynb | jeroarenas/MLBigData | mit |
Task: Find the document with the largest positive weight for topic 0. Compare the document and the topic. | # Extract weights from corpus_lsi
# scode: weight0 = <FILL IN>
# Locate the maximum positive weight
nmax = np.argmax(weight0)
print nmax
print weight0[nmax]
print corpus_lsi[nmax]
# Get topic 0
# scode: topic_0 = <FILL IN>
# Compute a list of tuples (token, wordcount) for all tokens in topic_0, where wordcount is th... | 3_TopicModeling/TM2_Topic_Modeling_student.ipynb | jeroarenas/MLBigData | mit |
3.2.2. LDA using Sci-kit Learn
The input matrix to the sklearn implementation of LDA contains the token-counts for all documents in the corpus.
sklearn contains a powerfull CountVectorizer method that can be used to construct the input matrix from the corpus_bow.
First, we will define an auxiliary function to print th... | # Adapted from an example in sklearn site
# http://scikit-learn.org/dev/auto_examples/applications/topics_extraction_with_nmf_lda.html
# You can try also with the dataset provided by sklearn in
# from sklearn.datasets import fetch_20newsgroups
#ย dataset = fetch_20newsgroups(shuffle=True, random_state=1,
#ย ... | 3_TopicModeling/TM2_Topic_Modeling_student.ipynb | jeroarenas/MLBigData | mit |
Now, we need a dataset to feed the Count_Vectorizer object, by joining all tokens in corpus_clean in a single string, using a space ' ' as separator.
Task: Join all tokens from each document in a single string, using a white space as separator. | print("Loading dataset...")
# scode: data_samples = <FILL IN> # Usar join sobre corpus_clean.
data_samples = [" ".join(doc) for doc in corpus_clean]
data_samples = map(lambda x: " ".join(x), corpus_clean)
print 'Document 0:'
print data_samples[0][0:200], '...' | 3_TopicModeling/TM2_Topic_Modeling_student.ipynb | jeroarenas/MLBigData | mit |
Now we are ready to compute the token counts. | # Use tf (raw term count) features for LDA.
print("Extracting tf features for LDA...")
n_features = 1000
tf_vectorizer = CountVectorizer(max_df=0.95, min_df=2,
max_features=n_features,
stop_words='english')
t0 = time()
tf = tf_vectorizer.fit_transform(dat... | 3_TopicModeling/TM2_Topic_Modeling_student.ipynb | jeroarenas/MLBigData | mit |
Now we can apply the LDA algorithm.
Task: Create an LDA object with the following parameters:
n_topics=n_topics, max_iter=5,
learning_method='online',
learning_offset=50.,
random_state=0 | print("Fitting LDA models with tf features, "
"n_samples=%d and n_features=%d..."
% (n_samples, n_features))
# scode: lda = <FILL IN>
lda = LatentDirichletAllocation(n_topics=n_topics, max_iter=5,
learning_method='online',
learning_offset=50.,
... | 3_TopicModeling/TM2_Topic_Modeling_student.ipynb | jeroarenas/MLBigData | mit |
Task: Fit model lda with the token frequencies computed by tf_vectorizer. | t0 = time()
corpus_lda = lda.fit_transform(tf)
print("done in %0.3fs." % (time() - t0))
print("\nTopics in LDA model:")
tf_feature_names = tf_vectorizer.get_feature_names()
print_top_words(lda, tf_feature_names, n_top_words) | 3_TopicModeling/TM2_Topic_Modeling_student.ipynb | jeroarenas/MLBigData | mit |
Next, load the data that we are going to analyse using hoggorm. After the data has been loaded into the pandas data frame, we'll display it in the notebook. | # Load fluorescence data
X1_df = pd.read_csv('cheese_fluorescence.txt', index_col=0, sep='\t')
X1_df
# Load sensory data
X2_df = pd.read_csv('cheese_sensory.txt', index_col=0, sep='\t')
X2_df | examples/SMI/SMI_on_sensory_and_fluorescence.ipynb | olivertomic/hoggorm | bsd-2-clause |
Orthogonal Projections
The default comparison between two matrices with SMI is using Orthogonal Projections, i.e. ordinary least squares regression is used to relate the dominant subspaces in the two matrices.
In contrast to PLSR, SMI is not performing av prediction of sensory properties from fluorescence measurements,... | # Get the values from the data frame
X1 = X1_df.values
X2 = X2_df.values
smiOP = ho.SMI(X1, X2, ncomp1=10, ncomp2=10)
print(np.round(smiOP.smi, 2)) | examples/SMI/SMI_on_sensory_and_fluorescence.ipynb | olivertomic/hoggorm | bsd-2-clause |
Finally we visualize the SMI values and their corresponding P-values. | # Plot similarities
hop.plotSMI(smiOP, [10, 10], X1name='fluorescence', X2name='sensory') | examples/SMI/SMI_on_sensory_and_fluorescence.ipynb | olivertomic/hoggorm | bsd-2-clause |
The significance symbols in the diamond plot above indicate if a chosen subspace from one matrix can be found inside the subspace from the other matrix ($\supset$, $\subset$, =), or if there is signficant difference (P-values <0.001*** <0.01 ** <0.05 * <0.1 . >=0.1).
From the P-values and plot we can observe that the... | smiPR = ho.SMI(X1, X2, ncomp1=10, ncomp2=10, projection="Procrustes")
print(np.round(smiPR.smi, 2)) | examples/SMI/SMI_on_sensory_and_fluorescence.ipynb | olivertomic/hoggorm | bsd-2-clause |
The number of permutations can be controlled for quick (100) or accurate (>10000) computations of significance. | print(np.round(smiPR.significance(B = 100),2))
hop.plotSMI(smiPR, X1name='fluorescence', X2name='sensory') | examples/SMI/SMI_on_sensory_and_fluorescence.ipynb | olivertomic/hoggorm | bsd-2-clause |
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://www.tensorflow.org/federated/tutorials/building_your_own_federated_learning_algorithm"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org์์ ๋ณด๊ธฐ</a></td>
<td> <a target="_blank" href="https://colab.res... | #@test {"skip": true}
!pip install --quiet --upgrade tensorflow-federated
!pip install --quiet --upgrade nest-asyncio
import nest_asyncio
nest_asyncio.apply()
import tensorflow as tf
import tensorflow_federated as tff | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ฐธ๊ณ : ์ด Colab์ <code>tensorflow_federated</code> pip ํจํค์ง์ <a>์ต์ ๋ฆด๋ฆฌ์ฆ ๋ฒ์ </a>์์ ๋์ํ๋ ๊ฒ์ผ๋ก ํ์ธ๋์์ง๋ง Tensorflow Federated ํ๋ก์ ํธ๋ ์์ง ์ํํ ๊ฐ๋ฐ ์ค์ด๋ฉฐ main์์ ๋์ํ์ง ์์ ์ ์์ต๋๋ค.
๊ณ ์ ํ ํ๋๋ ์ด์
ํ์ต ์๊ณ ๋ฆฌ์ฆ ๊ตฌ์ถํ๊ธฐ
์ด๋ฏธ์ง ๋ถ๋ฅ ๋ฐ ํ
์คํธ ์์ฑ ํํ ๋ฆฌ์ผ์์๋ ํ๋๋ ์ด์
ํ์ต(FL)์ ์ํ ๋ชจ๋ธ ๋ฐ ๋ฐ์ดํฐ ํ์ดํ๋ผ์ธ์ ์ค์ ํ๋ ๋ฐฉ๋ฒ์ ๋ฐฐ์ ๊ณ TFF์ tff.learning API ๊ณ์ธต์ ํตํด ํ๋๋ ์ด์
ํ์ต์ ์ํํ์ต๋๋ค.
์ด๊ฒ์ FL ์ฐ๊ตฌ์ ๊ด๋ จํ์ฌ ๋น์ฐ์ ์ผ๊ฐ์ ๋ถ... | emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data() | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
๋ฐ์ดํฐ์ธํธ๋ฅผ ๋ชจ๋ธ์ ์ ๊ณตํ๊ธฐ ์ํด ๋ฐ์ดํฐ๋ฅผ ํ๋ฉดํํ๊ณ ๊ฐ ์์ ๋ฅผ (flattened_image_vector, label) ํ์์ ํํ๋ก ๋ณํํฉ๋๋ค. | NUM_CLIENTS = 10
BATCH_SIZE = 20
def preprocess(dataset):
def batch_format_fn(element):
"""Flatten a batch of EMNIST data and return a (features, label) tuple."""
return (tf.reshape(element['pixels'], [-1, 784]),
tf.reshape(element['label'], [-1, 1]))
return dataset.batch(BATCH_SIZE).map(bat... | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ด์ ์์์ ํด๋ผ์ด์ธํธ๋ฅผ ์ ํํ๊ณ ์์ ์ ์ฒ๋ฆฌ๋ฅผ ๋ฐ์ดํฐ์ธํธ์ ์ ์ฉํฉ๋๋ค. | client_ids = sorted(emnist_train.client_ids)[:NUM_CLIENTS]
federated_train_data = [preprocess(emnist_train.create_tf_dataset_for_client(x))
for x in client_ids
] | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
๋ชจ๋ธ ์ค๋นํ๊ธฐ
์ด๋ฏธ์ง ๋ถ๋ฅ ํํ ๋ฆฌ์ผ์์์ ๋์ผํ ๋ชจ๋ธ์ ์ฌ์ฉํฉ๋๋ค. ์ด ๋ชจ๋ธ(tf.keras๋ฅผ ํตํด ๊ตฌํ๋จ)์๋ ํ๋์ ์จ๊ฒจ์ง ๋ ์ด์ด, ๊ทธ๋ฆฌ๊ณ ์ด์ด์ ์ํํธ๋งฅ์ค ๋ ์ด์ด๊ฐ ์์ต๋๋ค. | def create_keras_model():
initializer = tf.keras.initializers.GlorotNormal(seed=0)
return tf.keras.models.Sequential([
tf.keras.layers.Input(shape=(784,)),
tf.keras.layers.Dense(10, kernel_initializer=initializer),
tf.keras.layers.Softmax(),
]) | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
TFF์์ ์ด ๋ชจ๋ธ์ ์ฌ์ฉํ๊ธฐ ์ํด Keras ๋ชจ๋ธ์ tff.learning.Model๋ก ๋ํํฉ๋๋ค. ์ด๋ฅผ ํตํด TFF ๋ด์์ ๋ชจ๋ธ์ ์ ๋ฐฉํฅ ์ ๋ฌ์ ์ํํ๊ณ ๋ชจ๋ธ ์ถ๋ ฅ์ ์ถ์ถํ ์ ์์ต๋๋ค. ์์ธํ ๋ด์ฉ์ ์ด๋ฏธ์ง ๋ถ๋ฅ ํํ ๋ฆฌ์ผ์ ์ฐธ์กฐํ์ธ์. | def model_fn():
keras_model = create_keras_model()
return tff.learning.from_keras_model(
keras_model,
input_spec=federated_train_data[0].element_spec,
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ฌ๊ธฐ์๋ tf.keras๋ฅผ ์ฌ์ฉํ์ฌ tff.learning.Model์ ์์ฑํ์ง๋ง TFF๋ ํจ์ฌ ๋ ๋ง์ ์ผ๋ฐ ๋ชจ๋ธ์ ์ง์ํฉ๋๋ค. ์ด๋ฌํ ๋ชจ๋ธ์๋ ๋ชจ๋ธ ๊ฐ์ค์น๋ฅผ ์บก์ฒํ๋ ๋ค์๊ณผ ๊ฐ์ ๊ด๋ จ ์์ฑ์ด ์์ต๋๋ค.
trainable_variables: ํ์ต ๊ฐ๋ฅํ ๋ ์ด์ด์ ํด๋นํ๋ ํ
์์ ์ดํฐ๋ฌ๋ธ์
๋๋ค.
non_trainable_variables: ํ์ตํ ์ ์๋ ๋ ์ด์ด์ ํด๋นํ๋ ํ
์์ ์ดํฐ๋ฌ๋ธ์
๋๋ค.
์ฌ๊ธฐ์๋ ๋ชฉ์ ์ trainable_variables๋ง ์ฌ์ฉํฉ๋๋ค(์ฐ๋ฆฌ ๋ชจ๋ธ์๋ ์ด๊ฒ๋ง ์์ผ๋ฏ๋ก!).
๊ณ ์ ํ ํ๋๋ ์ด์
ํ์ต ์๊ณ ๋ฆฌ์ฆ ๊ตฌ์ถํ๊ธฐ
tff.learning API... | def initialize_fn():
model = model_fn()
return model.trainable_variables | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ด ํจ์๋ ๋ฌธ์ ์์ด ๋ณด์ด์ง๋ง "TFF ๊ณ์ฐ"์ด ๋๋๋ก ์ฝ๊ฐ ์์ ํด์ผ ํฉ๋๋ค. ์ด ๋ด์ฉ์ ๋์ค์ ์์๋ณผ ๊ฒ์
๋๋ค.
๋ํ, ์ฐ๋ฆฌ๋ next_fn๋ฅผ ์ค์ผ์นํ๋ ค๊ณ ํฉ๋๋ค. | def next_fn(server_weights, federated_dataset):
# Broadcast the server weights to the clients.
server_weights_at_client = broadcast(server_weights)
# Each client computes their updated weights.
client_weights = client_update(federated_dataset, server_weights_at_client)
# The server averages these updates.
... | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ด ๋ค ๊ฐ์ง ๊ตฌ์ฑ ์์๋ฅผ ๊ฐ๋ณ์ ์ผ๋ก ๊ตฌํํ๋ ๋ฐ ์ค์ ์ ๋ ๊ฒ์
๋๋ค. ๋จผ์ ์์ TensorFlow์์ ๊ตฌํํ ์ ์๋ ๋ถ๋ถ, ์ฆ ํด๋ผ์ด์ธํธ ๋ฐ ์๋ฒ ์
๋ฐ์ดํธ ๋จ๊ณ์ ์ด์ ์ ๋ง์ถ ๊ฒ์
๋๋ค.
TensorFlow ๋ธ๋ก
ํด๋ผ์ด์ธํธ ์
๋ฐ์ดํธ
tff.learning.Model์ ์ฌ์ฉํ์ฌ ๊ธฐ๋ณธ์ ์ผ๋ก TensorFlow ๋ชจ๋ธ์ ํ๋ จํ๋ ๊ฒ๊ณผ ๋์ผํ ๋ฐฉ์์ผ๋ก ํด๋ผ์ด์ธํธ ํ๋ จ์ ์ํํฉ๋๋ค. ํนํ, ์ฐ๋ฆฌ๋ tf.GradientTape๋ฅผ ์ฌ์ฉํ์ฌ ๋ฐ์ดํฐ ๋ฐฐ์น์ ๋ํ ๊ทธ๋ ๋์ธํธ๋ฅผ ๊ณ์ฐํ ๋ค์ client_optimizer๋ฅผ ์ฌ์ฉํ์ฌ ์ด๋ฌํ ๊ทธ๋ ๋์ธํธ๋ฅผ ์ ์ฉํฉ๋๋ค. ์ฐ๋ฆฌ๋ ํ๋ จ ๊ฐ๋ฅํ ๊ฐ์ค... | @tf.function
def client_update(model, dataset, server_weights, client_optimizer):
"""Performs training (using the server model weights) on the client's dataset."""
# Initialize the client model with the current server weights.
client_weights = model.trainable_variables
# Assign the server weights to the client ... | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
์๋ฒ ์
๋ฐ์ดํธ
FedAvg์ ๋ํ ์๋ฒ ์
๋ฐ์ดํธ๋ ํด๋ผ์ด์ธํธ ์
๋ฐ์ดํธ๋ณด๋ค ๊ฐ๋จํฉ๋๋ค. ์ฐ๋ฆฌ๋ ๋จ์ํ ์๋ฒ ๋ชจ๋ธ ๊ฐ์ค์น๋ฅผ ํด๋ผ์ด์ธํธ ๋ชจ๋ธ ๊ฐ์ค์น์ ํ๊ท ์ผ๋ก ๋ฐ๊พธ๋ "๋ฐ๋๋ผ" ํ๋๋ ์ด์
ํ๊ท ํ๋ฅผ ๊ตฌํํ ๊ฒ์
๋๋ค. ๋ค์ ๋งํ์ง๋ง, ์ฐ๋ฆฌ๋ ํ๋ จ ๊ฐ๋ฅํ ๊ฐ์ค์น์๋ง ์ด์ ์ ๋ง์ถฅ๋๋ค. | @tf.function
def server_update(model, mean_client_weights):
"""Updates the server model weights as the average of the client model weights."""
model_weights = model.trainable_variables
# Assign the mean client weights to the server model.
tf.nest.map_structure(lambda x, y: x.assign(y),
m... | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
๋จ์ํ mean_client_weights๋ฅผ ๋ฐํํ์ฌ ์ค๋ํซ์ ๋จ์ํํ ์ ์์ต๋๋ค. ๊ทธ๋ฌ๋ Federated Averaging์ ๊ณ ๊ธ ๊ตฌํ์์๋ ๋ชจ๋ฉํ
๋๋ ์ ์์ฑ๊ณผ ๊ฐ์ ๋ณด๋ค ์ ๊ตํ ๊ธฐ์ ๊ณผ ํจ๊ป mean_client_weights๋ฅผ ์ฌ์ฉํฉ๋๋ค.
๊ณผ์ : model_weights ๋ฐ mean_client_weights์ ์ค๊ฐ์ ์ด ๋๋๋ก ์๋ฒ ๊ฐ์ค์น๋ฅผ ์
๋ฐ์ดํธํ๋ server_update ๋ฒ์ ์ ๊ตฌํํฉ๋๋ค(์ฐธ๊ณ : ์ด๋ฌํ ์ข
๋ฅ์ "์ค๊ฐ์ " ์ ๊ทผ ๋ฐฉ์์ Lookahead ์ตํฐ๋ง์ด์ ์ ๋ํ ์ต๊ทผ์ ์์
๊ณผ ์ ์ฌํฉ๋๋ค!).
์ง๊ธ๊น์ง ์์ํ TensorFlow ์ฝ๋๋ง ์์ฑํ์ต๋๋ค... | federated_float_on_clients = tff.FederatedType(tf.float32, tff.CLIENTS) | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
ํ๋๋ ์ด์
์ ํ์ ํด๋น ๊ตฌ์ฑ์ ๊ตฌ์ฑ ์์(์: tf.float32)์ ์ ํ T์ ์ฅ์น ๊ทธ๋ฃน G๋ก ์ง์ ๋ฉ๋๋ค. G๊ฐ tff.CLIENTS ๋๋ tff.SERVER์ธ ๊ฒฝ์ฐ์ ์ค์ ์ ๋ ๊ฒ์
๋๋ค. ์ด๋ฌํ ํ๋๋ ์ด์
์ ํ์ ์๋์ ๊ฐ์ด {T}@G๋ก ํ์๋ฉ๋๋ค. | str(federated_float_on_clients) | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
๊ฒ์ฌ ์์น์ ๊ด์ฌ์ด ๋ง์ ์ด์ ๋ ๋ฌด์์
๋๊น? TFF์ ํต์ฌ ๋ชฉํ๋ ์ค์ ๋ถ์ฐ ์์คํ
์ ๋ฐฐํฌํ ์ ์๋ ์ฝ๋๋ฅผ ์์ฑํ ์ ์๋๋ก ํ๋ ๊ฒ์
๋๋ค. ์ฆ, ์ฅ์น์ ํ์ ์งํฉ์ด ์ด๋ค ์ฝ๋๋ฅผ ์คํํ๊ณ ๋ค๋ฅธ ๋ฐ์ดํฐ ์กฐ๊ฐ์ด ์ด๋์ ์๋์ง ์ถ๋ก ํ๋ ๊ฒ์ด ์ค์ํฉ๋๋ค.
TFF๋ ๋ฐ์ดํฐ, ๋ฐ์ดํฐ๊ฐ ๋ฐฐ์น๋๋ ์์น ๋ฐ ๋ฐ์ดํฐ๊ฐ ๋ณํ๋๋ ๋ฐฉ๋ฒ์ ์ธ ๊ฐ์ง์ ์ค์ ์ ๋ก๋๋ค. ์ฒ์ ๋ ๊ฐ๋ ํ๋๋ ์ด์
์ ํ์ผ๋ก ์บก์ํ๋๊ณ ๋ง์ง๋ง ๋ ๊ฐ๋ ํ๋๋ ์ด์
๊ณ์ฐ์ ์บก์ํ๋ฉ๋๋ค.
ํ๋๋ ์ด์
๊ณ์ฐ
TFF๋ ๊ธฐ๋ณธ ๋จ์๊ฐ ํ๋๋ ์ด์
๊ณ์ฐ์ธ ๊ฐ๋ ฅํ ํ์์ ํจ์ํ ํ๋ก๊ทธ๋๋ฐ ํ๊ฒฝ์
๋๋ค. ์ด๋ค์ ํ๋๋ ์ด์
๊ฐ์ ์
๋ ฅ์ผ๋ก ... | @tff.federated_computation(tff.FederatedType(tf.float32, tff.CLIENTS))
def get_average_temperature(client_temperatures):
return tff.federated_mean(client_temperatures) | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
TensorFlow์ tf.function ๋ฐ์ฝ๋ ์ดํฐ์ ์ด๋ป๊ฒ ๋ค๋ฅธ์ง ๋ฌผ์ด๋ณผ ์ ์์ต๋๋ค. ํต์ฌ์ ์ธ ๋๋ต์ tff.federated_computation์ ์ํด ์์ฑ๋ ์ฝ๋๊ฐ TensorFlow๋ ์๋๊ณ Python ์ฝ๋๋ ์๋๋ผ๋ ๊ฒ์
๋๋ค. ๋ด๋ถ ํ๋ซํผ ๋
๋ฆฝ์ ์ธ ๊ธ๋ฃจ ์ธ์ด๋ก ๋ ๋ถ์ฐ ์์คํ
์ ์ฌ์์
๋๋ค.
๋ณต์กํ๊ฒ ๋ค๋ฆด ์ ์์ง๋ง TFF ๊ณ์ฐ์ ์ ์ ์๋ ํ์ ์๋ช
์ด ์๋ ํจ์๋ก ์๊ฐํ ์ ์์ต๋๋ค. ์ด๋ฌํ ์ ํ ์๋ช
์ ์ง์ ์ฟผ๋ฆฌํ ์ ์์ต๋๋ค. | str(get_average_temperature.type_signature) | site/ko/federated/tutorials/building_your_own_federated_learning_algorithm.ipynb | tensorflow/docs-l10n | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.