tensorflow笔记(一):tensorflow基本框架

tensorflow将搭建网络与计算网络中的数值进行了割裂,也就是说在搭建网络阶段并不计算数值。

一、计算图

如以下代码:

# coding:utf-8
# 0导入模块 ,生成模拟数据集
import tensorflow as tf

# 定义神经网络的输入、参数和输出,定义前向传播过程


def get_weight(shape, regularizer):
    w = tf.Variable(tf.random_normal(shape), dtype=tf.float32)
    tf.add_to_collection(
        'losses', tf.contrib.layers.l2_regularizer(regularizer)(w))
    return w


def get_bias(shape):
    b = tf.Variable(tf.constant(0.01, shape=shape))
    return b


def forward(x, regularizer):

    w1 = get_weight([2, 11], regularizer)
    b1 = get_bias([11])
    y1 = tf.nn.relu(tf.matmul(x, w1) + b1)

    w2 = get_weight([11, 1], regularizer)
    b2 = get_bias([1])
    y = tf.matmul(y1, w2) + b2

    return y

其中,get_weight是获得权重的函数,get_bias是获得偏置的函数,forward是描述神经网络的前向传播过程的函数,也就是tensorflow中的计算图,在执行此代码段时神经网络并不计算任何中间值。

二、会话(session)

创建会话对象后,可以使用 sess.run (node) 返回节点的值,并且 Tensorflow 将执行确定该值所需的所有计算。

假设我们有一组原始数据x,使用上面的forward搭建神经网络。

y = forward(x, REGULARIZER)
with tf.Session() as sess:
    print(sess.run(y))

第一行代码是搭建计算图,第二行代码是实例化tf.Session(),第三行是打印出y的值。sess.run(y)返回y的值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章