Tensorflow编程学习笔记(1)

xiaoxiao2021-02-28  47

Test1 常量、变量、Fetch、Feed、Session

在tensorflow中,常量通过constant函数来定义。 在tensorflow中,变量通过Variable函数来定义,注意:只要用到变量,就一定要run一下initialize_all_variables()来初始化变量。 Session在tensorflow中就像指针一样,指向需要运行的代码。 Session运行结束后,需要关闭。 Fetch对多个操作节点取值。 Feed给占位符赋值。

import tensorflow as tf a = tf.constant(3.0) #定义常量(赋值) b = tf.Variable(1.0) #定义变量(赋值) c = tf.placeholder(tf.float32) #定义占位符(位数) d1 = tf.add(a,b) #a+b d2 = tf.sub(a,b) #a-bb d3 = tf.mul(a,b) #a*b d4 = tf.div(a,b) #a/b e1 = tf.mod(a,b) #a%b e2 = tf.abs(c) #|c| e3 = tf.sqrt(c) #平方根 e4 = tf.pow(a,b) #a^b f1 = tf.maximum(a,b) f2 = tf.minimum(a,b) m1 = tf.constant([[3,3]]) m2 = tf.constant([[2],[3]]) g = tf.matmul(m1,m2) #矩阵乘法[2*3+3*3]=[15] with tf.Session() as sess: sess.run(tf.global_variables_initializer()) #变量初始化 result = sess.run([d1,d2,d3,d4,e1,e4,f1,f2,g]) #Fetch print(result) print (sess.run(e2, feed_dict={c: -3})) #Feed print (sess.run(e3, feed_dict={c: 4})) print(g) print(sess.run(g)) print(sess.run([g])) 123456789101112131415161718192021222324252627282930313233

运行结果:

[4.0, 2.0, 3.0, 3.0, 0.0, 3.0, 3.0, 1.0, array([[15]])] 3.0 2.0 Tensor("MatMul:0", shape=(1, 1), dtype=int32) [[15]] [array([[15]])] 1234567

Test2 循环

import tensorflow as tf #创建一个op变量,初始化为0 state = tf.Variable(0) #创建一个op,作用是使state+1 new_state = tf.add(state,1) #赋值op: state = new_value即把new_state的值赋值给state。在执行Session时,会根据定义的运算逻辑,逐个向上查找。因为在update里用到了new_state,所以会执行new_state定义的内容。 update =tf.assign(state,new_state) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(state)) #循环5次 for _ in range(5): sess.run(update) print(sess.run(state)) 12345678910111213141516

运行结果:

0 1 2 3 4 5 123456

Test3 简单实例

import tensorflow as tf import numpy as np #使用numpy生产100个随机点 x_data = np.random.rand(100) #一条斜率为0.1、偏移是0.2的直线 y_data = x_data*0.1+0.2 #构造一个线性模型 b = tf.Variable(0.) k = tf.Variable(0.) #斜率k,偏移b,变量x_data y = k*x_data + b #优化变量k、b使线性模型接近于上面样本点的分布 #定义二次代价(或者叫目标/损失)函数 # reduce_mean()求平均值、square()求平方 # y_data是真实值,y是预测值 loss = tf.reduce_mean(tf.square(y_data-y)) #定义一个梯度下降法来进行训练的优化器 # GradientDescentOptimizer()梯度下降法优化器(括号内给定学习率) optimizer = tf.train.GradientDescentOptimizer(0.2) #最小化代价(或者叫目标/损失)函数 train = optimizer.minimize(loss) #初始化变量 init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) #迭代201次 for step in range(201): sess.run(train) #每训练20次打印一次 if step%20 == 0: print(step,sess.run([k,b])) 1234567891011121314151617181920212223242526272829303132333435363738

运行结果:

0 [0.047159102, 0.097865961] 20 [0.098292276, 0.20082079] 40 [0.099039868, 0.2004616] 60 [0.099460147, 0.20025954] 80 [0.099696465, 0.20014593] 100 [0.099829316, 0.20008205] 120 [0.099904031, 0.20004614] 140 [0.099946037, 0.20002595] 160 [0.09996964, 0.20001459] 180 [0.099982917, 0.20000821] 200 [0.099990398, 0.20000462] 1234567891011

可以看到k接近0.1、b接近0.2 关于reduce_mean()的博文: tensorflow学习之常用函数总结:tensorflow官方例子中的诸如tf.reduce_mean()这类函数


Test4 线性回归

import tensorflow as tf import numpy as np import matplotlib.pyplot as plt #使用numpy从[-0.5,0.5]区间内生成均匀分布的200个随机点 #[:,np.newaxis]增加维度,200行1列的数据 x_data = np.linspace(-0.5, 0.5, 200)[:,np.newaxis] #生成干扰项,随机值 noise = np.random.normal(0,0.02,x_data.shape) #U型曲线 y_data = np.square(x_data) + noise #定义两个占位符placeholder,n行1列[None,1] x = tf.placeholder(tf.float32, [None,1]) y = tf.placeholder(tf.float32, [None,1]) #layer1 #定义神经网络中间层 #权重变量,1行10列,随机初始化 Weights_L1 = tf.Variable(tf.random_normal([1,10])) #偏移量,1行10列,初始化为0 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) #layer2 #定义神经网络输出层 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()) #迭代2000次 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) #'r-':画一条红色实线 plt.plot(x_data,prediction_value,'r-',lw=5) plt.show() 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354

运行结果: 

转载请注明原文地址: https://www.6miu.com/read-2612885.html

最新回复(0)