0%

ML Tensorflow start

This is about environment configuration and a very first example.

Normal Way

1.Install Anaconda
2.Activate the tensorflow environment

1
source activate tensorflow

3.Create Tensorflow environment

1
conda create -n tensorflow python=3.x

4.Install

1
pip install tensorflow

If use apple silicon (error:”zsh: illegal hardware instruction”)

1.Activate the tensorflow environment

1
source activate tensorflow

2.Create Tensorflow environment

1
conda create -n tensorflow python=3.x

3.Using Conda rather than pip

1
conda install tensorflow-mkl

Very First Example

Pycharm interpreter: Py 3.x (tensorflow) ~/opt/ana3/envs/tf/bin/py.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import tensorflow as tf                                  # import tensorflow
mnist = tf.keras.datasets.mnist # load dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data() # convert int to float
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')
]) # combine muti-layers to establish model.
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']) # select optimizer and loss functions
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test, verbose=2) # training and test

Results
This training has 5 epoches and the final recognition accuracy is 97.72%.