tensorflow实战例子

1.简单线性回归

(1)数据准备

实际的数据大家可以通过pandas等package读入,也可以使用自带的Boston House Price数据集,这里为了简单,我们自己手造一点数据集。

%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (14,8)

n_observations = 100
xs = np.linspace(-3, 3, n_observations)
ys = np.sin(xs) + np.random.uniform(-0.5, 0.5, n_observations)
plt.scatter(xs, ys)
plt.show()

在这里插入图片描述

(2)准备好placeholder

X = tf.placeholder(tf.float32, name='X')
Y = tf.placeholder(tf.float32, name='Y')

(3)初始化参数/权重

W = tf.Variable(tf.random_normal([1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')

(4)计算预测结果

Y_pred = tf.add(tf.multiply(X, W), b)

(5)计算损失函数值

loss = tf.square(Y - Y_pred, name='loss')

(6)初始化optimizer

learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)

(7)指定迭代次数,并在session里执行graph

n_samples = xs.shape[0]
with tf.Session() as sess:
	# 记得初始化所有变量
	sess.run(tf.global_variables_initializer()) 
	
	writer = tf.summary.FileWriter('./graphs/linear_reg', sess.graph)
	
	# 训练模型
	for i in range(50):
		total_loss = 0
		for x, y in zip(xs, ys):
			# 通过feed_dic把数据灌进去
			_, l = sess.run([optimizer, loss], feed_dict={X: x, Y:y}) 
			total_loss += l
		if i%5 ==0:
			print('Epoch {0}: {1}'.format(i, total_loss/n_samples))

	# 关闭writer
	writer.close() 
	
	# 取出w和b的值
	W, b = sess.run([W, b]) 

在这里插入图片描述

2.多项式回归

对于非线性的数据分布,用线性回归拟合程度一般,我们来试试多项式回归

(1)数据准备

%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (14,8)

n_observations = 100
xs = np.linspace(-3, 3, n_observations)
ys = np.sin(xs) + np.random.uniform(-0.5, 0.5, n_observations)
plt.scatter(xs, ys)
plt.show()

在这里插入图片描述

(2)准备好placeholder

X = tf.placeholder(tf.float32, name='X')
Y = tf.placeholder(tf.float32, name='Y')

(3)初始化参数/权重

W = tf.Variable(tf.random_normal([1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')

(4)计算预测结果

Y_pred = tf.add(tf.multiply(X, W), b)
#添加高次项
W_2 = tf.Variable(tf.random_normal([1]), name='weight_2')
Y_pred = tf.add(tf.multiply(tf.pow(X, 2), W_2), Y_pred)
W_3 = tf.Variable(tf.random_normal([1]), name='weight_3')
Y_pred = tf.add(tf.multiply(tf.pow(X, 3), W_3), Y_pred)

(5)计算损失函数值

sample_num = xs.shape[0]
loss = tf.reduce_sum(tf.pow(Y_pred - Y, 2)) / sample_num

(6)初始化optimizer

learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)

(7)指定迭代次数,并在session里执行graph

n_samples = xs.shape[0]
with tf.Session() as sess:
	# 记得初始化所有变量
	sess.run(tf.global_variables_initializer()) 
	
	writer = tf.summary.FileWriter('./graphs/polynomial_reg', sess.graph)
	
	# 训练模型
	for i in range(1000):
		total_loss = 0
		for x, y in zip(xs, ys):
			# 通过feed_dic把数据灌进去
			_, l = sess.run([optimizer, loss], feed_dict={X: x, Y:y}) 
			total_loss += l
		if i%20 ==0:
			print('Epoch {0}: {1}'.format(i, total_loss/n_samples))

	# 关闭writer
	writer.close()
    # 取出w和b的值
	W, W_2, W_3, b = sess.run([W, W_2, W_3, b])

在这里插入图片描述

print("W:"+str(W[0]))
print("W_2:"+str(W_2[0]))
print("W_3:"+str(W_3[0]))
print("b:"+str(b[0]))

在这里插入图片描述

plt.plot(xs, ys, 'bo', label='Real data')
plt.plot(xs, xs*W + np.power(xs,2)*W_2 + np.power(xs,3)*W_3 + b, 'r', label='Predicted data')
plt.legend()
plt.show()

在这里插入图片描述

3.逻辑回归

(1)数据准备

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import time
#使用tensorflow自带的工具加载MNIST手写数字集合
mnist = input_data.read_data_sets('/data/mnist', one_hot=True) 

在这里插入图片描述

#查看一下数据维度
mnist.train.images.shape

在这里插入图片描述

#查看target维度
mnist.train.labels.shape

在这里插入图片描述

(2)准备好placeholder

batch_size = 128
X = tf.placeholder(tf.float32, [batch_size, 784], name='X_placeholder') 
Y = tf.placeholder(tf.int32, [batch_size, 10], name='Y_placeholder')

(3)初始化参数/权重

w = tf.Variable(tf.random_normal(shape=[784, 10], stddev=0.01), name='weights')
b = tf.Variable(tf.zeros([1, 10]), name="bias")

(4)拿到每个类别的score

logits = tf.matmul(X, w) + b 

(5)计算多分类softmax的loss function

# 求交叉熵损失
entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y, name='loss')
# 求平均
loss = tf.reduce_mean(entropy)

(6)初始化optimizer

这里的最优化用的是随机梯度下降,我们可以选择AdamOptimizer这样的优化器

learning_rate = 0.01
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)

(7)指定迭代次数,并在session里执行graph

#迭代总轮次
n_epochs = 30

with tf.Session() as sess:
	# 在Tensorboard里可以看到图的结构
	writer = tf.summary.FileWriter('./graphs/logistic_reg', sess.graph)

	start_time = time.time()
	sess.run(tf.global_variables_initializer())	
	n_batches = int(mnist.train.num_examples/batch_size)
	for i in range(n_epochs): # 迭代这么多轮
		total_loss = 0

		for _ in range(n_batches):
			X_batch, Y_batch = mnist.train.next_batch(batch_size)
			_, loss_batch = sess.run([optimizer, loss], feed_dict={X: X_batch, Y:Y_batch}) 
			total_loss += loss_batch
		print('Average loss epoch {0}: {1}'.format(i, total_loss/n_batches))

	print('Total time: {0} seconds'.format(time.time() - start_time))

	print('Optimization Finished!')

	# 测试模型
	
	preds = tf.nn.softmax(logits)
	correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y, 1))
	accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))
	
	n_batches = int(mnist.test.num_examples/batch_size)
	total_correct_preds = 0
	
	for i in range(n_batches):
		X_batch, Y_batch = mnist.test.next_batch(batch_size)
		accuracy_batch = sess.run([accuracy], feed_dict={X: X_batch, Y:Y_batch}) 
		total_correct_preds += accuracy_batch[0]
	
	print('Accuracy {0}'.format(total_correct_preds/mnist.test.num_examples))

	writer.close()

