tensorflow第一篇、理解与变量

tensorflow

1.简单介绍

Tensorflow是一个编程系统,使用图(graphs)来表示计算任务,图(graphs)中的节点称之为op
(operation),一个op获得0个或多个Tensor,执行计算,产生0个或多个Tensor。Tensor看作是一个n维的数组或列表。图必须在会话(Session)里被启动。

在这里插入图片描述
使用图(graphs)来表示计算任务
在被称之为会话(Session)的上下文(context)中执行图
使用tensor表示数据
通过变量(Variable)维护状态
使用feed和fetch可以为任意的操作赋值或者从其中获取数据

import tensorflow as tf

m1 = tf.constant([[3,3]]) #创建一个一行两列的常量op
m2 = tf.constant([[2],[3]]) #创建一个两行一列的插常量op
product = tf.matmul(m1,m2)  #创建矩阵乘法op
print(product)

输出结果:Tensor(“MatMul:0”, shape=(1, 1), dtype=int32)

#定义一个会话,启动默认图
sess = tf.Session()
#run方法出发三个op
result = sess.run(product) 
sess.closde()

输出结果:[[15]]

采用下边方法可以不用关闭sess

with tf.Session() as sess:
	result = sess.run(product)
	print(result)

2. 变量定义 tf.Variable([])

2.1 定义变量的几种形式总结归纳:

  • a = tf.Variable(2, name=“scalar”) # create variable a with scalar value
  • b = tf.Variable([2, 3], name=“vector”) # create variable b as a vector
  • c = tf.Variable([[0, 1], [2, 3]], name=“matrix”) # create variable c as a 2x2 matrix
  • W = tf.Variable(tf.zeros([784,10])) ##create variable W as 784 x 10 tensor, filled with zeros

2.2Variable vs constant

Variable 是tensorflow的一个类,里面封装了很多operations,简称ops,所以它是大写的,而tensorflow的op是小写的。又知constant是一个operation,简写为op,所以它小写了。

定义变量示例

x = tf.Variable([1,2])
a= tf.constant([1,2])
#增加一个减法op
sub = tf.subtract(x,a)
#增加一个加法op
add = tf.add(x,a)
with tf.Session() as sess:
	result1 = sess.run(sub)
	result2 = sess.run(add)
	print(result)

此时出现报错:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable
[[node Variable/read (defined at E:/pycham文件/tensorflow/tensorflow1.py:13) = IdentityT=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"]]

原因是变量没有初始化。初始化方法有两种

  • 所有变量初始化

    init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init)

  • 指定变量初始化

    W = tf.Variable(tf.zeros([784,10])) with tf.Session() as sess: sess.run(W.initializer)

x = tf.Variable([1,2])
a= tf.constant([1,2])
#增加一个减法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)
	result1 = sess.run(sub)
	result2 = sess.run(add)
	print(result)

2.3 定义赋值变量tf.assign(state,new_value)

#创建一个变最初始化为0,起一个名字叫counter
state=tf.Variable(0,name='counter'#创递一个op,作用是state加1
new_value=tf.add(state,1#赋值op 
update=tf.assign(state,new_value)
#变量初始化
init=tf.global_variables_initializerO 
with tf.Session0 as sess:
	sess.run(init)
    print(sess.run(state))
    for _ in range5):                
        sess.run(update)
        print(sess.run(state))
  • tf.assign(var,n)把n赋给var

    关于tensorflow中assign的理解,assign相当于python中的=。但是在tensorflow中使用时,需要注意调用的数值,有没有有改变例如:

    def test_1():
        a = tf.Variable([10, 20])
        b = tf.assign(a, [20, 30])
        c = a + [10, 20]
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            print("test_1 run a : ",sess.run(a)) # => [10 20] 
            print("test_1 run c : ",sess.run(c)) # => [10 20]+[10 20] = [20 40] 因为b没有被run所以a还是[10 20]
            ###此时assign将[20,30]赋给a,然后赋值给b,同时此时a的值已经发生改变变为[20,30]
            print("test_1 run b : ",sess.run(b)) # => ref:a = [20 30] 运行b,对a进行assign
            print("test_1 run a again : ",sess.run(a)) # => [20 30] 因为b被run过了,所以a为[20 30]
            print("test_1 run c again : ",sess.run(c)) # => [20 30] + [10 20] = [30 50] 因为b被run过了,所以a为[20,30], 那么c就是[30 50]
    
    import tensorflow as tf
    W = tf.Variable(10)
    W.assign(100)
    w1 = W.assign(100)
    with tf.Session() as sess:
        print(sess.run(W.initializer))      ##==>None  这是初始化的语句,没有进行赋值,所以为0
        print (W.eval() )                   ##==>10    W.assign(100) 并不会给W赋值,assign()是一个op,所以它返回一个op object,需要在Session中run这个op object,才会赋值给W.
        print(sess.run(w1))                 ##==>100
        print(sess.run(W))                  ##==>100
    
    

2.4 fetch and feed

2.4.1 fetch

在会话中可以得到多个op的结果

##fetch
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)

add = tf.add(input2,input3)
mul = tf.multiply(input1,add)

with tf.Session() as sess:
    result = sess.run([add,mul])
    print(result)

因为在此段程序中,没有出现变量。全部都是常量,所以不需要初始化变量。并且不可以进行input2=input1的操作,因为在tensorflow中赋值必须要用到tf.assign()

2.4.2Feed

Feed,这里相当于定义变量的时候不赋值,但是给一个值得类型,用的时候再往里添加值

###feed
##创建占位符
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.0],input2:[2.0]}))

