Overview
The content of this page is summarized by my experience using Python. This will be updated frequently.
Please note:
- Some commands are only for Linux. If you are using Windows, please modify the command accordingly.
- Some codes are only for python 3+. If you are using python 2+, please modify the code accordingly.
Pycharm
Create project
Click on File -> New Project -- Pure Python
Location: /home/junqi/PycharmProjects/ProjectName
Project Interpreter: Existing interpreter -- Python 3.6 (build) ~/git/aaal/build/bin/python
Notice:
You need to add the interpreter manually if the python(build) does not exist in the Existing interpreter. In that case, please add the python under the …/build/bin, not python 3.6 or 3.7!!!
Import directory/file
Click on File -> Open
Open the directory,attach it to the current project
copy its files to the current project if necessary
Rename directory/file
Right click on the directory or file, click “Refactor” -> “Rename”
Change working directory
Right Click on the directory which is chosen to be working directory
Click "Mark directory as" -> "Source Root"
Notice:
The default working directory is the project folder.
Search
- search everywhere
Press “Shift” twice, choose “include non-project items” - search in the current file
Ctrl + F
Comment
Ctrl + / # comment several lines
Indent
tab # increase indent
shift+tab # decrease indent
Folding
crtl+'-' # fold current layer
ctrl+'+' # unfold current layer
ctrl+shift+'-' # fold all layers
ctrl+shift+'+' # unfold all layers
Plot settings
- Show plot results in a new window
File->Settings->Tools->Python Scientific
Cancel the option "Show plots in toolwindow"
Python
Terminal Command
Check version (using terminal)
which python # show the path of current python
whereis python # show the path of every python
Activate environment
For aaal
. ~/git/aaal/scripts/activate.bash
For Anaconda
conda_init # activate the conda
conda activate ENV_NAME # activate the specific env
conda deactivate # deactivate the env and get back to the base conda env
Notice:
The activation only works under the current terminal. Check the current version of Python before activate other environments.
Numpy
import numpy as np
np.random
- np.random.rand(Size).astype(NpType)
# randomly generate an array with size=100 and type=float32 x_data = np.random.rand(100).astype(np.float32)
- np.random.normal(Mean, Variance, Shape)
# randomly generate the noise following normal distribution # and match its shape with x_data # mean = 0, variance = 0.05 noise = np.random.normal(0, 0.05, x_data.shape)
- np.random.seed(Num)
# With fixed seed, numpy will generate a fixed array of numbers. np.random.seed(1)
others in np module
- np.square()
y_data = np.square(x_data) - 0.5
- np.linspace()
# generate an one-dimensional array from -1 to 1, # with 300 uniformly distributed elements x_data = np.linspace(-1,1,300) # shape is (300, )
- np.newaxis: add one dimension to the array
# add a column-dimension x_data = np.linspace(-1,1,300)[:, np.newaxis] # shape is (300, 1) # add a row-domension x_data = np.linspace(-1,1,300)[np.newaxis,:] # shape is (1, 300)
- np.hstack: stack several arrays in the horizontal direction
arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) res = np.hstack((arr1, arr2)) [1 2 3 4 5 6] arr1 = np.array([[1, 2], [3, 4], [5, 6]]) arr2 = np.array([[7, 8], [9, 0], [0, 1]]) res = np.hstack((arr1, arr2)) [[1 2 7 8] [3 4 9 0] [5 6 0 1]]
Plot
import matplotlib.pyplot as plt
-
create a figure
fig = plt.figure()
-
create subplot
ax = fig.add_subplot(1,1,1)
-
show the plot
plt.show()
-
dynamic plot
plt.ion() # do this before plt.show()
-
plot points
ax.scatter(x_data, y_data)
-
plot lines
# red color, solid line, line width = 5 lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
-
remove lines
ax.lines.remove(lines[0])
-
pause during plot
plt.pause(1)
Try & except
Example 1
try:
ax.lines.remove(lines[0])
except Exception:
pass
String
assign with existing variables
layer_name = 'layer%s' % n_layer
Class
hasattr
Usage: hasattr(object, name), return True/False
Description: check if the corresponding attribute exists in the class.
# check if memory_counter exists in the object
if not hasattr(self, 'memory_counter'):
self.memory_counter = 0