When running TensorFlow on CPU, first ensure that the correct version of TensorFlow is installed. TensorFlow supports both CPU and GPU execution environments, but by default, if no GPU is detected in the system, TensorFlow automatically runs on CPU.
Install TensorFlow
-
Install Python: TensorFlow requires a Python environment; it is recommended to use Python versions between 3.5 and 3.8.
-
Create a Virtual Environment (Optional): Using a virtual environment can avoid dependency conflicts and create an isolated environment for TensorFlow. You can use
venv(built-in Python) orconda(Anaconda suite) to create a virtual environment.bash# Using venv python -m venv tf_env source tf_env/bin/activate # Use tf_env\Scripts\activate on Windows # Using conda conda create -n tf_env python=3.8 conda activate tf_env -
Install TensorFlow: Install TensorFlow using pip. To ensure it runs on CPU, directly install the
tensorflowpackage instead oftensorflow-gpu.bashpip install tensorflow
Verify Installation
After installation, verify that TensorFlow is correctly installed and runs on CPU by running a simple TensorFlow program.
pythonimport tensorflow as tf # Create a TensorFlow constant hello = tf.constant('Hello, TensorFlow!') # Start TF session tf_session = tf.compat.v1.Session() # Run session to get results print(tf_session.run(hello))
Configure TensorFlow to Use CPU
Although TensorFlow automatically runs on CPU, you may need to explicitly configure it to use only CPU, especially when the system has both CPU and GPU. This can be achieved by setting environment variables or configuring within the code.
pythonimport os import tensorflow as tf os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # This tells TensorFlow to ignore GPU # Create some TensorFlow operations a = tf.constant([[1.0, 2.0], [3.0, 4.0]]) b = tf.constant([[1.0, 1.0], [0.0, 1.0]]) c = tf.matmul(a, b) print(c)
Example
For example, try using the CPU version of TensorFlow to implement a simple linear model.
pythonimport tensorflow as tf import numpy as np # Model and data parameters X_data = np.array([[1.0, 2.0], [2.0, 3.0], [3.0, 4.0], [4.0, 5.0]]) y_data = np.array([[1.0], [2.0], [3.0], [4.0]]) # Build the model X = tf.placeholder(tf.float32, shape=[None, 2]) y = tf.placeholder(tf.float32, shape=[None, 1]) W = tf.Variable(tf.random_normal([2, 1]), name='weight') b = tf.Variable(tf.random_normal([1]), name='bias') hypothesis = tf.matmul(X, W) + b # Loss function and optimizer cost = tf.reduce_mean(tf.square(hypothesis - y)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost) # Initialize variables init = tf.global_variables_initializer() # Start session with tf.Session() as sess: sess.run(init) # Train the model for step in range(2000): cost_val, hy_val, _ = sess.run([cost, hypothesis, optimizer], feed_dict={X: X_data, y: y_data}) if step % 500 == 0: print(step, "Cost:", cost_val, "\nPrediction:\n", hy_val)
The above example demonstrates how to create and train a simple linear regression model using TensorFlow on CPU. These steps ensure that TensorFlow effectively runs on CPU and processes data.