垂耳兔带你快速上手机器学习,17行代码就可以学习

垂耳兔带你快速上手机器学习,17行代码就可以学习

基本原理图

源代码

import tensorflow as tf
#下载数据
mnist = tf.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
#定义模型 add relu和softmax
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'])
​#5次训练
model.fit(x_train, y_train, epochs=5)
#评估
result=model.evaluate(x_test, y_test)
print(result)

17行带你直接运行机器学习

​运行结果为:

Train on 60000 samples

Epoch 1/5

60000/60000 [==============================] - 3s 49us/sample - loss: 0.2967 - accuracy: 0.9141

Epoch 2/5

60000/60000 [==============================] - 3s 44us/sample - loss: 0.1425 - accuracy: 0.9582

Epoch 3/5

60000/60000 [==============================] - 3s 44us/sample - loss: 0.1058 - accuracy: 0.9679

Epoch 4/5

60000/60000 [==============================] - 3s 43us/sample - loss: 0.0865 - accuracy: 0.9731

Epoch 5/5

60000/60000 [==============================] - 3s 44us/sample - loss: 0.0740 - accuracy: 0.9769

10000/10000 [==============================] - 0s 32us/sample - loss: 0.0708 - accuracy: 0.9792 

[0.07080405750581995, 0.9792] 结果还不错,97%精度

猜你喜欢

转载自blog.csdn.net/keny88888/article/details/105917425
今日推荐