TensorFlow实战(一)

简单示例:

# encoding:utf-8
import tensorflow as tf
import numpy as np

# 使用numpy生成随机点
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

# 二次代价函数
# reduce_mean求平均值
# square求平方
loss = tf.reduce_mean(tf.square(y_data - y))

# 定义一个梯度下降法来进行训练的优化器
# 最小化代价函数
train = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
# 初始化变量
init = tf.global_variables_initializer()

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

运行结果:

0 [array([0.05426404], dtype=float32), array([0.10033498], dtype=float32), 0.015278633]
20 [array([0.10386088], dtype=float32), array([0.1979034], dtype=float32), 1.2314013e-06]
40 [array([0.10230231], dtype=float32), array([0.19874981], dtype=float32), 4.378718e-07]
60 [array([0.1013729], dtype=float32), array([0.1992545], dtype=float32), 1.5570348e-07]
80 [array([0.10081868], dtype=float32), array([0.19955544], dtype=float32), 5.5366186e-08]
100 [array([0.10048818], dtype=float32), array([0.19973491], dtype=float32), 1.9686736e-08]
120 [array([0.1002911], dtype=float32), array([0.19984193], dtype=float32), 6.9999326e-09]
140 [array([0.10017359], dtype=float32), array([0.19990574], dtype=float32), 2.4891336e-09]
160 [array([0.10010351], dtype=float32), array([0.1999438], dtype=float32), 8.850558e-10]
180 [array([0.10006171], dtype=float32), array([0.19996649], dtype=float32), 3.1458092e-10]
200 [array([0.10003681], dtype=float32), array([0.19998], dtype=float32), 1.1189112e-10]
220 [array([0.10002195], dtype=float32), array([0.19998808], dtype=float32), 3.9791646e-11]
240 [array([0.10001309], dtype=float32), array([0.1999929], dtype=float32), 1.4155521e-11]
260 [array([0.1000078], dtype=float32), array([0.19999576], dtype=float32), 5.031431e-12]
280 [array([0.10000467], dtype=float32), array([0.19999747], dtype=float32), 1.8003177e-12]

回归:

代码:

# encoding:utf-8
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# 使用numpy来生成200个随机点
# 从-0.5到0.5产生200个随机点
# 生成200行1列的数据
x_data = np.linspace(-0.5, 0.5, 200)[:, np.newaxis]
'''
生成正态分布的随机点
loc:float
    此概率分布的均值(对应着整个分布的中心centre)
scale:float
    此概率分布的标准差(对应于分布的宽度,scale越大越矮胖,scale越小,越瘦高)
size:int or tuple of ints
    输出的shape,默认为None,只输出一个值
'''
noise = np.random.normal(0, 0.02, x_data.shape)
y_data = np.square(x_data) + noise

# 定义两个placeholder
# placeholder的定义需要根据样本的形状
x = tf.placeholder(tf.float32, [None, 1])
y = tf.placeholder(tf.float32, [None, 1])

# 定义神经网络中间层
Weights_L1 = tf.Variable(tf.random_normal([1, 10]))
biases_L1 = tf.Variable(tf.zeros([1, 10]))
Wx_plus_b_l1 = tf.matmul(x, Weights_L1) + biases_L1

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

# 定义二次代价函数
loss = tf.reduce_mean(tf.square(prediction - y_data))
# 定义梯度下降算法训练
train = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

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

with tf.Session() as sess:
    sess.run(init)
    for step in range(2000):
        sess.run(train, 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)
    # 'r-'红色实线
    plt.plot(x_data, prediction_value, 'r-', lw=5)
    plt.show()

运行结果:

分类:

可参考TensorFlow MNIST数据集手写数字识别(并解决MNIST数据集下载问题)

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# 载入数据集
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# 每个批次的大小,一次性放入神经网络的数据数量,以矩阵的形式放入
# 批次优化
batch_size = 100
# batch_size = 100
# 计算一共有多少个批次 //是整除的意思
n_batch = mnist.train.num_examples // batch_size

# 定义两个placehlder,None指的是可以是任意的值,根据传入的批次进行确定
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])

# 增加隐藏层---优化
# 创建一个简单的神经网络
# W = tf.Variable(tf.zeros([784, 10]))
# b = tf.Variable(tf.zeros([10]))
# prediction = tf.nn.softmax(tf.matmul(x, W) + b)

W1 = tf.Variable(tf.truncated_normal([784, 300], stddev=0.1))
b1 = tf.Variable(tf.zeros([300]))
l_1 = tf.nn.sigmoid(tf.matmul(x, W1) + b1)

W2 = tf.Variable(tf.zeros([300, 10]))
b2 = tf.Variable(tf.zeros([10]))
# 输出层使用softmax函数做分类
prediction = tf.nn.softmax(tf.matmul(l_1, W2) + b2)
# 二次代价函数-----优化使用交叉熵
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))
# loss = tf.reduce_mean(tf.square(y-prediction))
# 梯度下降法-->可以修改学习率,可以更改为其他的优化方法
train = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
# train = tf.train.AdamOptimizer(0.2).minimize(loss)

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

# equal比较两个参数是否是一样的,相同返回True,不同返回False argmax求最大的值在那个位置(比如求预测的概率最大的数字在什么位置)
# 结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))

# 求准确率 cast:转换类型,布尔型转换为浮点型
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

with tf.Session() as sess:
    sess.run(init)
    # 迭代21个周期--->可以增加训练的轮数
    # for epoch in range(21):
    for epoch in range(100):
        # 每个周期一共训练的批次
        for batch in range(n_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train, feed_dict={x: batch_xs, y: batch_ys})
        acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
        print('第', str(epoch + 1), '轮准确率:', acc)

二次代价函数:权重和偏置的更新与激活函数的梯度有关,梯度越大,更新越快。

交叉熵函数:权重和偏执的更新与误差项相关,误差越大,更新越快。

当输出神经元是线性的时候,选择二次代价函数比较好,当输出神经元是S型函数的时候,选择交叉熵代价函数。

猜你喜欢

转载自blog.csdn.net/github_39611196/article/details/81171206