By: n JuliaLang - The Julia programming language n
Re-posted from: https://julialang.org/blog/2018/08/one-point-zero-zh_cn/index.html
Julia 1.0 正式发布 (Simplified Chinese) | 备受期待的Julia语言 (https://julialang.org)的1.0版本积累了富有野心的程序员们的十年心血。…
By: n JuliaLang - The Julia programming language n
Re-posted from: https://julialang.org/blog/2018/08/one-point-zero-zh_cn/index.html
Julia 1.0 正式发布 (Simplified Chinese) | 备受期待的Julia语言 (https://julialang.org)的1.0版本积累了富有野心的程序员们的十年心血。…
By: n JuliaLang - The Julia programming language n
Re-posted from: https://julialang.org/blog/2018/08/one-point-zero/index.html
Announcing the release of Julia 1.0. The much anticipated 1.0 release of Julia is the culmination of…
Re-posted from: https://tensorflowjulia.blogspot.com/2018/08/introduction-to-tensorflowjl.html
Tensorflow.jl does not expose tf.contrib.estimator.clip_gradients_by_norm (to my knowledge),
so instead of tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0) we use the construction
my_optimizer=(train.GradientDescentOptimizer(learning_rate))
gvs = train.compute_gradients(my_optimizer, loss)
capped_gvs = [(clip_by_norm(grad, 5.), var) for (grad, var) in gvs]
my_optimizer = train.apply_gradients(my_optimizer,capped_gvs)
The Jupyter Notebook can be downloaded here. It is also displayed below.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
using Plots
gr()
using DataFrames
using TensorFlow
import CSV
sess=Session()
Session(Ptr{Void} @0x000000011ba9dd70)
2018-08-05 21:12:46.959154: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.2 AVX AVX2 FMA
california_housing_dataframe = CSV.read("california_housing_train.csv", delim=",");
median_house_value to be in units of thousands, so it can be learned a little more easily with learning rates in a range that we usually use.california_housing_dataframe = california_housing_dataframe[shuffle(1:size(california_housing_dataframe, 1)),:];
california_housing_dataframe[:median_house_value] /= 1000.0
california_housing_dataframe
| longitude | latitude | housing_median_age | total_rooms | total_bedrooms | population | households | median_income | median_house_value | |
|---|---|---|---|---|---|---|---|---|---|
| 1 | -121.44 | 38.56 | 52.0 | 906.0 | 165.0 | 257.0 | 166.0 | 2.8542 | 139.4 |
| 2 | -122.13 | 37.77 | 24.0 | 2459.0 | 317.0 | 916.0 | 324.0 | 7.0712 | 293.0 |
| 3 | -117.96 | 34.14 | 33.0 | 1994.0 | 405.0 | 993.0 | 403.0 | 3.766 | 163.9 |
| 4 | -117.89 | 34.1 | 35.0 | 3185.0 | 544.0 | 1858.0 | 564.0 | 3.8304 | 175.9 |
| 5 | -118.21 | 34.09 | 37.0 | 1822.0 | 498.0 | 1961.0 | 506.0 | 1.9881 | 159.2 |
| 6 | -122.3 | 37.53 | 37.0 | 1338.0 | 215.0 | 535.0 | 221.0 | 5.4351 | 376.6 |
| 7 | -118.64 | 34.19 | 33.0 | 3017.0 | 494.0 | 1423.0 | 470.0 | 5.6163 | 248.4 |
| 8 | -121.23 | 37.8 | 11.0 | 2451.0 | 665.0 | 1155.0 | 533.0 | 2.2254 | 130.8 |
| 9 | -117.09 | 34.07 | 24.0 | 6260.0 | 1271.0 | 3132.0 | 1189.0 | 2.5156 | 103.0 |
| 10 | -121.71 | 37.99 | 27.0 | 3861.0 | 718.0 | 2085.0 | 707.0 | 3.3558 | 129.7 |
| 11 | -122.0 | 37.54 | 26.0 | 1910.0 | 371.0 | 852.0 | 357.0 | 5.8325 | 298.9 |
| 12 | -122.48 | 37.75 | 52.0 | 2515.0 | 494.0 | 1583.0 | 477.0 | 4.3393 | 317.6 |
| 13 | -118.97 | 37.64 | 14.0 | 1847.0 | 439.0 | 238.0 | 98.0 | 3.6042 | 137.5 |
| 14 | -120.85 | 37.51 | 5.0 | 2899.0 | 745.0 | 1593.0 | 633.0 | 2.2292 | 127.5 |
| 15 | -116.2 | 33.63 | 23.0 | 1152.0 | 273.0 | 1077.0 | 235.0 | 2.5 | 96.3 |
| 16 | -122.39 | 38.37 | 33.0 | 1066.0 | 191.0 | 403.0 | 163.0 | 6.8 | 240.8 |
| 17 | -118.3 | 33.89 | 37.0 | 2132.0 | 565.0 | 1369.0 | 565.0 | 3.285 | 218.1 |
| 18 | -117.01 | 32.73 | 22.0 | 2526.0 | 530.0 | 1556.0 | 529.0 | 2.8646 | 120.8 |
| 19 | -122.42 | 37.79 | 52.0 | 3457.0 | 1021.0 | 2286.0 | 994.0 | 2.565 | 225.0 |
| 20 | -118.02 | 34.15 | 44.0 | 2267.0 | 426.0 | 980.0 | 372.0 | 3.6 | 307.4 |
| 21 | -119.63 | 36.58 | 22.0 | 1794.0 | 435.0 | 1127.0 | 359.0 | 1.2647 | 55.3 |
| 22 | -118.12 | 33.87 | 21.0 | 3764.0 | 1081.0 | 1919.0 | 977.0 | 2.5057 | 156.3 |
| 23 | -118.15 | 34.71 | 36.0 | 1338.0 | 250.0 | 709.0 | 250.0 | 3.5625 | 101.4 |
| 24 | -118.06 | 33.72 | 22.0 | 4311.0 | 531.0 | 1426.0 | 533.0 | 9.8177 | 500.001 |
| 25 | -121.93 | 37.28 | 34.0 | 2422.0 | 370.0 | 1010.0 | 395.0 | 5.6494 | 376.2 |
| 26 | -118.54 | 34.23 | 35.0 | 3422.0 | 601.0 | 1690.0 | 574.0 | 4.375 | 232.9 |
| 27 | -118.4 | 33.88 | 35.0 | 1753.0 | 296.0 | 615.0 | 275.0 | 7.5 | 500.001 |
| 28 | -121.64 | 36.72 | 17.0 | 4203.0 | 816.0 | 2900.0 | 827.0 | 4.1742 | 159.9 |
| 29 | -118.31 | 33.73 | 52.0 | 1665.0 | 280.0 | 656.0 | 282.0 | 5.249 | 351.9 |
| 30 | -117.68 | 34.11 | 16.0 | 3190.0 | 471.0 | 1414.0 | 464.0 | 5.5292 | 208.6 |
| ⋮ | ⋮ | ⋮ | ⋮ | ⋮ | ⋮ | ⋮ | ⋮ | ⋮ | ⋮ |
describe(california_housing_dataframe)
| variable | mean | min | median | max | nunique | nmissing | eltype | |
|---|---|---|---|---|---|---|---|---|
| 1 | longitude | -119.562 | -124.35 | -118.49 | -114.31 | 0 | Float64 | |
| 2 | latitude | 35.6252 | 32.54 | 34.25 | 41.95 | 0 | Float64 | |
| 3 | housing_median_age | 28.5894 | 1.0 | 29.0 | 52.0 | 0 | Float64 | |
| 4 | total_rooms | 2643.66 | 2.0 | 2127.0 | 37937.0 | 0 | Float64 | |
| 5 | total_bedrooms | 539.411 | 1.0 | 434.0 | 6445.0 | 0 | Float64 | |
| 6 | population | 1429.57 | 3.0 | 1167.0 | 35682.0 | 0 | Float64 | |
| 7 | households | 501.222 | 1.0 | 409.0 | 6082.0 | 0 | Float64 | |
| 8 | median_income | 3.88358 | 0.4999 | 3.5446 | 15.0001 | 0 | Float64 | |
| 9 | median_house_value | 207.301 | 14.999 | 180.4 | 500.001 | Float64 |
median_house_value, which will be our label (sometimes also called a target). We’ll use total_rooms as our input feature.total_rooms. The following code pulls the total_rooms data from our california_housing_dataframe and defines a feature and targer column:# Define the input feature: total_rooms.
my_feature = california_housing_dataframe[:total_rooms]
# Configure a numeric feature column for total_rooms.
feature_columns = placeholder(Float32)
target_columns = placeholder(Float32)
<Tensor placeholder_2:1 shape=unknown dtype=Float32>
median_house_value. Again, we can pull it from our california_housing_dataframe:# Define the label.
targets = california_housing_dataframe[:median_house_value];
GradientDescentOptimizer, which implements Mini-Batch Stochastic Gradient Descent (SGD). The learning_rate argument controls the size of the gradient step.clip_gradients_by_norm. Gradient clipping ensures the magnitude of the gradients do not become too large during training, which can cause gradient descent to fail.# Configure the linear regression model with our feature columns and optimizer.
m=Variable(0.05)
b=Variable(0.0)
y=m.*feature_columns+b
loss=reduce_sum((target_columns - y).^2)
# Use gradient descent as the optimizer for training the model.
# Set a learning rate of 0.0000001 for Gradient Descent.
learning_rate=0.0000001;
my_optimizer=(train.GradientDescentOptimizer(learning_rate))
gvs = train.compute_gradients(my_optimizer, loss)
capped_gvs = [(clip_by_norm(grad, 5.), var) for (grad, var) in gvs]
my_optimizer = train.apply_gradients(my_optimizer,capped_gvs)
<Tensor Group:1 shape=unknown dtype=Any>
batch_size, to be repeated for the specified number of epochs (num_epochs).num_epochs=None is passed to repeat(), the input data will be repeated indefinitely.shuffle is set to True, we’ll shuffle the data so that it’s passed to the model randomly during training. The buffer_size argument specifies the size of the dataset from which shuffle will randomly sample.function create_batches(features, targets, steps, batch_size=5, num_epochs=0)
if(num_epochs==0)
num_epochs=ceil(batch_size*steps/length(features))
end
features_batches=Union{Float64, Missings.Missing}[]
target_batches=Union{Float64, Missings.Missing}[]
for i=1:num_epochs
select=shuffle(1:length(features))
append!(features_batches, features[select])
append!(target_batches, targets[select])
end
return features_batches, target_batches
end
create_batches (generic function with 3 methods)
function next_batch(features_batches, targets_batches, batch_size, iter)
select=mod((iter-1)*batch_size+1, length(features_batches)):mod(iter*batch_size, length(features_batches));
ds=features_batches[select];
target=targets_batches[select];
return ds, target
end
next_batch (generic function with 1 method)
function my_input_fn(features_batches, targets_batches, iter, batch_size=5, shuffle_flag=1):
"""Trains a linear regression model of one feature.
Args:
features: pandas DataFrame of features
targets: pandas DataFrame of targets
batch_size: Size of batches to be passed to the model
shuffle: True or False. Whether to shuffle the data.
num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely
Returns:
Tuple of (features, labels) for next data batch
"""
# Construct a dataset, and configure batching/repeating.
ds, target = next_batch(features_batches, targets_batches, batch_size, iter)
# Shuffle the data, if specified.
if shuffle_flag==1
select=shuffle(1:size(ds, 1));
ds = ds[select,:]
target = target[select, :]
end
# Return the next batch of data.
return convert.(Float64,ds), convert.(Float64,target)
end
my_input_fn (generic function with 3 methods)
train() on our my_optimizer to train the model. To start, we’ll train for 100 steps.steps=100;
batch_size=5;
run(sess, global_variables_initializer())
features_batches, targets_batches = create_batches(my_feature, targets, steps, batch_size)
for i=1:steps
features, labels = my_input_fn(features_batches, targets_batches, i, batch_size)
run(sess, my_optimizer, Dict(feature_columns=>features, target_columns=>labels))
end
weight = run(sess,m)
0.05002900000000003
bias = run(sess,b)
3.899999999999994e-5
# Run the TF session on the data to make predictions.
predictions = run(sess, y, Dict(feature_columns=>convert.(Float64, my_feature)));
# Print Mean Squared Error and Root Mean Squared Error.
mean_squared_error = mean((predictions- targets).^2);
root_mean_squared_error = sqrt(mean_squared_error);
println("Mean Squared Error (on training data): ", mean_squared_error)
println("Root Mean Squared Error (on training data): ", root_mean_squared_error)
Mean Squared Error (on training data): 27662.40649651179
Root Mean Squared Error (on training data): 166.32019269021964
min_house_value = minimum(california_housing_dataframe[:median_house_value])
max_house_value = maximum(california_housing_dataframe[:median_house_value])
min_max_difference = max_house_value - min_house_value
println("Min. Median House Value: " , min_house_value)
println("Max. Median House Value: " , max_house_value)
println("Difference between Min. and Max.: " , min_max_difference)
println("Root Mean Squared Error: " , root_mean_squared_error)
Min. Median House Value: 14.999
Max. Median House Value: 500.001
Difference between Min. and Max.: 485.00199999999995
Root Mean Squared Error: 166.32019269021964
calibration_data = DataFrame();
calibration_data[:predictions] = predictions;
calibration_data[:targets] = targets;
describe(calibration_data)
| variable | mean | min | median | max | nunique | nmissing | eltype | |
|---|---|---|---|---|---|---|---|---|
| 1 | predictions | 132.26 | 0.100097 | 106.412 | 1897.95 | Float64 | ||
| 2 | targets | 207.301 | 14.999 | 180.4 | 500.001 | Float64 |
sample = california_housing_dataframe[rand(1:size(california_housing_dataframe,1), 300),:];
# Get the min and max total_rooms values.
x_0 = minimum(sample[:total_rooms])
x_1 = maximum(sample[:total_rooms])
# Retrieve the final weight and bias generated during training.
weight = run(sess,m)
bias = run(sess,b)
# Get the predicted median_house_values for the min and max total_rooms values.
y_0 = weight * x_0 + bias
y_1 = weight * x_1 + bias
# Plot our regression line from (x_0, y_0) to (x_1, y_1).
plot([x_0, x_1], [y_0, y_1], c=:red, ylabel="median_house_value", xlabel="total_rooms", label="Fit line")
# Plot a scatter plot from our data sample.
scatter!(sample[:total_rooms], sample[:median_house_value], c=:blue, label="Data")
input_feature=:total_rooms
:total_rooms
function train_model(learning_rate, steps, batch_size, input_feature=:total_rooms)
"""Trains a linear regression model of one feature.
Args:
learning_rate: A `float`, the learning rate.
steps: A non-zero `int`, the total number of training steps. A training step
consists of a forward and backward pass using a single batch.
batch_size: A non-zero `int`, the batch size.
input_feature: A `string` specifying a column from `california_housing_dataframe`
to use as input feature.
"""
periods = 10
steps_per_period = steps / periods
my_feature = input_feature
my_feature_data = convert.(Float32,california_housing_dataframe[my_feature])
my_label = :median_house_value
targets = convert.(Float32,california_housing_dataframe[my_label])
# Create feature columns.
feature_columns = placeholder(Float32)
target_columns = placeholder(Float32)
# Create a linear regressor object.
# Configure the linear regression model with our feature columns and optimizer.
m=Variable(0.0)
b=Variable(0.0)
y=m.*feature_columns .+ b
loss=reduce_sum((target_columns - y).^2)
features_batches, targets_batches = create_batches(my_feature_data, targets, steps, batch_size)
# Use gradient descent as the optimizer for training the model.
my_optimizer=(train.GradientDescentOptimizer(learning_rate))
gvs = train.compute_gradients(my_optimizer, loss)
capped_gvs = [(clip_by_norm(grad, 5.), var) for (grad, var) in gvs]
my_optimizer = train.apply_gradients(my_optimizer,capped_gvs)
run(sess, global_variables_initializer())
# Set up to plot the state of our model's line each period.
sample = california_housing_dataframe[rand(1:size(california_housing_dataframe,1), 300),:];
p1=scatter(sample[my_feature], sample[my_label], title="Learned Line by Period", ylabel=my_label, xlabel=my_feature,color=:coolwarm)
colors= [ColorGradient(:coolwarm)[i] for i in linspace(0,1, periods+1)]
# Train the model, but do so inside a loop so that we can periodically assess
# loss metrics.
println("Training model...")
println("RMSE (on training data):")
root_mean_squared_errors = []
for period in 1:periods
# Train the model, starting from the prior state.
for i=1:steps_per_period
features, labels = my_input_fn(features_batches, targets_batches, convert(Int,(period-1)*steps_per_period+i), batch_size)
run(sess, my_optimizer, Dict(feature_columns=>features, target_columns=>labels))
end
# Take a break and compute predictions.
predictions = run(sess, y, Dict(feature_columns=>convert.(Float64, my_feature_data)));
# Compute loss.
mean_squared_error = mean((predictions- targets).^2)
root_mean_squared_error = sqrt(mean_squared_error)
# Occasionally print the current loss.
println(" period ", period, ": ", root_mean_squared_error)
# Add the loss metrics from this period to our list.
push!(root_mean_squared_errors, root_mean_squared_error)
# Finally, track the weights and biases over time.
# Apply some math to ensure that the data and line are plotted neatly.
y_extents = [0 maximum(sample[my_label])]
weight = run(sess,m)
bias = run(sess,b)
x_extents = (y_extents - bias) / weight
x_extents = max.(min.(x_extents, maximum(sample[my_feature])),
minimum(sample[my_feature]))
y_extents = weight .* x_extents .+ bias
p1=plot!(x_extents', y_extents', color=colors[period], linewidth=2)
end
println("Model training finished.")
# Output a graph of loss metrics over periods.
p2=plot(root_mean_squared_errors, title="Root Mean Squared Error vs. Periods", ylabel="RMSE", xlabel="Periods")
# Output a table with calibration data.
calibration_data = DataFrame()
calibration_data[:predictions] = predictions
calibration_data[:targets] = targets
describe(calibration_data)
println("Final RMSE (on training data): ", root_mean_squared_errors[end])
println("Final Weight (on training data): ", weight)
println("Final Bias (on training data): ", bias)
return p1, p2
end
train_model (generic function with 2 methods)
sess=Session()
p1, p2= train_model(
0.0001, # learning rate
20, # steps
5 # batch size
)
Training model...
RMSE (on training data):
period 1: 235.10452754834785
period 2: 232.69434701416756
period 3: 230.30994696291228
period 4: 227.95213639459652
period 5: 225.62174891342735
period 6: 223.31964301811482
period 7: 221.04670233191547
period 8: 218.80383576386936
period 9: 216.59197759206555
period 10: 214.4120874591565
Model training finished.
(Plot{Plots.GRBackend() n=11}, Plot{Plots.GRBackend() n=1})
Final RMSE (on training data): 214.4120874591565
Final Weight (on training data): 0.05002900000000003
Final Bias (on training data): 3.899999999999994e-5
plot(p1, p2, layout=(1,2), legend=false)
p1, p2= train_model(
0.001, # learning rate
20, # steps
5 # batch size
)
Training model...
RMSE (on training data):
period 1: 214.4120874591565
period 2: 194.600111798902
period 3: 179.20684050800634
period 4: 169.44086805355903
period 5: 166.29657770919368
period 6: 170.14148129718657
period 7: 170.13862388370202
period 8: 170.13576700999337
period 9: 180.5271084663441
period 10: 170.13291067608785
Model training finished.
(Plot{Plots.GRBackend() n=11}, Plot{Plots.GRBackend() n=1})
Final RMSE (on training data): 170.13291067608785
Final Weight (on training data): 0.05002900000000003
Final Bias (on training data): 3.899999999999994e-5
plot(p1, p2, layout=(1,2), legend=false)
# YOUR CODE HERE
p1, p2= train_model(
0.0001, # learning rate
300, # steps
5, # batch size
:population #feature
)
Training model...
RMSE (on training data):
period 1: 219.99196584705817
period 2: 204.6500256564945
period 3: 192.7864903464405
period 4: 183.76726822988732
period 5: 178.63082652548096
period 6: 177.0318900993104
period 7: 176.3389445217556
period 8: 175.9467609063822
period 9: 176.1995685595212
period 10: 176.62301419567666
Model training finished.
(Plot{Plots.GRBackend() n=11}, Plot{Plots.GRBackend() n=1})
Final RMSE (on training data): 176.62301419567666
Final Weight (on training data): 0.05002900000000003
Final Bias (on training data): 3.899999999999994e-5
plot(p1, p2, layout=(1,2), legend=false)