markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Display Spectrogram + Aubio Pitch + Aubio Beat | plt.figure(1)
spec_res = specgram_.results['spectrogram_analyzer']
N = spec_res.parameters['fft_size']
plt.imshow(20 * np.log10(spec_res.data.T),
origin='lower',
extent=[spec_res.time[0], spec_res.time[-1], 0,
(N // 2 + 1) / N * spec_res.data_object.frame_metadata.samplerate],
... | docs/ipynb/02_Aubio.ipynb | Parisson/TimeSide | agpl-3.0 |
Display waveform + Onsets | plt.figure(2)
res_wave = waveform.results['waveform_analyzer']
plt.plot(res_wave.time, res_wave.data)
res_onsets = aubio_temporal.results['aubio_temporal.onset']
for time in res_onsets.time:
plt.axvline(time, color='r')
plt.grid()
plt.title('Waveform + Aubio onset')
plt.show()
res_pitch.render();
res_beats.render... | docs/ipynb/02_Aubio.ipynb | Parisson/TimeSide | agpl-3.0 |
Supported functions
Here are some examples of supported function implementations that Autograd can differentiate. Keep in mind that this list over examples is not comprehensive, but rather explores which basic constructions one might often use.
Functions using simple arithmetics | def f1(x):
return x**3 + 1
f1_grad = grad(f1)
# Remember to send in float as argument to the computed gradient from Autograd!
a = 1.0
# See the evaluated gradient at a using autograd:
print("The gradient of f1 evaluated at a = %g using autograd is: %g"%(a,f1_grad(a)))
# Compare with the analytical derivative, t... | doc/src/Optimization/autodiff/examples_allowed_functions.ipynb | CompPhysics/MachineLearning | cc0-1.0 |
Functions with two (or more) arguments
To differentiate with respect to two (or more) arguments of a Python function, Autograd need to know at which variable the function if being differentiated with respect to. | def f2(x1,x2):
return 3*x1**3 + x2*(x1 - 5) + 1
# By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1
f2_grad_x1 = grad(f2,0)
# ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad
f2_grad_x2 = grad(f2,1)
x1 = 1.0
x2 = 3.0
print("Ev... | doc/src/Optimization/autodiff/examples_allowed_functions.ipynb | CompPhysics/MachineLearning | cc0-1.0 |
Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable.
Functions using the elements of its argument directly | def f3(x): # Assumes x is an array of length 5 or higher
return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2
f3_grad = grad(f3)
x = np.linspace(0,4,5)
# Print the computed gradient:
print("The computed gradient of f3 is: ", f3_grad(x))
# The analytical gradient is: (2, 3, 5, 7, 22*x[4])
f3_grad_analytical = n... | doc/src/Optimization/autodiff/examples_allowed_functions.ipynb | CompPhysics/MachineLearning | cc0-1.0 |
Note that in this case, when sending an array as input argument, the output from Autograd is another array. This is the true gradient of the function, as opposed to the function in the previous example. By using arrays to represent the variables, the output from Autograd might be easier to work with, as the output is c... | def f4(x):
return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)
f4_grad = grad(f4)
x = 2.7
# Print the computed derivative:
print("The computed derivative of f4 at x = %g is: %g"%(x,f4_grad(x)))
# The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi
f4_grad_analytical = x/np.sqrt(1 + x**... | doc/src/Optimization/autodiff/examples_allowed_functions.ipynb | CompPhysics/MachineLearning | cc0-1.0 |
Functions using if-else tests | def f5(x):
if x >= 0:
return x**2
else:
return -3*x + 1
f5_grad = grad(f5)
x = 2.7
# Print the computed derivative:
print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x)))
# The analytical derivative is:
# if x >= 0, then 2*x
# else -3
if x >= 0:
f5_grad_analytical = 2*x... | doc/src/Optimization/autodiff/examples_allowed_functions.ipynb | CompPhysics/MachineLearning | cc0-1.0 |
Functions using for- and while loops | def f6_for(x):
val = 0
for i in range(10):
val = val + x**i
return val
def f6_while(x):
val = 0
i = 0
while i < 10:
val = val + x**i
i = i + 1
return val
f6_for_grad = grad(f6_for)
f6_while_grad = grad(f6_while)
x = 0.5
# Print the computed derivaties of f6_for an... | doc/src/Optimization/autodiff/examples_allowed_functions.ipynb | CompPhysics/MachineLearning | cc0-1.0 |
Functions using recursion | def f7(n): # Assume that n is an integer
if n == 1 or n == 0:
return 1
else:
return n*f7(n-1)
f7_grad = grad(f7)
n = 2.0
print("The computed derivative of f7 at n = %d is: %g"%(n,f7_grad(n)))
# The function f7 is an implementation of the factorial of n.
# By using the product rule, one can f... | doc/src/Optimization/autodiff/examples_allowed_functions.ipynb | CompPhysics/MachineLearning | cc0-1.0 |
Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.
Unsupported functions
Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.
Assigning a value to the variable being differenti... | def f8(x): # Assume x is an array
x[2] = 3
return x*2
f8_grad = grad(f8)
x = 8.4
print("The derivative of f8 is:",f8_grad(x)) | doc/src/Optimization/autodiff/examples_allowed_functions.ipynb | CompPhysics/MachineLearning | cc0-1.0 |
Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.
The syntax a.dot(b) when finding the dot product | def f9(a): # Assume a is an array with 2 elements
b = np.array([1.0,2.0])
return a.dot(b)
f9_grad = grad(f9)
x = np.array([1.0,0.0])
print("The derivative of f9 is:",f9_grad(x)) | doc/src/Optimization/autodiff/examples_allowed_functions.ipynb | CompPhysics/MachineLearning | cc0-1.0 |
Here we are told that the 'dot' function does not belong to Autograd's version of a Numpy array.
To overcome this, an alternative syntax which also computed the dot product can be used: | def f9_alternative(x): # Assume a is an array with 2 elements
b = np.array([1.0,2.0])
return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2
f9_alternative_grad = grad(f9_alternative)
x = np.array([3.0,0.0])
print("The gradient of f9 is:",f9_alternative_grad(x))
# The analytical gradient of the dot product of v... | doc/src/Optimization/autodiff/examples_allowed_functions.ipynb | CompPhysics/MachineLearning | cc0-1.0 |
Calling the original FORTRAN code | # Initialization of setup:
# Figure 4 in Lane R. Johnson - Green’s Function for Lamb’s Problem, 1974
# is reproduced when the following parameters are given
# -----------------------------------------------------------------------------
r = 10.0 # km
vp = 8.0 # P-wave velocity km/s
vs = 4.62 # s-wave velo... | lambs_problem/lambs_problem_solution.ipynb | davofis/computational_seismology | gpl-3.0 |
Visualization of the Green's function | # Plotting
# -----------------------------------------------------------------------------
seis = [u_rx, u_tx, u_zx, u_rz, u_zz] # Collection of seismograms
labels = ['$u_{rx}(t) [cm]$','$u_{tx}(t)[cm]$','$u_{zx}(t)[cm]$','$u_{rz}(t)[cm]$','$u_{zz}(t)[cm]$']
cols = ['b','r','k','g','c']
# Initialize animated plot
fig... | lambs_problem/lambs_problem_solution.ipynb | davofis/computational_seismology | gpl-3.0 |
Convolution
Let $S(t)$ be a general source time function, then the displacent seismogram is given in terms of the Green's function $G$ via
\begin{equation}
u(\mathbf{x},t) = G(\mathbf{x},t; \mathbf{x}',t') \ast S(t)
\end{equation}
Exercise
Compute the convolution of the source time function 'ricker' with the Green's fu... | # call the source time function
T = 1/5 # Period
src = ricker(dt,T)
# Normalize source time function
src = src/max(src)
# Initialize source time function
f = np.zeros(nt)
f[0:int(2 * T/dt)] = src
# Compute convolution
u = np.convolve(u_zz, f)
u = u[0:nt]
# ---------------------------------------------------------... | lambs_problem/lambs_problem_solution.ipynb | davofis/computational_seismology | gpl-3.0 |
Load Data
We are going to use daily gas, electricity and water consumption data and weather data. Because we don't want to overload the weather API, we will only use 1 location (Ukkel).
First, let's define the start and end date of the identification data. That is the data to be used to find the model. Later, we will... | start = pd.Timestamp('2015-01-01', tz='Europe/Brussels')
end = pd.Timestamp('now', tz='Europe/Brussels')
end_model = pd.Timestamp('2016-12-31', tz='Europe/Brussels') #last day of the data period for the model | notebooks/Analysis/Multivariable_regression_cached_data.ipynb | JrtPec/opengrid | apache-2.0 |
Energy data
We for each consumption type (electricity, gas and water), we create a daily dataframe and save it in the dictionary dfs. The data is obtained from the daily caches. | caches = {}
dfs = {}
for cons in ['electricity', 'gas', 'water']:
caches[cons] = caching.Cache(variable='{}_daily_total'.format(cons))
dfs[cons] = caches[cons].get(sensors = hp.get_sensors(sensortype=cons)) | notebooks/Analysis/Multivariable_regression_cached_data.ipynb | JrtPec/opengrid | apache-2.0 |
Weather and other exogenous data
Run this block to download the weather data and save it to a pickle. This is a large request, and you can only do 2 or 3 of these per day before your credit with Forecast.io runs out!
We also add a column for each day-of-week which may be used by the regression algorithm on a daily basi... | from opengrid.library import forecastwrapper
weather = forecastwrapper.Weather(location=(50.8024, 4.3407), start=start, end=end - pd.Timedelta(days=1))
irradiances=[
(0, 90), # north vertical
(90, 90), # east vertical
(180, 90), # south vertical
(270, 90), # west vertical
]
orientations = [0, 90, 180, 2... | notebooks/Analysis/Multivariable_regression_cached_data.ipynb | JrtPec/opengrid | apache-2.0 |
Put data together
The generator below will return a dataframe with sensor id as first column and all exogenous data as other columns. | def data_generator(consumable):
dfcons = dfs[consumable]
for sensorid in dfcons.columns:
df = pd.concat([dfcons[sensorid], weather_data], axis=1).dropna()
df = df.tz_convert('Europe/Brussels')
yield sensorid, df | notebooks/Analysis/Multivariable_regression_cached_data.ipynb | JrtPec/opengrid | apache-2.0 |
Let's have a peek | cons = 'gas'
analysis_data = data_generator(cons)
sensorid, peek = next(analysis_data)
peek = peek.resample(rule='MS').sum()
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot_date(peek.index, peek[sensorid], '-', color='grey', lw=8, label=cons)
for column in peek.columns[1:]:
if 'heatingDegreeDays' in column:
... | notebooks/Analysis/Multivariable_regression_cached_data.ipynb | JrtPec/opengrid | apache-2.0 |
Run Regression Analysis
We run the analysis on monthly and weekly basis. | cons = 'water'
save_figures = True
analysis_data = data_generator(cons)
mrs_month = []
mrs_month_cv = []
mrs_week = []
for sensorid, data in analysis_data:
data.rename(columns={sensorid:cons}, inplace=True)
df = data.resample(rule='MS').sum()
if len(df) < 2:
continue
# monthly mode... | notebooks/Analysis/Multivariable_regression_cached_data.ipynb | JrtPec/opengrid | apache-2.0 |
Hyperparameters
N_FORWARD = 1: works but model struggles to predict from some positions<br/>
N_FORWARD = 4: better but still bad occasionnally<br/>
N_FORWARD = 8: works perfectly | NB_EPOCHS = 5 # number of times the model sees all the data during training
N_FORWARD = 8 # train the network to predict N in advance (traditionnally 1)
RESAMPLE_BY = 5 # averaging period in days (training on daily data is too much)
RNN_CELLSIZE = 128 # size of the RNN cells
N_LAYERS = 2 # numb... | tensorflow-rnn-tutorial/old-school-tensorflow/tutorial/02_RNN_generator_temperatures_solution.ipynb | GoogleCloudPlatform/tensorflow-without-a-phd | apache-2.0 |
Temperature data
This is what our temperature datasets looks like: sequences of daily (Tmin, Tmax) from 1960 to 2010. They have been cleaned up and eventual missing values have been filled by interpolation. Interpolated regions of the dataset are marked in red on the graph. | all_filenames = gfile.get_matching_files(ALL_FILEPATTERN)
eval_filenames = gfile.get_matching_files(EVAL_FILEPATTERN)
train_filenames = list(set(all_filenames) - set(eval_filenames))
# By default, this utility function loads all the files and places data
# from them as-is in an array, one file per line. Later, we will... | tensorflow-rnn-tutorial/old-school-tensorflow/tutorial/02_RNN_generator_temperatures_solution.ipynb | GoogleCloudPlatform/tensorflow-without-a-phd | apache-2.0 |
Resampling
Our RNN would need ot be unrolled across 365 steps to capture the yearly temperature cycles. That's a bit too much. We will resample the temparatures and work with 5-day averages for example. This is what resampled (Tmin, Tmax) temperatures look like. | # This time we ask the utility function to average temperatures over 5-day periods (RESAMPLE_BY=5)
ite = utils_batching.rnn_multistation_sampling_temperature_sequencer(eval_filenames, RESAMPLE_BY, tminmax=True)
evaltemps, _, evaldates, _, _ = next(ite)
# display five years worth of data
WEATHER_STATION = 0 ... | tensorflow-rnn-tutorial/old-school-tensorflow/tutorial/02_RNN_generator_temperatures_solution.ipynb | GoogleCloudPlatform/tensorflow-without-a-phd | apache-2.0 |
Visualize training sequences
This is what the neural network will see during training. | # The function rnn_multistation_sampling_temperature_sequencer puts one weather station per line in
# a batch and continues with data from the same station in corresponding lines in the next batch.
# Features and labels are returned with shapes [BATCHSIZE, SEQLEN, 2]. The last dimension of size 2
# contains (Tmin, Tmax... | tensorflow-rnn-tutorial/old-school-tensorflow/tutorial/02_RNN_generator_temperatures_solution.ipynb | GoogleCloudPlatform/tensorflow-without-a-phd | apache-2.0 |
The model definition
<div style="text-align: right; font-family: monospace">
X shape [BATCHSIZE, SEQLEN, 2]<br/>
Y shape [BATCHSIZE, SEQLEN, 2]<br/>
H shape [BATCHSIZE, RNN_CELLSIZE*NLAYERS]
</div>
When executed, this function instantiates the Tensorflow graph for our model. | def model_rnn_fn(features, Hin, labels, step, dropout_pkeep):
X = features # shape [BATCHSIZE, SEQLEN, 2], 2 for (Tmin, Tmax)
batchsize = tf.shape(X)[0]
seqlen = tf.shape(X)[1]
pairlen = tf.shape(X)[2] # should be 2 (tmin, tmax)
cells = [tf.nn.rnn_cell.GRUCell(RNN_CELLSIZE, activation=ACTIVATI... | tensorflow-rnn-tutorial/old-school-tensorflow/tutorial/02_RNN_generator_temperatures_solution.ipynb | GoogleCloudPlatform/tensorflow-without-a-phd | apache-2.0 |
Instantiate the model | tf.reset_default_graph() # restart model graph from scratch
# placeholder for inputs
Hin = tf.placeholder(tf.float32, [None, RNN_CELLSIZE * N_LAYERS])
features = tf.placeholder(tf.float32, [None, None, 2]) # [BATCHSIZE, SEQLEN, 2]
labels = tf.placeholder(tf.float32, [None, None, 2]) # [BATCHSIZE, SEQLEN, 2]
step = tf.... | tensorflow-rnn-tutorial/old-school-tensorflow/tutorial/02_RNN_generator_temperatures_solution.ipynb | GoogleCloudPlatform/tensorflow-without-a-phd | apache-2.0 |
Initialize Tensorflow session
This resets all neuron weights and biases to initial random values | # variable initialization
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run([init])
saver = tf.train.Saver(max_to_keep=1) | tensorflow-rnn-tutorial/old-school-tensorflow/tutorial/02_RNN_generator_temperatures_solution.ipynb | GoogleCloudPlatform/tensorflow-without-a-phd | apache-2.0 |
The training loop
You can re-execute this cell to continue training. <br/>
<br/>
Training data must be batched correctly, one weather station per line, continued on the same line across batches. This way, output states computed from one batch are the correct input states for the next batch. The provided utility functio... | losses = []
indices = []
last_epoch = 99999
last_fileid = 99999
for i, (next_features, next_labels, dates, epoch, fileid) in enumerate(
utils_batching.rnn_multistation_sampling_temperature_sequencer(train_filenames,
RESAMPLE_BY,
... | tensorflow-rnn-tutorial/old-school-tensorflow/tutorial/02_RNN_generator_temperatures_solution.ipynb | GoogleCloudPlatform/tensorflow-without-a-phd | apache-2.0 |
Inference
This is a generative model: run an trained RNN cell in a loop | def prediction_run(predict_fn, prime_data, run_length):
H = np.zeros([1, RNN_CELLSIZE * N_LAYERS]) # zero state initially
Yout = np.zeros([1, N_FORWARD, 2])
data_len = prime_data.shape[0]-N_FORWARD
# prime the state from data
if data_len > 0:
Yin = np.array(prime_data[:-N_FORWARD])
... | tensorflow-rnn-tutorial/old-school-tensorflow/tutorial/02_RNN_generator_temperatures_solution.ipynb | GoogleCloudPlatform/tensorflow-without-a-phd | apache-2.0 |
Validation | QYEAR = 365//(RESAMPLE_BY*4)
YEAR = 365//(RESAMPLE_BY)
# Try starting predictions from January / March / July (resp. OFFSET = YEAR or YEAR+QYEAR or YEAR+2*QYEAR)
# Some start dates are more challenging for the model than others.
OFFSET = 30*YEAR+1*QYEAR
PRIMELEN=5*YEAR
RUNLEN=3*YEAR
PRIMELEN=512
RUNLEN=256
RMSELEN=3*... | tensorflow-rnn-tutorial/old-school-tensorflow/tutorial/02_RNN_generator_temperatures_solution.ipynb | GoogleCloudPlatform/tensorflow-without-a-phd | apache-2.0 |
1.1 Reading data from a csv file
You can read data from a CSV file using the read_csv function. By default, it assumes that the fields are comma-separated.
We're going to be looking some cyclist data from Montréal. Here's the original page (in French), but it's already included in this repository. We're using the data ... | broken_df = pd.read_csv('../data/bikes.csv')
# Look at the first 3 rows
broken_df[:3] | October 13th 2017 - Intro to Python/Lesson 1/Chapter 1 - Reading from a CSV.ipynb | aapeebles/tibertraining | mit |
You'll notice that this is totally broken! read_csv has a bunch of options that will let us fix that, though. Here we'll
change the column separator to a ;
Set the encoding to 'latin1' (the default is 'utf8')
Parse the dates in the 'Date' column
Tell it that our dates have the date first instead of the month first
Set... | fixed_df = pd.read_csv('../data/bikes.csv', sep=';', encoding='latin1', parse_dates=['Date'], dayfirst=True, index_col='Date')
fixed_df[:3] | October 13th 2017 - Intro to Python/Lesson 1/Chapter 1 - Reading from a CSV.ipynb | aapeebles/tibertraining | mit |
1.2 Selecting a column
When you read a CSV, you get a kind of object called a DataFrame, which is made up of rows and columns. You get columns out of a DataFrame the same way you get elements out of a dictionary.
Here's an example: | fixed_df['Berri 1'] | October 13th 2017 - Intro to Python/Lesson 1/Chapter 1 - Reading from a CSV.ipynb | aapeebles/tibertraining | mit |
1.3 Plotting a column
Just add .plot() to the end! How could it be easier? =)
We can see that, unsurprisingly, not many people are biking in January, February, and March, | fixed_df['Berri 1'].plot() | October 13th 2017 - Intro to Python/Lesson 1/Chapter 1 - Reading from a CSV.ipynb | aapeebles/tibertraining | mit |
We can also plot all the columns just as easily. We'll make it a little bigger, too.
You can see that it's more squished together, but all the bike paths behave basically the same -- if it's a bad day for cyclists, it's a bad day everywhere. | fixed_df.plot(figsize=(15, 10)) | October 13th 2017 - Intro to Python/Lesson 1/Chapter 1 - Reading from a CSV.ipynb | aapeebles/tibertraining | mit |
1.4 Putting all that together
Here's the code we needed to write do draw that graph, all together: | df = pd.read_csv('../data/bikes.csv', sep=';', encoding='latin1', parse_dates=['Date'], dayfirst=True, index_col='Date')
df['Berri 1'].plot() | October 13th 2017 - Intro to Python/Lesson 1/Chapter 1 - Reading from a CSV.ipynb | aapeebles/tibertraining | mit |
With this many layers, it's going to take a lot of iterations for this network to learn. By the time you're done training these 800 batches, your final test and validation accuracies probably won't be much better than 10%. (It will be different each time, but will most likely be less than 15%.)
Using batch normalizatio... | def fully_connected(prev_layer, num_units, is_training):
"""
Create a fully connectd layer with the given layer as input and the given number of neurons.
:param prev_layer: Tensor
The Tensor that acts as input into this layer
:param num_units: int
The size of the layer. That is, the... | batch-norm/Batch_Normalization_Exercises.ipynb | AlphaGit/deep-learning | mit |
TODO: Modify conv_layer to add batch normalization to the convolutional layers it creates. Feel free to change the function's parameters if it helps. | def conv_layer(prev_layer, layer_depth, is_training):
"""
Create a convolutional layer with the given layer as input.
:param prev_layer: Tensor
The Tensor that acts as input into this layer
:param layer_depth: int
We'll set the strides and number of feature maps based on the layer's... | batch-norm/Batch_Normalization_Exercises.ipynb | AlphaGit/deep-learning | mit |
TODO: Edit the train function to support batch normalization. You'll need to make sure the network knows whether or not it is training, and you'll need to make sure it updates and uses its population statistics correctly. | def train(num_batches, batch_size, learning_rate):
# Build placeholders for the input samples and labels
inputs = tf.placeholder(tf.float32, [None, 28, 28, 1])
labels = tf.placeholder(tf.float32, [None, 10])
is_training = tf.placeholder(tf.bool)
# Feed the inputs into a series of 20 convolutio... | batch-norm/Batch_Normalization_Exercises.ipynb | AlphaGit/deep-learning | mit |
With batch normalization, you should now get an accuracy over 90%. Notice also the last line of the output: Accuracy on 100 samples. If this value is low while everything else looks good, that means you did not implement batch normalization correctly. Specifically, it means you either did not calculate the population m... | def fully_connected(prev_layer, num_units):
"""
Create a fully connectd layer with the given layer as input and the given number of neurons.
:param prev_layer: Tensor
The Tensor that acts as input into this layer
:param num_units: int
The size of the layer. That is, the number of un... | batch-norm/Batch_Normalization_Exercises.ipynb | AlphaGit/deep-learning | mit |
Unit Test
The following unit test is expected to fail until you solve the challenge. | # %load test_path_exists.py
from nose.tools import assert_equal
class TestPathExists(object):
def test_path_exists(self):
nodes = []
graph = Graph()
for id in range(0, 6):
nodes.append(graph.add_node(id))
graph.add_edge(0, 1, 5)
graph.add_edge(0, 4, 3)
... | interactive-coding-challenges/graphs_trees/graph_path_exists/path_exists_challenge.ipynb | saashimi/code_guild | mit |
The concept of correlated colour temperature should not be used if the chromaticity of the test source differs more than $\Delta C=5\cdot10^{-2}$ from the Planckian radiator with: <a name="back_reference_2"></a><a href="#reference_2">[2]</a>
$$
\Delta C= \Biggl[ \Bigl(u_t^\prime-u_p^\prime\Bigr)^2+\cfrac{4}{9}\Bigl(v_t... | colour.temperature.uv_to_CCT_Robertson1968((0.19783451566098664, 0.31221744678060825)) | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
colour.uv_to_CCT definition is implemented as a wrapper for various correlated colour temperature computation methods: | colour.uv_to_CCT((0.19783451566098664, 0.31221744678060825), 'Robertson 1968') | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Note: 'robertson1968' is defined as a convenient alias for 'Robertson 1968': | colour.uv_to_CCT((0.19783451566098664, 0.31221744678060825), 'robertson1968') | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Converting from correlated colour temperature $T_{cp}$ and distance $D_{uv}$ to chomaticity coordinates $uv$: | colour.CCT_to_uv(6503.03994225557, 'Robertson 1968', D_uv=0.0032556165414977167)
colour.CCT_to_uv(6503.03994225557, 'robertson1968', D_uv=0.0032556165414977167) | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Ohno (2013) Method
Ohno (2013) presented new practical accurate methods to calculate the correlated colour temperature $T_{cp}$ and distance $D_{uv}$ with an error of 1 $K$ in $T_{cp}$ range from 1000 to 20,000 and $\pm$0.03 in $D_{uv}$. <a name="back_reference_4"></a><a href="#reference_4">[4]</a>
Triangular Solution
... | colour.temperature.uv_to_CCT_Ohno2013((0.19783451566098664, 0.31221744678060825)) | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Precision can be changed by passing a value to the iterations argument: | for i in range(10):
print(colour.temperature.uv_to_CCT_Ohno2013(
(0.19783451566098664, 0.31221744678060825), iterations=i + 1)) | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Using the colour.uv_to_CCT wrapper definition: | colour.uv_to_CCT((0.19783451566098664, 0.31221744678060825), 'Ohno 2013') | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Note: 'ohno2013' is defined as a convenient alias for 'Ohno 2013': | colour.uv_to_CCT((0.19783451566098664, 0.31221744678060825), 'ohno2013') | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Converting from correlated colour temperature $T_{cp}$ and distance $D_{uv}$ to chomaticity coordinates $uv$: | colour.CCT_to_uv(6503.03994225557, 'Ohno 2013', D_uv=0.0032556165414977167, )
colour.CCT_to_uv(6503.03994225557, 'Ohno 2013', D_uv=0.0032556165414977167) | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
McCamy (1992) Method
McCamy (1992) proposed an equation to compute correlated colour temperature $T_{cp}$ from CIE 1931 2° Standard Observer chromaticity coordinates $x$, $y$ by using a chromaticity epicenter ($x_e$, $y_e$) where the isotemperature lines in some of the correlated colour temperature range converge and t... | colour.temperature.xy_to_CCT_McCamy1992((0.31271, 0.32902)) | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
The colour.xy_to_CCT definition is implemented as a wrapper for various correlated colour temperature computation methods from CIE 1931 2° Standard Observer chromaticity coordinates $x$, $y$: | colour.xy_to_CCT((0.31271, 0.32902), 'McCamy 1992') | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Note: 'mccamy1992' is defined as a convenient alias for 'McCamy 1992': | colour.xy_to_CCT((0.31271, 0.32902), 'mccamy1992') | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Hernandez-Andres, Lee and Romero (1999) Method
Hernandez-Andres, Lee and Romero (1999) extended McCamy (1992) work by using a second epicenter to extend the accuracy over a wider correlated colour temperature and chromaticity coordinates range ($3000$–$10^6K$). <a name="back_reference_6"></a><a href="#reference_6">[6]<... | colour.temperature.xy_to_CCT_Hernandez1999((0.31271, 0.32902)) | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Using the colour.xy_to_CCT wrapper definition: | colour.xy_to_CCT((0.31271, 0.32902), 'Hernandez 1999') | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Note: 'hernandez1999' is defined as a convenient alias for 'Hernandez 1999': | colour.xy_to_CCT((0.31271, 0.32902), 'hernandez1999') | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Krystek (1985) Method
Krystek (1985) proposed a polynomial approximation valid from $1000K$ to $15000K$. <a name="back_reference_7"></a><a href="#reference_7">[7]</a>
The CIE UCS colourspace chromaticity coordinates $u$, $v$ are given by the following equations: <a name="back_reference_7"></a><a href="#reference_7">[7]... | colour.temperature.CCT_to_uv_Krystek1985(6504.389383048972) | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Using the colour.CCT_to_uv wrapper definition: | colour.CCT_to_uv(6504.389383048972, 'Krystek 1985') | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Kang et al. (2002) Method
Kang et al. (2002) proposed an advanced colour-temperature control system for HDTV applications in the range from $1667K$ to $25000K$. <a name="back_reference_8"></a><a href="#reference_8">[8]</a>
The CIE 1931 2° Standard Observer chromaticity coordinates $x$, $y$ are given by the following eq... | colour.temperature.CCT_to_xy_Kang2002(6504.389383048972) | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
The colour.CCT_to_xy definition is implemented as a wrapper for various CIE 1931 2° Standard Observer chromaticity coordinates $x$, $y$ computation from correlated colour temperature: | colour.CCT_to_xy(6504.389383048972, 'Kang 2002') | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Note: 'kang2002' is defined as a convenient alias for 'Kang 2002': | colour.CCT_to_xy(6504.389383048972, 'kang2002') | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
CIE Illuminant D Series Method
Judd et al. (1964) defined the following equations to calculate the CIE 1931 2° Standard Observer chromaticity coordinates $x_D$, $y_D$ of a CIE Illuminant D Series: <a name="back_reference_9"></a><a href="#reference_9">[9]</a>
$$
\begin{equation}
\begin{aligned}
x_D&\ =\begin{cases}-4,60... | colour.temperature.CCT_to_xy_CIE_D(6504.389383048972) | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Using the colour.CCT_to_xy wrapper definition: | colour.CCT_to_xy(6504.389383048972, 'CIE Illuminant D Series') | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Note: 'cie_d' is defined as a convenient alias for 'CIE Illuminant D Series': | colour.CCT_to_xy(6504.389383048972, 'cie_d') | notebooks/temperature/cct.ipynb | colour-science/colour-ipython | bsd-3-clause |
Configure imports
Import TensorFlow and the other required Python modules. By default, TensorFlow uses eager execution to evaluate operations immediately, returning concrete values instead of creating a computational graph that is executed later. If you are used to a REPL or the python interactive console, this feels f... | import os
import matplotlib.pyplot as plt
import tensorflow as tf
print(f"TensorFlow version: {tf.__version__}")
print(f"Eager execution: {tf.executing_eagerly()}") | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
The Iris classification problem
Imagine you are a botanist seeking an automated way to categorize each Iris flower you find. Machine learning provides many algorithms to classify flowers statistically. For instance, a sophisticated machine learning program could classify flowers based on photographs. Our ambitions are ... | train_dataset_url = "https://storage.googleapis.com/download.tensorflow.org/data/iris_training.csv"
train_dataset_fp = tf.keras.utils.get_file(
fname=os.path.basename(train_dataset_url), origin=train_dataset_url
)
print(f"Local copy of the dataset file: {train_dataset_fp}") | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Inspect the data
This dataset, iris_training.csv, is a plain text file that stores tabular data formatted as comma-separated values (CSV). Use the head -n5 command to take a peek at the first five entries: | !head -n5 {train_dataset_fp} | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
From this view of the dataset, notice the following:
The first line is a header containing information about the dataset:
There are 120 total examples. Each example has four features and one of three possible label names.
Subsequent rows are data records, one example per line, where:
The first four fields are features... | # column order in CSV file
column_names = [
"sepal_length",
"sepal_width",
"petal_length",
"petal_width",
"species",
]
feature_names = column_names[:-1]
label_name = column_names[-1]
print(f"Features: {feature_names}")
print(f"Label: {label_name}") | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Each label is associated with string name (for example, "setosa"), but machine learning typically relies on numeric values. The label numbers are mapped to a named representation, such as:
0: Iris setosa
1: Iris versicolor
2: Iris virginica
For more information about features and labels, see the ML Terminology sectio... | class_names = ["Iris setosa", "Iris versicolor", "Iris virginica"] | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Create a tf.data.Dataset
TensorFlow's Dataset API handles many common cases for loading data into a model. This is a high-level API for reading data and transforming it into a form used for training.
Since the dataset is a CSV-formatted text file, use the tf.data.experimental.make_csv_dataset function to parse the data... | batch_size = 32
train_dataset = tf.data.experimental.make_csv_dataset(
train_dataset_fp,
batch_size,
column_names=column_names,
label_name=label_name,
num_epochs=1,
) | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
The make_csv_dataset function returns a tf.data.Dataset of (features, label) pairs, where features is a dictionary: {'feature_name': value}
These Dataset objects are iterable. Let's look at a batch of features: | features, labels = next(iter(train_dataset))
print(features) | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Notice that like-features are grouped together, or batched. Each example row's fields are appended to the corresponding feature array. Change the batch_size to set the number of examples stored in these feature arrays.
You can start to see some clusters by plotting a few features from the batch: | plt.scatter(
features["petal_length"], features["sepal_length"], c=labels, cmap="viridis"
)
plt.xlabel("Petal length")
plt.ylabel("Sepal length")
plt.show() | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
To simplify the model building step, create a function to repackage the features dictionary into a single array with shape: (batch_size, num_features).
This function uses the tf.stack method which takes values from a list of tensors and creates a combined tensor at the specified dimension: | def pack_features_vector(features, labels):
"""Pack the features into a single array."""
features = tf.stack(list(features.values()), axis=1)
return features, labels | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Then use the tf.data.Dataset#map method to pack the features of each (features,label) pair into the training dataset: | train_dataset = train_dataset.map(pack_features_vector) | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
The features element of the Dataset are now arrays with shape (batch_size, num_features). Let's look at the first few examples: | features, labels = next(iter(train_dataset))
print(features[:5]) | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Select the type of model
Why model?
A model is a relationship between features and the label. For the Iris classification problem, the model defines the relationship between the sepal and petal measurements and the predicted Iris species. Some simple models can be described with a few lines of algebra, but complex mac... | # TODO 1
# TODO -- Your code here. | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
The activation function determines the output shape of each node in the layer. These non-linearities are important—without them the model would be equivalent to a single layer. There are many tf.keras.activations, but ReLU is common for hidden layers.
The ideal number of hidden layers and neurons depends on the problem... | predictions = model(features)
predictions[:5] | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Here, each example returns a logit for each class.
To convert these logits to a probability for each class, use the softmax function: | tf.nn.softmax(predictions[:5]) | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Taking the tf.argmax across classes gives us the predicted class index. But, the model hasn't been trained yet, so these aren't good predictions: | print(f"Prediction: {tf.argmax(predictions, axis=1)}")
print(f"Labels: {labels}") | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Train the model
Training is the stage of machine learning when the model is gradually optimized, or the model learns the dataset. The goal is to learn enough about the structure of the training dataset to make predictions about unseen data. If you learn too much about the training dataset, then the predictions only wor... | loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
def loss(model, x, y, training):
# TODO 2
# TODO -- Your code here. | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Use the tf.GradientTape context to calculate the gradients used to optimize your model: | def grad(model, inputs, targets):
with tf.GradientTape() as tape:
loss_value = loss(model, inputs, targets, training=True)
return loss_value, tape.gradient(loss_value, model.trainable_variables) | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Create an optimizer
An optimizer applies the computed gradients to the model's variables to minimize the loss function. You can think of the loss function as a curved surface (see Figure 3) and we want to find its lowest point by walking around. The gradients point in the direction of steepest ascent—so we'll travel th... | optimizer = tf.keras.optimizers.SGD(learning_rate=0.01) | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
We'll use this to calculate a single optimization step: | loss_value, grads = grad(model, features, labels)
print(
"Step: {}, Initial Loss: {}".format(
optimizer.iterations.numpy(), loss_value.numpy()
)
)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
print(
"Step: {},Loss: {}".format(
optimizer.iterations.numpy(),
loss... | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Training loop
With all the pieces in place, the model is ready for training! A training loop feeds the dataset examples into the model to help it make better predictions. The following code block sets up these training steps:
Iterate each epoch. An epoch is one pass through the dataset.
Within an epoch, iterate over e... | ## Note: Rerunning this cell uses the same model variables
# Keep results for plotting
train_loss_results = []
train_accuracy_results = []
num_epochs = 201
for epoch in range(num_epochs):
epoch_loss_avg = tf.keras.metrics.Mean()
epoch_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
# Training lo... | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Visualize the loss function over time
While it's helpful to print out the model's training progress, it's often more helpful to see this progress. TensorBoard is a nice visualization tool that is packaged with TensorFlow, but we can create basic charts using the matplotlib module.
Interpreting these charts takes some e... | fig, axes = plt.subplots(2, sharex=True, figsize=(12, 8))
fig.suptitle("Training Metrics")
axes[0].set_ylabel("Loss", fontsize=14)
axes[0].plot(train_loss_results)
axes[1].set_ylabel("Accuracy", fontsize=14)
axes[1].set_xlabel("Epoch", fontsize=14)
axes[1].plot(train_accuracy_results)
plt.show() | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Evaluate the model's effectiveness
Now that the model is trained, we can get some statistics on its performance.
Evaluating means determining how effectively the model makes predictions. To determine the model's effectiveness at Iris classification, pass some sepal and petal measurements to the model and ask the model ... | test_url = (
"https://storage.googleapis.com/download.tensorflow.org/data/iris_test.csv"
)
test_fp = tf.keras.utils.get_file(
fname=os.path.basename(test_url), origin=test_url
)
test_dataset = tf.data.experimental.make_csv_dataset(
test_fp,
batch_size,
column_names=column_names,
label_name="sp... | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Evaluate the model on the test dataset
Unlike the training stage, the model only evaluates a single epoch of the test data. In the following code cell, we iterate over each example in the test set and compare the model's prediction against the actual label. This is used to measure the model's accuracy across the entire... | test_accuracy = tf.keras.metrics.Accuracy()
for (x, y) in test_dataset:
# training=False is needed only if there are layers with different
# behavior during training versus inference (e.g. Dropout).
logits = model(x, training=False)
prediction = tf.argmax(logits, axis=1, output_type=tf.int32)
test_... | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
We can see on the last batch, for example, the model is usually correct: | tf.stack([y, prediction], axis=1) | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Use the trained model to make predictions
We've trained a model and "proven" that it's good—but not perfect—at classifying Iris species. Now let's use the trained model to make some predictions on unlabeled examples; that is, on examples that contain features but not a label.
In real-life, the unlabeled examples could ... | # TODO 3
# TODO -- Your code here. | notebooks/introduction_to_tensorflow/labs/basic_intro_logistic_regression.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Tabular training
How to use the tabular application in fastai
To illustrate the tabular application, we will use the example of the Adult dataset where we have to predict if a person is earning more or less than $50k per year using some general data. | from fastai.tabular.all import * | nbs/44_tutorial.tabular.ipynb | fastai/fastai | apache-2.0 |
We can download a sample of this dataset with the usual untar_data command: | path = untar_data(URLs.ADULT_SAMPLE)
path.ls() | nbs/44_tutorial.tabular.ipynb | fastai/fastai | apache-2.0 |
Then we can have a look at how the data is structured: | df = pd.read_csv(path/'adult.csv')
df.head() | nbs/44_tutorial.tabular.ipynb | fastai/fastai | apache-2.0 |
Some of the columns are continuous (like age) and we will treat them as float numbers we can feed our model directly. Others are categorical (like workclass or education) and we will convert them to a unique index that we will feed to embedding layers. We can specify our categorical and continuous column names, as well... | dls = TabularDataLoaders.from_csv(path/'adult.csv', path=path, y_names="salary",
cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race'],
cont_names = ['age', 'fnlwgt', 'education-num'],
procs = [Categorify, FillMissing, Normalize]) | nbs/44_tutorial.tabular.ipynb | fastai/fastai | apache-2.0 |
The last part is the list of pre-processors we apply to our data:
Categorify is going to take every categorical variable and make a map from integer to unique categories, then replace the values by the corresponding index.
FillMissing will fill the missing values in the continuous variables by the median of existing v... | splits = RandomSplitter(valid_pct=0.2)(range_of(df))
to = TabularPandas(df, procs=[Categorify, FillMissing,Normalize],
cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race'],
cont_names = ['age', 'fnlwgt', 'education-num'],
... | nbs/44_tutorial.tabular.ipynb | fastai/fastai | apache-2.0 |
Once we build our TabularPandas object, our data is completely preprocessed as seen below: | to.xs.iloc[:2] | nbs/44_tutorial.tabular.ipynb | fastai/fastai | apache-2.0 |
Now we can build our DataLoaders again: | dls = to.dataloaders(bs=64) | nbs/44_tutorial.tabular.ipynb | fastai/fastai | apache-2.0 |
Later we will explore why using TabularPandas to preprocess will be valuable.
The show_batch method works like for every other application: | dls.show_batch() | nbs/44_tutorial.tabular.ipynb | fastai/fastai | apache-2.0 |
We can define a model using the tabular_learner method. When we define our model, fastai will try to infer the loss function based on our y_names earlier.
Note: Sometimes with tabular data, your y's may be encoded (such as 0 and 1). In such a case you should explicitly pass y_block = CategoryBlock in your constructor ... | learn = tabular_learner(dls, metrics=accuracy) | nbs/44_tutorial.tabular.ipynb | fastai/fastai | apache-2.0 |
And we can train that model with the fit_one_cycle method (the fine_tune method won't be useful here since we don't have a pretrained model). | learn.fit_one_cycle(1) | nbs/44_tutorial.tabular.ipynb | fastai/fastai | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.