Notebook

计算图的概念

import tensorflow as tf
a = tf.constant([1.0,2.0],name = "a")
b = tf.constant([2.0,3.0],name = "b")
result = a + b
#通过a.graph可以查看张量所属的计算图。因为没有特定指定,所以这个计算图应该等于
#当前默认的计算图。所以下面这个操作输出值为True
print(a.graph is tf.get_default_graph())

与系统对话

import tensorflow as tf


# 相当于实例化一个类g1
g1 = tf.Graph()

# 将计算图g1设置为默认图
with g1.as_default():
    # 在计算图g1中定义变量“v”,并设置初始值为0。
    # 进行初始化  "v"表示名称 initializer表示初始化,可以使用各种初始化的方法
    # tf.zeros_initializer(shape=[1])   初始化为0
    v = tf.get_variable(
        "v",shape=[1], initializer=tf.zeros_initializer())

g2 = tf.Graph()
with g2.as_default():
    # 在计算图g2中定义变量“v”,并设置初始值为1。
    v = tf.get_variable(
        "v", shape=[1],initializer=tf.ones_initializer())

# 在计算图g1中读取变量“v”的取值。
# 将g1作为当前的作用域
with tf.Session(graph=g1) as sess:
    # 初始化所有的变量
    tf.initialize_all_variables().run()
    # tf.variable_scope返回相应的变量
    with tf.variable_scope("", reuse=True):
        # 在计算图g1中,变量“v”的取值应该为0,所以下面这行会输出[0.]。
        print(sess.run(tf.get_variable("v")))

    # 在计算图g2中读取变量“v”的取值。
with tf.Session(graph=g2) as sess:
    tf.initialize_all_variables().run()
    with tf.variable_scope("", reuse=True):
        # 在计算图g2中,变量“v”的取值应该为1,所以下面这行会输出[1.]。
        print(sess.run(tf.get_variable("v")))

跑程序的选择(cpu 和 gpu)

g= tf.Graph()
#指定计算运行的设备
with g.device('cpu:0'):
    result = a+b
名称 内容 场景
tf.GraphKey.VARIABLES 所有变量 持久化TensorFlow模型
tf.GraphKey.TRAINABLE_VARIABLES 可学习的变量(参数) 模型训练、生成模型可视化内容
tf.GraphKey.SUNNARIES 日志生产相关的张量 计算可视化
tf.GraphKey.QUEUE_RUNNERS 处理输入的QueueRunner 输入处理
tf.GraphKey.MOVING_AVERAGE_VARIABLES 所有计算滑动平均值的变量 计算变量的滑动平均值

张量

张量(tensor)

标量(scalar)

张量在TensorFlow中的实现并不是直接采用数组的形式,而是一种运算结果的引用。并没有储存数字,而是保存计算过程。

使用

inport tensorflow as tf
#使用张量记录中间的结果
a = tf.constant([1.0,2.0],name = "a")
b = tf.constant([2.0,3.0],name = "b")
result = a + b

#直接计算向量的和,这样可读性可能会差

result = tf.constant([1.0,2.0],name ="a") + \
         tf.constant([2.0,3.0],name ="b")

运行模型——会话

#创建一个会话
sess = tf.Session()
#使用这个创建好的会话得到关心的运算结果。比如可以调用sess.run(result),
#来得到3.1样例中的result的取值
sess.run(...)
#关闭会话可使资源释放,以免造成泄漏
sess.close()
#创建一个会话,并通过Python中的资源管理器来管理会话
with tf.Session() as sess:
	#使用创建好的会话计算关心的结果
	sess.run(...)

#不再需要调用Session.close()函数来关闭会话
#自动释放资源

当默认会话被指定之后可以通过tf.Tensorflow.eval函数来计算一个张量的取值

以下展示默认会话计算的张量取值

sess = tf.Session()
with sess.as_fault():
	print(result.eval())		#sess.as_fault()创建一个默认的会话

以下功能相同

sess = tf.Session()

#以下功能相同
print(sess.run(result)))
print(result.eval(session = sess))

交互环境之下,设置默认会话的方法来获取张量的取值更加方便

tf.InteractiveSession()自动生成会话注册默认会话

sess = tf.InteractiveSession()

print(result.eval())
sess.close()

省略会话注册为默认会话的过程

