tensorflow

1、一个线性规划的例子

import tensorflow as tf
import numpy as np

x_data=np.random.rand(100).astype(np.float32)
y_data=x_data*0.1+0.3

####创建tensorflow结构
W=tf.Variable(tf.random_uniform([1],-1.0,1.0))
b=tf.Variable(tf.zeros([1]))

y=W*x_data+b

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) #激活神经网络

for step in range(201):
    sess.run(train)
    if step%20==0:
        print(step,sess.run(W),sess.run(b))

2、session会话控制

import tensorflow as tf
import numpy as np

matrix1=tf.constant([[3,3],
                     [2,3]])
matrix2=tf.constant([[2],
                     [2]])
product=tf.matmul(matrix1,matrix2)

#method 1
sess=tf.Session()
result=sess.run(product)
print(result)
sess.close()  #关闭session

#method 2
with tf.Session() as sess:  #用完之后不用关闭session
    result2=sess.run(product)

    print(result2)

3、variable变量

import tensorflow as tf
import numpy as np

state=tf.Variable(0)
one=tf.constant(1)
tmp=tf.add(state,one)
update=tf.assign(state,tmp)#state<-tmp

init=tf.global_variables_initializer() #初始化,定义了tf变量都要初始化

with tf.Session()as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        result=sess.run(state)
        print(result)

4、placeholder传入值

input1=tf.placeholder(tf.float32)#参数是type即tf处理的数据形式 第二个参数可以是结构比如【2,2】
input2=tf.placeholder(tf.float32)

output=tf.multiply(input1,input2)

with tf.Session()as sess:
    print(sess.run(output,feed_dict={input1:[2],input2:[1]}))

5、def add_layer()添加层

def add_layer(inputs,in_size,out_size,activation_function=None):
    W=tf.Variable(tf.random_normal([in_size,out_size]))
    b=tf.Variable(tf.zeros([1,out_size])+0.1)
    Wx_plus_b=tf.matmul(inputs,W)+b
    if activation_function is None:
        outputs=Wx_plus_b
    else:
        outputs=activation_function(Wx_plus_b)
    return outputs


6、建造神经网络

######数据准备
x_data=np.linspace(-1,1,300)[:,np.newaxis]#把1*300转化为300*1
noise=np.random.normal(0,0.05,x_data.shape)
y_data=np.square(x_data)-0.5+noise #y=x^2-0.5

xs=tf.placeholder(tf.float32,[None,1])
ys=tf.placeholder(tf.float32,[None,1])
######神经网络结构
hl=add_layer(xs,1,10,activation_function=tf.nn.relu) #隐藏层 1->10
prediction=add_layer(hl,10,1,activation_function=None)#输出层 10->1

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.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()#show之后不暂停
plt.show()

for i in range(1000):
    sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
    if i%50:
        #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,ys:y_data})
        lines=ax.plot(x_data,prediction_value,'r-',lw=5)
        plt.pause(0.1)

7、tensorflow可视化

with tf.name_scope('loss'):

writer=tf.summary.FileWriter("logs/",sess.graph)

def add_layer(inputs,in_size,out_size,n_layer,activation_function=None):
    layer_name='layer%s'%n_layer
    with tf.name_scope(layer_name):
        with tf.name_scope('W'):
            W=tf.Variable(tf.random_normal([in_size,out_size]),name='W')
            tf.summary.histogram(layer_name+'/W',W)
   with tf.name_scope('loss'):
    loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),
                             reduction_indices=[1]))
    tf.summary.scalar('loss',loss)

sess=tf.Session()
merged=tf.summary.merge_all()
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:
        result=sess.run(merged,feed_dict={xs:x_data,ys:y_data})
        writer.add_summary(result,i)

8、tensorflow分类

from tensorflow.examples.tutorials.mnist import input_data

mnist=input_data.read_data_sets('MNIST_data',one_hot=True)

######计算准确度
def compute_accuracy(v_xs,v_ys):
    global prediction
    y_pre=sess.run(prediction,feed_dict={xs:v_xs})
    correct_prediction=tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))
    accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
    result=sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys})
    return result

######数据准备
xs=tf.placeholder(tf.float32,[None,784])#28*28
ys=tf.placeholder(tf.float32,[None,10])

######神经网络结构
prediction=add_layer(xs,784,10,activation_function=tf.nn.softmax)#softmax做分类用

cross_entropy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),
                             reduction_indices=[1]))#交叉熵损失函数

train_step=tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

#########开始训练
for i in range(1000):
    batch_xs,batch_ys=mnist.train.next_batch(100)#每一步训练100个图片
    sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})
    if i%50==0:#计算准确度
        print(compute_accuracy(
            mnist.test.images,mnist.test.labels))

9、CNN

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#######load data
mnist=input_data.read_data_sets('MNIST_data',one_hot=True)

######计算准确度
def compute_accuracy(v_xs,v_ys):
    global prediction
    y_pre=sess.run(prediction,feed_dict={xs:v_xs,keep_prob:1})
    correct_prediction=tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))
    accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
    result=sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys,keep_prob:1})
    return result

def w_variable(shape):
    initial=tf.truncated_normal(shape,stddev=0.1)
    return tf.Variable(initial)

def b_variable(shape):
    initial=tf.constant(0.1,shape=shape)
    return tf.Variable(initial)

def conv2d(x,W):
    #strides[1,x_movement,y_movement,1]
    #must have strides[0]=strides[3]=1
    return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')

