Fork me on GitHub

初学tensorflow-自编码

我理解的自编码是对原数据进行降维处理,从而能够减少无用特征,提高模型效率。以下对MNIST数据集进行自编码处理。

1、导入功能包

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data

2、下载数据集

mnist = input_data.read_data_sets("/tmp/data/", one_hot=False)

3、配置参数

learning_rate = 0.01
training_epochs = 5
batch_size = 256
examples_to_show = 10
n_input = 784
n_hidden_1 = 256 # 1st layer num features
n_hidden_2 = 128 # 2nd layer num features
  • 从上到下依次是学习率、训练轮数、批数据、测试个数、MNIST数据集原始维度、两个隐层的节点数。

4、权重与偏置

weights = {
    'encoder_h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
    'encoder_h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    'decoder_h1': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_1])),
    'decoder_h2': tf.Variable(tf.random_normal([n_hidden_1, n_input])),
            }
biases = {
    'encoder_b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'encoder_b2': tf.Variable(tf.random_normal([n_hidden_2])),
    'decoder_b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'decoder_b2': tf.Variable(tf.random_normal([n_input])),
            }
  • 权重与偏置,两层用于自编码的压缩,两层用于自编码的解压。
  • 以解压后的数据与原数据做对比,计算损失,进行优化。

5、模型输入

X = tf.placeholder("float", [None, n_input])

6、模型(压缩与解压)

def encoder(x):
layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['encoder_h1']),
                               biases['encoder_b1']))
layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['encoder_h2']),
                               biases['encoder_b2']))
return layer_2

def decoder(x):
layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['decoder_h1']),
                               biases['decoder_b1']))
layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['decoder_h2']),
                               biases['decoder_b2']))
return layer_2
encoder_op = encoder(X)
pred = decoder(encoder_op)
  • 有关第一个方法,采用sigmoid激活函数,对数据进行压缩,压缩后的维度为256.layer2继续压缩,后维度为128.
  • 有关第二个方法,根据压缩后的数据进行复原,以128维扩展至256维,扩展至784维。

7、模型编译

cost = tf.reduce_mean(tf.pow(X - pred, 2))
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)
  • 注意此处的误差计算方式,目前没有理解。

8、模型训练并测试测试集

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    total_batch = int(mnist.train.num_examples / batch_size)
    for epoch in range(training_epochs):
        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)  # max(x) = 1, min(x) = 0
            _, c = sess.run([optimizer, cost], feed_dict={X: batch_xs})
        print("Epoch:", '%04d' % (epoch+1),
              "cost=", "{:.9f}".format(c))
print("Optimization Finished!")
!!!#test
encode_decode = sess.run(
    pred, feed_dict={X: mnist.test.images[:examples_to_show]})
f, a = plt.subplots(2, 10, figsize=(10, 2))
for i in range(examples_to_show):
    a[0][i].imshow(np.reshape(mnist.test.images[i], (28, 28)))
    a[1][i].imshow(np.reshape(encode_decode[i], (28, 28)))
plt.show()
  • 第一部分用于训练,每次丢入256个数据进行训练,至全部丢入为一个epoch,共训练10轮epoch。_, c = sess.run([optimizer, cost], feed_dict={X: batch_xs})run运行[optimizer, cost],其实只需一个optimzer即可,但是为了显示每一轮epoch后的损失,将其加入至run,反馈回cost用于输出。
  • 第二部分用于测试与画图,画图部分暂时未精确学习,后续。

9、代码已上传本人github,其主要根据莫烦代码修改而成。

参考文献:1、莫烦tensorflow教程

初学tensorflow-RNN

使用RNN对MNIST数据集分类

1、 功能包导入

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
from tensorflow.examples.tutorials.mnist import input_data

2、数据集下载

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

3、参数配置

lr = 0.001#学习率
training_iters = 100#训练轮数
batch_size = 128
n_inputs = 28
n_steps = 28
n_hidden_units = 128
n_classes = 10

  • lr为网络学习率,training_iters为训练轮数,batch_size为每次丢入网络的simple,n_inputs是输入层的结点个数(MNIST每张图片是28*28,每行28个像素点作为网络的输入,28步后可以将整张图片全部输入),n_steps是步数(28步之后可以将整张图片输入)。n_hidden_units为隐层个数,即ceil中的结点个数.n_classes是10个类别。

4、权重、偏置初始化

weights = {
'in': tf.Variable(tf.random_normal([n_inputs, n_hidden_units])),
'out': tf.Variable(tf.random_normal([n_hidden_units, n_classes]))
}# (28, 128)、# (128, 10)
biases = {
'in': tf.Variable(tf.constant(0.1, shape=[n_hidden_units, ])),
'out': tf.Variable(tf.constant(0.1, shape=[n_classes, ]))
}# (128, )、# (10, )
  • 输入数据,经过权重与偏置计算到达ceil,在ceil处理之后通过权重与偏置计算输出。
  • 以上为输入与输出的权重、偏置。

