参考——莫烦python
包括:
1.变量定义
2.session控制
3.占位符
4.添加层
5.搭建神经网络
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18/2/27 下午5:11
# @Author : cicada@hole
# @File : tf.py
# @Desc : tensorflow测试文件
# @Link :
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def func1():
# d
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3
# m
Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
biases = tf.Variable(tf.zeros([1]))
y = Weights * x_data + biases
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
session = tf.Session()
session.run(init)
for step in range(201):
session.run(train)
if step % 20 == 0:
print(step, session.run(Weights), session.run(biases))
def sessionControl():
# 创建两个矩阵
matrix1 = tf.constant([[3,3],[2,3]])
matrix2 = tf.constant([[2],[2]])
product = tf.matmul(matrix1, matrix2)
#用session来激活product并得到计算结果
sess = tf.Session()
# method1
result = sess.run(product)
print(result)
sess.close()
# method 2
with tf.Session() as sess:
result2 = sess.run(product)
print(result2)
def tfVarDefine():
# 定义变量 语法: state = tf.Variable()
state = tf.Variable(0, name='counter')
# 定义常量 one
one = tf.constant(1)
# 定义加法步骤(此步并没有直接计算)
new_value = tf.add(state, one)
# 将state 更新为 new_value
update = tf.assign(state, new_value)
# 定义的变量需要激活
init = tf.global_variables_initializer()
# 使用session
with tf.Session() as sess:
sess.run(init)
for _ in range(3):
sess.run(update)
print('---------state ',sess.run(state)) # 需要把sess的指针指向state 再print
#-------占位符placeholder----
def placeHolderTest():
input1 = tf.placeholder(tf.float32) #大部分形式f32
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2) #乘法运算
with tf.Session() as sess:
print(sess.run(output, feed_dict={input1:[7.],input2:[2.]}))
# feed_dict和placeholder进行绑定,能传值
#----激励函数-----如sigmod等
def activationFunctionTest():
pass
#----添加层 ----add_layer()----
def add_layer(inputs, in_size, out_size, activation_function=None):
Weights = tf.Variable(tf.random_normal([in_size, out_size])) #in_size行out_size列的随机矩阵
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1) #biases推荐值不为零
Wx_plus_b = tf.matmul(inputs, Weights) + biases #神经网络未激活的值
#activation_function = None时,输出Wx_plus_b,不为None时,输出激活后的Wx_plus_b
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
#----搭建网络-----
def buildNN():
#导入数据
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
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
#输入层1个、隐藏层10个、输出层1个的神经网络
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)#输入层只有一个属性
#输入就是隐藏层的输出——l1,输入有10层(隐藏层的输出层),输出有1层
prediction = add_layer(l1, 10, 1, activation_function=None)
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))#平均误差
# reduction_indices表示函数的处理维度
# 让机器学习提升准确率 以0.1的效率来最小化误差loss
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x_data, y_data)
plt.ion() # 连续显示
plt.show()
for i in range(1000):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 50 == 0:
# to visualize the result and improvement
try:
ax.lines.remove(lines[0])
except Exception:
pass
prediction_value = sess.run(prediction, feed_dict={xs: x_data})
# plot the prediction
lines = ax.plot(x_data, prediction_value, 'r-', lw=5) #显示预测的数据
plt.pause(0.1)
if __name__ == '__main__':
# sessionControl()
# tfVarDefine()
# placeHolderTest()
buildNN()
本文通过实例介绍了TensorFlow的基础操作,包括变量定义、会话控制、占位符使用、添加神经网络层及搭建简单的神经网络等内容。
1340

被折叠的 条评论
为什么被折叠?



