TensorFlow基础学习及讲解

视频讲解参考B站:白夜_叉烧包

写在前面的:由于TensorFlow版本问题,新版本的TensorFlow变化比较大,比如新版本不再支持tf.Session(),要使用tf.compat.v1.Session()...还有很多就不一一列举了,本次介绍的均为2.1以后的版本,博主python版本3.6.4(匹配TensorFlow版本以python3.6为准,TensorFlow2.2和2.3版本对py3.6有些不稳定)。

通过官网pip速度很慢,这里给个快速下载TensorFlow的命令:参考TensorFlow版本安装

1、Tensorflow的基本使用

包括对图(graphs),会话(session),张量(tensor),变量(Variable)的一些解释和操作。

 

1.1 

import tensorflow as tf

# 如果你安装的是CPU(pip install tensorflow),则执行下面两行代码,忽略CPU和GPU引起的版本问题
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.compat.v1.disable_eager_execution()  # 保证sess.run()能够正常运行
m1 = tf.constant([[3, 3]])  # 创建一个常量op
m2 = tf.constant([[2], [3]])
product = tf.matmul(m1, m2)  # 创建一个矩阵乘法op,把m1和m2传入
print(product)  # 这里将输出一个Tensor
# # 定义一个会话,启动默认图

with tf.compat.v1.Session() as sess:
    result = sess.run(product)  # 调用run方法来执行矩阵乘法
    print(result)

1.2

import tensorflow as tf
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.compat.v1.disable_eager_execution()  # 保证sess.run()能够正常运行
x = tf.Variable([1, 2])
a = tf.constant([3, 3])
sub = tf.subtract(x, a)  # 增加一个减法op
add = tf.add(x, sub)  # 增加一个加法op
# 注意再多个变量的情况下,变量在使用之前要再sess中做初始化
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
    sess.run(init)
    print(sess.run(sub))
    print(sess.run(add))
#

# 实现累加操作
state = tf.Variable(0, name='counter')  # 创建一个名字为‘counter’的变量 初始化0
new_value = tf.add(state, 1)  # 创建一个op,作用是使state加1
update = tf.compat.v1.assign(state, new_value)  # 赋值op
init = tf.compat.v1.global_variables_initializer()
# 实现累加,每次给state+1
with tf.compat.v1.Session() as sess:
    sess.run(init)
    print(sess.run(state))
    for _ in range(5):
        sess.run(update)
        print(sess.run(state))

 1.3

import tensorflow as tf
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.compat.v1.disable_eager_execution()  # 保证sess.run()能够正常运行
# Fetch概念 在session中同时运行多个op
input1 = tf.constant(3.0)  # constant()是常量不用进行init初始化
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)

add = tf.add(input2, input3)
mul = tf.multiply(input1, add)

with tf.compat.v1.Session() as sess:
    result = sess.run([mul, add])  # 这里的[]就是Fetch操作
    print(result)

# Feed
# 创建占位符
input1 = tf.compat.v1.placeholder(tf.float32)
input2 = tf.compat.v1.placeholder(tf.float32)
# 定义乘法op,op被调用时可通过Feed的方式将input1、input2传入
output = tf.multiply(input1, input2)

with tf.compat.v1.Session() as sess:
    # feed的数据以字典的形式传入
    print(sess.run(output, feed_dict={input1: [7.], input2: [2.]}))

1.4 TensorFlow模型构造和模型优化简单实战

import tensorflow as tf
import numpy as np
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.compat.v1.disable_eager_execution()  # 保证sess.run()能够正常运行
# 使用numpy生成100个随机点
x_data = np.random.rand(100)
# print(x_data)
y_data = x_data * 0.1 + 0.2  # 这里我们设定已知直线的k为0.1 b为0.2得到y_data

# 构造一个线性模型
b = tf.compat.v1.Variable(0.)
k = tf.compat.v1.Variable(0.)
y = k * x_data + b

# 二次代价函数(真实值和预测值之差平方后取平均值)
loss = tf.reduce_mean(tf.square(y_data - y))
# 定义一个梯度下降法来进行训练的优化器(其实就是按梯度下降的方法改变线性模型k和b的值,注意这里的k和b一开始初始化都为0.0,后来慢慢向0.1、0.2靠近)
optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.2)  # 梯度下降学习率定义为0.2.
# 最小化代价函数(训练的方式就是使loss值最小,接近最真实的斜率0.1和截距0.2)
train = optimizer.minimize(loss)

init = tf.compat.v1.global_variables_initializer()

with tf.compat.v1.Session() as sess:
    sess.run(init)
    for step in range(201):  # 迭代次数200次
        sess.run(train)  # 每次迭代train,就会最小化一次loss
        if step % 20 == 0:  # 每二十次打印一次结果
            print(step, sess.run([k, b]))  # 这里使用fetch的方式只是打印k、b的值,每20次打印一下,改变k、b的值是梯度下降的工作
            # 结果可以看出k和b的值都在无限接近真实的斜率和截距

 

2、Tensorflow线性回归以及分类的简单使用,softmax介绍。

2.1 、TensorFlow实现简单的回归模型

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.compat.v1.disable_eager_execution()  # 保证sess.run()能够正常运行
x_data = np.linspace(-0.5, 0.5, 200)[:, np.newaxis]  # 200行一列的二维数组
noise = np.random.normal(0, 0.02, x_data.shape)
y_data = np.square(x_data) + noise

# 定义两个placeholder
x = tf.compat.v1.placeholder(tf.float32, [None, 1])  # 行不确定,一列
y = tf.compat.v1.placeholder(tf.float32, [None, 1])

# 定义神经网络中间层
Weights_L1 = tf.compat.v1.Variable(tf.compat.v1.random_normal([1, 10]))  # 一行十列随机值#
# tf.random_normal()函数用于从“服从指定正态分布的序列”中随机取出指定个数的值。
biases_L1 = tf.compat.v1.Variable(tf.compat.v1.zeros([1, 10]))  # 一行十列,随机值为0
Wx_plus_b_L1 = tf.compat.v1.matmul(x, Weights_L1) + biases_L1
L1 = tf.compat.v1.nn.tanh(Wx_plus_b_L1)  # 使用激活函数
# tf.nn :提供神经网络相关操作的支持,包括卷积操作(conv)、池化操作(pooling)、归一化、loss、分类操作、embedding、RNN、Evaluation。

# 定义神经网络输出层
Weights_L2 = tf.compat.v1.Variable(tf.compat.v1.random_normal([10, 1]))
biases_L2 = tf.compat.v1.Variable(tf.compat.v1.zeros([1, 1]))
Wx_plus_b_L2 = tf.compat.v1.matmul(L1, Weights_L2) + biases_L2
prediction = tf.compat.v1.tanh(Wx_plus_b_L2)

# 二次代价函数
loss = tf.compat.v1.reduce_mean(tf.square(y - prediction))
# 使用梯度下降法训练
train_step = tf.compat.v1.train.GradientDescentOptimizer(0.1).minimize(loss)  # 最小化loss

with tf.compat.v1.Session() as sess:
    # 变量初始化
    sess.run(tf.compat.v1.global_variables_initializer())
    for _ in range(2000):
        sess.run(train_step, feed_dict={x: x_data, y: y_data})

    # 获取预测值
    prediction_value = sess.run(prediction, feed_dict={x: x_data})
    # 画图
    plt.figure()
    plt.scatter(x_data, y_data)
    plt.plot(x_data, prediction_value, 'r-', lw=5)
    plt.show()

运行截图:

 

-------------------------------------有待更新----------------------------------------

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值