In [0]:
import math
import numpy as np
import tensorflow as tf
import pandas as pd
In [2]:
def generate_cylinder_dataset(size):
base_radius = np.random.uniform(low=0.5, high=2.0, size=size)
height = np.random.uniform(low=0.5, high=2.0, size=size)
volume = math.pi * (base_radius ** 2) * height
return pd.DataFrame({'base_radius': base_radius, 'height': height, 'volume': volume})
cylinder_train_df = generate_cylinder_dataset(500000)
cylinder_test_df = generate_cylinder_dataset(1000)
print cylinder_train_df.head()
In [0]:
feature_columns = [
tf.feature_column.numeric_column("base_radius"),
tf.feature_column.numeric_column("height")
]
def make_input_fn(df, num_epochs, batch_size=512):
return tf.estimator.inputs.pandas_input_fn(
df,
df['volume'],
batch_size=batch_size,
num_epochs=num_epochs,
shuffle=True
)
def predict_input_fn():
features = {
"base_radius": tf.constant([1.5]),
"height": tf.constant([2.0])
}
return features
In [5]:
model = tf.estimator.DNNRegressor(
feature_columns=feature_columns,
hidden_units=[64, 32, 32, 16],
optimizer=tf.train.AdagradOptimizer(learning_rate=0.05)
)
model.train(make_input_fn(cylinder_train_df, None, 1000), max_steps=5000)
predictions = model.predict(predict_input_fn)
print predictions.next()
print math.pi * (1.5 ** 2) * 2.0
In [6]:
def print_rmse(model, name, df):
metrics = model.evaluate(input_fn = make_input_fn(cylinder_test_df, 1))
print('RMSE on {} dataset = {}'.format(name, np.sqrt(metrics['average_loss'])))
print_rmse(model, 'test', cylinder_test_df)
Copyright 2018 Google Inc. 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 http://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
In [0]: