Ai
1 Star 0 Fork 0

Houor/ml-py

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
mnist_tf.py 1.99 KB
一键复制 编辑 原始数据 按行查看 历史
Houor 提交于 2019-12-02 01:10 +08:00 . matplotlib1
import os
import sys
import numpy as np
import tensorflow as tf
from tensorflow import keras
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
np.set_printoptions(linewidth=1000)
# 加载mnist数据,以numpy形式返回,分割为60000/10000两部分
(x, y), (x_val, y_val) = keras.datasets.mnist.load_data()
print('training dataset shape: ', x.shape, y.shape) # (60000, 28, 28) (60000,)
print('testing dataset shape: ', x_val.shape, y_val.shape) # (10000, 28, 28) (10000,)
print('x[0] in training dataset: \n', x[0], sep='\t', end='\n', file=sys.stdout)
x = tf.convert_to_tensor(x, dtype=tf.float32) / 255.
y = tf.convert_to_tensor(y, dtype=tf.int32)
# one hot encoding
y = tf.one_hot(y, depth=10)
print('y after one hot encoding: ', y.shape)
print('y[0] after one hot encoding: ', y[0])
train_dataset = tf.data.Dataset.from_tensor_slices((x, y))
train_dataset = train_dataset.batch(100)
print(train_dataset)
model = keras.Sequential([
keras.layers.Dense(512, activation='relu'),
keras.layers.Dense(256, activation='relu'),
keras.layers.Dense(10)])
optimizer = keras.optimizers.SGD(learning_rate=0.001)
def train_epoch(epoch):
# Step4.loop
for step, (x, y) in enumerate(train_dataset):
with tf.GradientTape() as tape:
# [b, 28, 28] => [b, 784]
x = tf.reshape(x, (-1, 28 * 28))
# Step1. compute output
# [b, 784] => [b, 10]
out = model(x)
# Step2. compute loss
loss = tf.reduce_sum(tf.square(out - y)) / x.shape[0]
# Step3. optimize and update w1, w2, w3, b1, b2, b3
grads = tape.gradient(loss, model.trainable_variables)
# w' = w - lr * grad
optimizer.apply_gradients(zip(grads, model.trainable_variables))
if step % 100 == 0:
print(epoch, step, 'loss:', loss.numpy())
def train():
for epoch in range(30):
train_epoch(epoch)
if __name__ == '__main__':
train()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/houor/ml-py.git
git@gitee.com:houor/ml-py.git
houor
ml-py
ml-py
master

搜索帮助