TensorFlow常用函数API介绍
TensorFlow是目前深度学习领域最为常用的开源框架之一。在使用TensorFlow时,熟练掌握常用的函数API是非常重要的。本文就常用的一些函数API进行介绍,并提供相应的示例。
1. tf.constant
tf.constant(value, dtype=None, shape=None, name='Const')
tf.constant是TensorFlow中最基本的常量操作之一。它用于创建一个常量张量。其中,value表示常量的值;dtype表示常量的类型,如int32、float32等;shape表示常量的形状,如(1,2)、(2,2,2)等。
import tensorflow as tf
a = tf.constant(1,name='a')
b = tf.constant(2,name='b')
c = a + b
with tf.Session() as sess:
print(sess.run(c))
2. tf.Variable
tf.Variable(initial_value=None, trainable=True, collections=None, validate_shape=True, name=None)
tf.Variable用于定义一个可训练的变量。其中,initial_value表示变量的初始值;trainable表示该变量是否可以被训练,可选项为True或False;collections可以为变量指定一个或多个变量集合;validate_shape表示是否对变量的形状进行验证;name表示变量名。
import tensorflow as tf
W = tf.Variable(tf.zeros([2,2]), name='weights')
b = tf.Variable(tf.zeros([2]), name='biases')
x = tf.placeholder(tf.float32, [None, 2],name='input')
y_ = tf.placeholder(tf.float32, [None, 2],name='outcome')
y = tf.matmul(x, W) + b
loss = tf.reduce_mean(tf.square(y - y_))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
for i in range(100):
sess.run(train_step, feed_dict={x: input_data, y_:outcome_data})
3. tf.placeholder
tf.placeholder(dtype, shape=None, name=None)
tf.placeholder用于定义占位符,可以看作模型在运行时需要输入的数据。其中,dtype表示占位符的类型;shape表示占位符的形状;name表示占位符的名字。
import tensorflow as tf
x = tf.placeholder(tf.float32, [None, 2],name='input')
y_ = tf.placeholder(tf.float32, [None, 1],name='outcome')
W = tf.Variable(tf.zeros([2,1]))
b = tf.Variable(tf.zeros([1]))
y = tf.matmul(x, W) + b
loss = tf.reduce_mean(tf.square(y - y_))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
data = [[0,0],[0,1],[1,0],[1,1]]
outcome = [[0],[1],[1],[0]]
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(500):
sess.run(train_step, feed_dict={x: data, y_:outcome})
if i%50 == 0:
print('step:%d,loss:%f' % (i,sess.run(loss,feed_dict={x: data, y_:outcome})))
4. tf.nn.relu
tf.nn.relu(features, name=None)
tf.nn.relu用于定义ReLU激活函数,即修正线性单元激活函数。其中,features为张量。
import tensorflow as tf
import numpy as np
x = tf.placeholder(tf.float32, shape=(None, 5), name='x')
W = tf.Variable(tf.random_uniform([5, 5], -1, 1), name='W')
b = tf.Variable(tf.zeros([5]), name='b')
output = tf.nn.relu(tf.matmul(x, W) + b)
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
input_data = np.random.rand(10, 5)
output_data = sess.run(output, feed_dict={x: input_data})
print(output_data)
5. tf.train.AdamOptimizer
tf.train.AdamOptimizer(learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-08, use_locking=False)
tf.train.AdamOptimizer使用Adam算法进行优化。其中,learning_rate为学习率;beta1和beta2分别表示一阶矩估计和二阶矩估计的指数衰减率;epsilon为数值稳定性常数;use_locking表示是否使用锁进行操作。
import tensorflow as tf
import numpy as np
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
x = tf.placeholder(tf.float32,[None,1],name='x')
y = tf.placeholder(tf.float32,[None,1],name='y')
W1 = tf.Variable(tf.random_normal([1,10],stddev=1.0))
b1 = tf.Variable(tf.zeros([1,10]))
W2 = tf.Variable(tf.random_normal([10,1],stddev=1.0))
b2 = tf.Variable(tf.zeros([1,1]))
hidden_layer = tf.nn.relu(tf.matmul(x, W1) + b1)
prediction = tf.matmul(hidden_layer, W2) + b2
loss = tf.reduce_mean(tf.square(y-prediction))
train_step = tf.train.AdamOptimizer(0.1).minimize(loss)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(1000):
sess.run(train_step,feed_dict={x:x_data,y:y_data})
if i%100 == 0:
print('step:%d,loss:%f'% (i,sess.run(loss,feed_dict={x:x_data,y:y_data})))
以上就是一些常用的TensorFlow函数API的介绍,并提供了相关的示例代码。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:tensorflow常用函数API介绍 - Python技术站