5、网络输入

#input
xs = tf.placeholder(tf.float32, [None, n_steps, n_inputs])
ys = tf.placeholder(tf.float32, [None, n_classes])
  • MNIST数据为simple784,需要将其还原为2828结构。
  • 10分类,采用one_hot编码,同样需要将label重塑为[simple.10]结构。

6、RNN隐层

def RNN(X, weights, biases):#输入,权重,偏置
    X = tf.reshape(X, [-1, 28])#(128 * 28, 28 )
    X_in = tf.matmul(X, weights['in']) + biases['in']#(128 * 28, 128 )
    X_in = tf.reshape(X_in, [-1, n_steps, n_hidden_units])#(128 ,28, 128 )#时间序列
    cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden_units, forget_bias=1.0, state_is_tuple=True)
    init_state = cell.zero_state(batch_size=batch_size, dtype=tf.float32)
    outputs, final_state = tf.nn.dynamic_rnn(cell, X_in, initial_state=init_state, time_major=False)#time_major代表时间序列
    outputs = tf.unstack(tf.transpose(outputs, [1, 0, 2]))
    results = tf.matmul(outputs[-1], weights['out']) + biases['out']#(另外一种定义方法,不理解)results = tf.matmul(final_state[1], weights['out']) + biases['out']#应该是仅仅考虑了短期记忆
    return results
pred = RNN(xs, weights, biases)
  • 形参(输入数据、权重、偏置)
  • 将数据重塑为[simple*28,28]结构,使数据能够根据权重进行计算,计算完成后需要继续重塑,目的是能够以时间序列输入至ceil中,重塑后的结构为[simple.28.128],(其中simple是进入的数据个数,28是时间序列,128是数据根据权重计算出来的新维度)。
  • init_state中,需要对batch_size进行初始化,目的是为每张图片增添一个可传递的记忆状态。(每张图片分28步进行,RNN根据之前的记忆与当前的输入进行分类或回归)
  • tf.nn.dynamic_rnn暂时理解为融合当前数据与记忆得出的结果。
    图片来源为https://www.zhihu.com/question/41949741?sort=created

7、网络编译

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=ys))
train_op = tf.train.AdamOptimizer(lr).minimize(cost)
  • 采用交叉熵损失计算方法与Adam优化器

8、参数初始化与网络训练

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    for i in range(training_iters):
        batch_xs, batch_ys = mnist.train.next_batch(128)
        batch_xs = batch_xs.reshape([batch_size, n_steps, n_inputs])
        sess.run(train_op, feed_dict={xs: batch_xs, ys: batch_ys})

9、代码已上传本人github,其主要根据莫烦代码修改而成。

参考文献:

1、RNN输入输出详解
2、莫烦tensorflow教程

初学tensorflow-CNN

使用CNN对MNIST分类。

1、导入功能包

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
from tensorflow.examples.tutorials.mnist import input_data

2、下载MNIST数据集

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

3、定义权重方法

def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)
  • 此处使用的是truncated_normal()方法进行初始化权重,在CNN效果好。

4、定义偏置方法

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)


5、定义卷积层方法

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  • x代表输入image,结构为[simple个数(一般用-1),图片长,图片宽,图片通道]。w为权重,结构为[卷积核长,卷积核宽,卷积核通道(要与图片通道相等),卷积核个数]。strides为步长,[固定,x轴移动步数,Y轴移动步数,固定],pading为全0填充。参考下图可以加深卷积核的理解,重点是理解输出通道以及计算方式。
    卷积核

6、定义模型输入

xs = tf.placeholder(tf.float32, [None, 784])#/255. # 28x28
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1, 28, 28, 1])#转换维度[全部例子,图片长,图片宽,图片通道个数]
  • mnist数据集被拉成一串,为784列(2828),所以xs结构为[none,784]。keep_prob为dropout。将mnist数据集还原为2828结构,用作卷积神经网络的输入,x_image作用既如此。

7、定义模型卷积、池化层

W_conv1 = weight_variable([5,5, 1,32]) #[卷积核长,卷积核宽,输入图片通道个数,输出图片通道个数]
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) #28x28x32
h_pool1 = max_pool_2x2(h_conv1)#14*14*32
W_conv2 = weight_variable([5,5, 32,64]) #[卷积核长,卷积核宽,输入图片通道个数,输出图片通道个数]
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) #14x14x64
h_pool2 = max_pool_2x2(h_conv2)#7*7*64
  • 采用最大池化max_pool_22()方法,两层卷积池化后图片结构为77*64,不断卷积池化的过程就是将图片变小变厚的过程。

