Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
surelion
apachecn-dl-zh
提交
f684a9df
A
apachecn-dl-zh
项目概览
surelion
/
apachecn-dl-zh
与 Fork 源项目一致
Fork自
OpenDocCN / apachecn-dl-zh
通知
1
Star
0
Fork
0
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
0
列表
看板
标记
里程碑
合并请求
0
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
A
apachecn-dl-zh
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
0
Issue
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
Pages
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
提交
Issue看板
体验新版 GitCode,发现更多精彩内容 >>
提交
f684a9df
编写于
8月 13, 2020
作者:
W
wizardforcel
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
2020-08-13 22:54:51
上级
64309f82
变更
2
隐藏空白更改
内联
并排
Showing
2 changed file
with
58 addition
and
29 deletion
+58
-29
docs/tf-1x-dl-cookbook/02.md
docs/tf-1x-dl-cookbook/02.md
+52
-26
docs/tf-1x-dl-cookbook/07.md
docs/tf-1x-dl-cookbook/07.md
+6
-3
未找到文件。
docs/tf-1x-dl-cookbook/02.md
浏览文件 @
f684a9df
...
...
@@ -298,7 +298,8 @@ learning_rate = tf.train.exponential_decay(initial_learning_rate, global_step, d
```
py
import
tensorflow
as
tf
*
# Global parameters* DATA_FILE = 'boston_housing.csv' BATCH_SIZE = 10
# Global parameters
DATA_FILE
=
'boston_housing.csv'
BATCH_SIZE
=
10
NUM_FEATURES
=
14
```
...
...
@@ -319,7 +320,9 @@ defdata_generator(filename):
```
py
f_queue
=
tf
.
train
.
string_input_producer
(
filename
)
reader
=
tf
.
TextLineReader
(
skip_header_lines
=
1
)
*
# Skips the first line* _, value = reader.read(f_queue)
reader
=
tf
.
TextLineReader
(
skip_header_lines
=
1
)
# Skips the first line
_
,
value
=
reader
.
read
(
f_queue
)
```
4.
我们指定了数据丢失时要使用的数据。 解码
`.csv`
并选择我们需要的功能。 对于示例,我们选择 RM,PTRATIO 和 LSTAT:
...
...
@@ -349,9 +352,12 @@ return feature_batch, label_batch
```
py
def
generate_data
(
feature_batch
,
label_batch
):
with
tf
.
Session
()
as
sess
:
*
# intialize the queue threads* coord = tf.train.Coordinator()
# intialize the queue threads
coord
=
tf
.
train
.
Coordinator
()
threads
=
tf
.
train
.
start_queue_runners
(
coord
=
coord
)
for
_
in
range
(
5
):
*
# Generate 5 batches* features, labels = sess.run([feature_batch, label_batch])
for
_
in
range
(
5
):
# Generate 5 batches
features
,
labels
=
sess
.
run
([
feature_batch
,
label_batch
])
print
(
features
,
"HI"
)
coord
.
request_stop
()
coord
.
join
(
threads
)
...
...
@@ -410,7 +416,8 @@ def normalize(X):
3.
现在,我们使用 TensorFlow
`contrib`
数据集加载波士顿房价数据集,并将其分为
`X_train`
和
`Y_train`
。 我们可以选择在此处标准化数据:
```
py
*
# Data* boston = tf.contrib.learn.datasets.load_dataset('boston')
# Data
boston
=
tf
.
contrib
.
learn
.
datasets
.
load_dataset
(
'boston'
)
X_train
,
Y_train
=
boston
.
data
[:,
5
],
boston
.
target
#X_train = normalize(X_train) # This step is optional here
n_samples
=
len
(
X_train
)
...
...
@@ -419,7 +426,8 @@ n_samples = len(X_train)
4.
我们为训练数据声明 TensorFlow 占位符:
```
py
*
# Placeholder for the Training Data* X = tf.placeholder(tf.float32, name='X')
# Placeholder for the Training Data
X
=
tf
.
placeholder
(
tf
.
float32
,
name
=
'X'
)
Y
=
tf
.
placeholder
(
tf
.
float32
,
name
=
'Y'
)
```
...
...
@@ -441,29 +449,35 @@ Y_hat = X * w + b
7.
定义
`loss`
功能:
```
py
*
# Loss function* loss = tf.square(Y - Y_hat, name='loss')
# Loss function
loss
=
tf
.
square
(
Y
-
Y_hat
,
name
=
'loss'
)
```
8.
我们选择梯度下降优化器:
```
py
*
# Gradient Descent with learning rate of 0.01 to minimize loss* optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)
# Gradient Descent with learning rate of 0.01 to minimize loss
optimizer
=
tf
.
train
.
GradientDescentOptimizer
(
learning_rate
=
0.01
).
minimize
(
loss
)
```
9.
声明初始化运算符:
```
py
*
# Initializing Variables* init_op = tf.global_variables_initializer()
# Initializing Variables
init_op
=
tf
.
global_variables_initializer
()
total
=
[]
```
10.
现在,我们开始计算图。 我们进行了 100 个时期的训练:
```
py
*
# Computation Graph* with tf.Session() as sess:
*
# Initialize variables* sess.run(init_op)
# Computation Graph
with
tf
.
Session
()
as
sess
:
# Initialize variables
sess
.
run
(
init_op
)
writer
=
tf
.
summary
.
FileWriter
(
'graphs'
,
sess
.
graph
)
*
# train the model for 100 epochs* for i in range(100):
# train the model for 100 epochs
for
i
in
range
(
100
):
total_loss
=
0
for
x
,
y
in
zip
(
X_train
,
Y_train
):
_
,
l
=
sess
.
run
([
optimizer
,
loss
],
feed_dict
=
{
X
:
x
,
Y
:
y
})
...
...
@@ -479,7 +493,8 @@ total = []
```
py
Y_pred
=
X_train
*
w_value
+
b_value
print
(
'Done'
)
*
# Plot the result* plt.plot(X_train, Y_train, 'bo', label='Real Data')
# Plot the result
plt
.
plot
(
X_train
,
Y_train
,
'bo'
,
label
=
'Real Data'
)
plt
.
plot
(
X_train
,
Y_pred
,
'r'
,
label
=
'Predicted Data'
)
plt
.
legend
()
plt
.
show
()
...
...
@@ -501,7 +516,7 @@ plt.show()
![](
img/4b0030fc-dad5-4ad4-9dd7-ee47af77ad05.png
)
该图具有两个名称作用域节点,即
**变量**
和
**Variable_1**
,它们是分别表示偏差和权重的高级节点。 名为 gradient 的节点也是高级节点。 扩展节点,我们可以看到它接受了七个输入并计算了
**梯度**
,然后
`GradientDescentOptimizer`
使用了这些梯度来计算权重和偏差并应用更新:
该图具有两个名称作用域节点,即
`Variable`
和
`Variable_1`
,它们是分别表示偏差和权重的高级节点。 名为
`gradient`
的节点也是高级节点。 扩展节点,我们可以看到它接受了七个输入并计算了
`gradient`
,然后
`GradientDescentOptimizer`
使用了这些梯度来计算权重和偏差并应用更新:
![](
img/f9692463-d4f6-4776-b899-087b3dfbac21.png
)
...
...
@@ -546,17 +561,22 @@ def append_bias_reshape(features,labels):
3.
现在,我们使用 TensorFlow contrib 数据集加载波士顿房价数据集,并将其分为
`X_train`
和
`Y_train`
。 观察到这次
`X_train`
包含所有功能。 我们可以在此处选择对数据进行规范化,也可以使用附加偏差并为网络重塑数据:
```
py
*
# Data* boston = tf.contrib.learn.datasets.load_dataset('boston')
# Data
boston
=
tf
.
contrib
.
learn
.
datasets
.
load_dataset
(
'boston'
)
X_train
,
Y_train
=
boston
.
data
,
boston
.
target
X_train
=
normalize
(
X_train
)
X_train
,
Y_train
=
append_bias_reshape
(
X_train
,
Y_train
)
m
=
len
(
X_train
)
*
#Number of training examples* n = 13 + 1 *# Number of features + bias*
m
=
len
(
X_train
)
#Number of training examples
n
=
13
+
1
# Number of features + bias
```
4.
声明 TensorFlow 占位符以获取训练数据。 观察
`X`
占位符形状的变化。
```
py
*
# Placeholder for the Training Data* X = tf.placeholder(tf.float32, name='X', shape=[m,n])
# Placeholder for the Training Data
X
=
tf
.
placeholder
(
tf
.
float32
,
name
=
'X'
,
shape
=
[
m
,
n
])
Y
=
tf
.
placeholder
(
tf
.
float32
,
name
=
'Y'
)
```
...
...
@@ -570,25 +590,29 @@ w = tf.Variable(tf.random_normal([n,1]))
6.
定义要用于预测的线性回归模型。 现在我们需要矩阵乘法来完成任务:
```
py
*
# The Linear Regression Model* Y_hat = tf.matmul(X, w)
# The Linear Regression Model
Y_hat
=
tf
.
matmul
(
X
,
w
)
```
7.
为了更好的区分,我们定义
`loss`
函数:
```
py
*
# Loss function* loss = tf.reduce_mean(tf.square(Y - Y_hat, name='loss'))
# Loss function
loss
=
tf
.
reduce_mean
(
tf
.
square
(
Y
-
Y_hat
,
name
=
'loss'
))
```
8.
选择合适的优化器:
```
py
*
# Gradient Descent with learning rate of 0.01 to minimize loss* optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)
# Gradient Descent with learning rate of 0.01 to minimize loss
optimizer
=
tf
.
train
.
GradientDescentOptimizer
(
learning_rate
=
0.01
).
minimize
(
loss
)
```
9.
定义初始化运算符:
```
py
*
# Initializing Variables* init_op = tf.global_variables_initializer()
# Initializing Variables
init_op
=
tf
.
global_variables_initializer
()
total
=
[]
```
...
...
@@ -596,9 +620,11 @@ total = []
```
py
with
tf
.
Session
()
as
sess
:
*
# Initialize variables* sess.run(init_op)
# Initialize variables
sess
.
run
(
init_op
)
writer
=
tf
.
summary
.
FileWriter
(
'graphs'
,
sess
.
graph
)
*
# train the model for 100 epcohs* for i in range(100):
# train the model for 100 epcohs
for
i
in
range
(
100
):
_
,
l
=
sess
.
run
([
optimizer
,
loss
],
feed_dict
=
{
X
:
X_train
,
Y
:
Y_train
})
total
.
append
(
l
)
print
(
'Epoch {0}: Loss {1}'
.
format
(
i
,
l
))
...
...
@@ -638,7 +664,7 @@ print('Predicted value: ${0} Actual value: / ${1}'.format(Y_pred[0]*1000, Y_tra
此配方基于
[
https://www.tensorflow.org/get_started/mnist/beginners
](
https://www.tensorflow.org/get_started/mnist/beginners
)
提供的 MNIST 的逻辑回归,但我们将添加一些 TensorBoard 摘要以更好地理解它。 你们大多数人必须已经熟悉 MNIST 数据集-就像机器学习的 ABC 一样。 它包含手写数字的图像和每个图像的标签,说明它是哪个数字。
对于逻辑回归,我们对输出 Y 使用一热编码。因此,我们有 10 位代表输出; 每个位可以具有 0 或 1 的值,并且为 1 热点意味着对于标签 Y 中的每个图像,10 个位中只有 1 个位的值为 1,其余为 0。 在这里,您可以看到手写数字 8 的图像及其热编码值
**[0 0 0 0 0 0 0 0 0 1 0]**
:
对于逻辑回归,我们对输出 Y 使用一热编码。因此,我们有 10 位代表输出; 每个位可以具有 0 或 1 的值,并且为 1 热点意味着对于标签 Y 中的每个图像,10 个位中只有 1 个位的值为 1,其余为 0。 在这里,您可以看到手写数字 8 的图像及其热编码值
`[0 0 0 0 0 0 0 0 0 1 0]`
:
![](
img/47ba5240-9d42-4475-866b-5ab156ecbdb0.png
)
...
...
@@ -745,11 +771,11 @@ with tf.Session() as sess:
![](
img/ffe5c0f6-d355-41d1-872c-b16fd621470a.png
)
在
[直方图]标签下,我们可以看到
**权重**
和
**偏差
**
的直方图:
在
“直方图”标签下,我们可以看到
**权重**
和
**偏置
**
的直方图:
![](
img/eb143b58-3eea-4de2-aa9c-bad0af0c03b2.png
)
**权重**
和
**偏
差
**
的分布如下:
**权重**
和
**偏
置
**
的分布如下:
![](
img/76ebf278-276f-4f9a-afa6-eef915425f89.png
)
...
...
docs/tf-1x-dl-cookbook/07.md
浏览文件 @
f684a9df
...
...
@@ -166,10 +166,13 @@ with tf.Session() as sess:
saver
.
save
(
sess
,
os
.
path
.
join
(
LOG_DIR
,
'images.ckpt'
))
config
=
projector
.
ProjectorConfig
()
*
# One can add multiple embeddings.* embedding = config.embeddings.add()
# One can add multiple embeddings.
embedding
=
config
.
embeddings
.
add
()
embedding
.
tensor_name
=
images
.
name
*
# Link this tensor to its metadata file (e.g. labels).* embedding.metadata_path = metadata
*
# Saves a config file that TensorBoard will read during startup.* projector.visualize_embeddings(tf.summary.FileWriter(LOG_DIR), config)
# Link this tensor to its metadata file (e.g. labels).
embedding
.
metadata_path
=
metadata
# Saves a config file that TensorBoard will read during startup.
projector
.
visualize_embeddings
(
tf
.
summary
.
FileWriter
(
LOG_DIR
),
config
)
```
嵌入已准备就绪,现在可以使用 TensorBoard 看到。 通过 CLI
`tensorboard --logdir=log`
启动 TensorBoard,在 Web 浏览器中打开 TensorBoard,然后转到 EMBEDDINGS 选项卡。 这是使用 PCA 的 TensorBoard 投影,前三个主要成分为轴:
...
...
编辑
预览
Markdown
is supported
0%
请重试
或
添加新附件
.
添加附件
取消
You are about to add
0
people
to the discussion. Proceed with caution.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录