TensorFlow Basics

TensorFlow基础培训

解决安装超时导致失败的问题: pip使用国内镜像安装相关工具包

1
$ pip install -i https://pypi.tuna.tsinghua.edu.cn/simple jupyter --upgrade


2. 可视化Tensorflow

playground.tensorflow

2.1 Data选项:

  • Data set
  • training/test比值
  • Noise : 噪声
  • Batch Size : 调整输入每批数据的多少

2.2 Features:

  • x1, x2, x1^2, x2^2, x1*x2 …

2.3 Hidden Layers:

  • 隐层之间的连线表示weight, 蓝色表示用神经元的原始输出, 黄色表示用神经元的负输出, 线条粗细表示weight绝对值大小, 点击可以修改

2.4 顶层选项

  • Learning rate
  • Activation : ReLU, tanh, sigmoid, Linear
  • Regularization : None, L1, L2
  • Regularization rate
  • Problem type : classification, regression

2.5 Tensorflow board

TF Board

3. mnist example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env python
# coding: utf-8

import tensorflow as tf
from tensorflow import keras

#tensorflow version: 2.0.0
print(tf.__version__)

mnist = keras.datasets.mnist
(x_train, y_train), (x_test,y_test) = mnist.load_data()
x_train, x_test = x_train/255.0, x_test/255.0

model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test, verbose=2)



#read test result and plot
import matplotlib
import matplotlib.pyplot as plt
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"

print("Result Array Shape:",x_test.shape,y_test.shape)

for i in range(0,1000):
some_digit = x_test[i]
some_digit_image = some_digit.reshape(28,28)
some_label = y_test[i]
print("Test Label: index=",i,"label=", some_label)
plt.imshow(some_digit_image, cmap=matplotlib.cm.binary, interpolation="nearest")
plt.axis('off')
plt.show()