8、定义模型平坦层

h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])#-1代表全部例子
  • 平坦层后接全连接层,需要对池化后的数据在进行变形,将其拉成一串。结构为[所有的simple,将[7,7,14]结构转换为7714]。作为全连接网络的输入。

9、定义模型全连接层

W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
  • 注意此处使用了dropout方法,通过每次训练过程,使部分神经元不激活,从而避免了过拟合现象。所谓过拟合,即在训练集损失很低,在测试集损失确很高。
  • 此处使用了两层隐层,激活函数使用softmax,因为要做分类。

10、模型编译

cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
                                          reduction_indices=[1])) 
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
  • 采用交叉熵方法计算损失。
  • 采用Adam优化器进行参数优化。

11、参数初始化

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

12、模型训练

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
  • 每次丢入模型100个数据进行训练,其结果并不会比全部数据丢入模型效果差。

13、定义模型评估方法

def compute_accuracy(v_xs, v_ys):
    global prediction            
    y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})
    correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})
    return result
  • 计算准确率。

print(compute_accuracy(
    mnist.test.images[:1000], mnist.test.labels[:1000]))

14、代码已上传本人github,其主要根据莫烦代码修改而成。

参考文献:

1、神经网络黑盒的简单解释(推荐)
2、莫烦tensorflow教程

初学tensorflow-分类

学习使用tensorflow的数字10分类教程

1、导入功能包

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
from tensorflow.examples.tutorials.mnist import input_data

2、下载数据集

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

3、设计隐层权重、偏置

def add_layer(inputs, in_size, out_size, activation_function=None,):
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1,)
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b,)
    return outputs

4、模型输入

xs = tf.placeholder(tf.float32, [None, 784])
ys = tf.placeholder(tf.float32, [None, 10])
  • 此题的输入图像为28*28个像素点,需要全部输入网络中训练,所以输入结构为784列。另外此教程为10分类问题,输出结构为10列(one-hot编码)。

5、模型隐层

prediction = add_layer(xs, 784, 10,  activation_function=tf.nn.softmax)
  • 此处与回归模型不同,使用的是softmax激活函数,本次设计1层隐层。

6、模型编译

cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
                                                      reduction_indices=[1])) 
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
  • 注意此处计算误差的方式也与回归有区别,此处暂时理解为与激活函数对应。优化器有多种方案,同回归一样。

7、初始化参数

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

8、模型训练

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
       sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})
  • 每次训练时并没有把全部数据丢入模型进行训练,此处使用的是全部数据集的100个数据,依据莫烦教程讲解,100个数据依旧能把模型训练的很好。

9、模型评估

def compute_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction, feed_dict={xs: v_xs})
    correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))#计算准确率
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
    return result
  • 定义模型评估函数

print(compute_accuracy(
    mnist.test.images, mnist.test.labels))
  • 输出测试集的准确率,评估模型。

10、代码已上传本人github,其主要根据莫烦代码修改而成。

参考文献:1、莫烦tensorflow教程

注意:在tensorflow2.0版本是不存在MNIST教程的,需要额外下载。下载教程

初学tensorflow-tensorboard使用

在线性回归基础上,利用tensorboard进行可视化。

1、显示网络框架

with tf.name_scope('inputs'):
   xs = tf.placeholder(tf.float32, [None, 1], name='x_input')
   ys = tf.placeholder(tf.float32, [None, 1], name='y_input')
  • 例子如上:可视化1线性回归的输入层。通过with tf.name_scope(xxx):命令可以可视化网络的任意结构。

2、显示权重、偏置数据

Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
tf.summary.histogram(layer_name + '/weights', Weights)
  • 例子如上:可视化权重数据。通过tf.summary.histogram(xxx,xxx)可视化数据信息。

3、显示损失数据

loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
                                        reduction_indices=[1]))
tf.summary.scalar('loss', loss)
  • 例子如上:可视化损失数据。通过tf.summary.scalar(xxx, loss)可视化损失信息。

4、(1,2,3)步需要以下命令相配合

sess = tf.Session()
writer = tf.summary.FileWriter("logs/", sess.graph)
merged = tf.summary.merge_all()
  • 含义:建立文件,存储融合数据。
  • 注意:此时没有数据,显示的是网络结构与数据框图。

result = sess.run(merged,
                          feed_dict={xs: x_data, ys: y_data})
writer.add_summary(result, i)
  • 含义:将数据丢入模型(此处丢入的是merged,不是train!!),得到一批数据,将数据加入到数据融合文件,系统会自动将数据显示在数据框图中。

5、可视化截图

  • tensorboard启动:在存储数据文件目录下,输入tensorboard --logdir==“logs\”,在浏览器输入localhost:6006即可。

1、网络结构

