Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

Ubuntu 20.04 LTS 自带 Python 3.8.10, 只需简单修改python默认版本即可。
还可以下两个工具:
pip (用于 Python 的标准包管理器) ,以及venv(用于创建和管理轻型虚拟环境的标准模块)

pip安装

  1. ubuntu

安装 pip

1
sudo apt install python3-pip

安装 venv :

1
sudo apt install python3-venv
  1. archlinux

安装 python

1
yay -S python36 python37 python35

通过 ensurepip module安装 pip

1
python -m ensurepip --upgrade

参考文献:萌宅鹿, 南方老F

pip列出已安装包

列出已安装包

1
pip list 

或者

1
pip freeze

pip网络安装程序

网络安装程序

1
pip install package 	

如:pip install opencv-python

pip本地安装程序

本地安装程序

1
2
pip install <目录>/<文件名>
pip install --use-wheel --no-index --find-links=wheelhouse/ <包名>

如:pip install /home/liu/gdal-3.3.3-cp38-cp38.whl

pip批量安装

  1. 导出环所有依赖到 requirements.txt 文件
1
pip freeze > requirements.txt
  1. 批量安装requirements.txt中指定的包

    1
    pip install -r requirements.txt
  2. 列出已安装包

    1
    pip freeze

pip升级包

  1. 查询可升级的包
    1
    pip list -o
    2.升级包
    1
    pip install -U <包名>
  2. 升级pip
    1
    pip install -U pip

pip卸载包

  1. 卸载单一包
    1
    pip uninstall <包名>
  2. 批量卸载包
    1
    pip uninstall -r requirements.txt

pip显示包目录

显示包所在的目录

1
pip show -f <包名>

pip打包

1
pip wheel <包名>

pip搜索下载包

搜索包网址: https://pypi.org/
pip search <搜索关键字>

  1. 安装 `pip-search
    1
    pip install pip-search
  2. 搜索
    1
    pip_search tensorflow

pip下载包而不安装

1
pip install <包名> -d <目录>

pip指定单次安装源

1
pip install <包名> -i http://pypi.v2ex.com/simple

如:pip3 install onnxruntime==1.12.1 -i https://pypi.douban.com/simple --trusted-host pypi.douban.com

pip查看当前源

1
pip3 config list

修改源

  1. 命令行修改源:
    1
    pip3 config set global.index-url https://pypi.douban.com/simple/
  2. 源配置文件
    修改 ~/.pip/pip.conf
1
2
3
4
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host=mirrors.aliyun.com
  1. 常用源
    a) 清华大学TUNA
    https://pypi.tuna.tsinghua.edu.cn/simple/
    b) ali
    http://mirrors.aliyun.com/pypi/simple/
    c) 中国科学技术大学
    https://pypi.mirrors.ustc.edu.cn/simple/
    d) 豆瓣
    https://pypi.douban.com/simple/
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13

    # pip安装virtualenv:
    virtualenv 是一个创建隔绝的Python环境的 工具。virtualenv创建一个包含所有必要的可执行文件的文件夹,用来使用Python工程所需的包。

    virtualenv是如何创建“独立”的Python运行环境的呢?原理很简单,就是把系统Python复制一份到virtualenv的环境,用命令source venv/bin/activate进入一个virtualenv环境时,virtualenv会修改相关环境变量,让命令python和pip均指向当前的virtualenv环境。virtualenv为应用提供了隔离的Python运行环境,解决了不同应用间多版本的冲突问题。
    - [参考文献](https://blog.csdn.net/change_can/article/details/83789712)。

    ``` bash
    sudo apt install python3-pip
    pip install virtualenv
    export PATH=/home/liupei/.local/bin:$PATH
    virtualenv --version
    virtualenv -h

virtualenv project 将会在当前的目录中创建一个文件夹,包含了Python可执行文件, 以及 pip 库的一份拷贝,这样就能安装其他包了。虚拟环境的名字(此例中是 project ) 可以是任意的;若省略名字将会把文件均放在当前目录。

  1. virtualenv 虚拟环境使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
liupei@mac:~$ mkdir test && cd test
liupei@mac:~$ virtualenv project
liupei@mac:~$ virtualenv -p /usr/bin/python2.7 project
liupei@mac:~$ virtualenv --no-site-packages project

New python executable in /root/test/project/bin/python
Installing setuptools, pip, wheel...
done.

2. 查看当前默认的版本
liupei@mac:~$ python -V