def max_pool_2x2(x):
    return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
    
######数据准备
keep_prob=tf.placeholder(tf.float32)
xs=tf.placeholder(tf.float32,[None,784])
ys=tf.placeholder(tf.float32,[None,10])
x_image=tf.reshape(xs,[-1,28,28,1])
print(x_image.shape)#[n_samples,28,28,1]

#############神经网络结构##########
####卷积层1
W_conv1=w_variable([5,5,1,32])#patch 5*5 insize 1输入的厚度  outsize:32
b_conv1=b_variable([32])
h_conv1=tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)#outputsize:28*28*32
h_pool1=max_pool_2x2(h_conv1)#outputsize:14*14*32
####卷积层2
W_conv2=w_variable([5,5,32,64])#patch 5*5 insize 32输入的厚度  outsize:64
b_conv2=b_variable([64])
h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)#outputsize:14*14*64
h_pool2=max_pool_2x2(h_conv2)#outputsize:7*7*64
#####func1 layer
w_fc1=w_variable([7*7*64,1024])
b_fc1=b_variable([1024])
h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64])#[n_samples,7,7,64]->[n_samples,7*7*64]
h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,w_fc1)+b_fc1)
h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)
#####func2 layer
w_fc2=w_variable([1024,10])
b_fc2=b_variable([10])
prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,w_fc2)+b_fc2)
##############神经网络结构##########
cross_entropy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),
                             reduction_indices=[1]))#交叉熵损失函数
train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

init=tf.global_variables_initializer()
sess=tf.Session()
sess.run(init)
#########开始训练
for i in range(1000):
    batch_xs,batch_ys=mnist.train.next_batch(70)#每一步训练100个图片
    sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys,keep_prob:0.5})
    if i%50==0:#计算准确度
            print(compute_accuracy(
                mnist.test.images,mnist.test.labels))

10、saver读取

写入

W=tf.Variable([[1,2,3],[4,5,6]],dtype=tf.float32,name='weight')
b=tf.Variable([[1,2,3]],dtype=tf.float32,name='biases')

init=tf.global_variables_initializer()
saver=tf.train.Saver()
with tf.Session() as sess:
    sess.run(init)
    save_path=saver.save(sess,"my_net/save_net.ckpt")

读取 要定义同样大小和同样的类型

W=tf.Variable(np.arange(6).reshape((2,3)),dtype=tf.float32,name='weight')
b=tf.Variable(np.arange(3).reshape((1,3)),dtype=tf.float32,name='biases')

saver=tf.train.Saver()
with tf.Session() as sess:
    saver.restore(sess,"my_net/save_net.ckpt")
    print("weight:",sess.run(W))
    print("biases:",sess.run(b))

11、RNN

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#######load data
mnist=input_data.read_data_sets('MNIST_data',one_hot=True)

#hyperparameters
lr=0.001
training_iters=100000
batch_size=128

n_inputs=28 #mnist data input(image shape:28*28)
n_steps=28  #time steps
n_hidden_units=128 #neurons in hidden layer
n_classes=10  #mnist classed(0-9digits)

#tf graph input
x=tf.placeholder(tf.float32,[None,n_steps,n_inputs])
y=tf.placeholder(tf.float32,[None,n_classes])

#difine weights
weights={
    #(28,128)
    'in':tf.Variable(tf.random_normal([n_inputs,n_hidden_units])),
    #(128,10)
    'out':tf.Variable(tf.random_normal([n_hidden_units,n_classes]))
}
biases={
    #(128,)
    'in':tf.Variable(tf.constant(0.1,shape=[n_hidden_units,])),
    #(10,)
    'out':tf.Variable(tf.constant(0.1,shape=[n_classes,]))
}

def RNN(X,weights,biases):
    ##hidden layer for input
    X=tf.reshape(X,[-1,n_inputs])#X(128,28,28)->(128*28,28)
    X_in=tf.matmul(X,weights['in'])+biases['in'] #(128*28,128)
    X_in=tf.reshape(X_in,[-1,n_steps,n_hidden_units])#(128*28,128)->(128,28,128)
    
    ##cell
    lstm_cell=tf.nn.rnn_cell.BasicLSTMCell(n_hidden_units,forget_bias=1.0,state_is_tuple=True)
    _init_state=lstm_cell.zero_state(batch_size,dtype=tf.float32) #(c_state,m_state)
    outputs,states=tf.nn.dynamic_rnn(lstm_cell,X_in,initial_state=_init_state,time_major=False)
    
    ##hidden layer for output
    results=tf.matmul(states[1],weights['out'])+biases['out']
 
    return results

pred=RNN(x,weights,biases)
cost=tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(logits=pred,labels=y))
train_op=tf.train.AdamOptimizer(lr).minimize(cost)

 
correct_pred=tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
accuracy=tf.reduce_mean(tf.cast(correct_pred,tf.float32))

init=tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    step=0
    while step*batch_size<training_iters:
        batch_xs,batch_ys=mnist.train.next_batch(batch_size)
        batch_xs=batch_xs.reshape([batch_size,n_steps,n_inputs])
        sess.run([train_op],feed_dict={
            x:batch_xs,
            y:batch_ys,
        })
        if step%20==0:
            print(sess.run(accuracy,feed_dict={
            x:batch_xs,
            y:batch_ys,
            }))
        step+=1


 

 


        
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值