2、权重及偏置

3、损失


6、代码已上传本人github,其主要根据莫烦代码修改而成。

注意:计算机名需要设置为英文,中文情况下生成的tensorboard文件乱码

参考文献:

1、莫烦tensorflow教程

初学tensorflow-线性回归

通过tensorflow拟合y=a^2-0.5+槽点,以下为代码,分步解析

1、导入功能包

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
import numpy as np
import matplotlib.pyplot as plt

2、设置需要拟合的函数及数据

x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise

3、设计隐层的权重、偏置等

def add_layer(inputs, in_size, out_size, activation_function=None):
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs
  • 偏置不能设置为0,令其加0.1.权重用numpy数组随机初始化,通常比全零效果好。
  • input为输入数据,insize为输入维度,outsize为输出维度,activation_function为激活函数。
  • tf.variable为tensorflow的变量声明,tf.constant表示常量,tf.add(a,b)表示相加,tf.assign(a,b)表示将b赋值给a,tf.matmul(a,b)表示相乘。

    4、设计网络的输入层

    xs = tf.placeholder(tf.float32, [None, 1]) ys = tf.placeholder(tf.float32, [None, 1])
  • tensorflow通过占位符placeholder来进行数据的输入,[None,1]表示任意行1列的数据,必须包括类型

    5、设计网络的隐层

    l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu) prediction = add_layer(l1, 10, 1, activation_function=None)
  • 回归一般用relu函数即可。如上,隐层为两层,每层包含10个神经元。

    6、模型编译

    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
  • 设计网络的损失函数与优化器,常用的优化器还包括SGD、Adam、Momentum等,优化器能加速网络的训练速度,与学习率相关。

    7、参数初始化

    sess = tf.Session() init = tf.global_variables_initializer() sess.run(init)
  • 整个程序内只要包含变量,必须用tf.global——进行初始化。另外,所有的操作都必须通过会话即session.run(xxx)来执行。

    8、模型训练

    for i in range(1000):
    sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
  • feeddict包含的是输入数据,将数据输入至train_step中进行训练。

    9、代码已上传本人github,其主要根据莫烦代码修改而成。

参考文献:1、莫烦tensorflow教程

ubuntu两个python分别同时安装tensorflow

1、两个python安装tensorflow的详细教程

2、单个python版本tensorflow-gpu的第一种安装方式此种方式对cuda的安装说明不完整,可点击此阅读第2部分

3、单个python版本tensorflow-gpu的第二种安装方式

测试

1、测试CUDA是否能用
2、cudnn不需要测试
3、测试tensor gpu是否可用

测试问题解决方案

1、运行pip 提示(warning, RequestsDependencyWarning)解决方案
2、libcudart.so.8.0: cannot open shared object file: No such file or directory 的解决方案

自选

1、修改ubuntu两个python优先级
2、ubuntu换源提高下载速度(pip也可设置源)

注意

1、在python2.7安装功能包时要用pip2,在python3.5安装功能包时要用pip3!!!!
2、tensorflow-gpu需要对应相应的cuda与cudnn,详情见tensorflow对应···版本
3、ubuntu16.04自带python2、python3,但是相应的pip并没有进行安装,安装教程可借鉴本文

ubuntu安装ros存在的rosdep_update问题

对于ROS安装存在的rosdep-update与sudo rosdep init问题,解决方案如下

1、rosdep init失败提示error··不能下载、网站不能访问等。

(1)可直接在浏览器访问终端提示的链接,将其内容复制到sourse-list中的20-······文件(文件名在浏览器中已提示)。之后跳过rosdep init即可。
(2)若在浏览器依旧不能访问链接,可在/etc下修改hosts文件,在末尾处增加151.101.84.133 raw.githubusercontent.com即可。

2、对于rosdep update问题,以下三种方法亲测有效。

(1)推荐首先使用4g热点尝试。
(2)若依旧失败,可修改源,在ubuntu的服务器设置中测试最佳服务器,然后更新,最后终端敲写sudo apt-get update。
(3)依旧失败,则终端敲写sudo gedit /etc/resolv.conf,将原有的nameserver这一行注释,并添加以下两行:nameserver 8.8.8.8 #google域名服务器、nameserver 8.8.4.4 #google域名服务器。依次敲写 sudo apt-get update 、rosdep update。
(4)若依旧失败,可在/etc下修改hosts文件,在末尾处增加151.101.84.133 raw.githubusercontent.com,然后在敲写rosdep update。


参考文献

1、ubuntu安装ROS进行到rosdep update时出现错误,如ERROR: unable to process source …
2、rosdep update 一直失败问题

  • © 2015-2021 高腾腾
  • Powered by Hexo Theme Ayer
  • PV: UV:

谢谢大爷

支付宝
微信