3. 激活虚拟环境:
liupei@mac:~$ source project/bin/activate

4. 关闭虚拟环境:
(project) liupei@mac:~$ deactivate

5. 要删除一个虚拟环境,只需删除它的文件夹即可
rm -rf project

6. 虚拟环境重建
(project) liupei@mac:~$ pip freeze > requirements.txt
(project) liupei@mac:~$ pip install -r requirements.txt

python帮助

Linux网页查看

Python3自带的帮助文档,REF

1
2
3
4
5
6
7
8
u@lab:~$ pydoc -p 8000
Server ready at http://localhost:8000/
Server commands: [b]rowser, [q]uit
server>
打开浏览器,在地址栏输入 http://localhost:8000/

如果要查看Python3.5的文档
pydoc3 -p 8000

在控制台查看

直接在命令行Terminal查看帮助,REF

1
2
3
4
5
6
7
8
$ python
Python 2.7.15 |Anaconda, Inc.| (default, Dec 14 2018, 19:04:19)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help()
help> modules
输入要查看的module,如numpy
help> numpy

python导入文件的方法

调试代码的时候,程序一直提示没有该模块,一直很纳闷,因为我导入文件一直是用绝对路径进行导入的。按道理来讲是不会出现模块找不到的情况的。最后仔细分析了整个代码的目录结构,才发现了问题。

(1)主程序与模块程序在同一目录下:

如下面程序结构:

1
2
3
– src
  |– mod1.py
  |– test1.py

若在程序test1.py中导入模块mod1, 则直接使用import mod1from mod1 import *;

(2)主程序所在目录是模块所在目录的父(或祖辈)目录
如下面程序结构:

1
2
3
4
5
– src
|– mod1.py
|– mod2
  | – mod2.py
– test1.py

若在程序test1.py中导入模块mod2, 需要在mod2文件夹中建立空文件__init__.py文件(也可以在该文件中自定义输出模块接口); 然后使用 from mod2.mod2 import * import mod2.mod2.

(3)主程序导入上层目录中模块或其他目录(平级)下的模块
如下面程序结构:

1
2
3
4
5
6
7
– src
  |– mod1.py
  |– mod2
   |– mod2.py
  |– sub
    | – test2.py
  – test1.py

  若在程序test2.py中导入模块mod1.pymod2.py。首先需要在mod2下建立__init__.py文件(同(2)),src下不必建立该文件。然后调用方式如下:
  下面程序执行方式均在程序文件所在目录下执行,如test2.py是在cd sub;之后执行python test2.py
test1.py是在cd src;之后执行python test1.py; 不保证在src目录下执行python sub/test2.py成功。

1
2
3
4
import sys
sys.path.append(“..”)
import mod1
import mod2.mod2

(4)从(3)可以看出,导入模块关键是能够根据sys.path环境变量的值,找到具体模块的路径。

总结:
  通过总结可以发现,当你要导入的文件在和你的当前文件在同一个目录时,你直接导入这个文件名就好了。

  当你要导入的文件或者目录不和你的当前文件同目录时,你需要跳到这个你要导入文件的父级目录,然后一级一级的用点号连接走过的目录或者文件,然后就可以了 至于要怎么跳到这个这个父级目录。比较通用的就是,将父级目录加入系统路径,然后用点号一级一级的寻找,直到到达你要导入的模块。

自定义第三方库

一般安装Python的三方库,直接使用conda或Python的包管理工具pip,或下载源码包后,使用其中的setup.py安装,就可以直接安装在Python的系统库目录中了。

如果想使用一个三方库,又不想安装在Python的默认库目录中,可以程序中使用”sys.path.append(“具体路径”)”将三方库路径暂时加入库路径。如果想操作一次,之后任何程序都可以直接使用,比如自己写的库?以linux系统conda环境为例,示例如下:

建立自己的库

1
2
3
4
mkdir libpy && vim libpy/liu.py 
wsl@t470:~$ head libpy/liu.py
def testme():
print('hello world')

把三方库路径写入”.pth”文件

1
2
wsl@t470:~$ vim anaconda2/lib/python2.7/site-packages/x.pth
# 添加内容 /home/wsl/libpy

查看python默认路径

conda下python默认路径文件