通过ConfigProto配置会话的方法:

config = tf.COnfigProto(allow _soft_placement = True,log_device_placement =True)
sess1 = tf.InteractiveSession(config = config)
sess2 = tf.Session(config = config)

第一个allow_soft_placement参数为True时,满足其一(1.运算无法运行GPU;2.没有GPU资源;3.运算输入包含CPU运算结果引用),Falses时为使移植性更强,在GPU的环境下一般设为True,当某些运算无法被当前GPU支持时,可以调整到CPU上,而不报错
第二个log_device_placement参数布尔型,为True时日志将会记录每个节点安排位置以便调试,实际设false减少日志量。
向前传播算法(forward-propagation)和向后传播算法(back-propagation)

完整神经网络样例程序

import tensorflow as tf
from numpy.random import RandomState

#定义训练数据batch的大小
batch_size = 8

#定义神经网路的参数
w1 = tf.Variable(tf.random.normal([2,3],stddev=1,seed=1))
w2 = tf.Variable(tf.random.normal([3,1],stddev=1,seed=1))

#在shape的一个维度上使用None可以方便使用不同的batch的大小

x = tf.placeholder(tf.float32,shape =(None,2),name = 'x-input')
y_ = tf.placeholder(tf.float32,shape =(None,1),name = 'y-input')

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

#定义损失函数与反向传播的算法
y = tf.sigmoid(y)
cross_emtropy = -tf.reduce_mean(
    y_*tf.log(tf.clip_by_value(y,1e-10,1.0))
    +(1-y_)*tf.log(tf.clip_by_value(1-y,1e-10,1.0)))
train_step = tf.train.AdamOptimizer(0.001).minimize(cross_emtropy)

#通过随机生成一个模拟
rdm = RandomState(1)
dataset_size=128
X = rdm.rand(dataset_size,2)

Y = [[int(x1+x2 < 1) for (x1,x2) in X]]

#创建一个会话来运行TensorFlow程序
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    #初始化
    sess.run(init_op)
    print sess.run(w1)
    print sess.run(w2)

    STEEPS  = 5000
    for i in range(STEEPS):
        #每次选取batch_size个样本进行训练
        start = (i*batch_size)%dataset_size
        end = min(start+batch_size,dataset_size)

        sess.run(train_step,feed_dict={
   x:X[start:end],y:Y[start:end]})
        if i%1000==0:
            #每隔一段时间计算在所有的数据上的交叉嫡并输出
            total_cross_entropy = sess.run(
                cross_emtropy,feed_dict={
   x:X,y_:Y}
            )
            print("After %d trainning step(s),cross entropy on all datais %g"%
                  (i,total_cross_entropy))
print sess.run(w1)
print sess.run(w2)


problem1:

/home/sohne/PycharmProjects/test/venv/bin/python /home/sohne/PycharmProjects/test/Demon.py
2019-10-26 15:35:50.314079: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2019-10-26 15:35:50.335866: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 1800000000 Hz
2019-10-26 15:35:50.336988: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x3a31ec0 executing computations on platform Host. Devices:
2019-10-26 15:35:50.337024: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): Host, Default Version
Traceback (most recent call last):
  File "/home/sohne/PycharmProjects/test/Demon.py", line 42, in <module>
    x = tf.placeholder(tf.float32,shape =(None,2),name = 'x-input')
AttributeError: module 'tensorflow' has no attribute 'placeholder'


solution:

tensorflow2.0提示错误:

module 'tensorflow' has no attribute 'placeholder'
1

解决办法:
不要使用:

import tensorflow as tf
1

替换为:

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
12

tensorflow的新变化,后续查到具体的文档,再补充。

原文地址:https://stackoverflow.com/questions/37383812/tensorflow-module-object-has-no-attribute-placeholder

problem2:

/home/sohne/PycharmProjects/test/venv/bin/python /home/sohne/PycharmProjects/test/Demon.py
WARNING:tensorflow:From /home/sohne/PycharmProjects/test/venv/lib/python3.6/site-packages/tensorflow_core/python/compat/v2_compat.py:65: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.
Instructions for updating:
non-resource variables are not supported in the long term
2019-10-26 16:12:06.745449: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2019-10-26 16:12:06.767878: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 1800000000 Hz
2019-10-26 16:12:06.768469: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x3cf00f0 executing computations on platform Host. Devices:
2019-10-26 16:12:06.768497: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): Host, Default Version
[[-0.8113182   1.4845988   0.06532937]
 [-2.4427042   0.0992484   0.5912243 ]]
