1.# 为了使函数具有更好的泛化能力,定义一个load_data
# 用于从pickle文件将数据读取进来
def load_data(filename):
'''read data from data file.'''
with open(filename, 'rb') as f:
data = cPickle.load(f, encoding='bytes')
return data[b'data'], data[b'labels']
# 先搭建tensorflow计算图,再执行
x = tf.placeholder(tf.float32, [None, 3072]) # None表示可变性
# [None]
y = tf.placeholder(tf.int64, [None])
# (3072, 1)
w = tf.get_variable('w', [x.get_shape()[-1], 1], # 因为是二分类,所以只有一个输出结果,定义为1
initializer=tf.random_normal_initializer(0, 1)) #initializer表示初始化,这里使用正态分布,均值为0,方差为1
# (1, )
b = tf.get_variable('b', [1],
initializer=tf.constant_initializer(0.0)) # b使用常量初始化
# get_variable表示获取变量,如果已经定义好了就使用,如果没有就定义
# [None, 3072] * [3072, 1] = [None, 1]
y_ = tf.matmul(x, w) + b
# [None, 1]
p_y_1 = tf.nn.sigmoid(y_) # 概率值
# 因为y维度不一样,所以需要进行一下reshape
# [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_float - p_y_1)) # 类型不一致需要变换
predict = p_y_1 > 0.5 # true:1 false:0
# [1, 0, 1, 1, 0, 1,...]
correct_prediction = tf.equal(tf.cast(predict, tf.int64), y_reshaped) # bool
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float64))
# 定义梯度下降的方法
with tf.name_scope('train_op'):
train_op = tf.train.AdamOptimizer(1e-3).minimize(loss) # 最小化loss,到这里,计算图构建完成
注意类型变换和loss梯度下降