1
2
3
4
5
6
7
wsl@t470:~$ python
Python 2.7.16 |Anaconda, Inc.| (default, Sep 24 2019, 21:51:30)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/wsl/anaconda2/lib/python27.zip', '/home/wsl/anaconda2/lib/python2.7', '/home/wsl/anaconda2/lib/python2.7/plat-linux2', '/home/wsl/anaconda2/lib/python2.7/lib-tk', '/home/wsl/anaconda2/lib/python2.7/lib-old', '/home/wsl/anaconda2/lib/python2.7/lib-dynload', '/home/wsl/anaconda2/lib/python2.7/site-packages', '/home/wsl/anaconda2/lib/python2.7/site-packages', '/home/wsl/libpy']

调用三方库

调用自己python库函数

1
2
3
4
5
6
7
8
wsl@t470:~$ python
Python 2.7.16 |Anaconda, Inc.| (default, Sep 24 2019, 21:51:30)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from liu import testme
>>> testme()
hello world
>>>

python导入路径

1
sys.path.insert(0, "/home/u/gcForest/lib")

小例子

调用liu.py库,实现pkl格式自动转换为mat格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# pkl2mat
def pkl2mat(filename):
"trans .pkl to .mat filename: obia7.pkl"
print('original image will be shown...');
DATA_PATH= os.path.join(os.getcwd(),"Data")
input_mat=scipy.io.loadmat(os.path.join(DATA_PATH,'gf1.mat'))['gf1']
padIn = np.zeros((input_mat.shape[0]+3*2,input_mat.shape[1]+3*2,input_mat.shape[2]))
for i in range(input_mat.shape[2]):
padIn[:,:,i] = np.pad(input_mat[:,:,i],((3,3),(3,3)),'constant',constant_values = (0,0))
input_mat = padIn;
outpath=os.getcwd();
print('predicted image will be trans...');
with open(os.path.join(outpath,filename),'rb') as f:
predicted_image=pkl.load(f)
scipy.io.savemat(os.path.join(outpath,filename+'.mat'),mdict={'predicted_image':predicted_image})
# main.py
(cnn) wsl@t470:~/work$ cat main.py
from liu import pkl2mat
import sys
if __name__=="__main__":
pkl2mat(sys.argv[1])
# run main.py
(cnn) wsl@t470:~/work$ python main.py obia23.pkl
original image will be shown...
predicted image will be trans...

conda安装

1
2
3
4
wget -c https://repo.anaconda.com/archive/Anaconda2-2019.10-Linux-x86_64.sh --no-check-certificate
chmod 744 Anaconda2-2018.12-Linux-x86_64.sh
bash Anaconda2-2018.12-Linux-x86_64.sh
## export PATH=/home/liupei/anaconda3/bin:$PATH

清华源 下载anaconda

conda帮助

conda安装后验证等

1
2
3
4
conda -V
python -V
conda update conda
conda -h

conda卸载

1
2
# 卸载 anaconda
rm -rf ~/anaconda2

conda修改源

清华源

  1. 查看当前源
1
conda config --show channels

显示如下:

1
2
3
4
5
6
7
channels:
- defaults
```
2. anaconda修改镜像源(conda源)
```bash
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --set show_channel_urls yes
  1. 再次查看当前源
    1
    conda config --show channels
    显示如下:
    1
    2
    3
    4
    5
    6
    7
    channels:
    - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
    - defaults
    ```
    4. 恢复默认channel
    ```bash
    conda config --remove-key channels

conda环境管理

  1. 取消启动base
1
2
conda config --set auto_activate_base false 
conda config --set auto_activate_base true
  1. 显示已安装环境
    1
    conda env list 
  2. 创建环境
    1
    2
    conda create -n py2 python=2.7 
    conda create -n py3 python=3.7
  3. 激活环境
    1
    conda activate py3	
  4. 反激活环境
    1
    conda deactivate
  5. 克隆环境
    1
    conda create --name py2 --clone python2	 
  6. 删除环境
    1
    conda remove --name py2 --all	 

conda包管理

  1. 列出已安装包
    1
    conda list
  2. 安装包
    1
    conda install pandas
  3. 删除包
    1
    conda remove pandas
  4. 从指定环境中删除包
    1
    conda remove --name python2 pandas
  5. 升级包
    升级单一包
    1
    conda upgrade pandas
    升级所有包
    1
    conda upgrade --all

conda 批量导出

  1. 环境导出
    1
    conda env export > py36.yaml 
  2. conda 批量安装
    1
    conda env create -f py36.yaml
    or
  3. 批量导出
    1
    conda list -e > requirements.txt
  4. 批量安装
    1
    conda install --yes --file requirements.txt

