Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
tensorflow_tutorials/python/05_basic_convnet.py at master · CMLBEmmL/tensorflow_tutorials · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
Platform
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
Solutions
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
See all industries
View all solutions
Resources
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
Open Source
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
Enterprise
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
CMLBEmmL
tensorflow_tutorials
Repository navigation
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
More
items
Files
Expand file tree
master
Breadcrumbs
tensorflow_tutorials
/
python
/
05_basic_convnet.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
105 lines (88 loc) · 3.75 KB
master
Breadcrumbs
tensorflow_tutorials
/
python
/
05_basic_convnet.py
Copy path
Top
File metadata and controls
Code
Blame
105 lines (88 loc) · 3.75 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""Simple tutorial following the TensorFlow example of a Convolutional Network.
Parag K. Mital, Jan. 2016"""
# %% Imports
import
tensorflow
as
tf
import
tensorflow
.
examples
.
tutorials
.
mnist
.
input_data
as
input_data
from
libs
.
utils
import
*
import
matplotlib
.
pyplot
as
plt
# %% Setup input to the network and true output label. These are
# simply placeholders which we'll fill in later.
mnist
=
input_data
.
read_data_sets
(
'MNIST_data/'
,
one_hot
=
True
)
x
=
tf
.
placeholder
(
tf
.
float32
, [
None
,
784
])
y
=
tf
.
placeholder
(
tf
.
float32
, [
None
,
10
])
# %% Since x is currently [batch, height*width], we need to reshape to a
# 4-D tensor to use it in a convolutional graph. If one component of
# `shape` is the special value -1, the size of that dimension is
# computed so that the total size remains constant. Since we haven't
# defined the batch dimension's shape yet, we use -1 to denote this
# dimension should not change size.
x_tensor
=
tf
.
reshape
(
x
, [
-
1
,
28
,
28
,
1
])
# %% We'll setup the first convolutional layer
# Weight matrix is [height x width x input_channels x output_channels]
filter_size
=
5
n_filters_1
=
16
W_conv1
=
weight_variable
([
filter_size
,
filter_size
,
1
,
n_filters_1
])
# %% Bias is [output_channels]
b_conv1
=
bias_variable
([
n_filters_1
])
# %% Now we can build a graph which does the first layer of convolution:
# we define our stride as batch x height x width x channels
# instead of pooling, we use strides of 2 and more layers
# with smaller filters.
h_conv1
=
tf
.
nn
.
relu
(
tf
.
nn
.
conv2d
(
input
=
x_tensor
,
filter
=
W_conv1
,
strides
=
[
1
,
2
,
2
,
1
],
padding
=
'SAME'
)
+
b_conv1
)
# %% And just like the first layer, add additional layers to create
# a deep net
n_filters_2
=
16
W_conv2
=
weight_variable
([
filter_size
,
filter_size
,
n_filters_1
,
n_filters_2
])
b_conv2
=
bias_variable
([
n_filters_2
])
h_conv2
=
tf
.
nn
.
relu
(
tf
.
nn
.
conv2d
(
input
=
h_conv1
,
filter
=
W_conv2
,
strides
=
[
1
,
2
,
2
,
1
],
padding
=
'SAME'
)
+
b_conv2
)
# %% We'll now reshape so we can connect to a fully-connected layer:
h_conv2_flat
=
tf
.
reshape
(
h_conv2
, [
-
1
,
7
*
7
*
n_filters_2
])
# %% Create a fully-connected layer:
n_fc
=
1024
W_fc1
=
weight_variable
([
7
*
7
*
n_filters_2
,
n_fc
])
b_fc1
=
bias_variable
([
n_fc
])
h_fc1
=
tf
.
nn
.
relu
(
tf
.
matmul
(
h_conv2_flat
,
W_fc1
)
+
b_fc1
)
# %% We can add dropout for regularizing and to reduce overfitting like so:
keep_prob
=
tf
.
placeholder
(
tf
.
float32
)
h_fc1_drop
=
tf
.
nn
.
dropout
(
h_fc1
,
keep_prob
)
# %% And finally our softmax layer:
W_fc2
=
weight_variable
([
n_fc
,
10
])
b_fc2
=
bias_variable
([
10
])
y_pred
=
tf
.
nn
.
softmax
(
tf
.
matmul
(
h_fc1_drop
,
W_fc2
)
+
b_fc2
)
# %% Define loss/eval/training functions
cross_entropy
=
-
tf
.
reduce_sum
(
y
*
tf
.
log
(
y_pred
))
optimizer
=
tf
.
train
.
AdamOptimizer
().
minimize
(
cross_entropy
)
# %% Monitor accuracy
correct_prediction
=
tf
.
equal
(
tf
.
argmax
(
y_pred
,
1
),
tf
.
argmax
(
y
,
1
))
accuracy
=
tf
.
reduce_mean
(
tf
.
cast
(
correct_prediction
,
'float'
))
# %% We now create a new session to actually perform the initialization the
# variables:
sess
=
tf
.
Session
()
sess
.
run
(
tf
.
initialize_all_variables
())
# %% We'll train in minibatches and report accuracy:
batch_size
=
100
n_epochs
=
5
for
epoch_i
in
range
(
n_epochs
):
for
batch_i
in
range
(
mnist
.
train
.
num_examples
//
batch_size
):
batch_xs
,
batch_ys
=
mnist
.
train
.
next_batch
(
batch_size
)
sess
.
run
(
optimizer
,
feed_dict
=
{
x
:
batch_xs
,
y
:
batch_ys
,
keep_prob
:
0.5
})
print
(
sess
.
run
(
accuracy
,
feed_dict
=
{
x
:
mnist
.
validation
.
images
,
y
:
mnist
.
validation
.
labels
,
keep_prob
:
1.0
}))
# %% Let's take a look at the kernels we've learned
W
=
sess
.
run
(
W_conv1
)
plt
.
imshow
(
montage
(
W
/
np
.
max
(
W
)),
cmap
=
'coolwarm'
)
You can’t perform that action at this time.