Skip to content

Commit c951890

Browse files
committed
Add 'temp/' from commit 'dc248cfa56396f276c22017554bcf17b4dc0e934'
git-subtree-dir: temp git-subtree-mainline: f974d04 git-subtree-split: dc248cf
2 parents f974d04 + dc248cf commit c951890

14 files changed

+8322
-0
lines changed

temp/get_started/_index.ipynb

Lines changed: 223 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,223 @@
1+
{
2+
"nbformat": 4,
3+
"nbformat_minor": 0,
4+
"metadata": {
5+
"colab": {
6+
"name": "_index.ipynb",
7+
"version": "0.3.2",
8+
"views": {},
9+
"default_view": {},
10+
"provenance": []
11+
}
12+
},
13+
"cells": [
14+
{
15+
"metadata": {
16+
"id": "rX8mhOLljYeM",
17+
"colab_type": "text"
18+
},
19+
"cell_type": "markdown",
20+
"source": [
21+
"##### Copyright 2018 The TensorFlow Authors.\n",
22+
"\n",
23+
"Licensed under the Apache License, Version 2.0 (the \"License\");"
24+
]
25+
},
26+
{
27+
"metadata": {
28+
"id": "BZSlp3DAjdYf",
29+
"colab_type": "code",
30+
"colab": {
31+
"autoexec": {
32+
"startup": false,
33+
"wait_interval": 0
34+
}
35+
},
36+
"cellView": "form"
37+
},
38+
"cell_type": "code",
39+
"source": [
40+
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
41+
"# you may not use this file except in compliance with the License.\n",
42+
"# You may obtain a copy of the License at\n",
43+
"#\n",
44+
"# https://www.apache.org/licenses/LICENSE-2.0\n",
45+
"#\n",
46+
"# Unless required by applicable law or agreed to in writing, software\n",
47+
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
48+
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
49+
"# See the License for the specific language governing permissions and\n",
50+
"# limitations under the License."
51+
],
52+
"execution_count": 0,
53+
"outputs": []
54+
},
55+
{
56+
"metadata": {
57+
"id": "3wF5wszaj97Y",
58+
"colab_type": "text"
59+
},
60+
"cell_type": "markdown",
61+
"source": [
62+
"# Get Started with TensorFlow"
63+
]
64+
},
65+
{
66+
"metadata": {
67+
"id": "DUNzJc4jTj6G",
68+
"colab_type": "text"
69+
},
70+
"cell_type": "markdown",
71+
"source": [
72+
"<table class=\"tfo-notebook-buttons\" align=\"left\"><td>\n",
73+
"<a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/models/blob/master/samples/core/get_started/_index.ipynb\">\n",
74+
" <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /><span>Run in Google Colab</span></a> \n",
75+
"</td><td>\n",
76+
"<a target=\"_blank\" href=\"https://github.com/tensorflow/models/blob/master/samples/core/get_started/_index.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /><span>View source on GitHub</span></a></td></table>"
77+
]
78+
},
79+
{
80+
"metadata": {
81+
"id": "hiH7AC-NTniF",
82+
"colab_type": "text"
83+
},
84+
"cell_type": "markdown",
85+
"source": [
86+
"This is a [Google Colaboratory](https://colab.research.google.com/notebooks/welcome.ipynb) notebook file. Python programs are run directly in the browser—a great way to learn and use TensorFlow. To run the Colab notebook:\n",
87+
"\n",
88+
"1. Connect to a Python runtime: At the top-right of the menu bar, select *CONNECT*.\n",
89+
"2. Run all the notebook code cells: Select *Runtime* > *Run all*.\n",
90+
"\n",
91+
"For more examples and guides (including details for this program), see [Get Started with TensorFlow](https://www.tensorflow.org/get_started/).\n",
92+
"\n",
93+
"Let's get started, import the TensorFlow library into your program:"
94+
]
95+
},
96+
{
97+
"metadata": {
98+
"id": "0trJmd6DjqBZ",
99+
"colab_type": "code",
100+
"colab": {
101+
"autoexec": {
102+
"startup": false,
103+
"wait_interval": 0
104+
}
105+
}
106+
},
107+
"cell_type": "code",
108+
"source": [
109+
"import tensorflow as tf"
110+
],
111+
"execution_count": 0,
112+
"outputs": []
113+
},
114+
{
115+
"metadata": {
116+
"id": "7NAbSZiaoJ4z",
117+
"colab_type": "text"
118+
},
119+
"cell_type": "markdown",
120+
"source": [
121+
"Load and prepare the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset. Convert the samples from integers to floating-point numbers:"
122+
]
123+
},
124+
{
125+
"metadata": {
126+
"id": "7FP5258xjs-v",
127+
"colab_type": "code",
128+
"colab": {
129+
"autoexec": {
130+
"startup": false,
131+
"wait_interval": 0
132+
}
133+
}
134+
},
135+
"cell_type": "code",
136+
"source": [
137+
"mnist = tf.keras.datasets.mnist\n",
138+
"\n",
139+
"(x_train, y_train), (x_test, y_test) = mnist.load_data()\n",
140+
"x_train, x_test = x_train / 255.0, x_test / 255.0"
141+
],
142+
"execution_count": 0,
143+
"outputs": []
144+
},
145+
{
146+
"metadata": {
147+
"id": "BPZ68wASog_I",
148+
"colab_type": "text"
149+
},
150+
"cell_type": "markdown",
151+
"source": [
152+
"Build the `tf.keras` model by stacking layers. Select an optimizer and loss function used for training:"
153+
]
154+
},
155+
{
156+
"metadata": {
157+
"id": "h3IKyzTCDNGo",
158+
"colab_type": "code",
159+
"colab": {
160+
"autoexec": {
161+
"startup": false,
162+
"wait_interval": 0
163+
}
164+
}
165+
},
166+
"cell_type": "code",
167+
"source": [
168+
"model = tf.keras.models.Sequential([\n",
169+
" tf.keras.layers.Flatten(),\n",
170+
" tf.keras.layers.Dense(512, activation=tf.nn.relu),\n",
171+
" tf.keras.layers.Dropout(0.2),\n",
172+
" tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n",
173+
"])\n",
174+
"\n",
175+
"model.compile(optimizer='adam',\n",
176+
" loss='sparse_categorical_crossentropy',\n",
177+
" metrics=['accuracy'])"
178+
],
179+
"execution_count": 0,
180+
"outputs": []
181+
},
182+
{
183+
"metadata": {
184+
"id": "ix4mEL65on-w",
185+
"colab_type": "text"
186+
},
187+
"cell_type": "markdown",
188+
"source": [
189+
"Train and evaluate model:"
190+
]
191+
},
192+
{
193+
"metadata": {
194+
"id": "F7dTAzgHDUh7",
195+
"colab_type": "code",
196+
"colab": {
197+
"autoexec": {
198+
"startup": false,
199+
"wait_interval": 0
200+
}
201+
}
202+
},
203+
"cell_type": "code",
204+
"source": [
205+
"model.fit(x_train, y_train, epochs=5)\n",
206+
"\n",
207+
"model.evaluate(x_test, y_test)"
208+
],
209+
"execution_count": 0,
210+
"outputs": []
211+
},
212+
{
213+
"metadata": {
214+
"id": "T4JfEh7kvx6m",
215+
"colab_type": "text"
216+
},
217+
"cell_type": "markdown",
218+
"source": [
219+
"You’ve now trained an image classifier with ~98% accuracy on this dataset. See [Get Started with TensorFlow](https://www.tensorflow.org/get_started/) to learn more."
220+
]
221+
}
222+
]
223+
}

