TensorFlow学习(1)基础使用

基本概念

基本结构

创建图和启动图,常量使用

import tensorflow as tf

# 创建 op 常量
m1 = tf.constant([[3,3]])
m2 = tf.constant([[2],[3]])

product = tf.matmul(m1, m2)
print(product)

# Tensor("MatMul:0", shape=(1, 1), dtype=int32)

# 自定义一个会话, 使用默认图
sess = tf.Session()
# 调用 sess 的 run 方法来执行矩阵乘法 op
# run(product) 触发了 3 个 op
result = sess.run(product)
print(result)
# [[15]]
sess.close()

# 自动关闭
with tf.Session() as sess:
    result = sess.run(product)
    print(result)
# [[15]]

变量

import tensorflow as tf

x = tf.Variable([1,2])
a = tf.constant([3,3])
# 增加一个减法 op
sub = tf.subtract(x,a)

# 增加一个加法 op
add = tf.add(x, sub)

# 全局变量初始化
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(sub))
    print(sess.run(add))

'''
[-2 -1]
[-1  1]
'''

# 想得到最后结果,直接 run 最后一个 op即可,不用手动 run 前面的 op
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(add))
# [-1  1]

# 循环赋值
# 创建一个变量初始化为 0
state = tf.Variable(0, name = 'counter')
# 创建一个 op ,作用是使 state 加 1
new_value = tf.add(state, 1)
# 赋值 op,把 new_value 的值 赋给 state
update = tf.assign(state, new_value)
# 全局变量初始化
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(state))
    for _ in range(5):
        sess.run(update)
        # state 是变量不是常量,赋值后它的值不再是 0
        print(sess.run(state))
'''
0
1
2
3
4
5
'''

shift + tab 能看描述

Fetch 和 Feed 

import tensorflow as tf

input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)

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

# Fetch
with tf.Session() as sess:
    result = sess.run([mul,add])
    print(result)
    print(sess.run(mul))
#[21.0, 7.0]
#21.0

# Feed
# 创建占位符
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)

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

一个简单的示例

import tensorflow as tf
import numpy as np

# 生成 100 个随机数
x_data = np.random.rand(100)
y_data = x_data * 0.1 + 0.2

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

# 定义二次代价函数
loss = tf.reduce_mean(tf.square(y_data - y))
# 定义一个梯度下降法来进行训练的优化器,学习率是 0.2
optimizer = tf.train.GradientDescentOptimizer(0.2)
# 最小化代价函数
train = optimizer.minimize(loss)

# 初始化变量
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for step in range(201):
        sess.run(train)
        if step % 20 == 0:
            print(step, sess.run([k,b]))

0 [0.06040984, 0.10231642]
20 [0.108255275, 0.19508757]
40 [0.104978055, 0.19703776]
60 [0.103001826, 0.19821373]
80 [0.10181014, 0.19892286]
100 [0.101091556, 0.19935046]
120 [0.10065822, 0.19960831]
140 [0.10039692, 0.1997638]
160 [0.10023935, 0.19985758]
180 [0.10014433, 0.19991411]
200 [0.10008703, 0.1999482]

非线性回归神经网络案列

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

# 使用 numpy 生成 200 个随机点,在 -0.5 到 0.5 范围里均匀分布
x_data = np.linspace(-0.5, 0.5, 200)
# (200,)
# 新添一个列
x_data = x_data[:,np.newaxis]
# (200, 1)
# 生成随机值,形状与 x_data 一样
noise = np.random.normal(0, 0.02, x_data.shape)
y_data = np.square(x_data) + noise

# 行不确定填 None,列为 1
x = tf.placeholder(tf.float32,[None, 1])
y = tf.placeholder(tf.float32,[None, 1])

# 定义神经网络中间层
# 定义权值
Weight_L1 = tf.Variable(tf.random.normal([1, 10]))
# 偏置
biases_L1 = tf.Variable(tf.zeros([1, 10]))
# 矩阵乘法
Wx_plus_b_L1 = tf.matmul(x, Weight_L1) + biases_L1
# 中间层输出,使用激活函数
L1 = tf.nn.tanh(Wx_plus_b_L1)

# 定义输出层
# 中间层有 10 个神经元,所以权重为 10 行,1 列
Weight_L2 = tf.Variable(tf.random_normal([10, 1]))
# 输出层只有一个神经元,所以只有一个偏置值
biases_L2 = tf.Variable(tf.zeros([1, 1]))
Wx_plus_b_L2 = tf.matmul(L1, Weight_L2) + biases_L2
# 最后的信号是预测的结果
prediction = tf.nn.tanh(Wx_plus_b_L2)

# 二次代价函数
loss = tf.reduce_mean(tf.square(y - prediction))
# 梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for _ in range(2000):
        sess.run(train_step, feed_dict={x: x_data, y: y_data})
    # 传入 x,获得预测值
    prediction_value = sess.run(prediction,feed_dict={x:x_data})
    # 画图
    plt.figure()
    plt.scatter(x_data, y_data)
    # 红色实线,线宽 5
    plt.plot(x_data, prediction_value, 'r-', lw=5)
    plt.show()

猜你喜欢

转载自blog.csdn.net/HAIYUANBOY/article/details/89811628
今日推荐