深度学习——反向传播tensorflow实现

  1 import tensorflow as tf
  2 import numpy as np
  3 
  4 """
  5 使用tensorflow 实现简单的 线性回归  y = np.dot(x, W) + b
  6 """
  7 
  8 def f1():
  9     """
 10     先使用常量进行构建,展示大致的业务逻辑
 11     :return:
 12     """
 13     # 一、建图
 14     with tf.Graph().as_default():
 15         # 1、创建模型输入
 16         input_x = tf.constant(
 17             value=[[1,2,3],
 18                    [2,3,4],
 19                    [12,34,23],
 20                    [2,3,9]], dtype=tf.float32, shape=[4, 3], name='input_x'
 21         )
 22         # 2、创建变量
 23         weights = tf.constant(
 24             value=[[-5],
 25                    [3],
 26                    [2]], dtype=tf.float32, shape=[3, 1], name='weights'
 27         )
 28         bias = tf.constant(
 29             value=[2], dtype=tf.float32, shape=[1], name='bias'
 30         )
 31 
 32         # 3、构建正向传播过程
 33         y_hat = tf.matmul(input_x, weights) + bias
 34         print(y_hat)
 35 
 36         # 二、构建会话
 37         with tf.Session() as sess:
 38             # 执行模型图
 39             y_hat_ = sess.run(y_hat)
 40             print(y_hat_)
 41 
 42 #将常量用variable换为变量
 43 def f2():
 44     """
 45     变量使用 tf.Variable()来构建
 46     :return:
 47     """
 48     # 一、建图
 49     with tf.Graph().as_default():
 50         # 1、创建模型输入
 51         input_x = tf.constant(
 52             value=[[1,2,3],
 53                    [2,3,4],
 54                    [12,34,23],
 55                    [2,3,9]], dtype=tf.float32, shape=[4, 3], name='input_x'
 56         )
 57         """
 58         tf.Variable(self,
 59                initial_value=None,    # 给定初始化的值,可以是python的基本数据类型,也可以是tf的tensor对象
 60                trainable=True,        # bool 该变量是否参与模型训练。也就是该变量是否会执行梯度下降
 61                collections=None,
 62                validate_shape=True,
 63                caching_device=None,
 64                name=None,            # tensorflow底层的名字。
 65                variable_def=None,
 66                dtype=None,           # 数据类型
 67                expected_shape=None,
 68                import_scope=None,
 69                constraint=None):
 70         """
 71         # 2、创建变量
 72         weights = tf.Variable(
 73             initial_value=[[-5],
 74                            [3],
 75                            [2]], dtype=tf.float32, name='weights'
 76         )
 77         print(weights)
 78         bias_value = tf.constant(
 79             value=[2], dtype=tf.float32, shape=[1], name='bias'
 80         )
 81         bias = tf.Variable(initial_value=bias_value, dtype=tf.float32, name='bias')
 82 
 83         # 3、构建正向传播过程
 84         y_hat = tf.matmul(input_x, weights) + bias
 85         print(y_hat)
 86 
 87         # 二、构建会话
 88         with tf.Session() as sess:
 89             # fixme 执行变量初始化赋值
 90             sess.run(tf.global_variables_initializer())
 91             # 执行模型图
 92             y_hat_ = sess.run(y_hat)
 93             print(y_hat_)
 94 
 95 
 96 def f3():
 97     """
 98     占位符的使用
 99     :return:
100     """
101     # 一、建图
102     with tf.Graph().as_default():
103         # 1、创建模型输入(占位符),
104         # todo 可以使用 shape=[None, 3], None使用类似于numpy。
#tf.placeholder与tf.placeholder_with_default均为占位符,不同的是后者可以设置默认的输入数据,调用时可以不传入数据。而前者无默认的数据,使用时必须传入数据
105         input_x = tf.placeholder(dtype=tf.float32, shape=[None, 3], name='input_x')
106         input_c = tf.placeholder_with_default(
107             input=1.0, shape=[], name='input_c'
108         )
109         # 2、创建变量
110         weights = tf.Variable(
111             initial_value=[[-5],
112                            [3],
113                            [2]], dtype=tf.float32, name='weights'
114         )
115         print(weights)
116         bias_value = tf.constant(
117             value=[2], dtype=tf.float32, shape=[1], name='bias'
118         )
119         bias = tf.Variable(initial_value=bias_value, dtype=tf.float32, name='bias')
120 
121         # 3、构建正向传播过程
122         y_hat = tf.matmul(input_x, weights) + bias
123         y_hat1 = y_hat + input_c
124         print(y_hat)
125 
126         # 二、构建会话
127         with tf.Session() as sess:
128             # fixme 执行变量初始化赋值
129             sess.run(tf.global_variables_initializer())
130             # 加载训练数据
131             data1 = [[1,2,3],
132                    [2,3,4],
133                    [12,34,23],
134                    [2,3,9]]
135             # 执行模型图
136             y_hat_, y_hat1_ = sess.run(
137                 fetches=[y_hat, y_hat1], feed_dict={input_x: data1})
#y_hat与y_hat1分别是那两种构建占位符的方式下的正向传播过程,feed_dict是传入data1数据,通过占位符input_x,传给y_hat或者y_hat1


138             print(y_hat_, y_hat1_)
139 
140             data2 = [[1, 2, 3],
141                      [2, 3, 4],
142                      [2, 3, 9]]
143             y_hat_, y_hat1_ = sess.run(
144                 fetches=[y_hat, y_hat1], feed_dict={input_x: data2, input_c: 10.0})
145             print(y_hat_, y_hat1_)
146 
147 
148 if __name__ == '__main__':
149     f3()
原文地址:https://www.cnblogs.com/qianchaomoon/p/12196132.html