版权声明:置顶文章如需转载请联系作者 https://blog.csdn.net/Bonstoppo/article/details/85253814
一、简单写一个回归方程
import tensorflow as tf
import numpy as np
#creat data
x_data = np.random.rand(100).astype(np.float32)#在x中生成随机数,随机数以np的float32类型展示
y_data= x_data * 0.1 + 0.3 #基本的函数
# create tensorflow structure start#
Weights= tf.Variable(tf.random_uniform([1] , -1.0 , 1.0))#初始化Weights(权重)的张量,均匀分布
biases = tf.Variable(tf.zeros([1]))#初始化biases(偏移量)张量,一维的数据
y = Weights * x_data + biases #依据的Weight和biases两个建立一个模型
lost = tf.reduce_mean(tf.square(y - y_data))#lost的数值为求得的是(y-y.data)^2的平均值
optimizer = tf.train.GradientDescentOptimizer(0.5)#梯度下降优化器,范围为0.5
train = optimizer.minimize(lost)
init = tf.global_variables_initializer();
# create tensorflow structure end #
sess = tf.Session()#建立访问
sess.run(init) #运行
for step in range(201):
sess.run(train)
if(step % 20) == 0:
print(step , sess.run(Weights), sess.run(biases))
二、tensorflow的会话机制:Session
#Session的两种写法
import tensorflow as tf
martix1 = tf.constant([[3 , 3]])
martix2 = tf.constant([[2],
[2]])
product = tf.matmul(martix1 , martix2)
# #method 1
# sess = tf.Session()#Session记得要大写
# result = sess.run(product)
# print(result)
# sess.close()
#method 2
with tf.Session() as sess:
result2 = sess.run(product)
print(result2)
三、tensorflow的初始化机制:Variable
#Variable:建立变量
import tensorflow as tf
state = tf.Variable(0 , name = 'counter')
# print(state.name)
one = tf.constant(1)
new_value = tf.add(state , one)
update = tf.assign(state , new_value)#assign:转让编制;将new_value赋值给state,return state
#使用tf.global_variables_initializer()添加节点用于初始化所有的变量。
#在你构建完整个模型并在会话中加载模型后,运行这个节点。c231
init = tf.global_variables_initializer()#初始化模型
with tf.Session() as sess:
sess.run(init)
for _ in range(3):
sess.run(update)
print(sess.run(state))
四、placeholder
#placeholder:在运行的时候再去给我的值,而不是一开始就先赋值。
import tensorflow as tf
input1 = tf.placeholder(tf.float32)
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的数值传入output
五、搭建一个神经网络
#定义一个添加层
#建造神经网络
%matplotlib qt5
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#添加激励函数
def add_layer(inputs, in_size, out_size, activation_function = None):
with tf.name_scope('layer'):
Weights = tf.Variable(tf.random_normal([in_size , out_size]) , name = 'W')
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1 , out_size]) + 0.1 , name = 'b')#初始化让所有的数值都是0.1
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.matmul(inputs , Weights) + biases #矩阵的乘法,表达式
if activation_function is None: #没有激励的话直接输出
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b) #有激励的话就做激励
return outputs
#定义数据形式
x_data = np.linspace(-1 , 1 , 300)[: , np.newaxis]#300行有300个例子
noise = np.random.normal(0 , 0.05 , x_data.shape)#形成一些噪点
y_data = np.square(x_data) - 0.5 + noise
with tf.name_scope('inputs'):
xs = tf.placeholder(tf.float32 , [None , 1] , name = 'x_input')#传进来的数值
ys = tf.placeholder(tf.float32 , [None , 1] , name = 'y_input')#传进来的数值 ?????
l1 = add_layer(xs , 1 , 10 , activation_function = tf.nn.relu)#隐藏层,10个因子
prediction = add_layer(l1 , 10 , 1 , activation_function = None)#输出层
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction) , reduction_indices = [1]))#求误差
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)#梯度下降算法,学习效率0.1
init = tf.global_variables_initializer()
sess = tf.Session()
writer = tf.summary.FileWriter("logs/" , sess.graph)
sess.run(init)
fig = plt.figure()
ax = fig.add_subplot(1 , 1 , 1)
ax.scatter(x_data , y_data)
plt.ion()
plt.show()
#plt.ioff()
for i in range(1000):
sess.run(train_step , feed_dict = {xs:x_data , ys:y_data})
if i % 50 == 0:
try:
ax.lines.remove(lines[0])
except Exception:
pass
#print(sess.run(loss , feed_dict = {xs:x_data , ys:y_data}))
prediction_value = sess.run(prediction , feed_dict = {xs : x_data})
lines = ax.plot(x_data , prediction_value , 'r-' , lw = 5)
plt.pause(0.1)