先看看系统环境
In [1]:
import platform
platform.python_version()
Out[1]:
In [2]:
import tensorflow as tf
tf.__version__
Out[2]:
获取训练数据和测试数据
In [3]:
from tensorflow.keras import utils
train_path = utils.get_file('iris_training.csv', 'http://download.tensorflow.org/data/iris_training.csv')
test_path = utils.get_file('iris_test.csv', 'http://download.tensorflow.org/data/iris_training.csv')
(train_path, test_path)
Out[3]:
In [4]:
CSV_COLUMN_NAMES = ['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth', 'Species']
SPECIES = ['Setosa', 'Versicolor', 'Virginica']
import pandas as pd
train = pd.read_csv(train_path, names=CSV_COLUMN_NAMES, header=0)
test = pd.read_csv(test_path, names=CSV_COLUMN_NAMES, header=0)
train.head()
Out[4]:
In [5]:
x_train, y_train = train, train.pop(CSV_COLUMN_NAMES[-1])
x_test, y_test = test, test.pop(CSV_COLUMN_NAMES[-1])
x_train.shape, y_train.shape
Out[5]:
In [6]:
from tensorflow.keras import models, layers, activations
model = models.Sequential([
layers.Dense(10, activation=activations.relu, input_shape=(4,)),
layers.Dense(10, activation=activations.relu),
layers.Dense(3, activation=activations.softmax)
])
model.summary()
In [7]:
from tensorflow.keras import optimizers, losses, metrics
model.compile(
optimizer=optimizers.Adam(),
loss=losses.sparse_categorical_crossentropy,
metrics=[metrics.sparse_categorical_accuracy])
history=model.fit(x_train, y_train, epochs=50, validation_data=(x_test, y_test))
In [8]:
%matplotlib inline
%config InlineBackend.figure_format = 'png'
from plt_utils import plot_metric
In [9]:
plot_metric(history, 'loss')
In [10]:
plot_metric(history, 'sparse_categorical_accuracy')