tensorflow学习笔记

基于tensorflow的NN:

 用张量表示数据,用计算图搭建神经网络,用会话执行计算图,优化线上的权重(参数),得到模型。

张量(tensor):

多维数组(列表)

阶:

张量的维数

张量可以表示0阶到n阶数组(列表)

维数 名字 例子 0-D 0 标量(scalar) s=1 2 3 1-D 1 向量(vector) v=[1, 2, 3] 2-D 2 矩阵(matrix) m=[[1,2,3],[4,5,6],[7,8,9]] 3-D 3 张量(tensor)

t=[[[... 

n 个

 数据类型:

 tf.float32   tf.int32

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:        第0个输出

shape: 维度

(2, ):一维数组, 长度为2

结果表明:输出的为tensor,并没有常量的运算结果,只是定义了一个计算图(计算图只存储计算过程,不运行计算结果)

会话(Sessions):执行计算图中的节点运算

with tf.Session() as sess:

       print(sess.run(xxxx)) #xxxx表示计算图中的计算变量

import tensorflow as tf

x = tf.constant([[1., 2.]]) #定义一个二维常量 维度为1x2
w = tf.constant([[3.], [4.]])#定义一个二维常量 维度为2x1

y = tf.matmul(x, w)
print()

with tf.Session() as sess:
    print(sess.run(y)) # 计算最终的数据流图结果

参数:用变量表示,随机给初值

w = tf.Variable(tf.random_normal([2, 3], stddev=2, mean=0, seed=1))

# tf.random_normal:正态分布  或者使用 tf.truncated_normal():去掉过大偏离点的正态分布

# stddev:标准差 mean:均值 seed:随机种子

变量初始化、计算图节点运算都要用会话(with)结构实现:

with tf.Session() as sess:

       sess.run()

变量初始化:在sess.run()函数中用tf.global_variables_initializer()

y = tf.global_variables_initializer()

sess.run(y)

 

用tf.placeholder占位,在sess.run()函数中用feed_dict喂数据

喂一组数据:.

x = tf.placeholder(tf.float32, shape=(1, 2))

sess.run(y, feed_dict={x: [[1., 2.]]})

喂多组数据:

x = tf.placeholder(tf.float32, shape=(None, 2))

sess.run(y, feed_dict={x: [[1., 2.], [3., 4.], [3., 2.], [0.4, 0.5]......]})

#-*- coding:utf-8 -*-

# 两层简单的神经网络(全连接)

import tensorflow as tf

#定义输入和参数
x = tf.constant([[0.7, 0.5]])
w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))

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

#用会话计算结果
with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    sess.run(y)

反向传播:

训练模型参数,在所有参数上用梯度下降,使模型在训练数据上的损失函数最小

损失函数(loss):预测值与groundtruth的差距

常用损失函数为均方误差(MSE):MSE(y_, y) = \frac{\sum_{n}^{i-1} (y-y_)^{2}}{n}

tensorflow的实现为:

loss = tf.reduce_mean(tf.square(y_-y))

 

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值