-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocker与tensorflow结合使用.html
774 lines (310 loc) · 72.1 KB
/
docker与tensorflow结合使用.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
<!DOCTYPE html>
<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">
<link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">
<meta name="keywords" content="docker,tensorflow," />
<link rel="alternate" href="/atom.xml" title="个人博客" type="application/atom+xml" />
<meta name="description" content="最近这段时间一直在学习docker的使用,以及如何在docker中使用tensorflow.今天就把在docker中如何使用tensorflow记录一下. docker安装我是把docker安装在centos 7.4操作系统上面,在vmware中装的centos,vmware中安装centos很简单.具体的网络配置可以参考vmware nat配置.docker安装很简单,找到docker官网,直接">
<meta property="og:type" content="article">
<meta property="og:title" content="docker与tensorflow结合使用">
<meta property="og:url" content="https://lightnine/github.io/docker%E4%B8%8Etensorflow%E7%BB%93%E5%90%88%E4%BD%BF%E7%94%A8.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="最近这段时间一直在学习docker的使用,以及如何在docker中使用tensorflow.今天就把在docker中如何使用tensorflow记录一下. docker安装我是把docker安装在centos 7.4操作系统上面,在vmware中装的centos,vmware中安装centos很简单.具体的网络配置可以参考vmware nat配置.docker安装很简单,找到docker官网,直接">
<meta property="og:locale">
<meta property="og:image" content="https://lightnine/docker%E4%B8%8Etensorflow%E7%BB%93%E5%90%88%E4%BD%BF%E7%94%A8/docker-version.png">
<meta property="og:image" content="https://lightnine/docker%E4%B8%8Etensorflow%E7%BB%93%E5%90%88%E4%BD%BF%E7%94%A8/jupyter.png">
<meta property="og:image" content="https://lightnine/docker%E4%B8%8Etensorflow%E7%BB%93%E5%90%88%E4%BD%BF%E7%94%A8/tensorflow.png">
<meta property="og:image" content="https://lightnine/docker%E4%B8%8Etensorflow%E7%BB%93%E5%90%88%E4%BD%BF%E7%94%A8/container.png">
<meta property="article:published_time" content="2018-08-10T14:03:08.000Z">
<meta property="article:modified_time" content="2024-06-10T07:00:19.049Z">
<meta property="article:author" content="liang">
<meta property="article:tag" content="docker">
<meta property="article:tag" content="tensorflow">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://lightnine/docker%E4%B8%8Etensorflow%E7%BB%93%E5%90%88%E4%BD%BF%E7%94%A8/docker-version.png">
<script type="text/javascript" id="hexo.configurations">
var NexT = window.NexT || {};
var CONFIG = {
root: '',
scheme: 'Muse',
version: '5.1.4',
sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
fancybox: true,
tabs: true,
motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
duoshuo: {
userId: '0',
author: '博主'
},
algolia: {
applicationID: '',
apiKey: '',
indexName: '',
hits: {"per_page":10},
labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
}
};
</script>
<link rel="canonical" href="https://lightnine/github.io/docker与tensorflow结合使用.html"/>
<title>docker与tensorflow结合使用 | 个人博客</title>
<meta name="generator" content="Hexo 7.0.0"></head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container sidebar-position-left page-post-detail">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-brand-wrapper">
<div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">个人博客</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle"></p>
</div>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
</div>
<nav class="site-nav">
<ul id="menu" class="menu">
<li class="menu-item menu-item-home">
<a href="/" rel="section">
<i class="menu-item-icon fa fa-fw fa-home"></i> <br />
首页
</a>
</li>
<li class="menu-item menu-item-about">
<a href="/about/" rel="section">
<i class="menu-item-icon fa fa-fw fa-user"></i> <br />
关于
</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags/" rel="section">
<i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
标签
</a>
</li>
<li class="menu-item menu-item-categories">
<a href="/categories/" rel="section">
<i class="menu-item-icon fa fa-fw fa-th"></i> <br />
分类
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives/" rel="section">
<i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
归档
</a>
</li>
</ul>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<div id="posts" class="posts-expand">
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="https://lightnine/github.io/docker%E4%B8%8Etensorflow%E7%BB%93%E5%90%88%E4%BD%BF%E7%94%A8.html">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="">
<meta itemprop="description" content="">
<meta itemprop="image" content="/images/avatar.gif">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="个人博客">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">docker与tensorflow结合使用</h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-10T22:03:08+08:00">
2018-08-10
</time>
</span>
<span class="post-category" >
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/docker/" itemprop="url" rel="index">
<span itemprop="name">docker</span>
</a>
</span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>最近这段时间一直在学习docker的使用,以及如何在docker中使用tensorflow.今天就把在docker中如何使用tensorflow记录一下.</p>
<h1 id="docker安装"><a href="#docker安装" class="headerlink" title="docker安装"></a>docker安装</h1><p>我是把docker安装在centos 7.4操作系统上面,在vmware中装的centos,vmware中安装centos很简单.具体的网络配置可以参考<a href="https://segmentfault.com/a/1190000008743806">vmware nat配置</a>.docker安装很简单,找到docker官网,直接按照上面的步骤安装即可.运行<code>docker version</code>查看版本如下</p>
<img src="/docker%E4%B8%8Etensorflow%E7%BB%93%E5%90%88%E4%BD%BF%E7%94%A8/docker-version.png" class="">
<p>因为docker 采用的是客户端/服务端的结构,所以这里可以看到client以及server,它们分别都有版本号.</p>
<h1 id="tensorflow"><a href="#tensorflow" class="headerlink" title="tensorflow"></a>tensorflow</h1><p>在docker中运行tensorflow的第一步就是要找到自己需要的镜像,我们可以去<a href="https://hub.docker.com">docker hub</a>找到自己需要的tensorflow镜像.tensorflow的镜像主要分两类,一种是在CPU上面跑的,还有一种是在GPU上面跑的,如果需要GPU的,那么还需要安装<strong>nvidia-docker</strong>.这里我使用的是CPU版本的.当然我们还需要选择具体的tensorflow版本.这里我拉取的命令如下:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker pull tensorflow/tensorflow:1.9.0-devel-py3</span><br></pre></td></tr></table></figure>
<p>拉取成功之后,运行<code>docker images</code>可以看到有tensorflow镜像.</p>
<h1 id="tensorflow在docker中使用"><a href="#tensorflow在docker中使用" class="headerlink" title="tensorflow在docker中使用"></a>tensorflow在docker中使用</h1><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker run -it -p 8888:8888 --name tf-1.9 tensorflow/tensorflow:1.9.0-devel-py3</span><br></pre></td></tr></table></figure>
<p>运行上面的命令,在容器中启动镜像.<code>-p</code>表示指定端口映射,即将本机的8888端口映射到容器的8888端口.<code>--name</code>用来指定容器的名字为<code>tf-1.9</code>.因为这里采用的镜像是devel模式的,所以默认不启动jupyter.如果想使用默认启动jupyter的镜像,那么直接拉取不带devel的镜像就可以.即拉取最近的镜像<code>docker pull tensorflow/tensorflow</code><br>启动之后,我们就进入了容器,<code>ls /</code> 查看容器根目录内容,可以看到有<code>run_jupyter.sh</code>文件.运行此文件,即在根目录下执行<code>./run_jupyter.sh --allow-root</code>,<code>--allow-root</code>参数是因为jupyter启动不推荐使用root,这里是主动允许使用root.然后在浏览器中就可以访问jupyter的内容了.<br><img src="/docker%E4%B8%8Etensorflow%E7%BB%93%E5%90%88%E4%BD%BF%E7%94%A8/jupyter.png" class=""></p>
<h1 id="创建自己的镜像"><a href="#创建自己的镜像" class="headerlink" title="创建自己的镜像"></a>创建自己的镜像</h1><p>上面仅仅是跑了一个什么都没有的镜像,如果我们需要在镜像里面跑我们的深度学习程序怎么办呢?这首先做的第一步就是要制作我们自己的镜像.这里我们跑一个简单的mnist数据集,程序可以直接去tensorflow上面找一个例子程序.这里我的程序如下:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br><span class="line">358</span><br><span class="line">359</span><br><span class="line">360</span><br><span class="line">361</span><br><span class="line">362</span><br><span class="line">363</span><br><span class="line">364</span><br><span class="line">365</span><br><span class="line">366</span><br><span class="line">367</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Copyright 2015 The TensorFlow Authors. All Rights Reserved.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Licensed under the Apache License, Version 2.0 (the "License");</span></span><br><span class="line"><span class="comment"># you may not use this file except in compliance with the License.</span></span><br><span class="line"><span class="comment"># You may obtain a copy of the License at</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># http://www.apache.org/licenses/LICENSE-2.0</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Unless required by applicable law or agreed to in writing, software</span></span><br><span class="line"><span class="comment"># distributed under the License is distributed on an "AS IS" BASIS,</span></span><br><span class="line"><span class="comment"># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span></span><br><span class="line"><span class="comment"># See the License for the specific language governing permissions and</span></span><br><span class="line"><span class="comment"># limitations under the License.</span></span><br><span class="line"><span class="comment"># ==============================================================================</span></span><br><span class="line"></span><br><span class="line"><span class="string">"""Simple, end-to-end, LeNet-5-like convolutional MNIST model example.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">This should achieve a test error of 0.7%. Please keep this model as simple and</span></span><br><span class="line"><span class="string">linear as possible, it is meant as a tutorial for simple convolutional models.</span></span><br><span class="line"><span class="string">Run with --self_test on the command line to execute a short self-test.</span></span><br><span class="line"><span class="string">"""</span></span><br><span class="line"><span class="keyword">from</span> __future__ <span class="keyword">import</span> absolute_import</span><br><span class="line"><span class="keyword">from</span> __future__ <span class="keyword">import</span> division</span><br><span class="line"><span class="keyword">from</span> __future__ <span class="keyword">import</span> print_function</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> argparse</span><br><span class="line"><span class="keyword">import</span> gzip</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">import</span> logging</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> numpy</span><br><span class="line"><span class="keyword">from</span> six.moves <span class="keyword">import</span> urllib</span><br><span class="line"><span class="keyword">from</span> six.moves <span class="keyword">import</span> xrange <span class="comment"># pylint: disable=redefined-builtin</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"></span><br><span class="line"><span class="comment"># CVDF mirror of http://yann.lecun.com/exdb/mnist/</span></span><br><span class="line"><span class="comment"># 如果WORK_DIRECTORY中没有需要的数据,则从此地址下载数据</span></span><br><span class="line">SOURCE_URL = <span class="string">'https://storage.googleapis.com/cvdf-datasets/mnist/'</span></span><br><span class="line"><span class="comment"># 训练数据位置</span></span><br><span class="line"><span class="comment"># WORK_DIRECTORY = 'data'</span></span><br><span class="line">WORK_DIRECTORY = <span class="string">'./MNIST-data'</span></span><br><span class="line">IMAGE_SIZE = <span class="number">28</span></span><br><span class="line">NUM_CHANNELS = <span class="number">1</span></span><br><span class="line">PIXEL_DEPTH = <span class="number">255</span></span><br><span class="line">NUM_LABELS = <span class="number">10</span></span><br><span class="line">VALIDATION_SIZE = <span class="number">5000</span> <span class="comment"># Size of the validation set.</span></span><br><span class="line">SEED = <span class="number">66478</span> <span class="comment"># Set to None for random seed.</span></span><br><span class="line">BATCH_SIZE = <span class="number">64</span></span><br><span class="line">NUM_EPOCHS = <span class="number">10</span></span><br><span class="line">EVAL_BATCH_SIZE = <span class="number">64</span></span><br><span class="line">EVAL_FREQUENCY = <span class="number">100</span> <span class="comment"># Number of steps between evaluations.</span></span><br><span class="line"></span><br><span class="line">FLAGS = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 打印信息设置</span></span><br><span class="line"><span class="comment"># logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',</span></span><br><span class="line"><span class="comment"># level=logging.DEBUG)</span></span><br><span class="line">logging.basicConfig(level=logging.DEBUG, <span class="comment"># 控制台打印的日志级别</span></span><br><span class="line"> filename=<span class="string">'cnn_mnist.log'</span>,</span><br><span class="line"> filemode=<span class="string">'a'</span>, <span class="comment"># 模式,有w和a,w就是写模式,每次都会重新写日志,覆盖之前的日志</span></span><br><span class="line"> <span class="comment"># a是追加模式,默认如果不写的话,就是追加模式</span></span><br><span class="line"> <span class="built_in">format</span>=</span><br><span class="line"> <span class="string">'%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'</span></span><br><span class="line"> <span class="comment"># 日志格式</span></span><br><span class="line"> )</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">data_type</span>():</span><br><span class="line"> <span class="string">"""Return the type of the activations, weights, and placeholder variables."""</span></span><br><span class="line"> <span class="keyword">if</span> FLAGS.use_fp16:</span><br><span class="line"> <span class="keyword">return</span> tf.float16</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> <span class="keyword">return</span> tf.float32</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">maybe_download</span>(<span class="params">filename</span>):</span><br><span class="line"> <span class="string">"""Download the data from Yann's website, unless it's already here."""</span></span><br><span class="line"> <span class="keyword">if</span> <span class="keyword">not</span> tf.gfile.Exists(WORK_DIRECTORY):</span><br><span class="line"> tf.gfile.MakeDirs(WORK_DIRECTORY)</span><br><span class="line"> filepath = os.path.join(WORK_DIRECTORY, filename)</span><br><span class="line"> <span class="keyword">if</span> <span class="keyword">not</span> tf.gfile.Exists(filepath):</span><br><span class="line"> filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)</span><br><span class="line"> <span class="keyword">with</span> tf.gfile.GFile(filepath) <span class="keyword">as</span> f:</span><br><span class="line"> size = f.size()</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'Successfully downloaded'</span>, filename, size, <span class="string">'bytes.'</span>)</span><br><span class="line"> <span class="keyword">return</span> filepath</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">extract_data</span>(<span class="params">filename, num_images</span>):</span><br><span class="line"> <span class="string">"""Extract the images into a 4D tensor [image index, y, x, channels].</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"> Values are rescaled from [0, 255] down to [-0.5, 0.5].</span></span><br><span class="line"><span class="string"> """</span></span><br><span class="line"> logging.info(<span class="string">'Extracting'</span> + filename)</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'Extracting'</span>, filename)</span><br><span class="line"> <span class="keyword">with</span> gzip.<span class="built_in">open</span>(filename) <span class="keyword">as</span> bytestream:</span><br><span class="line"> bytestream.read(<span class="number">16</span>)</span><br><span class="line"> buf = bytestream.read(IMAGE_SIZE * IMAGE_SIZE * num_images * NUM_CHANNELS)</span><br><span class="line"> data = numpy.frombuffer(buf, dtype=numpy.uint8).astype(numpy.float32)</span><br><span class="line"> data = (data - (PIXEL_DEPTH / <span class="number">2.0</span>)) / PIXEL_DEPTH</span><br><span class="line"> data = data.reshape(num_images, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS)</span><br><span class="line"> <span class="keyword">return</span> data</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">extract_labels</span>(<span class="params">filename, num_images</span>):</span><br><span class="line"> <span class="string">"""Extract the labels into a vector of int64 label IDs."""</span></span><br><span class="line"> logging.info(<span class="string">'Extracting'</span> + filename)</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'Extracting'</span>, filename)</span><br><span class="line"> <span class="keyword">with</span> gzip.<span class="built_in">open</span>(filename) <span class="keyword">as</span> bytestream:</span><br><span class="line"> bytestream.read(<span class="number">8</span>)</span><br><span class="line"> buf = bytestream.read(<span class="number">1</span> * num_images)</span><br><span class="line"> labels = numpy.frombuffer(buf, dtype=numpy.uint8).astype(numpy.int64)</span><br><span class="line"> <span class="keyword">return</span> labels</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">fake_data</span>(<span class="params">num_images</span>):</span><br><span class="line"> <span class="string">"""Generate a fake dataset that matches the dimensions of MNIST."""</span></span><br><span class="line"> data = numpy.ndarray(</span><br><span class="line"> shape=(num_images, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS),</span><br><span class="line"> dtype=numpy.float32)</span><br><span class="line"> labels = numpy.zeros(shape=(num_images,), dtype=numpy.int64)</span><br><span class="line"> <span class="keyword">for</span> image <span class="keyword">in</span> xrange(num_images):</span><br><span class="line"> label = image % <span class="number">2</span></span><br><span class="line"> data[image, :, :, <span class="number">0</span>] = label - <span class="number">0.5</span></span><br><span class="line"> labels[image] = label</span><br><span class="line"> <span class="keyword">return</span> data, labels</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">error_rate</span>(<span class="params">predictions, labels</span>):</span><br><span class="line"> <span class="string">"""Return the error rate based on dense predictions and sparse labels."""</span></span><br><span class="line"> <span class="keyword">return</span> <span class="number">100.0</span> - (</span><br><span class="line"> <span class="number">100.0</span> *</span><br><span class="line"> numpy.<span class="built_in">sum</span>(numpy.argmax(predictions, <span class="number">1</span>) == labels) /</span><br><span class="line"> predictions.shape[<span class="number">0</span>])</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">main</span>(<span class="params">_</span>):</span><br><span class="line"> <span class="keyword">if</span> FLAGS.self_test:</span><br><span class="line"> logging.info(<span class="string">'Running self-test.'</span>)</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'Running self-test.'</span>)</span><br><span class="line"> train_data, train_labels = fake_data(<span class="number">256</span>)</span><br><span class="line"> validation_data, validation_labels = fake_data(EVAL_BATCH_SIZE)</span><br><span class="line"> test_data, test_labels = fake_data(EVAL_BATCH_SIZE)</span><br><span class="line"> num_epochs = <span class="number">1</span></span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> <span class="comment"># Get the data.</span></span><br><span class="line"> train_data_filename = maybe_download(<span class="string">'train-images-idx3-ubyte.gz'</span>)</span><br><span class="line"> train_labels_filename = maybe_download(<span class="string">'train-labels-idx1-ubyte.gz'</span>)</span><br><span class="line"> test_data_filename = maybe_download(<span class="string">'t10k-images-idx3-ubyte.gz'</span>)</span><br><span class="line"> test_labels_filename = maybe_download(<span class="string">'t10k-labels-idx1-ubyte.gz'</span>)</span><br><span class="line"></span><br><span class="line"> <span class="comment"># Extract it into numpy arrays.</span></span><br><span class="line"> train_data = extract_data(train_data_filename, <span class="number">60000</span>)</span><br><span class="line"> train_labels = extract_labels(train_labels_filename, <span class="number">60000</span>)</span><br><span class="line"> test_data = extract_data(test_data_filename, <span class="number">10000</span>)</span><br><span class="line"> test_labels = extract_labels(test_labels_filename, <span class="number">10000</span>)</span><br><span class="line"></span><br><span class="line"> <span class="comment"># Generate a validation set.</span></span><br><span class="line"> validation_data = train_data[:VALIDATION_SIZE, ...]</span><br><span class="line"> validation_labels = train_labels[:VALIDATION_SIZE]</span><br><span class="line"> train_data = train_data[VALIDATION_SIZE:, ...]</span><br><span class="line"> train_labels = train_labels[VALIDATION_SIZE:]</span><br><span class="line"> num_epochs = NUM_EPOCHS</span><br><span class="line"> train_size = train_labels.shape[<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line"> <span class="comment"># This is where training samples and labels are fed to the graph.</span></span><br><span class="line"> <span class="comment"># These placeholder nodes will be fed a batch of training data at each</span></span><br><span class="line"> <span class="comment"># training step using the {feed_dict} argument to the Run() call below.</span></span><br><span class="line"> train_data_node = tf.placeholder(</span><br><span class="line"> data_type(),</span><br><span class="line"> shape=(BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS))</span><br><span class="line"> train_labels_node = tf.placeholder(tf.int64, shape=(BATCH_SIZE,))</span><br><span class="line"> eval_data = tf.placeholder(</span><br><span class="line"> data_type(),</span><br><span class="line"> shape=(EVAL_BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS))</span><br><span class="line"></span><br><span class="line"> <span class="comment"># The variables below hold all the trainable weights. They are passed an</span></span><br><span class="line"> <span class="comment"># initial value which will be assigned when we call:</span></span><br><span class="line"> <span class="comment"># {tf.global_variables_initializer().run()}</span></span><br><span class="line"> conv1_weights = tf.Variable(</span><br><span class="line"> tf.truncated_normal([<span class="number">5</span>, <span class="number">5</span>, NUM_CHANNELS, <span class="number">32</span>], <span class="comment"># 5x5 filter, depth 32.</span></span><br><span class="line"> stddev=<span class="number">0.1</span>,</span><br><span class="line"> seed=SEED, dtype=data_type()))</span><br><span class="line"> conv1_biases = tf.Variable(tf.zeros([<span class="number">32</span>], dtype=data_type()))</span><br><span class="line"> conv2_weights = tf.Variable(tf.truncated_normal(</span><br><span class="line"> [<span class="number">5</span>, <span class="number">5</span>, <span class="number">32</span>, <span class="number">64</span>], stddev=<span class="number">0.1</span>,</span><br><span class="line"> seed=SEED, dtype=data_type()))</span><br><span class="line"> conv2_biases = tf.Variable(tf.constant(<span class="number">0.1</span>, shape=[<span class="number">64</span>], dtype=data_type()))</span><br><span class="line"> fc1_weights = tf.Variable( <span class="comment"># fully connected, depth 512.</span></span><br><span class="line"> tf.truncated_normal([IMAGE_SIZE // <span class="number">4</span> * IMAGE_SIZE // <span class="number">4</span> * <span class="number">64</span>, <span class="number">512</span>],</span><br><span class="line"> stddev=<span class="number">0.1</span>,</span><br><span class="line"> seed=SEED,</span><br><span class="line"> dtype=data_type()))</span><br><span class="line"> fc1_biases = tf.Variable(tf.constant(<span class="number">0.1</span>, shape=[<span class="number">512</span>], dtype=data_type()))</span><br><span class="line"> fc2_weights = tf.Variable(tf.truncated_normal([<span class="number">512</span>, NUM_LABELS],</span><br><span class="line"> stddev=<span class="number">0.1</span>,</span><br><span class="line"> seed=SEED,</span><br><span class="line"> dtype=data_type()))</span><br><span class="line"> fc2_biases = tf.Variable(tf.constant(</span><br><span class="line"> <span class="number">0.1</span>, shape=[NUM_LABELS], dtype=data_type()))</span><br><span class="line"></span><br><span class="line"> <span class="comment"># We will replicate the model structure for the training subgraph, as well</span></span><br><span class="line"> <span class="comment"># as the evaluation subgraphs, while sharing the trainable parameters.</span></span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">model</span>(<span class="params">data, train=<span class="literal">False</span></span>):</span><br><span class="line"> <span class="string">"""The Model definition."""</span></span><br><span class="line"> <span class="comment"># 2D convolution, with 'SAME' padding (i.e. the output feature map has</span></span><br><span class="line"> <span class="comment"># the same size as the input). Note that {strides} is a 4D array whose</span></span><br><span class="line"> <span class="comment"># shape matches the data layout: [image index, y, x, depth].</span></span><br><span class="line"> conv = tf.nn.conv2d(data,</span><br><span class="line"> conv1_weights,</span><br><span class="line"> strides=[<span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>],</span><br><span class="line"> padding=<span class="string">'SAME'</span>)</span><br><span class="line"> <span class="comment"># Bias and rectified linear non-linearity.</span></span><br><span class="line"> relu = tf.nn.relu(tf.nn.bias_add(conv, conv1_biases))</span><br><span class="line"> <span class="comment"># Max pooling. The kernel size spec {ksize} also follows the layout of</span></span><br><span class="line"> <span class="comment"># the data. Here we have a pooling window of 2, and a stride of 2.</span></span><br><span class="line"> pool = tf.nn.max_pool(relu,</span><br><span class="line"> ksize=[<span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">1</span>],</span><br><span class="line"> strides=[<span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">1</span>],</span><br><span class="line"> padding=<span class="string">'SAME'</span>)</span><br><span class="line"> conv = tf.nn.conv2d(pool,</span><br><span class="line"> conv2_weights,</span><br><span class="line"> strides=[<span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>],</span><br><span class="line"> padding=<span class="string">'SAME'</span>)</span><br><span class="line"> relu = tf.nn.relu(tf.nn.bias_add(conv, conv2_biases))</span><br><span class="line"> pool = tf.nn.max_pool(relu,</span><br><span class="line"> ksize=[<span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">1</span>],</span><br><span class="line"> strides=[<span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">1</span>],</span><br><span class="line"> padding=<span class="string">'SAME'</span>)</span><br><span class="line"> <span class="comment"># Reshape the feature map cuboid into a 2D matrix to feed it to the</span></span><br><span class="line"> <span class="comment"># fully connected layers.</span></span><br><span class="line"> pool_shape = pool.get_shape().as_list()</span><br><span class="line"> reshape = tf.reshape(</span><br><span class="line"> pool,</span><br><span class="line"> [pool_shape[<span class="number">0</span>], pool_shape[<span class="number">1</span>] * pool_shape[<span class="number">2</span>] * pool_shape[<span class="number">3</span>]])</span><br><span class="line"> <span class="comment"># Fully connected layer. Note that the '+' operation automatically</span></span><br><span class="line"> <span class="comment"># broadcasts the biases.</span></span><br><span class="line"> hidden = tf.nn.relu(tf.matmul(reshape, fc1_weights) + fc1_biases)</span><br><span class="line"> <span class="comment"># Add a 50% dropout during training only. Dropout also scales</span></span><br><span class="line"> <span class="comment"># activations such that no rescaling is needed at evaluation time.</span></span><br><span class="line"> <span class="keyword">if</span> train:</span><br><span class="line"> hidden = tf.nn.dropout(hidden, <span class="number">0.5</span>, seed=SEED)</span><br><span class="line"> <span class="keyword">return</span> tf.matmul(hidden, fc2_weights) + fc2_biases</span><br><span class="line"></span><br><span class="line"> <span class="comment"># Training computation: logits + cross-entropy loss.</span></span><br><span class="line"> logits = model(train_data_node, <span class="literal">True</span>)</span><br><span class="line"> loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(</span><br><span class="line"> labels=train_labels_node, logits=logits))</span><br><span class="line"></span><br><span class="line"> <span class="comment"># L2 regularization for the fully connected parameters.</span></span><br><span class="line"> regularizers = (tf.nn.l2_loss(fc1_weights) + tf.nn.l2_loss(fc1_biases) +</span><br><span class="line"> tf.nn.l2_loss(fc2_weights) + tf.nn.l2_loss(fc2_biases))</span><br><span class="line"> <span class="comment"># Add the regularization term to the loss.</span></span><br><span class="line"> loss += <span class="number">5e-4</span> * regularizers</span><br><span class="line"></span><br><span class="line"> <span class="comment"># Optimizer: set up a variable that's incremented once per batch and</span></span><br><span class="line"> <span class="comment"># controls the learning rate decay.</span></span><br><span class="line"> batch = tf.Variable(<span class="number">0</span>, dtype=data_type())</span><br><span class="line"> <span class="comment"># Decay once per epoch, using an exponential schedule starting at 0.01.</span></span><br><span class="line"> learning_rate = tf.train.exponential_decay(</span><br><span class="line"> <span class="number">0.01</span>, <span class="comment"># Base learning rate.</span></span><br><span class="line"> batch * BATCH_SIZE, <span class="comment"># Current index into the dataset.</span></span><br><span class="line"> train_size, <span class="comment"># Decay step.</span></span><br><span class="line"> <span class="number">0.95</span>, <span class="comment"># Decay rate.</span></span><br><span class="line"> staircase=<span class="literal">True</span>)</span><br><span class="line"> <span class="comment"># Use simple momentum for the optimization.</span></span><br><span class="line"> optimizer = tf.train.MomentumOptimizer(learning_rate,</span><br><span class="line"> <span class="number">0.9</span>).minimize(loss,</span><br><span class="line"> global_step=batch)</span><br><span class="line"></span><br><span class="line"> <span class="comment"># Predictions for the current training minibatch.</span></span><br><span class="line"> train_prediction = tf.nn.softmax(logits)</span><br><span class="line"></span><br><span class="line"> <span class="comment"># Predictions for the test and validation, which we'll compute less often.</span></span><br><span class="line"> eval_prediction = tf.nn.softmax(model(eval_data))</span><br><span class="line"></span><br><span class="line"> <span class="comment"># Small utility function to evaluate a dataset by feeding batches of data to</span></span><br><span class="line"> <span class="comment"># {eval_data} and pulling the results from {eval_predictions}.</span></span><br><span class="line"> <span class="comment"># Saves memory and enables this to run on smaller GPUs.</span></span><br><span class="line"> <span class="keyword">def</span> <span class="title function_">eval_in_batches</span>(<span class="params">data, sess</span>):</span><br><span class="line"> <span class="string">"""Get all predictions for a dataset by running it in small batches."""</span></span><br><span class="line"> size = data.shape[<span class="number">0</span>]</span><br><span class="line"> <span class="keyword">if</span> size < EVAL_BATCH_SIZE:</span><br><span class="line"> logging.error(<span class="string">"batch size for evals larger than dataset: %d"</span> % size)</span><br><span class="line"> <span class="keyword">raise</span> ValueError(<span class="string">"batch size for evals larger than dataset: %d"</span> % size)</span><br><span class="line"> predictions = numpy.ndarray(shape=(size, NUM_LABELS), dtype=numpy.float32)</span><br><span class="line"> <span class="keyword">for</span> begin <span class="keyword">in</span> xrange(<span class="number">0</span>, size, EVAL_BATCH_SIZE):</span><br><span class="line"> end = begin + EVAL_BATCH_SIZE</span><br><span class="line"> <span class="keyword">if</span> end <= size:</span><br><span class="line"> predictions[begin:end, :] = sess.run(</span><br><span class="line"> eval_prediction,</span><br><span class="line"> feed_dict={eval_data: data[begin:end, ...]})</span><br><span class="line"> <span class="keyword">else</span>:</span><br><span class="line"> batch_predictions = sess.run(</span><br><span class="line"> eval_prediction,</span><br><span class="line"> feed_dict={eval_data: data[-EVAL_BATCH_SIZE:, ...]})</span><br><span class="line"> predictions[begin:, :] = batch_predictions[begin - size:, :]</span><br><span class="line"> <span class="keyword">return</span> predictions</span><br><span class="line"></span><br><span class="line"> <span class="comment"># Create a local session to run the training.</span></span><br><span class="line"> start_time = time.time()</span><br><span class="line"> <span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line"> <span class="comment"># Run all the initializers to prepare the trainable parameters.</span></span><br><span class="line"> tf.global_variables_initializer().run()</span><br><span class="line"> logging.info(<span class="string">'Initialized!'</span>)</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'Initialized!'</span>)</span><br><span class="line"> <span class="comment"># Loop through training steps.</span></span><br><span class="line"> <span class="keyword">for</span> step <span class="keyword">in</span> xrange(<span class="built_in">int</span>(num_epochs * train_size) // BATCH_SIZE):</span><br><span class="line"> <span class="comment"># Compute the offset of the current minibatch in the data.</span></span><br><span class="line"> <span class="comment"># Note that we could use better randomization across epochs.</span></span><br><span class="line"> offset = (step * BATCH_SIZE) % (train_size - BATCH_SIZE)</span><br><span class="line"> batch_data = train_data[offset:(offset + BATCH_SIZE), ...]</span><br><span class="line"> batch_labels = train_labels[offset:(offset + BATCH_SIZE)]</span><br><span class="line"> <span class="comment"># This dictionary maps the batch data (as a numpy array) to the</span></span><br><span class="line"> <span class="comment"># node in the graph it should be fed to.</span></span><br><span class="line"> feed_dict = {train_data_node: batch_data,</span><br><span class="line"> train_labels_node: batch_labels}</span><br><span class="line"> <span class="comment"># Run the optimizer to update weights.</span></span><br><span class="line"> sess.run(optimizer, feed_dict=feed_dict)</span><br><span class="line"> <span class="comment"># print some extra information once reach the evaluation frequency</span></span><br><span class="line"> <span class="keyword">if</span> step % EVAL_FREQUENCY == <span class="number">0</span>:</span><br><span class="line"> <span class="comment"># fetch some extra nodes' data</span></span><br><span class="line"> l, lr, predictions = sess.run([loss, learning_rate, train_prediction],</span><br><span class="line"> feed_dict=feed_dict)</span><br><span class="line"> elapsed_time = time.time() - start_time</span><br><span class="line"> start_time = time.time()</span><br><span class="line"> logging.info(<span class="string">'Step %d (epoch %.2f), %.1f ms'</span> %(step, <span class="built_in">float</span>(step) * BATCH_SIZE / train_size, <span class="number">1000</span> * elapsed_time / EVAL_FREQUENCY))</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'Step %d (epoch %.2f), %.1f ms'</span> %</span><br><span class="line"> (step, <span class="built_in">float</span>(step) * BATCH_SIZE / train_size,</span><br><span class="line"> <span class="number">1000</span> * elapsed_time / EVAL_FREQUENCY))</span><br><span class="line"> logging.info(<span class="string">'Minibatch loss: %.3f, learning rate: %.6f'</span> % (l, lr))</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'Minibatch loss: %.3f, learning rate: %.6f'</span> % (l, lr))</span><br><span class="line"> logging.info(<span class="string">'Minibatch error: %.1f%%'</span> % error_rate(predictions, batch_labels))</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'Minibatch error: %.1f%%'</span> % error_rate(predictions, batch_labels))</span><br><span class="line"> logging.info(<span class="string">'Validation error: %.1f%%'</span> % error_rate(eval_in_batches(validation_data, sess), validation_labels))</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'Validation error: %.1f%%'</span> % error_rate(</span><br><span class="line"> eval_in_batches(validation_data, sess), validation_labels))</span><br><span class="line"> sys.stdout.flush()</span><br><span class="line"> <span class="comment"># Finally print the result!</span></span><br><span class="line"> test_error = error_rate(eval_in_batches(test_data, sess), test_labels)</span><br><span class="line"> logging.info(<span class="string">'Test error: %.1f%%'</span> % test_error)</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'Test error: %.1f%%'</span> % test_error)</span><br><span class="line"> <span class="keyword">if</span> FLAGS.self_test:</span><br><span class="line"> logging.info(<span class="string">'test_error'</span> + test_error)</span><br><span class="line"> <span class="built_in">print</span>(<span class="string">'test_error'</span>, test_error)</span><br><span class="line"> <span class="keyword">assert</span> test_error == <span class="number">0.0</span>, <span class="string">'expected 0.0 test_error, got %.2f'</span> % (</span><br><span class="line"> test_error,)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line"> parser = argparse.ArgumentParser()</span><br><span class="line"> parser.add_argument(</span><br><span class="line"> <span class="string">'--use_fp16'</span>,</span><br><span class="line"> default=<span class="literal">False</span>,</span><br><span class="line"> <span class="built_in">help</span>=<span class="string">'Use half floats instead of full floats if True.'</span>,</span><br><span class="line"> action=<span class="string">'store_true'</span>)</span><br><span class="line"> parser.add_argument(</span><br><span class="line"> <span class="string">'--self_test'</span>,</span><br><span class="line"> default=<span class="literal">False</span>,</span><br><span class="line"> action=<span class="string">'store_true'</span>,</span><br><span class="line"> <span class="built_in">help</span>=<span class="string">'True if running a self test.'</span>)</span><br><span class="line"></span><br><span class="line"> FLAGS, unparsed = parser.parse_known_args()</span><br><span class="line"> tf.app.run(main=main, argv=[sys.argv[<span class="number">0</span>]] + unparsed)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>这里我在原来的程序基础上面稍微改了下,因为我已经提前将数据下载好了,所以我让程序直接读取本机指定目录下的训练数据,同时增加了日志文件输出.这是为了在公司的容器云平台上测试获取容器输出文件</p>
<h2 id="编写Dockerfile"><a href="#编写Dockerfile" class="headerlink" title="编写Dockerfile"></a>编写Dockerfile</h2><p>我们可以在我们的用户目录下,创建一个空的文件夹,将mnist数据集以及程序文件都拷贝进这个文件夹下.其实数据集应该是放在数据卷中,但是这里为了方便,我直接将训练数据打进了镜像中.然后创建Dockerfile,文件内容如下</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">FROM tensorflow/tensorflow:1.9.0-devel-py3</span><br><span class="line"></span><br><span class="line">COPY . /home/ll</span><br><span class="line">WORKDIR /home/ll</span><br><span class="line">CMD [<span class="string">'python'</span>, <span class="string">'convolutional.py'</span>]</span><br></pre></td></tr></table></figure>
<p>即Dockerfile文件中最后一行表示容器启动的运行的命令</p>
<h2 id="build镜像"><a href="#build镜像" class="headerlink" title="build镜像"></a>build镜像</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker build -t tf:1.9 .</span><br></pre></td></tr></table></figure>
<p><code>-t</code>参数指定镜像跟tag,最后的<code>.</code>指定了镜像中的上下文.构建完之后使用<code>docker images</code>可以查看多了<code>tf:1.9</code>镜像</p>
<h2 id="运行镜像"><a href="#运行镜像" class="headerlink" title="运行镜像"></a>运行镜像</h2><p>运行下面的命令,运行上一步构建好的镜像</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker run -it --name <span class="built_in">test</span> tf:1.9</span><br></pre></td></tr></table></figure>
<p>然后就能够看到训练的输出.<br><img src="/docker%E4%B8%8Etensorflow%E7%BB%93%E5%90%88%E4%BD%BF%E7%94%A8/tensorflow.png" class=""><br>同时可以在看一个连接,进入容器,即运行下面命令</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker <span class="built_in">exec</span> -it <span class="built_in">test</span> /bin/bash</span><br></pre></td></tr></table></figure>
<p>可以看到如下内容<br><img src="/docker%E4%B8%8Etensorflow%E7%BB%93%E5%90%88%E4%BD%BF%E7%94%A8/container.png" class=""><br>即看到了cnn_mnist.log的日志输出文件</p>
</div>
<footer class="post-footer">
<div class="post-tags">
<a href="/tags/docker/" rel="tag"># docker</a>
<a href="/tags/tensorflow/" rel="tag"># tensorflow</a>
</div>
<div class="post-nav">
<div class="post-nav-next post-nav-item">
<a href="/docker%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4.html" rel="next" title="docker常用命令">
<i class="fa fa-chevron-left"></i> docker常用命令
</a>
</div>
<span class="post-nav-divider"></span>
<div class="post-nav-prev post-nav-item">
<a href="/linux%E9%B8%9F%E5%93%A5%E7%A7%81%E6%88%BF%E8%8F%9C%E6%94%B6%E8%8E%B7.html" rel="prev" title="linux鸟哥私房菜收获">
linux鸟哥私房菜收获 <i class="fa fa-chevron-right"></i>
</a>
</div>
</div>
</footer>
</div>
</article>
<div class="post-spread">
</div>
</div>
</div>
</div>
<div class="sidebar-toggle">
<div class="sidebar-toggle-line-wrap">
<span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
</div>
</div>
<aside id="sidebar" class="sidebar">
<div class="sidebar-inner">
<ul class="sidebar-nav motion-element">
<li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
文章目录
</li>
<li class="sidebar-nav-overview" data-target="site-overview-wrap">
站点概览
</li>
</ul>
<section class="site-overview-wrap sidebar-panel">
<div class="site-overview">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<p class="site-author-name" itemprop="name"></p>
<p class="site-description motion-element" itemprop="description"></p>
</div>
<nav class="site-state motion-element">
<div class="site-state-item site-state-posts">
<a href="/archives/%7C%7C%20archive">
<span class="site-state-item-count">37</span>
<span class="site-state-item-name">日志</span>
</a>
</div>
<div class="site-state-item site-state-categories">
<a href="/categories/index.html">
<span class="site-state-item-count">22</span>
<span class="site-state-item-name">分类</span>
</a>
</div>
<div class="site-state-item site-state-tags">
<a href="/tags/index.html">
<span class="site-state-item-count">45</span>
<span class="site-state-item-name">标签</span>
</a>
</div>
</nav>
<div class="feed-link motion-element">
<a href="/atom.xml" rel="alternate">
<i class="fa fa-rss"></i>
RSS
</a>
</div>
</div>
</section>
<!--noindex-->
<section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
<div class="post-toc">
<div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#docker%E5%AE%89%E8%A3%85"><span class="nav-number">1.</span> <span class="nav-text">docker安装</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#tensorflow"><span class="nav-number">2.</span> <span class="nav-text">tensorflow</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#tensorflow%E5%9C%A8docker%E4%B8%AD%E4%BD%BF%E7%94%A8"><span class="nav-number">3.</span> <span class="nav-text">tensorflow在docker中使用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E8%87%AA%E5%B7%B1%E7%9A%84%E9%95%9C%E5%83%8F"><span class="nav-number">4.</span> <span class="nav-text">创建自己的镜像</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BC%96%E5%86%99Dockerfile"><span class="nav-number">4.1.</span> <span class="nav-text">编写Dockerfile</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#build%E9%95%9C%E5%83%8F"><span class="nav-number">4.2.</span> <span class="nav-text">build镜像</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BF%90%E8%A1%8C%E9%95%9C%E5%83%8F"><span class="nav-number">4.3.</span> <span class="nav-text">运行镜像</span></a></li></ol></li></ol></div>
</div>
</section>
<!--/noindex-->
</div>
</aside>
</div>
</main>
<footer id="footer" class="footer">
<div class="footer-inner">
<div class="copyright">© <span itemprop="copyrightYear">2024</span>
<span class="with-love">
<i class="fa fa-user"></i>
</span>
<span class="author" itemprop="copyrightHolder">liang</span>
</div>
<div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>
<span class="post-meta-divider">|</span>
<div class="theme-info">主题 — <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>
</div>
</footer>
<div class="back-to-top">
<i class="fa fa-arrow-up"></i>
</div>
</div>
<script type="text/javascript">
if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
window.Promise = null;
}
</script>
<script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
<script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
<script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>
</body>
</html>