temp/get_started/custom_estimator.py

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
"""An Example of a custom Estimator for the Iris dataset."""
15+
from __future__ import absolute_import
16+
from __future__ import division
17+
from __future__ import print_function
18+
19+
import argparse
20+
import tensorflow as tf
21+
22+
import iris_data
23+
24+
parser = argparse.ArgumentParser()
25+
parser.add_argument('--batch_size', default=100, type=int, help='batch size')
26+
parser.add_argument('--train_steps', default=1000, type=int,
27+
help='number of training steps')
28+
29+
def my_model(features, labels, mode, params):
30+
"""DNN with three hidden layers, and dropout of 0.1 probability."""
31+
# Create three fully connected layers each layer having a dropout
32+
# probability of 0.1.
33+
net = tf.feature_column.input_layer(features, params['feature_columns'])
34+
for units in params['hidden_units']:
35+
net = tf.layers.dense(net, units=units, activation=tf.nn.relu)
36+
37+
# Compute logits (1 per class).
38+
logits = tf.layers.dense(net, params['n_classes'], activation=None)
39+
40+
# Compute predictions.
41+
predicted_classes = tf.argmax(logits, 1)
42+
if mode == tf.estimator.ModeKeys.PREDICT:
43+
predictions = {
44+
'class_ids': predicted_classes[:, tf.newaxis],
45+
'probabilities': tf.nn.softmax(logits),
46+
'logits': logits,
47+
}
48+
return tf.estimator.EstimatorSpec(mode, predictions=predictions)
49+
50+
# Compute loss.
51+
loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)
52+
53+
# Compute evaluation metrics.
54+
accuracy = tf.metrics.accuracy(labels=labels,
55+
predictions=predicted_classes,
56+
name='acc_op')
57+
metrics = {'accuracy': accuracy}
58+
tf.summary.scalar('accuracy', accuracy[1])
59+
60+
if mode == tf.estimator.ModeKeys.EVAL:
61+
return tf.estimator.EstimatorSpec(
62+
mode, loss=loss, eval_metric_ops=metrics)
63+
64+
# Create training op.
65+
assert mode == tf.estimator.ModeKeys.TRAIN
66+
67+
optimizer = tf.train.AdagradOptimizer(learning_rate=0.1)
68+
train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
69+
return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)
70+
71+
72+
def main(argv):
73+
args = parser.parse_args(argv[1:])
74+
75+
# Fetch the data
76+
(train_x, train_y), (test_x, test_y) = iris_data.load_data()
77+
78+
# Feature columns describe how to use the input.
79+
my_feature_columns = []
80+
for key in train_x.keys():
81+
my_feature_columns.append(tf.feature_column.numeric_column(key=key))
82+
83+
# Build 2 hidden layer DNN with 10, 10 units respectively.
84+
classifier = tf.estimator.Estimator(
85+
model_fn=my_model,
86+
params={
87+
'feature_columns': my_feature_columns,
88+
# Two hidden layers of 10 nodes each.
89+
'hidden_units': [10, 10],
90+
# The model must choose between 3 classes.
91+
'n_classes': 3,
92+
})
93+
94+
# Train the Model.
95+
classifier.train(
96+
input_fn=lambda:iris_data.train_input_fn(train_x, train_y, args.batch_size),
97+
steps=args.train_steps)
98+
99+
# Evaluate the model.
100+
eval_result = classifier.evaluate(
101+
input_fn=lambda:iris_data.eval_input_fn(test_x, test_y, args.batch_size))
102+
103+
print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result))
104+
105+
# Generate predictions from the model
106+
expected = ['Setosa', 'Versicolor', 'Virginica']
107+
predict_x = {
108+
'SepalLength': [5.1, 5.9, 6.9],
109+
'SepalWidth': [3.3, 3.0, 3.1],
110+
'PetalLength': [1.7, 4.2, 5.4],
111+
'PetalWidth': [0.5, 1.5, 2.1],
112+
}
113+
114+
predictions = classifier.predict(
115+
input_fn=lambda:iris_data.eval_input_fn(predict_x,
116+
labels=None,
117+
batch_size=args.batch_size))
118+
119+
for pred_dict, expec in zip(predictions, expected):
120+
template = ('\nPrediction is "{}" ({:.1f}%), expected "{}"')
121+
122+
class_id = pred_dict['class_ids'][0]
123+
probability = pred_dict['probabilities'][class_id]
124+
125+
print(template.format(iris_data.SPECIES[class_id],
126+
100 * probability, expec))
127+
128+
129+
if __name__ == '__main__':
130+
tf.logging.set_verbosity(tf.logging.INFO)
131+
tf.app.run(main)

0 commit comments

Comments
 (0)