2.5简单示例

拟合一条线性方程,求k与b

其中原始数据随机生成

x_data = np.random.rand(100)
y_data = x_data*0.1 +0.2

下边用tensorflow去做线性规划

x_data = np.random.rand(100)
y_data = x_data*0.1 +0.2

k= tf.Variable(0.0)
b= tf.Variable(0.0)
y = k*x_data +b
#定义损失函数,最小二乘法,其中reduce_mean是取均值,tf.square是取平方
loss = tf.reduce_mean(tf.square(y_data-y))

#定义梯度下降函数
optimizer = tf.train.GradientDescentOptimizer(0.2)

#通过梯度下降,训练得到最小的loss
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for step in range(200):
        #训练线性规划
        result = sess.run(train)
        #x训练的结果k,b
        print("result %d"%step,sess.run([k,b]))
bal_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for step in range(200):
        #训练线性规划
        result = sess.run(train)
        #x训练的结果k,b
        print("result %d"%step,sess.run([k,b]))

3.模型

3.1定义方式

   使用Sequential按层顺序构建模型,使用函数式API构建任意结构模型,继承Model基类构建自定义模型。
from tensorflow.keras import models,layers
model = models.Sequential()

3.2训练模型

    训练模型通常有3种方法,内置fit方法,内置train_on_batch方法,以及自定义训练循环。

其中history会返回history.history[metric]['val_'+metric]

history  = model.fit(x_train,y_train,batch_size = 64
								epochs = 30,
								validation_split = 0.2) #划分20%给验证集
train_metrics = history.history[metric]
val_metrics = history.history['val_'+metric]

3.3模型测试

model.evaluate(x = x_test,y=y_test)
model.predict(x_test)#预测概率
model.predict_classes(x_test)#预测类别

3.4保存模型

两种方式:

  • 使用Keras方式保存模型,
  • 使用TensorFlow原生方式保存。
    前者仅仅适合使用Python环境恢复模型,后者则可以跨平台进行模型部署。
3.4.1 Keras方式保存
#保存模型结构与权重
model.save('./data/keras_model.h5')  
del model  #删除现有模型
# identical to the previous one
model = models.load_model('./data/keras_model.h5')#加载模型
model.evaluate(x_test,y_test)
#保存模型结构
json_str = model.to_json()
model_json = models.model_from_json(json_str)
#只保存模型权重
model.save_weights('./data/keras_model.h5')
#恢复模型结构
model_json = models.model_from_json(json_str) 
model_json.compile(optimizer = 'adam',
					loss = 'binary_crossentropy,
					metrics = ['AUC'])
##加载权重
model_json.load_weights('./data/keras_model.h5')
3.4.2tensorflow方式保存
model.save_weghts('./data/tf_model_weights.ckpt',save_format='tf')
model_load = tf.keras.models.load_model('./data/tf_model_weights')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值