Preface¶
In the first chapter, we introduced the installation of PaddlePaddle. Next, we will introduce how to use PaddlePaddle. PaddlePaddle is a deep learning framework open-sourced by Baidu on September 27, 2016, and it is currently the only open-source deep learning framework in China. After version 0.11.0, PaddlePaddle introduced the Fluid version. Compared to the previous V2 version, the Fluid version has a clearer code structure and is more convenient to use. In this chapter, we will introduce how to use PaddlePaddle to calculate 1+1. The choice of this simple example is mainly to help readers understand the use of PaddlePaddle’s Fluid version and master the usage process of PaddlePaddle. We will introduce how to define a tensor with PaddlePaddle and how to perform calculations on the tensor.
Calculating 1+1 with Constants¶
PaddlePaddle is similar to a scientific computing library, such as numpy in Python, providing a large number of calculation operations. However, the calculation object of PaddlePaddle is a tensor. Let’s write a constant_sum.py Python file to use PaddlePaddle to calculate [[1, 1], [1, 1]] * [[1, 1], [1, 1]].
First, import the PaddlePaddle library. Most APIs are under paddle.fluid.
import paddle.fluid as fluid
Define two constant tensors x1 and x2, specifying their shape as [2, 2], filled with 1, and the data type as int64.
# Define two tensors
x1 = fluid.layers.fill_constant(shape=[2, 2], value=1, dtype='int64')
x2 = fluid.layers.fill_constant(shape=[2, 2], value=1, dtype='int64')
Next, define an operation to add the two tensors and return a summation operator. PaddlePaddle provides a large number of operations, such as addition, subtraction, multiplication, division, trigonometric functions, etc. Readers can find them in fluid.layers.
# Sum the two tensors
y1 = fluid.layers.sum(x=[x1, x2])
Then create an executor, where you can specify whether to use CPU or GPU for calculation. When using CPUPlace(), the CPU is used; when using CUDAPlace(), the GPU is used. The executor is used to perform calculations later. For example, before executing the calculation, we need to initialize the parameters of the program, which also requires the executor because only the executor can execute the program.
# Create an executor using CPU
place = fluid.CPUPlace()
exe = fluid.executor.Executor(place)
# Initialize parameters
exe.run(fluid.default_startup_program())
Finally, execute the calculation. The program parameter is the main program, not the program used for parameter initialization in the previous step. There are a total of two default programs: default_startup_program() and default_main_program(). The fetch_list parameter is the value to be output after the executor runs. We need to output the result of the addition calculation. The final result is also a tensor.
# Perform the calculation and output the result of y
result = exe.run(program=fluid.default_main_program(),
fetch_list=[y1])
print(result)
Output information:
[array([[2, 2],
[2, 2]], dtype=int64)]
Calculating 1+1 with Variables¶
The above calculation is for 1+1 with constant tensors, and the value of the tensor cannot be modified arbitrarily. Therefore, we will now write a variable_sum.py program file to use tensor variables as operands. This is similar to a placeholder, and the values to be calculated will be added to the placeholder during calculation.
Import the PaddlePaddle library and the numpy library.
import paddle.fluid as fluid
import numpy as np
Define two tensors without specifying their shape and value. They will be dynamically assigned later. Here, only their type and name are specified. The name is crucial for subsequent assignment.
# Define two tensors
a = fluid.layers.create_tensor(dtype='int64', name='a')
b = fluid.layers.create_tensor(dtype='int64', name='b')
Use the same method to define the addition operation of these two tensors.
# Sum the two tensors
y = fluid.layers.sum(x=[a, b])
Here, we also create an executor using the CPU and initialize the parameters.
# Create an executor using CPU
place = fluid.CPUPlace()
exe = fluid.executor.Executor(place)
# Initialize parameters
exe.run(fluid.default_startup_program())
Then use numpy to create the values of the two tensors that need to be calculated.
# Define two variables to calculate
a1 = np.array([3, 2]).astype('int64')
b1 = np.array([1, 1]).astype('int64')
This time, the parameters of exe.run() are a bit different. There is an additional feed parameter, which is used to assign values to the tensor variables. The assignment is in the form of key-value pairs, where the key is the name specified when defining the tensor variable, and the value is the value to be passed. In the fetch_list parameter, we want to output the values of a, b, and y, so we need to use three variables to receive the return values.
# Perform the calculation and output the result of y
out_a, out_b, result = exe.run(program=fluid.default_main_program(),
feed={'a': a1, 'b': b1},
fetch_list=[a, b, y])
print(out_a, " + ", out_b," = ", result)
Output information:
[3 2] + [1 1] = [4 3]
This concludes this chapter. In this chapter, we learned how to use PaddlePaddle. In the next chapter, we will use PaddlePaddle to complete our first installation—linear regression. See you in the next chapter.
Synced to Baidu AI Studio platform: http://aistudio.baidu.com/aistudio/projectdetail/29339
Synced to Kesci K-Lab platform: https://www.kesci.com/home/project/5bf75387954d6e0010668f76
Project code GitHub address: https://github.com/yeyupiaoling/LearnPaddle2/tree/master/note2
Note: The latest code is on GitHub.
Previous chapter: 《PaddlePaddle from Beginner to炼丹》I - Installation of the New Version of PaddlePaddle¶
Next chapter: 《PaddlePaddle from Beginner to炼丹》III - Linear Regression¶
References¶
- http://www.paddlepaddle.org/documentation/api/zh/1.0/layers.html