Ex_treme's blog.

数据处理与模型图构建(2)

2018/11/13 Share

模型图构建流程

  • 导包
  • 读数据模块
  • 模型图构建

导包

1
2
3
4
5
6
7
import tensorflow as tf
import os
import pickle
import numpy as np

CIFAR_DIR = 'cifar-10-batches-py'
print(os.listdir(CIFAR_DIR))

[‘batches.meta’, ‘test_batch’, ‘data_batch_1’, ‘data_batch_4’, ‘data_batch_5’, ‘readme.html’, ‘data_batch_2’, ‘data_batch_3’]

读数据模块

1
2
3
4
5
def load_data(filename):
"""read date from data file."""
with open(filename,'rb') as f:
data = pickle.load(f)
return data['data'],data['labels']

模型图构建

神经元

1
2
3
4
5
6
7
8
9
10
11
12
# 输入 [None,3072]
x = tf.placeholder(tf.float32,[None,3072])

# 输出 [None]
y = f.placeholder(tf.int64,[None])

# 权重 (3072,1)
w = tf.get_variable('w',[x.get_shape()[-1],1],
initializer=tf.random_normal_initializer(0,1))

# 偏置 (1, )
b = tf.get_variable('b',[1],initializer=tf.constant_initializer(0.0))

激活函数

1
2
# [None,3072]*[3072,1] = [None,1]
y_ =tf.matmul(x,w)+b

逻辑回归模型

1
2
# [None,1]
p_y_1 = tf.nn.sigmoid(y_)

损失函数

1
2
3
4
5
6
7
8
9
# [None,1]
y_reshaped = tf.reshape(y,(-1,1))
y_reshaped_float = tf.cast(y_reshaped,tf.float32)
loss = tf.reduce_mean(tf.square(y_reshaped - p_y_1))
#bool
predict = p_y_1 > 0.5
# [1,0,1,1,1,0]
correct_prediction = tf.equal(tf.cast(predict,tf.int64),y_reshaped)
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float64))

神经网络训练

1
2
with tf.name_scope('train_op'):
train_op = tf.train.AdamOptimizer(1e-3).minimize(loss)
CATALOG
  1. 1. 模型图构建流程
    1. 1.1. 导包
    2. 1.2. 读数据模块
    3. 1.3. 模型图构建