tensorflow课程笔记(一)

MOOC上的tensorflow课程笔记

import tensorflow as tf
"""
a = tf.constant([1.0,2.0])   #一行两列的张量
b = tf.constant([3.0,4.0])   #一行两列的张量
result = a + b
print(result)                #打印计算图
结果为:Tensor("add:0", shape=(2,), dtype=float32)
        add操作,第0个开始计算(?),一维的张量,有两个值,类型都是float32
"""
"""
#计算图:搭建神经网络的计算过程,只搭建,不计算
#现在要搭建y=XW = x1*w1 + x2*w2 的计算图
x = tf.constant([[1.0,2.0]])   #一行两列的张量
w = tf.constant([[3.0],[4.0]]) #两行一列的张量
y = tf.matmul(x,w)             #张量相乘
print(y)
#计算结果:Tensor("MatMul:0", shape=(1, 1), dtype=float32)
with tf.Session() as sess:
    print(sess.run(y))
#计算结果:[[11.]]

"""
"""
生成变量
w = tf.Variable(tf.random_normal([2,3],stddev=2,mean=0,seed=1))
                [2,3] 产生2*3的矩阵  stddev标准差 mean均值 seed随机种子
                tf.random_normal 正态分布
                tf.random_uniform 平均分布
生成常量
tf.zeros 全零数组
tf.ones  全1数组
tf.fill  全定值数组
tf.constant 直接给值
"""
"""
神经网络实现过程:
1.准备数据集,提取特征,作为输入喂给神经网络
2.搭建NN结构,从输入到输出(先搭计算图,再用会话执行)
    NN前向传播算法-》计算输出
3.大量特征数据喂给NN,迭代优化NN参数
    NN反向传播算法-》优化参数训练模型
4.使用训练好的模型预测和分类
"""
"""
使用tf.placeholder占位符喂数据
喂一组数据
x = tf.placeholder(tf.float32,shape=[1,2])  #一行两列
sess.run(y,feed_dict={x:[[0.5,0.6]]})
喂多组数据
x = tf.placeholder(tf.float32,shape=[None,2])
sess,run(y,feed_dict={x:[0.1,0.2],[0.2,0.3],[0.3,0.4],[0.4,0.5]})
"""

简单的神经网络搭建

#coding:utf-8
#两层神经网络(全连接)
import tensorflow as tf

#定义输入和参数
#x = tf.constant([[0.7,0.5]])   #定义一行两列的张量
#用placeholder实现输入定义(sess.run中喂一组数据)
x = tf.placeholder(tf.float32,shape=[None,2])    #这样表示多行2列
w1 = tf.Variable(tf.random_normal([2,3], stddev=1, seed=1))  #正态分布
w2 = tf.Variable(tf.random_normal([3,1], stddev=1, seed=1))  #三行一列
"""
 w1= [[-0.8113182   1.4845988   0.06532937]
 [-2.4427042   0.0992484   0.5912243 ]]
 w2= [[-0.8113182 ]
 [ 1.4845988 ]
 [ 0.06532937]]
 w1就是输入到隐藏层的三个过程的权重
 w2就是隐藏层到输出层的三个过程的权重
"""
"""
x11 --  w1 a1 w2
        w1 a2 w2  -- y
x12 --  w1 a3 w2

"""


#定义前向传播过程
a = tf.matmul(x, w1)        #x乘以w1
y = tf.matmul(a, w2)

"""
a= [[-1.7892749   1.0888433   0.34134272]]
y= [[3.0904665]]

a11 = w1 11*x11 + w2 21*x12
a12 = w1 12*x11 + w2 22*x12
a13 = w1 13*x11 + w2 23*x13
"""

#用会话计算结果
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    #print("y in this file is:\n",sess.run(y))
    """
    print("w1=",sess.run(w1))
    print("w2=",sess.run(w2))
    print("a=",sess.run(a))
    print("y=",sess.run(y))
    """
    print("y=",sess.run(y,feed_dict={x:[[0.7,0.5],[0.3,0.2],[0.8,0.9]]}))
    """
    输出结果:
    y= [[3.0904665]
    [1.2935174]
    [4.2442317]]
    """

猜你喜欢

转载自blog.csdn.net/haohulala/article/details/83508738