在这里插入图片描述

4.多层感知机

(1)数据准备

import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import time
#使用tensorflow自带的工具加载MNIST手写数字集合
mnist = input_data.read_data_sets('/data/mnist', one_hot=True) 

在这里插入图片描述

#查看一下数据维度
mnist.train.

在这里插入图片描述

(2)准备好placeholder

X = tf.placeholder(tf.float32, [None, 784], name='X_placeholder') 
Y = tf.placeholder(tf.int32, [None, 10], name='Y_placeholder')

(3)初始化参数/权重

# 网络参数
n_hidden_1 = 256 # 第1个隐层
n_hidden_2 = 256 # 第2个隐层
n_input = 784 # MNIST 数据输入(28*28*1=784)
n_classes = 10 # MNIST 总共10个手写数字类别

weights = {
    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1]), name='W1'),
    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2]), name='W2'),
    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]), name='W')
}
biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1]), name='b1'),
    'b2': tf.Variable(tf.random_normal([n_hidden_2]), name='b2'),
    'out': tf.Variable(tf.random_normal([n_classes]), name='bias')
}

(4)构建网格计算graph

def multilayer_perceptron(x, weights, biases):
    # 第1个隐层,使用relu激活函数
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'], name='fc_1')
    layer_1 = tf.nn.relu(layer_1, name='relu_1')
    # 第2个隐层,使用relu激活函数
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'], name='fc_2')
    layer_2 = tf.nn.relu(layer_2, name='relu_2')
    # 输出层
    out_layer = tf.add(tf.matmul(layer_2, weights['out']), biases['out'], name='fc_3')
    return out_layer

(5)拿到预测类别score

pred = multilayer_perceptron(X, weights, biases)

(6)计算损失函数值并初始化optimizer

learning_rate = 0.001
loss_all = tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=Y, name='cross_entropy_loss')
loss = tf.reduce_mean(loss_all, name='avg_loss')
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)

(7)初始化变量

init = tf.global_variables_initializer()

(8)在session中执行graph定义的运算

#训练总轮数
training_epochs = 15
#一批数据大小
batch_size = 128
#信息展示的频度
display_step = 1

with tf.Session() as sess:
    sess.run(init)
    writer = tf.summary.FileWriter('./graphs/MLP_DNN', sess.graph)

    # 训练
    for epoch in range(training_epochs):
        avg_loss = 0.
        total_batch = int(mnist.train.num_examples/batch_size)
        # 遍历所有的batches
        for i in range(total_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            # 使用optimizer进行优化
            _, l = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y})
            # 求平均的损失
            avg_loss += l / total_batch
        # 每一步都展示信息
        if epoch % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost=", \
                "{:.9f}".format(avg_loss))
    print("Optimization Finished!")

    # 在测试集上评估
    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(Y, 1))
    # 计算准确率
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print("Accuracy:", accuracy.eval({X: mnist.test.images, Y: mnist.test.labels}))
    writer.close()

在这里插入图片描述

  • 2
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值