wsl环境配置

wsl安装及配置参考:wsl安装

vim自动补全python

下载Pydiction

1
2
3
mkdir -p .vim/bundle
cd .vim/bundle/
git clone https://github.com/rkulla/pydiction.git

配置Pydiction

1
2160  cp -r ~/.vim/bundle/pydiction/after/ ~/.vim

在.vimrc文件添加如下配置

1
2
3
filetype plugin on
let g:pydiction_location = '~/.vim/bundle/pydiction/complete-dict'
let g:pydiction_menu_height = 20

参考文献:wengyupeng

非管理员安装python

1
2
3
4
5
6
7
8
9
download python: https://www.python.org/downloads/release
cd directory and
./configure --prefix=/users/installed/python2.7
make install
# add $PATH
vim .bashrc
export xport PATH=/public3/home/ch_cumtlp3/installed/python2.7/bin:$PATH
source .bashrc
python -V

更改python默认版本

  • 打开终端,输入python,可以看到当前系统中默认的python版本是 2.7.12
  • 进入”/usr/bin”目录下,输入”ls -l | grep python”显示所有名字中包含python的文件
  • 只要把python的指向改为python3即可,Python3指向的是Python3.x
1
2
3
sudo mv python python_backup
sudo ln -s /usr/bin/python3 /usr/bin/python
再执行Python命令,可以看到默认版本已经改成Python3.x.x了

gdal和rasterio安装

下载二进制包,通过pip安装,网址:gdal 和 rasterio,下载 GDALrasterio 包,然后 pip 安装。

  1. gdal 安装
    1
    pip3 install  C:\Users\liu\Downloads\GDAL-3.4.2-cp37-cp37m-win_amd64.whl
  2. rasterio 安装
    1
    pip3 install C:\Users\liu\Downloads\rasterio-1.2.10-cp37-cp37m-win_amd64.whl

pycache文件夹问题

运行脚本时添加 -B 参数

1
python -B foo.py

Reference

Latex中python代码高亮显示

Latex中高亮显示 python 看 Hight python in Latex, The package is loaded by the following line:

1
\usepackage{pythonhighlight}

It is then possible to include a Python snippet directly in the code using:

1
2
def f(x):
return x

It is also possible to include inline Python code in LaTeX with \lstinline{\pyth}:

1
The special method \pyth{__init__}... 

Last but not least, you can load an external Python file with:

1
\inputpython{python_file.py}{23}{50}

to display the contents of the file $python_file$ from line 23 to line 50.

jupyter notebook

Jupyter Notebook介绍、安装及使用教程,REF

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1. 安装jupyter
pip install jupyter
conda install jupyter notebook

2. 配准环境 IPython
from notebook.auth import passwd
passwd()
# c.NotebookApp.password = 'sha1:6e4d6f95274c:b1144336cc77d78c31c195cfd2a249e37845f75d'
c.NotebookApp.password='sha1:58ff51f6de2f:c6f429e0f8e2566e5185cedc817f5cc30f53746a'
c.NotebookApp.ip = '::'

c.NotebookApp.port = 9999

3. 使用 local
jupyter notebook --config=jupyter_config.py

linux 下命令行运行 python 脚本

脚本方式

方法是在.py文件的第一行加上下面的任意一行:

1
2
3
#!/usr/bin/python

#!/usr/bin/env python

二者的区别在于:

  • !/usr/bin/python是告诉操作系统在调用脚本时调用/usr/bin目录下的python解释器,python解释器的路径被明确给出。
  • !/usr/bin/env python是为了防止用户没有将python 装在默认的 /usr/bin 路径里。当系统看到这一行的时候,首先会到env设置里查找 python 的安装路径,再调用对应路径下的解释器程序完成操作。

!/usr/bin/env python会去环境设置寻找python目录通常推荐第二种写法。需要再次强调的是,上述解析路径应该放在Python 脚本的第一行。

交互式方式

在linux命令行模式中运行python,进入python交互式环境,写程序后直接输出结果。

python命令行调试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
python -m pdb test2.py
(Pdb) b 8 # 第8行设置断点
(Pdb) b # 显示所有断点
(Pdb) cl 2 # 清楚第2行断点

(Pdb) n # 下一步(遇函数不进入)
(Pdb) s # 下一步(遇函数进入)
(Pdb) r # 一直运行到函数返回
(Pdb) c # 继续运行直到断点或结束
(Pdb) j 10 # 跳转到第10行

