Python Tips

Overview

The content of this page is summarized by my experience using Python. This will be updated frequently.
Please note:

  1. Some commands are only for Linux. If you are using Windows, please modify the command accordingly.
  2. 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

  1. search everywhere
    Press “Shift” twice, choose “include non-project items”
  2. 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

  1. 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

  1. 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)
    
  2. 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)
    
  3. np.random.seed(Num)
    # With fixed seed, numpy will generate a fixed array of numbers.
    np.random.seed(1)
    

others in np module

  1. np.square()
    y_data = np.square(x_data) - 0.5
    
  2. 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, )
    
  3. 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)
    
  4. 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
  1. create a figure

    fig = plt.figure()
    
  2. create subplot

    ax = fig.add_subplot(1,1,1)
    
  3. show the plot

    plt.show()
    
  4. dynamic plot

    plt.ion()	# do this before plt.show()
    
  5. plot points

    ax.scatter(x_data, y_data)
    
  6. plot lines

    # red color, solid line, line width = 5
    lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
    
  7. remove lines

    ax.lines.remove(lines[0])
    
  8. 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
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值