Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
OpenDocCN
Deep-Learning-with-TensorFlow-book
提交
f278a56e
D
Deep-Learning-with-TensorFlow-book
项目概览
OpenDocCN
/
Deep-Learning-with-TensorFlow-book
通知
4
Star
2
Fork
1
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
0
列表
看板
标记
里程碑
合并请求
0
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
D
Deep-Learning-with-TensorFlow-book
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
0
Issue
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
Pages
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
提交
Issue看板
前往新版Gitcode,体验更适合开发者的 AI 搜索 >>
未验证
提交
f278a56e
编写于
11月 13, 2019
作者:
John(°_°)…
提交者:
GitHub
11月 13, 2019
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
Add files via upload
上级
e2bd5142
变更
1
隐藏空白更改
内联
并排
Showing
1 changed file
with
60 addition
and
0 deletion
+60
-0
ch03/demo.py
ch03/demo.py
+60
-0
未找到文件。
ch03/demo.py
0 → 100644
浏览文件 @
f278a56e
import
tensorflow
as
tf
from
tensorflow.keras
import
datasets
,
layers
,
optimizers
,
Sequential
,
metrics
# 设置GPU使用方式
# 获取GPU列表
gpus
=
tf
.
config
.
experimental
.
list_physical_devices
(
'GPU'
)
if
gpus
:
try
:
# 设置GPU为增长式占用
for
gpu
in
gpus
:
tf
.
config
.
experimental
.
set_memory_growth
(
gpu
,
True
)
except
RuntimeError
as
e
:
# 打印异常
print
(
e
)
(
xs
,
ys
),
_
=
datasets
.
mnist
.
load_data
()
print
(
'datasets:'
,
xs
.
shape
,
ys
.
shape
,
xs
.
min
(),
xs
.
max
())
batch_size
=
32
xs
=
tf
.
convert_to_tensor
(
xs
,
dtype
=
tf
.
float32
)
/
255.
db
=
tf
.
data
.
Dataset
.
from_tensor_slices
((
xs
,
ys
))
db
=
db
.
batch
(
batch_size
).
repeat
(
30
)
model
=
Sequential
([
layers
.
Dense
(
256
,
activation
=
'relu'
),
layers
.
Dense
(
128
,
activation
=
'relu'
),
layers
.
Dense
(
10
)])
model
.
build
(
input_shape
=
(
4
,
28
*
28
))
model
.
summary
()
optimizer
=
optimizers
.
SGD
(
lr
=
0.01
)
acc_meter
=
metrics
.
Accuracy
()
for
step
,
(
x
,
y
)
in
enumerate
(
db
):
with
tf
.
GradientTape
()
as
tape
:
# 打平操作,[b, 28, 28] => [b, 784]
x
=
tf
.
reshape
(
x
,
(
-
1
,
28
*
28
))
# Step1. 得到模型输出output [b, 784] => [b, 10]
out
=
model
(
x
)
# [b] => [b, 10]
y_onehot
=
tf
.
one_hot
(
y
,
depth
=
10
)
# 计算差的平方和,[b, 10]
loss
=
tf
.
square
(
out
-
y_onehot
)
# 计算每个样本的平均误差,[b]
loss
=
tf
.
reduce_sum
(
loss
)
/
x
.
shape
[
0
]
acc_meter
.
update_state
(
tf
.
argmax
(
out
,
axis
=
1
),
y
)
grads
=
tape
.
gradient
(
loss
,
model
.
trainable_variables
)
optimizer
.
apply_gradients
(
zip
(
grads
,
model
.
trainable_variables
))
if
step
%
200
==
0
:
print
(
step
,
'loss:'
,
float
(
loss
),
'acc:'
,
acc_meter
.
result
().
numpy
())
acc_meter
.
reset_states
()
编辑
预览
Markdown
is supported
0%
请重试
或
添加新附件
.
添加附件
取消
You are about to add
0
people
to the discussion. Proceed with caution.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录