(Pdb) p para #打印变量para
(Pdb) l # 列出脚本清单
(Pdb) a # 打印当前函数参数

(Pdb) h # 查看pdb帮助
(Pdb) q # 退出pdb
(Pdb) w # 查看所在的位置

windows 环境

前期准备

首先你需要有一台电脑 然后你需要保证这个电脑是干净的:没有额外安装 Python (因为之前安装过 Python 的原因导致我之后又重新装了一遍 Miniconda),没有安装miniconda/conda这些环境管理软件

miniconda安装

环境变量配置

电脑 - 属性 - 高级系统设置 - 高级 - 环境变量 - 对 path 进行设置,新建 环境变量

1
2
3
D:\miniconda3
D:\miniconda3\Scripts
D:\miniconda3\Library\bin

验证是否安装成功

conda info

conda 换源

由于 miniconda 下载文件/依赖库等默认的采用国外的服务器,下载速度一言难尽,一般改为国内的清华源/阿里源等方式解决。我这里安装的是清华的源。
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --set show_channel_urls yes # 生成".condarc"文件

虚拟环境设置

conda create –n py38 python=3.8

查看 conda 已有虚拟环境

conda info -e
conda env list

创建虚拟环境

conda create -n "envName" python=3.8

激活环境

activate "envName"
conda activate "envName"
source activate "envName"

退出环境

conda deactivate "envName"

移除环境

conda remove -n "envName" --all

指定环境下安装包

conda list
conda install [packageName]
conda install -n py27numpy
conda search [packageName]
conda uninstall [packageName]

科学计算包

  • numpy
  • pandas
  • scipy
  • scikit-learn

绘图相关包

  • matplotlib
  • seaborn

jupyter notebook

  • jupyter
  • notebook
  • ipykernel
  • nb_conda_kernels

其他

  • beautifulsoup4
  • reportlab
    参考文献:
    ZHIHU

常见问题

Could not fetch URL https:// ssl

使用下面的命令
pip3 install opencv-python-headless==4.6.0.66 -i https://pypi.douban.com/simple --trusted-host pypi.douban.com

  1. http://mirrors.aliyun.com/pypi/simple/ 阿里云
  2. https://pypi.mirrors.ustc.edu.cn/simple/ 中国科技大学
  3. http://pypi.douban.com/simple/ 豆瓣
  4. https://pypi.tuna.tsinghua.edu.cn/simple/ 清华大学
  5. http://pypi.mirrors.ustc.edu.cn/simple/ 中国科学技术大学

matplotlib中文显示

pyplot 并不默认支持中文显示,也没有自带中文字体,因此需要自行下载所需字体,并修改 rcParams 参数来显示中文。

系统 Ubuntu20.04,python3.8.10

  1. 下载并安装simhei
1
2
3
4
5
6
7
pan/01_pei_liup/02_software/linux/simhei.ttf
sudo cp simhei /usr/share/fonts/
sudo mkfontscale
sudo mkfontdir
fc-cache -fv

fc-list :lang=zh
  1. 查看 matplotlib 的字体路径
1
2
3
4
5
6
7
8
(pm25) liupei@asus:~/code/pm25$ python
Python 3.8.10 (default, Sep 28 2021, 16:10:42)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> print(matplotlib.matplotlib_fname())
/home/liupei/code/pm25/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc
>>>

得到的路径是 matplotlib 参数预加载文件matplotlibrc的路径,则字体的存放路径为mpl-data/fonts/ttf。将下载好的字体文件复制到该目录下

  1. 删除 matplotlib 的缓冲目录
    查看 matplotlib 的字体缓存路径:
1
2
3
4
5
6
7
8
(pm25) liupei@asus:~/code/pm25$ python
Python 3.8.10 (default, Sep 28 2021, 16:10:42)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> print(matplotlib.get_cachedir())
/home/liupei/.cache/matplotlib
>>>

得到的路径如~/.cache/matplotlib,在终端使用rm -rf ~/.cache/matplotlib命令删除缓存目录。
这样做之后,在使用 matplotlib 绘图时,会自动生成新的缓存目录。

  1. 设置参数

使用 matplotlib 绘图时,添加以下几行代码:

