User Tools

Site Tools


products:ict:python:machine_learning:tensorflow

Tensorflow examples

1. Hello, TensorFlow!

This is a simple example to ensure that TensorFlow is installed correctly. It prints “Hello, TensorFlow!” to the console.

import tensorflow as tf

# Create a TensorFlow constant hello = tf.constant('Hello, TensorFlow!')

# Start a TensorFlow session with tf.Session() as session:

  # Run the session and print the output
  print(session.run(hello))

2. Linear Regression:

Linear regression is a fundamental machine learning task. Here's a simple example using TensorFlow:

import tensorflow as tf import numpy as np

# Generate random data x = np.random.rand(100).astype(np.float32) y = 2 * x + 1

# Create TensorFlow variables for the model parameters W = tf.Variable(tf.random.normal([1])) b = tf.Variable(tf.zeros([1]))

# Define the linear regression model y_pred = W * x + b

# Define the loss function (Mean Squared Error) loss = tf.reduce_mean(tf.square(y_pred - y))

# Create an optimizer (e.g., Gradient Descent) optimizer = tf.train.GradientDescentOptimizer(0.1) train_op = optimizer.minimize(loss)

# Initialize the variables init = tf.global_variables_initializer()

# Create a TensorFlow session and train the model with tf.Session() as session:

  session.run(init)
  for step in range(1000):
      session.run(train_op)
  # Print the learned parameters
  learned_W, learned_b = session.run([W, b])
  print(f'Learned W: {learned_W[0]}, Learned b: {learned_b[0]}')

3. Image Classification with Convolutional Neural Network (CNN):

This example demonstrates image classification using a CNN with TensorFlow and the MNIST dataset.

import tensorflow as tf from tensorflow.keras import datasets, layers, models import matplotlib.pyplot as plt

# Load the MNIST dataset (train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()

# Preprocess the data train_images, test_images = train_images / 255.0, test_images / 255.0

# Build a simple CNN model model = models.Sequential([

  layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
  layers.MaxPooling2D((2, 2)),
  layers.Flatten(),
  layers.Dense(128, activation='relu'),
  layers.Dense(10)

])

# Compile the model model.compile(optimizer='adam',

            loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
            metrics=['accuracy'])

# Train the model model.fit(train_images, train_labels, epochs=5)

# Evaluate the model test_loss, test_acc = model.evaluate(test_images, test_labels) print(f“Test accuracy: {test_acc}”)

# Make predictions predictions = model.predict(test_images)

These examples cover a range of TensorFlow use cases, from simple “Hello, TensorFlow!” to more complex tasks like linear regression and image classification with convolutional neural networks. TensorFlow is a powerful library with extensive documentation and resources for further exploration and learning.

products/ict/python/machine_learning/tensorflow.txt · Last modified: 2023/10/11 23:42 by wikiadmin