1.普通机器学习预测函数系数(y=0.1x+0.3)
# -*- coding:gbk -*-
import tensorflow as tf
import numpy as np
#生成数据,y=0.1x+0.3
x_data=np.random.rand(100).astype(np.float32)
y_data=x_data*0.1+0.3
###开始创建tensorflow结构###
weight=tf.Variable(tf.random_uniform([1],-1.0,1.0))
biases=tf.Variable(tf.zeros([1]))
y=weight*x_data+biases
#误差
loss=tf.reduce_mean(tf.square(y-y_data))
#优化器
optimizer=tf.train.GradientDescentOptimizer(0.5)
#用优化器减少误差
train=optimizer.minimize(loss)
#定义初始化变量
init=tf.initialize_all_variables()
###完成创建tensorflow结构###
sess=tf.Session()
sess.run(init) #激活init
for step in range(201):
sess.run(train)
if step%20==0:
print(step,sess.run(weight),sess.run(biases))
2.构建简单神经网络预测y=x^2,可视化界面显示
# -*- coding:gbk -*-
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def add_layer(inputs,in_size,out_size,activation_function=None):
weight=tf.Variable(tf.random_normal([in_size,out_size]))
biases=tf.Variable(tf.zeros([1,out_size])+0.1)
wx_plus_b=tf.matmul(inputs,weight)+biases
if activation_function==None:
outputs=wx_plus_b
else:
outputs=activation_function(wx_plus_b)
return outputs
#numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
#在指定的间隔内返回均匀间隔的数字
#[:,np.newaxis]给每个元素增加新维度,就相当于矩阵转置,一行多列变一列多行
x_data=np.linspace(-1,1,300)[:,np.newaxis]
noise=np.random.normal(0,0.05,x_data.shape)
y_data=np.square(x_data)-0.5+noise
xs=tf.placeholder(tf.float32,[None,1])
ys=tf.placeholder(tf.float32,[None,1])
l1=add_layer(xs,1,10,activation_function=tf.nn.relu)
prediction=add_layer(l1,10,1,activation_function=None)
loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))
train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss)
init=tf.initialize_all_variables()
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:
#print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
try:
ax.lines.remove(lines[0])
except Exception:
pass
prediction_value=sess.run(prediction,feed_dict={xs:x_data})
lines=ax.plot(x_data,prediction_value,'r-',lw=5)
plt.pause(0.1)
3.tensorflow board学习。。。好像就是添加几个命名。。。。。
# -*- coding:gbk -*-
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'):
with tf.name_scope('weight'):
weight=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')
with tf.name_scope('wx_plus_b'):
wx_plus_b=tf.matmul(inputs,weight)+biases
if activation_function==None:
outputs=wx_plus_b
else:
outputs=activation_function(wx_plus_b)
return outputs
#numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
#在指定的间隔内返回均匀间隔的数字
#[:,np.newaxis]给每个元素增加新维度,就相当于矩阵转置,一行多列变一列多行
x_data=np.linspace(-1,1,300)[:,np.newaxis]
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)
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)
init=tf.initialize_all_variables()
sess=tf.Session()
writer=tf.summary.FileWriter("logs/",sess.graph)
sess.run(init)
for i in range(1000):
sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
if i%50==0:
print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))