tensorflow

#GPU测试代码
import os
os.environ['CUDA_VISIBLE_DEVICES'] = "0"#启用GPU
import tensorflow as tf

 
with tf.device('/cpu:0'):
    a = tf.constant([1.0,2.0,3.0],shape=[3],name='a')
    b = tf.constant([1.0,2.0,3.0],shape=[3],name='b')
with tf.device('/gpu:1'):
    c = a+b
   
#注意:allow_soft_placement=True表明:计算设备可自行选择,如果没有这个参数,会报错。
#因为不是所有的操作都可以被放在GPU上,如果强行将无法放在GPU上的操作指定到GPU上,将会报错。
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,log_device_placement=True))
#sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
sess.run(tf.global_variables_initializer())
print(sess.run(c))

禁用GPU
os.environ["CUDA_VISIBLE_DEVICES"]="-1"

定义变量
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0))
biases = tf.Variable(tf.zeros([1]))
state = tf.Variable(0,name="counter")
matrix1 = tf.constant([[3,3]])

TF placeholder
placeholder 是 Tensorflow 中的占位符,暂时储存变量.
Tensorflow 如果想要从外部传入data, 那就需要用到 tf.placeholder(), 然后以这种形式传输数据 sess.run(***, feed_dict={input: **}).

import tensorflow as tf

input1 = tf.placeholder(dtype=tf.float32)
input2 = tf.placeholder(dtype=tf.float32)

output = tf.multiply(input1,input2)

with tf.Session() as sess:
    print(sess.run(output,feed_dict={input1:[3.],input2:[5]}))

tensorboard

import tensorflow as tf
import numpy as np
#from tensorflow.python import debug as tf_debug

#输入数据
x_data = np.linspace(-1,1,300)[:, np.newaxis]
noise = np.random.normal(0,0.05, x_data.shape)
y_data = np.square(x_data)-0.5+noise

#输入层
with tf.name_scope('input_layer'): #输入层。将这两个变量放到input_layer作用域下,tensorboard会把他们放在一个图形里面
    xs = tf.placeholder(tf.float32, [None, 1], name = 'x_input') # xs起名x_input,会在图形上显示
    ys = tf.placeholder(tf.float32, [None, 1], name = 'y_input') # ys起名y_input,会在图形上显示


#隐层
with tf.name_scope('hidden_layer'): #隐层。将隐层权重、偏置、净输入放在一起
    with tf.name_scope('weight'): #权重
        W1 = tf.Variable(tf.random_normal([1,10]))
        tf.summary.histogram('hidden_layer/weight', W1)
    with tf.name_scope('bias'): #偏置
        b1 = tf.Variable(tf.zeros([1,10])+0.1)
        tf.summary.histogram('hidden_layer/bias', b1)
    with tf.name_scope('Wx_plus_b'): #净输入
        Wx_plus_b1 = tf.matmul(xs,W1) + b1
        tf.summary.histogram('hidden_layer/Wx_plus_b',Wx_plus_b1)
output1 = tf.nn.relu(Wx_plus_b1)


#输出层
with tf.name_scope('output_layer'): #输出层。将输出层权重、偏置、净输入放在一起
    with tf.name_scope('weight'): #权重
        W2 = tf.Variable(tf.random_normal([10,1]))
        tf.summary.histogram('output_layer/weight', W2)
    with tf.name_scope('bias'): #偏置
        b2 = tf.Variable(tf.zeros([1,1])+0.1)
        tf.summary.histogram('output_layer/bias', b2)
    with tf.name_scope('Wx_plus_b'): #净输入
        Wx_plus_b2 = tf.matmul(output1,W2) + b2
        tf.summary.histogram('output_layer/Wx_plus_b',Wx_plus_b2)
output2 = Wx_plus_b2

#损失
with tf.name_scope('loss'): #损失
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-output2),reduction_indices=[1]))
    tf.summary.scalar('loss',loss)
with tf.name_scope('train'): #训练过程
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

#初始化
init = tf.global_variables_initializer()
sess = tf.Session()

sess.run(init)
#s
merged = tf.summary.merge_all() #将图形、训练过程等数据合并在一起
writer = tf.summary.FileWriter('logs',sess.graph) #将训练日志写入到logs文件夹下
#sess = tf_debug.TensorBoardDebugWrapperSession(sess, "HXSDD12PC:7000")
#训练
for i in range(1000):
    sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
    if(i%50==0): #每50次写一次日志
        result = sess.run(merged,feed_dict={xs:x_data,ys:y_data}) #计算需要写入的日志数据
        writer.add_summary(result,i) #将日志数据写入文件

import os
os.system("D:\\python\\Anaconda3_64\\scripts\\tensorboard --logdir=logs )

该函数返回一个张量,这个张量是将原始input中所有维度为1的那些维都删掉的结果
axis可以用来指定要删掉的为1的维度,此处要注意指定的维度必须确保其是1,否则会报错

#  't' 是一个维度是[1, 2, 1, 3, 1, 1]的张量
tf.shape(tf.squeeze(t))   # [2, 3], 默认删除所有为1的维度

# 't' 是一个维度[1, 2, 1, 3, 1, 1]的张量
tf.shape(tf.squeeze(t, [2, 4]))  # [1, 2, 3, 1],标号从零开始,只删掉了2和4维的1

tf.distributions是TensorFlow提供的核心组件之一,用于实现一些常见的概率分布,并给出了一系列的辅助计算函数
norm_dist=tf.distributions.Normal(loc=mu,scale=sigma)
actor=norm_dist.sample(1)#采样
norm_dist.prob(actor)#评估该样本出现的概率

tf.GraphKeys包含所有graph collection中的标准集合名,有点像Python里的build-in fuction。

多项式分布

samples = tf.multinomial(tf.log([[10., 10., 10.]]), 5)意思是,有三个项,每项概率为pi=vi/sum(vi).产生5个数
with tf.Session() as sess:
print(sess.run(samples))

samples 可能是[0,1,1,0,2]

self.sess.run(tf.get_default_graph().get_tensor_by_name('agent/main/actor/layer_concat/kernel:0'))#查看网络某层权重参数值
tf的运算都必须要是相同Dim的才可以

posted @ 2019-03-26 19:35  blog_hfg  阅读(218)  评论(0)    收藏  举报