コードの実装:
インポートtensorflowのTF AS
から tensorflow.examples.tutorials.mnist インポートINPUT_DATA
インポートOSの
はos.environ [ ' TF_CPP_MIN_LOG_LEVEL ' ] = ' 2 'の
#は、初期化するために重み付け関数を定義
DEFのweight_varibles(形状):
W = tf.Variable(tf.random_normal (=シェイプ形状、平均値= 0.0、STDDEV = 1.0 ))
リターンW
#定義オフセット初期化機能
DEFのbias_varibles(形状):
B = tf.Variable(tf.constant(0.0、形状= シェイプ))
リターンB
DEF モデル():
"" "
畳み込みモデル定義以来
:リターン:
"" "
#のプレースホルダX [なし]、[784] 1.準備データy_true [なし]、[10]
(tf.variable_scopeと" データ」):
X = tf.placeholder(TF .float32、[なし]、784 ])
y_true = tf.placeholder(tf.int32、[なし]、[10 ])
#2畳み込み5,5,1,32の層畳み込みは、細胞活性化tf.nn.を活性化しませんreluをプール
(tf.variable_scopeと" CONV1 " :)
#ランダムに初期化重み
w_conv1 weight_varibles =([5,5,1,32 ])
#は、ランダムオフセット発生
b_conv1 bias_varibles =([32 ])
位X [なし]、[784]の形状変化は、配列を、[なし]、28,28,1]思考に変更される
- x_reshape tf.reshape =([1,28,28,1 X、])
x_relu = tf.nn.relu (tf.nn.conv2d(x_reshape、w_conv1、ストライド= [1,1,1,1]、パディング= " SAME ")+ b_conv1)
#1 プール2×2 strides2 [なし、28,28,32 ] - > [なし、14,14,32]
x_pool1 = tf.nn.max_pool(x_relu、ksize = [1,2,2,1]、ストライド= [1,2,2,1]、パディング= " SAME " )
#3レイヤ畳み込み
tf.variable_scope有する(" CONV2 " ):
#ランダムに初期化量重量[5,5,32,64]オフセット[64]
w_conv2 weight_varibles =([5,5,32,64 ])
b_conv2Bias_varibles =([64 ])
#の畳み込み活性化し、プール
#1 の畳み込み[なし、14,14,32] -----> [なし]、[14,14,64]
x_relu2 = tf.nn. RELU(tf.nn.conv2d(x_pool1、w_conv2、ストライド= [1,1,1,1]、パディング= " SAME ")+ b_conv2)
#2 * 2ストライド2プーリング、[なし] 、14,14,64 ] ---> [なし、7,7,64]
x_pool2 = tf.nn.max_pool(x_relu2、ksize = [1,2,2,1]、ストライド= [1,2,2,1]、パディング= " SAME " )
#4完全接続層[なし、7,7,64] ---> [なし、7 * 7 * 64] * [7 * 7 * 64,10] + [10] =なし、10 ]
tf.variable_scope(と"" ):#
ランダムに初期化重みおよびバイアス
w_fc weight_varibles =([7 7 * 64、10 ])
b_fc = bias_varibles([10 ])
#形状を変更し、[なし]、7,7,64] ---> [なし] ,. 7 7 * 64]
x_fc_reshape = tf.reshape(x_pool2、[ - L、7 7 * 64 * ])
#は、各サンプル10について得られた行列演算結果行う
y_predict = tf.matmul(x_fc_reshape、w_fc)+ b_fcの
戻りX、y_true、y_predict
DEF cunv_fcを():
#実際のデータ取得
MNIST = input_data.read_data_setsを(" 。 / MNIST / INPUT_DATA / "one_hot = TRUE)
#モデル由来の出力定義
X、y_true、y_predict = モデル()
#は、すべてのサンプルについて損失を求める平均
(持つtf.compat.v1.variable_scope " soft_cross " ):
#平均クロスエントロピー損失計算
損失= tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(= y_trueラベル、logits = y_predict))
#の決定勾配降下損失
TFとします。 compat.v1.variable_scope(" オプティマイザ" ):
train_op = tf.compat.v1.train.GradientDescentOptimizer(0.1 ).minimize(損失)
#の計算精度
tf.compat.v1.variable_scope有する(" ACC " ):
equal_list = tf.equal(tf.argmax(y_true ,. 1)、tf.argmax(y_predict ,. 1 ))
#変換タイプのサンプルと平均
精度=tf.reduce_mean(tf.cast(equal_list、tf.float32))
#の OPの変数定義の初期化
init_op = tf.global_variables_initializer()
#オープンセッションが実行され
、SESのAS tf.compat.v1.Session(と):
#は、変数の初期化
のSESを.RUN(init_op)
#訓練の反復回数は、パラメータ予測更新する
ための I における範囲(1000 ):
#は本当の固有値とターゲット抽出
mnist_x、mnist_y mnist.train.next_batch =(50 )
#の実行train_opトレーニング
sess.runを(train_op、feed_dict = {X:mnist_x、y_true:mnist_y})
プリント(" %Dの正解率F%のための訓練"%(I、sess.run(精度、feed_dict = {X:mnist_x、y_true:mnist_y})))
もし __name__ == ' __main__ ' :
cunv_fc()