1
2
3
4
5
6
7
8
9
mpl.rcParams['font.family'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
mpl.rcParams['font.size'] = 8
sns.set(font_scale=0.8,font='SimHei')
# sns.set_style('whitegrid',{'font.sans-serif':['ukai','Book']})
dfData = data.corr()
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Blues")
# plt.savefig('./BluesStateRelation.png')
plt.show()

参考文献:凌云飞鸿

Matplotlib is currently using agg, which is a non-GUI backend

Solution: install any of the matplotlib supported GUI backends

  • however you can also fix the issue by installing any of the matplolib GUI backends like Qt5Agg , GTKAgg , Qt4Agg , etc.
  • for example pip install pyqt5 will fix the issue also
1
pip install pyqt5

test using cat test.py

1
2
3
4
5
6
7
import matplotlib
import pandas as pd
import matplotlib.pyplot as plt

dataInit = pd.DataFrame([1,2,3,4,5,6])
plt.plot(dataInit)
plt.show()

如果出现错误: qt.qpa.plugin: Could not load the Qt platform plugin “xcb” in “ “ even though it was found.

sudo pacman -S tk for arch or manjaro

sudo apt install python3-tk for ubuntu

参考文献: stack over

‘index-url’ in section ‘global’ already exists

vim .config/pip/pip.conf
添加以下内容

1
2
3
4
5
6
7
8
[global]
index-url=https://mirrors.aliyun.com/pypi/simple/
extra-index-url=
https://pypi.tuna.tsinghua.edu.cn/simple/
https://pypi.mirrors.ustc.edu.cn/simple/
https://pypi.douban.com/simple/
[install]
trusted-host=mirrors.aliyun.com

UnicodeDecodeError: ‘gbk’ codec can’t decode

添加 ,encoding='utf-8'
参考文献:csdn

Python 学习项目

100 天学会机器学习

REF

spectral环境配置

1
2
3
4
5
6
7
8
9
10
conda install Numpy pillow wxPython matplotlib IPython PyOpenGL	# supported spectral
cp -rv spectral/ .
python setup.py install # install spectral

pip install scikit-learn # install sklearn
conda install pandas # install pandas
conda install joblib # install joblib
conda install -c https://conda.binstar.org/menpo opencv # install cv2 or
conda install opencv
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python

参考文献:

  1. spectral homepage
  2. github homepage

oc1环境配置

1
2
3
4
5
6
7
8
9
10
11
12
13
mkdir oc1
pip3 install --download oc1/ numpy
pip3 install --download oc1/ git+https://github.com/ AndriyMulyar/sklearn-oblique-tree
tar zcvf oc1.tar.gz oc1/
% upload to server
pip freeze >requirements.txt
pip install --no-index --find-links=oc1/ -r requirements.txt
pip install --no-index --find-links=oc1/ sklearn_oblique_tree
conda list sklearn-oblique-tree
% packages in environment at /public3/home/ch_cumtlp3/ anaconda2/envs/py3:
%
% Name Version Build Channel
sklearn-oblique-tree 1.0.0 pypi_0 pypi

oc1学生REF,oc1教授REF

gcForest

gcForest环境配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
conda install argparse
conda install joblib==0.13.2
conda install keras==2.2.4
conda install psutil==5.6.2
conda install scikit-learn==0.20.3
conda install scipy==1.2.1
conda install simplejson==3.16.0
conda install tensorflow==1.13.1
conda install tensorflow-base==1.13.1
conda install tensorflow-estimator==1.13.0
conda/pip install xgboost==0.82

conda install numpy==1.16.3
conda install pandas==0.24.2
conda install six==1.12.0
conda install sys==5.8
conda install pickle % cannot install
python -V % 2.7.16
conda install argparse joblib keras psutil scikit-learn scipy simplejson tensorflow

参考文献,最新版本,GITHUB, DF21

pytorch

pytorch安装 硬件cpu内存mem显卡(gpu)IP

1
pip3 install torch torchvision -i https://pypi.mirrors.ustc.edu.cn/simple/

ccfs

Rainforth-Canonical Correlation Forests 参考文献.参考文献

CNN

  1. CNN环境配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
conda create -n cnn python=3.5

conda install Numpy pillow wxPython matplotlib IPython PyOpenGL
cp -r installed/spectral/ .
python setup.py install

conda install scipy
conda install scikit-image
# conda install scikit-learn -y # No module named 'sklearn'
pip install -U scikit-learn
# conda install tensorflow
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn tensorflow==1.14.0
conda install six
conda install pandas
conda install matplotlib

conda install -c https://conda.binstar.org/menpo opencv
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python
  1. cnn使用方法
1
2
3
4
5
6
7
8
% 3. 修改 DataSet_Preparation_G.py,
python DataSet_Preparation_G.py | tee out.txt
% 4. 修改 CNN_G.py
python CNN_G.py | tee -a out.txt
% 5. 修改 Decoder_G.py
python Decoder_G.py | tee -a out.txt
./m_oa.py % cal OA
./m_show.py % display results

修改路径:CNN_G.py 中 m_path

1. patchsize.py 修改
2. IndianPinesCNN.py 修改
NUM_CLASSES = 16, 换数据改
CHANNELS = 220 (波段数),换数据改
weights = tf.get_variable(‘weights’, shape=[KERNEL_SIZE, KERNEL_SIZE, CHANNEL, conv1_channels], 换数 据改 (波段数 CHANNELS) % # Conv 1
z = tf.nn.conv2d(x_image, weights, strides=[1, 1, 1, 1], padding=’SAME‘), patchsize>1改为VALID
z = tf.nn.conv2d(h_pool1, weights, strides=[1, 1, 1, 1], padding=’SAME‘), patchsize>1改为VALID
3. DataSet_Preparation_G.py 修改
COUNT=200; 进行过采样之后每一个类别内的样本数目, 基本不改
OUTPUT_CLASSES=16; GT中类别数 (6),换数据改
TEST_FRAC = 0.25; 测试数据百分比, 基本不改
input_mat=scipy.io.loadmat(os.path.join(DATA_PATH,’gf1.mat’))[‘gf1’],换数据-文件夹改
target_mat =scipy.io.loadmat(os.path.join(DATA_PATH,’gf1_gt.mat’))‘gf1_gt’,换数据-文件夹改
TRAIN_PATCH = TRAIN_PATCH. reshape((-1,220,PATCH_SIZE,PATCH_SIZE)) ,[line 178:] (波段数)
注意修改循环次数,GT是通过ENVI ->roi2img ->window save as tif.
4. 修改 CNN_G.py,或, g_cnn.py … based on (a)
TRAIN_FILES = 8, [line 38:]
TEST_FILES = 6, [line 39:]
saver.save([line 225:] (路径m_path)
temp_ image = temp_ image. reshape (temp_ image. shape[0], IMAGE_ SIZE,IMAGE_ SIZE, 220 (波段数), [line 125:]
5. 修改 Decoder_G.py,或 g_decoder.py
from sklearn.metrics import accuracy_score, [line 1:]
input_mat=scipy.io.loadmat(os.path.join(DATA_PATH,’gyl321.mat‘))[‘gyl321‘], [line 24]
target_mat=scipy.io.loadmat(os.path.join(DATA_PATH,’gyl321gt.mat‘))[‘gyl321gt‘], [line 25]
注意修改循环类别个数
model_name = ‘model- spatial- CNN-11X11. ckpt-3999′ (patchsize), [line 28:]

在运行完一个patch_size的值之后,最好文件夹下面所生成的 checkpoint 文件和__pycache__ 文件 删掉,不然会影响不同值的运行.

参考来源1,参考来源2

tr

  1. 配置 pip 源,加快下载速度
1
2
3
pip config list
pip3 config set global.index-url https://pypi.douban.com/simple/
pip config list
  1. 安装软件

python版本为3.7

1
2
3
4
5
6
7
8
9
10
11
pip3 install torch torchvision -i https://pypi.mirrors.ustc.edu.cn/simple/
pip3 install lightning
pip3 install albumentations
yum install gdal
pip3 install rasterio -i https://pypi.mirrors.ustc.edu.cn/simple/
pip3 install opencv-python -i https://pypi.mirrors.ustc.edu.cn/simple/
pip3 install matplotlib -i https://pypi.mirrors.ustc.edu.cn/simple/
pip3 install numpy -i https://pypi.mirrors.ustc.edu.cn/simple/
pip3 install pandas -i https://pypi.mirrors.ustc.edu.cn/simple/
pip3 install scikit-image -i https://pypi.mirrors.ustc.edu.cn/simple/
pip3 install timm

beancount

hledger

Reference

pytorch 安装并配置GPU

  1. 安装
    参考文献
  1. 验证:
    >>> import torch
    >>> torch.__version__
    >>> torch.cuda.is_available()
    >>> torch.cuda.get_device_name(0)

参考文献

评论