Here’s a cheat sheet for TensorFlow, a popular open-source machine learning library:
TensorFlow Basics
Import TensorFlow:
import tensorflow as tf
TensorFlow Version:
TensorFlow Version
Constants:
# Define a constant
x = tf.constant(5, name="x")
Variables:
# Define a variable
y = tf.Variable(10, name="y")
# Initialize variables
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
sess.run(init)
TensorFlow Operations
Addition:
z = x + y
Matrix Multiplication:
matrix_a = tf.constant([[1, 2], [3, 4]])
matrix_b = tf.constant([[5, 6], [7, 8]])
result = tf.matmul(matrix_a, matrix_b)
Activation Functions:
# Sigmoid
sigmoid_result = tf.nn.sigmoid(x)
# ReLU (Rectified Linear Unit)
relu_result = tf.nn.relu(x)
# Softmax
softmax_result = tf.nn.softmax(x)
TensorFlow Sessions
Session Creation:
with tf.compat.v1.Session() as sess:
# Run operations
result_value = sess.run(result)
print(result_value)
TensorFlow Placeholder
Create a Placeholder:
# Placeholder for a vector of 3 elements
input_data = tf.compat.v1.placeholder(tf.float32, shape=(3,))
Feed Data into Placeholder:
input_values = [1.0, 2.0, 3.0]
with tf.compat.v1.Session() as sess:
result = sess.run(z, feed_dict={x: 5, input_data: input_values})
print(result)
TensorFlow Neural Network Example
# Define a simple neural network
input_features = tf.compat.v1.placeholder(tf.float32, shape=(None, 2), name="input_features")
weights = tf.Variable(tf.random.normal([2, 1]), name="weights")
bias = tf.Variable(tf.zeros([1]), name="bias")
output = tf.nn.sigmoid(tf.matmul(input_features, weights) + bias, name="output")
# Train the neural network
labels = tf.compat.v1.placeholder(tf.float32, shape=(None, 1), name="labels")
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=output, labels=labels), name="loss")
optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(loss)
# Run a training session
with tf.compat.v1.Session() as sess:
sess.run(tf.compat.v1.global_variables_initializer())
for step in range(num_steps):
_, current_loss = sess.run([train_op, loss], feed_dict={input_features: input_data, labels: labels_data})
if step % display_step == 0:
print(f"Step {step}, Loss={current_loss}")
This is a basic TensorFlow cheat sheet covering some fundamental operations. For more advanced topics and functionalities, refer to the official TensorFlow documentation.