[[-0.8113182 ]
 [ 1.4845988 ]
 [ 0.06532937]]
Traceback (most recent call last):
  File "/home/sohne/PycharmProjects/test/Demon.py", line 80, in <module>
    sess.run(train_step,feed_dict={
   x:X[start:end],y:Y[start:end]})
  File "/home/sohne/PycharmProjects/test/venv/lib/python3.6/site-packages/tensorflow_core/python/client/session.py", line 956, in run
    run_metadata_ptr)
  File "/home/sohne/PycharmProjects/test/venv/lib/python3.6/site-packages/tensorflow_core/python/client/session.py", line 1156, in _run
    (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (1, 128) for Tensor 'Sigmoid:0', which has shape '(?, 1)'

Process finished with exit code 1
Process finished with exit code 1


多层网络解决异或运算

深度运算的重要性质——多层变换

单层的神经网络

损失函数定义

神经网络模型的效果以及优化的目标是通过损失函数(loss function)来定义

经典损失函数

分类问题和回归问题

交叉滴(cross entropy)是判断输出向量和期望向量有多接近

  • 如何将神经网络的输出变成一个概率分布,加上softmax回归的神经网络结构图
    s o f t m a x ( y ) i = y i ′ = e y i / s u m ( e y j ) softmax(y)_i = y_i' = {e^{y_i}}/{sum({e^{y_j})}} softmax(y)i=yi=eyi/sum(eyj)

  • 这样就是把神经网络的输出变成一个概率分布,从而可以通过交叉第来计算预测的概率分布和真实的答案的概率分布之间的距离

均方误差

MSE,mean squared error
M S E ( y , y ′ ) = / n MSE(y,y')=/n MSE(y,y)=/n

神经网络经一步优化

学习率的设置

灵活甚至学习率的方法——指数衰减法

tf.train.exponetial_decay函数实现指数衰减率

decayed_learning_rate = \
	learning_rat * decay_rate ^(global_step /decay_steps)

深度学习——损失函数

之前由于个人懒惰的发了篇极差的文章,现在更正错误,发一篇正在学习tensorflow的笔记

在构建神经网络过程中,为了刻画神经网络模型的效果以及优化目标,需要使用到损失函数(loss function)

什么是损失函数

所谓损失函数使用来估计模型预测值与实际值的不一样程度,是一个绝对值,损失函数越小,模型的拟合度越好。

在之前的机械学习过程中,学过代价函数(cost function),在了解过后其实两者并没有差别。

经典损失函数

首先讲解分类问题和回归问题使用到的经典损失函数,利用之前学习到的知识。

分类问题

通俗来讲就是简单的将问题的分为两类答案(是/不是),但是当你应用于多类别虽有理论可行的阈值分类办法,但无法应用。

通过神经网络多输出节点,其中n为类别的个数,如果样本属于k类,那么对应节点输出值即为1,输出结果越接近该矩阵,损失函数的拟合性越好,而判定的标准则是交叉熵(cross entropy),刻画两个概率之间的距离。q来表示p的交叉熵:
H ( p , q ) = − [ ∑ x p ( x ) l o g q ( x ) ] H(p,q) = -[\displaystyle \sum_{x}p(x)logq(x)] H(p,q)=[xp(x)logq(x)]
交叉熵是刻画两个概率的距离,而神经网络输出的类别。概率分布刻画不同事件发生概率。满足:

任意事件发生的概率都在0和1之间,且总有某一事件发生(概率的和为1),即非负即正。

如何在前向传播过程中的概率分布:softmax回归

softmax回归作为优化分类结果,Tensorflow中进行参数优化,在神经网络中当作原始输出层与最终输出层之间的隐藏层。

输出为:
s o f t m a x ( y ) i = y i ′ = e y i / [ ∑ j = 1 n e y i ] softmax(y)_i = y_i' = e^{y_i}/ [\displaystyle \sum_{j=1}^n e^{y^i}] softmax(y)i=yi=eyi/[j=1ne

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值