#1、创建图,启动图
import tensorflow as tf
#创建两个常量op:m1,m2
m1=tf.constant([[1,2,3],[2,3,4]])
m2=tf.constant([[3,5],[2,3],[4,5]])
print(m1,m2)
#创建矩阵乘法op
p=tf.matmul(m1,m2)
print(p)
#创建会话,启动默认图
sess=tf.Session()
#调用运行图的方法:run
result=sess.run(p)
print(result)
#关闭会话
sess.close()
#会话启用的简易操作,自动关闭会话
with tf.Session() as sess:
result=sess.run(p)
print(result)
#2、变量
#定义变量
x=tf.Variable([7,8])
#定义常量
a=tf.constant([3,5])
#加法运算op
sub=tf.subtract(x,a)
#减法运算op
add=tf.add(x,a)
#全局变量初始化
init=tf.global_variables_initializer()
#启动会话
with tf.Session() as sess:
sess.run(init)
print(sess.run(sub))
print(sess.run(add))
#创建一个循环变量
state=tf.Variable(0,name='counter')
new_state=tf.add(state,1)
upstate=tf.assign(state,new_state)
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(state))
for _ in range(5):
sess.run(upstate)
print(sess.run(state),end=',')
#3、fetch and feed
#fetch同时执行多个节点OP
input1=tf.constant(2)
input2=tf.constant(5)
input3=tf.constant(7)
add=tf.add(input1,input2)
mul=tf.multiply(add,input3)
with tf.Session() as sess:
result=sess.run([add,mul])
print(result)
#Feed
#创建占位符
input1=tf.placeholder(tf.float32)
input2=tf.placeholder(tf.float32)
mul=tf.multiply(input1,input2)
with tf.Session() as sess:
print(sess.run(mul,feed_dict={input1:[7.],input2:[8.]}))#以数据字典的形式输入数据
#简单实例
import numpy as np
#使用numpy生成100个随机数样本
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
#二次代价函数
loss=tf.reduce_mean(tf.square(y_data-y))
#梯度下降训练优化
optimizer=tf.train.GradientDescentOptimizer(0.2)
#代价函数最小化
train=optimizer.minimize(loss)
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for step in range(201):
sess.run(train)
if step%20 == 0:
print(step,sess.run([k,b]))
#非线性回归模型
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#使用numpy生成200个随机点
x_data=np.linspace(-0.5,0.5,200)[:,np.newaxis]#增加新的维度
noise=np.random.normal(0,0.02,x_data.shape)#生成噪点数据
y_data=np.square(x_data) + noise
#定义两个占位符
x=tf.placeholder(tf.float32,[None,1])#32位浮点数,[任意形状,一列]
y=tf.placeholder(tf.float32,[None,1])#32位浮点数,[任意形状,一列]
#定义神经网络中间层
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(y-prediction))
#梯度下降法
train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss)
#定义会话
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for _ in range(2000):
sess.run(train_step,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)
plt.plot(x_data,prediction_value,'r-',lw=5)
plt.show()
网友评论