分类目录Python

scikit-learn机器学习

from sklearn import metrics

评分函数评估模型性能

对分类器评分
1. metrics.accuracy_score(y_true,y_pred) 准确率
1. metrics.precision_score(y_true,y_pred) 精确率
1. metrics.recall_score(y_true,y_pred) 召回率(敏感率)

对回归器评分
1. metrics.mean_squared_error(y_true,y_pred) 均方差
1. metrics.explained_variance_score(y_true,y_pred) 可释方差
1. metrics.r2_score(y_true,y_pred) R方值


k-NN算法

k邻近算法 一个数据点很可能与它邻近的点属于同类

# 1. 生成训练数据
train_data, labels = generate_data(11)
# 分离标签数据
blue = train_data[labels.ravel() == 0]
red = train_data[labels.ravel() == 1]
# 画出所有点
plot_data(blue, red)

# 2. 训练分类器
# 创建分类器
knn = cv2.ml.KNearest_create()
# 传入训练数据 成功返回True
knn.train(train_data, cv2.ml.ROW_SAMPLE, labels)

# 3. 预测新数据点的类别
# 生成新的点
newcomer, _ = generate_data(1)
# 绘制新的点
plt.plot(newcomer[0, 0], newcomer[0, 1], 'go', markersize=14)
plt.show()
# 根据最近邻数据点的标签预测新数据点的标签
ret, results, neighbor, dist = knn.findNearest(newcomer, k=3)
print('Predicted label: \t', results)
print('Neighbor label: \t', neighbor)
print('Distance to Neighbor: ', dist)

回归模型预测连续后果

  1. 线性回归, 通过特征的线性组合描述目标变量 如房价预测
    linreg = linear_model.LinearRegression()
    正侧化-降低过拟合过程,
    L1-Lasso回归 linreg = linear_model.Lasso()
    L2-ridge回归 linreg = linear_model.Ridge() /linear_model.RidgeRegression()
  2. 逻辑回归 用于目标的分类模型,把任意输入的实值x转为0~1区间的一个预测值,比如判定物品的种类
    linreg = cv2.ml.LogisticRegression_create()

特征工程

特征选择,特征提取

  1. 数据预处理
    数据格式化,数据清理,数据采样

    1. 特征标准化
      每个点减去所有数据的平均值再除以方差
      x_scaled = preprocessing.scale(x)
      x_scaled.mean(axis=0) 每行均值近似为0 x_scaled.std(axis=0) 每行方差为1
    2. 特征归一化
      L1范数(曼哈顿距离) l1=preprocessing.normalize(X,norm=’l1′)
      L2范数(欧氏距离) l2=preprocessing.normalize(X,norm=’l2′)
    3. 特征缩放在一定范围,一般0~1内
      min_max_scaler = preprocessing.MinMaxScaler() or MinMaxScaler(feature_range(-10,10))
      X_min_max = min_max_scaler.fit_transform(x)
    4. 特征二值化
      binarizer = preprocessing.Binarizer(threshold=0.5)
    5. 缺失数据处理
      mean将nan值换为指定坐标元素的平均值,默认axis=0
      median将nan值换为指定坐标元素的中值,默认axis=0
      most_frequest将nan值换为指定坐标元素中出现频率最高值,默认axis=0
      imp = preprocessing.Imputer(strategy=’mean’)
      x2= imp.fit_transform(x)
  2. 理解降维
    1. 主要成分分析PCA
      特征向量x和y组合成一个特征矩阵X
      x=np.vstack((x,y)).T
      矩阵X上计算PCA,mu投影前减去的平均值eig协方差矩阵的特征向量
      mu, eig = cv2.PCACompute(X,np.array([]))
      旋转投影数据
      x2=cv2.PACAProject(X,mu,eig)
    2. 独立成分分析ICA
      ica=decomposition.FastICA()
      x2=ica.fit_transform(x)
    3. 非负矩阵分解NMF
      nmf = decomposition.NMF()
      x2=nmf.fit_transform(x)
  3. 类别变量表示 类别特征(离散特征)
    独热编码 form sklearn.feature_extraction import DictVectorizer
    vec = DictVectorizer(aparse=False,dtype=int) or aparse=True稀疏矩阵紧凑表示
    vec.fit_transform(data)
    查看特征的顺序表
    vec.get_feature_names()
    某些算法如决策树,本身可以处理类别特征,不再需要使用独热编码

  4. 文本特征表示

    1. 单词计数 缺点:频繁出现的单词赋予过大权重
      form sklearn.feature_extraction.text import CountVectorizer
      vec = CountVectorizer()
      x = vec.fit_transform(data) 将特征矩X保存为一个稀疏矩阵
      x.toarray() 稀疏矩阵转换为常规数组
      vec.get_feature_names() 查看特征名字
      1.词频-逆文档频率TF-IDF 衡量单词在整个数据中出现的频率计算权重
      form sklearn.feature_extraction.text import TfidfVectorizer
      vec = TfidfVectorizer()
      x = vec.fit_transform(data) 将特征矩X保存为一个稀疏矩阵
      x.toarray() 稀疏矩阵转换为常规数组
  5. 图像表示
    1.使用色彩空间

    1. RGB,openCV中是BGR
      img_rgb=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    2. HSV / HLS /LAB / YUV
      cv2.COLOR_BGR2HSV …

    2.图像角点检测

    1. Harris角点检测(仅灰度图像) corners=cv2.cornerHarris(img_gray,blockSize,Ksize,k)
    2. Shi-Tomasi角点检测 cv2.goodFeaturesToTrack

    3.尺度不度特征变换SIFT
    sift = cv2.xfeatures2d.SIFT_create()

    1. kp = sift.detect(img_bgr) 关键点
      关键点可视化
      img_kp = np.zeros_like(img_bgr)
      img_kp = cv2.drawkeypoints(img_rgb,kp,img_kp,flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
      plt.show()
      计算关键点的特征值
      kp,des=sift.compute(img_bgr,kp) des的每个关键点有128个特征值
    2. 一步检测关键点并计算出特征描述符
      kp2,des2=sift.detectAndCompute(img_bgr,None)
      可以比较des与des2是否相等 print(np.allclose(des,des2))

    4.加速键状特征SURF
    与SIFT一样使用,且商业使用需要授权,比SIFT能得到更多特征,速度更快
    surf = cv2.xfeatures2d.SURF_create()

    5.cv2.ORB 开源代替SIFT,SURF方案
    使用FAST关键点检测子和BRIEF描述符


决策树

决策树是一个简单有效的监督学习算法
1. 数据预处理
得到训练集和测试集
1. 构建决策树
dtree=cv2.ml.dtree_create()
1. 训练决策树
dtree.train=(X_train,cv2.ml.ROW_SAMPLE,y_train)
1. 预测新数据点标签类别
y_pred=dtree.predict(x_test)
1. 检测算法性能-准确率
metrics.accuracy_score(y_test,dtree.predict(X_test)) 测试样本
metrics.accuracy_score(y_train,dtree.predict(X_train)) 训练数据

  1. 可视化训练决策树
    from sklearn import tree
    构造一个空的决策树
    dtc = tree.DecisionTreeClassifier(class_weigth=None,criterion=’gini’ ,max_depth=None,max_features=None,max_leaf_nodes=None,min_impurity_split=1e-07,min_samples_leaf=1,min_samples_split=2,min_weight_fraction_leaf=0.0,presort=False,random_state=None,splitter=’best’)
    fit训练决策树
    dtc.fit(X_train,y_train)
    DecisionTreeClassifier()
    测试准确率
    dtc.score(X_train,y_train)
    dtc.score(X_test,y_test)
    生成决策树文件.Pdf
    $conda install graphviz
    with open(‘tree.dot’,’w’): f=tree.export_graphviz(clf,out_file=f)
    $dot -Tpng tree.dot -o tree.png
    特征重要性评分
    dtc.feature_importances_
    决策规则
    criterion=’gini’ 基尼不纯度,目标是最小化分类错误的概率
    criterion=’entropy’ 信息增益,计算熵,选最低的,完美为0
    控制树的复杂度,避免过拟合,使用预剪枝和后剪枝
    max_depth控制最大深度
    max_leaf_nodes 最多叶结点数量
    min_samples_split 最小数据点数量持续对决策树进行分割
    更复杂的场景使用随机森林

线性回归不能使用gini,entropy,作为代替mse方差缩减,计算真实值和预测值的均方误差 mae计算真实值和预测值的平均绝对值差


支持向量机 SVM

是一种二分化模型,把无法线性分隔的数据映射到高维空间后再找到分类器最优的线性分类器,是一种基于关键点的分类算法,支持向量是离分类器最近的那些点.机器是指分类器,离分类器最近的点到分类器的距离称为间隔,希望间隔尽可能大,就会更准确,也称最大边缘分类器
1. opencv
生成用于后续训练的空分类器模型
svm = cv2.ml.SVM_create()
训练结果 = svm.train(训练数据,训练数据排列格式,训练数据的标签)
训练数据排列格式 cv2.ml.ROW_SAMPLE 按行 cv2.ml.COL_SAMPLE 按列
(返回值,返回结果) = svm.predict(测试数据)
参数调整:setType()设置类别 setKernel()设置核类型 setC()设置支持向量机的参数C(惩罚系数,对误差的宽容度,默认0)
1. sk-learn库
生成可以控制大小和复杂度的随机数据集
make_classification生成随机的n类分类问题,make_regression随机的回归问题,
X, y = datasets.make_classification(n_samples=100, n_features=2,n_redundant=0, n_classes=2,random_state=7816)
方向梯度直方图HOG,是一个图像的特征描述符,常用于人物人类,基本思想对像的局部形状和外观可以使用边缘方向的分布来表示,特别适合纹理丰富的数据.
hog = cv2.HOGDescriptor(win_size, block_size, block_stride, cell_size, num_bins)
调用hog.compute构建样本
X_pos.append(hog.compute(img, (64, 64)))

  1. LIBSVM

贝叶斯学习

一个事件的发生概率可以基于条件的先验知识进行估计,可以用于数据分类,分类正确概率估计.
判别模型,生成模型

# 使用正态贝叶斯分类器
model_norm = cv2.ml.NormalBayesClassifier_create()
# 训练
model_norm.train(X_train, cv2.ml.ROW_SAMPLE, y_train)
# 预测测试
_, y_pred = model_norm.predict(X_test)
# 预测测试评分
print(metrics.accuracy_score(y_test, y_pred))

# 使用朴素贝叶斯分类器
model_naive = naive_bayes.GaussianNB()
# 训练分类器
model_naive.fit(X_train, y_train)
GaussianNB(priors=None)
# 对分类器打分
print('GaussianNB score:', model_naive.score(X_test, y_test))
# 显示决策边界
plot_decision_boundary(model_norm, X, y)
plt.show()
# 预测测试数据,返回y_proba真正概率
yprob = model_naive.predict_proba(X_test)
print(yprob.round(2))

# 使用完整数据训练,需要更复杂的方法,sklearn中的朴素贝叶斯分类器可以处理稀疏矩阵
model_naive = naive_bayes.MultinomialNB()
model_naive.fit(X_train, y_train)

# 使用n-gram提升结果,考虑单词的顺序,但对于更长的文本无法有效的评估权重
counts = feature_extraction.text.CountVectorizer(ngram_range=(1, 2))
X = counts.fit_transform(data['text'].values)
# 分隔
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.2, random_state=42)
# 训练数据
model_naive = naive_bayes.MultinomialNB()
model_naive.fit(X_train, y_train)
MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True)

# 使用TD-IDF提升结果 词频-逆文档频率
tfidf = feature_extraction.text.TfidfTransformer()
X_new = tfidf.fit_transform(X)
X_train, X_test, y_train, y_test = ms.train_test_split(X_new, y, test_size=0.2, random_state=42)
model_naive = naive_bayes.MultinomialNB()
model_naive.fit(X_train, y_train)

非监督学习

降维,因子分析,聚类分析,评估方式使用手动检查,可以作为预处理或特征提取的步骤.
retval,bestLabels,centers = cv2.kmeans(data,K,bestLables,criteria,attempts,flags)
retval 距离值,返回每个点到相应中心距离的平方和,较高紧凑度表明所有点更靠近它们的聚类中心
bestLabels 各个数据点的最终分类标签(索引)
centers 每个分类的中心点数据
data 待处理的数据集合,np.float32类型,每个特征单独一列中
K 要分出簇的个数,常见2,表示2分类
bestLables 各个数据点的最终分类标签(索引),实际中设为None
criteria 算法迭代的终止条件,达到最大循环数目和指定精度阀值时终止,由3个参数构成type,max_iter,eps
type: cv2.TEEM_CRITERIA_EPS 精度满足 MAX_ITER 迭代次数超过阀值max_iter时停止 _EPS+MAX_ITER两个任意一个满足停止
max_iter 最大迭代次数
eps 精确度的阀值
attempts 使用不用的初始值多次(attempts次)偿试
flags 选择初始中心点的方法,主要有3种cv2.KMEANS_RANDOM_CENTERS 随机 cv2.KMEANS_PP_CENTERS基于中心算法 cv2.KMEANS_USE_INITIAL_LABELS 使用用户输入的数据作为第一次分类的中心点,需要多次偿试时后续使用随机或半随机值作为第一次分类中心点

迭代方法,k均值聚类期望最大化 , 高斯混合模型GMM

局限性
无法保证全局最优解(常常让算法在多个初始状态运行)
必须知道聚类个数(肘部法则,轮廓分析,高斯混合模型GMM使用贝叶斯信息准则获得正确数量,具有噪声的基于密度聚类DBSCAN,邻近传播算法)
决策边界是线性的(sklearn谱聚类SpectralClustering)
处理大数据时非常慢(sklearn谱聚类cluster.MiniBatchKMeans)

应用
压缩色彩空间 虽丢失一些细节,介仍可以清楚被识别,另一个方法使用双边滤波器
进行图像分类
字类识别
组织成层次树(c++API 快速最近邻逼近搜索函数cv::flann:hierarchicalClustering sklern自行实现cluster.AgglomerativeClustering)

# 创建4个不同的聚类,一共300个数据点
X, y_true = make_blobs(n_samples=300, centers=4, cluster_std=1.0, random_state=10)
# 算法迭代的终止条件
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# 选择初始中心点的方法
flags = cv2.KMEANS_RANDOM_CENTERS
# 聚类分析 指定聚类4,算法初始随机选择尝试次数10
compactness, labels, centers = cv2.kmeans(X.astype(np.float32), 4, None, criteria, 10, flags)

深度学习

人工神经网络 Google-DeepMind Facebook-DeepFace, Keras
McCulloch-Pitts神经元:本质上是一个线性的二元分类器,一般需要训练数据,代价函数,学习规则
感知器:只有当数据是线性可分,且学习率足够小的情况下,感知学习规则才可以保证收敛于最优解
把感知器应用到线性不可分的数据上时,测试结果失败,不存在一条直线可以完美分割
多层感知器MLP,万能逼近特性,给它足够的神经元和层,基本上可以学习任意的输入-输出函数
梯度下降:陷入局部最小值,解决方法可以添加噪声
使用反向传播训练多层感知器,用于估计神经网络中代价函数梯度, 链式法则

# 创建MLP分类器
mlp = cv2.ml.ANN_MLP_create()
# 第一层两个神经元
n_input = 2
# 单个隐藏层8个神经元
n_hidden = 8
# 最后一层两个神经元
n_output = 2
mlp.setLayerSizes(np.array([n_input, n_hidden, n_output]))

# 定制MLP分类器
# 定义网络中每个神经元的激活函数,可以使用自定或openCV
mlp.setActivationFunction(cv2.ml.ANN_MLP_SIGMOID_SYM, 2.5, 1.0)
# 定义一个合适的训练方法
mlp.setTrainMethod(cv2.ml.ANN_MLP_BACKPROP)
# 设置训练过程的终止条件
term_mode = cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS
term_max_iter = 300
term_eps = 0.01
mlp.setTermCriteria((term_mode, term_max_iter, term_eps))

# openCV提供激活函数
# cv2.ml.ANN_MLP_IDENTITY 线性激活函数f(x)=x
# cv2.ml.ANN_MLP_SIGMOID_SYM 对称的sigmoid双曲正切
# cv2.ml.ANN_GAUSSIAN 高斯函数 贝尔曲线

# 训练方法
# cv2.ml.ANN_MLP_BACKPROP 反向传播算法,通过mlp.setBackpropMomentumScale 和 mlp.setBackpropWeightScale设置额外的比例因子
# cv2.ml.ANN_MLP_RPROP Rprop算法 通过mlp.setRpropDW0, mlp.setRpropDWMax, mlp.setRpropDWMin, mlp.setRpropDWMinus,  \
#                              mlp.setRpropDWPlus设置额外的参数

# 训练MLP分类器
mlp.train(X, cv2.ml.ROW_SAMPLE, y)
# 预测目标标签
_, y_hat = mlp.predict(X)
# 测量准确率
print(accuracy_score(y_hat.round(), y))


深度学习,人工神经网络开源学习框架
谷歌 TensorFlow
微软 Cognitive Toolkit CNTK
加州大学伯克利分校 Caffe
蒙特利尔大学 Theano
Torch 基于Lua编程语言
Keras 定位一个接口


不同的算法组合

装袋方法(Bagging)
提升方法(Boosting)
随机森林(Random Forest)
自适应提升(AdaBoost)

合适的模型

选择正确的模型就是在偏差和方差之间找一个平衡

交叉验证
常用k折交叉验证,k是用户指定的数字(一般5或10),数据被分成大小差不多相等的k个部分,叫作折,使用k-1折用于训练,另一折用于测试,过程重复进行k次迭代,每次选择不同的折进行测试.
比把数据集分割为训练集和测试集更加稳定和全面

留一法交叉验证

自举
通过使用替代的方法来抽取样本

评估结果’
T检验 两个数据样本是否来自于相同的平均值或者期望值的潜在分布,返回参数p来接受或者驳回一个虚假设,p在0~1内,p=0.05表示这个虚假设仅在100次中正确5次
配对卡方检验 可以用在对对的数据上,来确定两个样本之间是否有任何差异

数据分类:
训练集: 用于构建模型
验证集: 用于选择模型的参数
测试集: 用于评估最终模型的性能

网格搜索结合交叉验证 GridSearchCV
网格搜索嵌套交叉验证
F值(计算精准率和召回率的调和平均值) 公式 2(精准率X召回率)/(精准率+召回率)
设置作业点 PR曲线工具
回归指标:
1. 均方误差 sklearn.metrics.mean_squared_error
1. 可释方差sklearn.metrics.explained_variance_score
1. R2值 sklearn.metrics.r2_score 大部分应用,使用默认的R2就够了
管道 Pipeline


如何解决问题

  1. 问题分类
    1. 按输入分类: 数据已标记,监督学习,通过环境交互来优化,强化学习,没有被标记,非监督学习
    2. 按输出分类: 输出的是数字,回归问题,输出是一个类,分类问题
  2. 找到可用的算法
    可参见速查表 http://aka.ms/MLCheatSheet
  3. 原型构建(实现所有适用的算法)
    1. 使用最少的特征工程,临时应急地实现多个算法
    2. 理想情况下,可以设置一个机器学习管道,使用一组精心准备的指标评测
    3. 特征工程 很重要
    4. 优化超参数

构建自己的估计器

  1. ClassifierMixin if you are writing a classifier (will provide a basic score method) 写一个分类器时
  2. RegressorMixin if you are writing a regressor (will provide a basic score method) 写一个回归器时
  3. ClusterMixin if you are writing a clustering algorithm (will provide a basic fit_predict method) 写一个聚类算法时
  4. TransformerMixin if you are writing a transformer (will provide a basic fit_predict method) 写一个转换器时

    importing BaseEstimator and ClassifierMixin
    class MyClassifier(BaseEstimator, ClassifierMixin):

常用数据集

  1. scikit-learn 内置数据样集
  2. scikit-learn 外部服务载入 mldata.org 参考http://scikit-learn.org/stable/datasets/index.html
  3. Kaggle http://www.kaggle.com 经常比赛,提供一个特定要优化的指标
  4. OpenML http://www.openml.org
  5. 加州大学欧文分校 http://archive.ics.uci.edu/ml/index.php

pysimplegui

https://pysimplegui.readthedocs.io/en/latest/

pip install pysimplegui
pip3 install pysimplegui

sudo apt-get install python3-tk


import PySimpleGUI as sg
print(sg)
print(sg.version)

Popup(args=*<1 or N object>,
    title=None,
    button_color=None,
    background_color=None,
    text_color=None,
    button_type=0,
    auto_close=False,
    auto_close_duration=None,
    custom_text=(None, None),
    non_blocking=False,
    icon=None,
    line_width=None,
    font=None,
    no_titlebar=False,
    grab_anywhere=False,
    keep_on_top=False,
    location=(None, None),
    any_key_closes=False,
    image=None,
    modal=True)

sg.popup('popup')  # Shows OK button
sg.popup_ok('popup_ok')  # Shows OK button
sg.popup_yes_no('popup_yes_no')  # Shows Yes and No buttons
sg.popup_cancel('popup_cancel')  # Shows Cancelled button
sg.popup_ok_cancel('popup_ok_cancel')  # Shows OK and Cancel buttons
sg.popup_error('popup_error')  # Shows red error button
sg.popup_timed('popup_timed')  # Automatically closes
sg.popup_auto_close('popup_auto_close')  # Same as PopupTimed

popup_scrolled(args=*<1 or N object>,
    title=None,
    button_color=None,
    background_color=None,
    text_color=None,
    yes_no=False,
    auto_close=False,
    auto_close_duration=None,
    size=(None, None),
    location=(None, None),
    non_blocking=False,
    no_titlebar=False,
    grab_anywhere=False,
    keep_on_top=False,
    font=None,
    image=None,
    modal=True)
sg.popup_scrolled(my_text)
sg.popup_scrolled(my_text, size=(80, None))

popup_no_wait(args=*<1 or N object>,
    title=None,
    button_type=0,
    button_color=None,
    background_color=None,
    text_color=None,
    auto_close=False,
    auto_close_duration=None,
    non_blocking=True,
    icon=None,
    line_width=None,
    font=None,
    no_titlebar=False,
    grab_anywhere=False,
    keep_on_top=False,
    location=(None, None),
    image=None,
    modal=False)

popup_get_text(message,
    title=None,
    default_text="",
    password_char="",
    size=(None, None),
    button_color=None,
    background_color=None,
    text_color=None,
    icon=None,
    font=None,
    no_titlebar=False,
    grab_anywhere=False,
    keep_on_top=False,
    location=(None, None),
    image=None,
    modal=True)
text = sg.popup_get_text('Title', 'Please input something')
sg.popup('Results', 'The value returned from PopupGetText', text)

popup_get_file(message,
    title=None,
    default_path="",
    default_extension="",
    save_as=False,
    multiple_files=False,
    file_types=(('ALL Files', '*.*'),),
    no_window=False,
    size=(None, None),
    button_color=None,
    background_color=None,
    text_color=None,
    icon=None,
    font=None,
    no_titlebar=False,
    grab_anywhere=False,
    keep_on_top=False,
    location=(None, None),
    initial_folder=None,
    image=None,
    modal=True)

popup_get_folder(message,
    title=None,
    default_path="",
    no_window=False,
    size=(None, None),
    button_color=None,
    background_color=None,
    text_color=None,
    icon=None,
    font=None,
    no_titlebar=False,
    grab_anywhere=False,
    keep_on_top=False,
    location=(None, None),
    initial_folder=None,
    image=None,
    modal=True)

popup_animated(image_source,
    message=None,
    background_color=None,
    text_color=None,
    font=None,
    no_titlebar=True,
    grab_anywhere=True,
    keep_on_top=True,
    location=(None, None),
    alpha_channel=None,
    time_between_frames=0,
    transparent_color=None,
    title="",
    icon=None)

one_line_progress_meter(title,
    current_value,
    max_value,
    key="OK for 1 meter",
    args=*<1 or N object>,
    orientation="v",
    bar_color=(None, None),
    button_color=None,
    size=(20, 20),
    border_width=None,
    grab_anywhere=False,
    no_titlebar=False)
for i in range(1,10000):
    sg.one_line_progress_meter('My Meter', i+1, 10000, 'key','Optional message')

Debug Output(easy_print = Print = eprint)
for i in range(100):
    sg.Print(i)

sg.theme('Dark Blue 3')  # please make your windows colorful
layout = [ [sg.Text('Enter a Number')],
           [sg.Input()],
           [sg.OK()] ],
           [sg.InputText(), sg.FileBrowse()],
           [sg.Submit(), sg.Cancel()]]

window = sg.Window('Enter a number example', layout)
event, values = window.read()

使用菜单
# ------ Menu Definition ------ #
menu_def = [['&File', ['&Open', '&Save', 'E&xit', 'Properties']],
            ['&Edit', ['Paste', ['Special', 'Normal', ], 'Undo'], ],
            ['&Help', '&About...'], ]
layout = [
    [sg.Menu(menu_def, tearoff=True)],

    # 定义右键菜单
    right_click_menu = ['Unused', ['Right::_Right_', '!&Click', '&Menu', 'E&xit', 'Properties']]
    # 定义布局
    layout = [[sg.Menu(menu_def, tearoff=False, pad=(20,1))],
               # 底部菜单
              [sg.ButtonMenu('ButtonMenu',key='-BMENU-', menu_def=menu_def[0])],]
    # 定义 Window
    window = sg.Window("Windows-like program",layout,
                       default_element_size=(12, 1),
                       grab_anywhere=True, # 非阻塞
                       right_click_menu=right_click_menu, # 添加右键菜单
                       default_button_element_size=(12, 1)
                      )
'Right::_Right_' 是指定该菜单的 Key 的方式。!禁用

Theme Name
There are 130 themes available. You can preview these themes by calling theme_previewer() which will create a LARGE window displaying all of the color themes available. Default is Dark Blue 3
Dark Color #
or
Light Color #
DarkAmber
    # print(sg.ListOfLookAndFeelValues())
    # ['SystemDefault', 'Reddit', 'Topanga', 'GreenTan', 'Dark', 'LightGreen', 'Dark2', 'Black', 'Tan', 'TanBlue',
    # 'DarkTanBlue', 'DarkAmber', 'DarkBlue', 'Reds', 'Green', 'BluePurple', 'Purple', 'BlueMono', 'GreenMono',
    # 'BrownBlue', 'BrightColors', 'NeutralBlue', 'Kayak', 'SandyBeach', 'TealMono']
sg.theme()窗口样式
sg.theme('BluePurple')
要查看您的PySimpleGUI版本的上述预览,请进行以下调用以生成所有可用主题的预览:
sg.theme_previewer()
如果您想在系统上看到一个窗口,如上面的主题预览屏幕截图,那么进行此调用,您将看到相同的窗口:
import PySimpleGUI as sg
sg.preview_all_look_and_feel_themes()
您还可以通过致电获取主题名称列表 theme_list
import PySimpleGUI as sg
theme_name_list = sg.theme_list()


Making your window modal
To make a Modal Wio=ndow you have 2 options.
    Set the moodel=True parameter in your Window calls.
    Call the method Window.make_modal() to chance a window from non-modal to modal. There is no modal to non-modal. Don't see the need for one. If one comes up, sure!
MPORTANT - Many of the Window methods require you to either call Window.read or Window.Finalize (or set finalize=True in your Window call) before you call the method. This is because these 2 calls are what actually creates the window using the underlying GUI Framework. Prior to one of those calls, the methods are likely to crash as they will not yet have their underlying widgets created.

"Elements" are the building blocks used to create windows. Some GUI APIs use the term "Widget" to describe these graphic elements.
    Text
    Single Line Input
    Buttons including these types:
        File Browse
        Folder Browse
        Calendar picker
        Date Chooser
        Read window
        Close window ("Button" & all shortcut buttons)
        Realtime
    Checkboxes
    Radio Buttons
    Listbox
    Slider
    Multi-line Text Input/Output
    Multi-line Text Output (not on tkinter version)
    Scroll-able Output
    Vertical Separator
    Progress Bar
    Option Menu
    Menu
    ButtonMenu
    Frame
    Column
    Graph
    Image
    Table
    Tree
    Tab, TabGroup
    StatusBar
    Pane
    Stretch (Qt only)
    Sizer (plain PySimpleGUI only)

Text Element | T == Txt == Text
Window.FindElement(key) shortened to Window[key]
window['-MULTILINE KEY-'].print('My variables are', a, b, c)     # Routed to your multiline element
Text Input Element | InputText == Input == In
Combo Element | Combo == InputCombo == DropDown == Drop
layout = [[sg.Listbox(values=['Listbox 1', 'Listbox 2', 'Listbox 3'], size=(30, 6))]]
layout = [[sg.Slider(range=(1,500),default_value=222,size=(20,15),orientation='horizontal',font=('Helvetica', 12))]]
layout =  [[sg.Radio('My first Radio!', "RADIO1", default=True),sg.Radio('My second radio!', "RADIO1")]]
Checkbox Element | CBox == CB == Check
layout =  [[sg.Checkbox('My first Checkbox!', default=True), sg.Checkbox('My second Checkbox!')]]
layout =  [[sg.Spin([i for i in range(1,11)], initial_value=1), sg.Text('Volume level')]]
layout = [[sg.Image(r'C:\PySimpleGUI\Logos\PySimpleGUI_Logo_320.png')],]
Button Element
    Button= ReadButton = RButton = ReadFormButton (Use Button, others are old methods)
    CloseButton = CButton
    RealtimeButton
    DummyButton
    layout =  [[sg.Button('Ok'), sg.Button('Cancel')]] layout =  [[sg.Ok(), sg.Cancel()]]
Button Element Shortcuts
    OK
    Ok
    Submit
    Cancel
    Yes
    No
    Exit
    Quit
    Help
    Save
    SaveAs
    Open
Chooser" Buttons
These buttons are used to show dialog boxes that choose something like a filename, date, color, etc.. that are filled into an InputText Element (or some other "target".... see below regarding targets)
    CalendarButton
    ColorChooserButton
    FileBrowse
    FilesBrowse
    FileSaveAs
    FolderBrowse
he code for the entire window could be:
layout = [[sg.T('Source Folder')],
              [sg.In()],
              [sg.FolderBrowse(target=(-1, 0)), sg.OK()]]
or if using keys, then the code would be:
layout = [[sg.T('Source Folder')],
              [sg.In(key='input')],
              [sg.FolderBrowse(target='input'), sg.OK()]]
sg.Button('Restart Song', button_color=(sg.theme_background_color(), sg.theme_background_color()),
               image_filename=image_restart, image_size=(50, 50), image_subsample=2, border_width=0)
VerticalSeparator(pad=None)
sg.OneLineProgressMeter('My Meter', i+1, 1000,  'key', 'Optional message')
Output(size=(80,20))


Qt Designer

https://github.com/nngogol/PySimpleGUIDesigner
pip install PySimpleGUIDesigner

Use GUI(by default):
PySimpleGUIDesigner

Use CLI:
PySimpleGUIDesigner -xml “~/folder1/test.ui” -ob “somegroupBox”

#removing (if installed) PySimpleGUIDesigner: 源码安装
pip uninstall -y PySimpleGUIDesigner

mkdir psgdesigner
cd psgdesigner
git clone https://github.com/nngogol/PySimpleGUIDesigner
python3 -m PySimpleGUIDesigner

python3 main.py –xmlfile=”~/folder1/test.ui” –objname=”somegroupBox”
#a bit shorter command:
python3 main.py -xml “~/folder1/test.ui” -ob “somegroupBox”

macOS Catalina上python调用摄像头权限问题

  1. xcode
    1)打开Xcode,新建项目,选择macOS,App。
    2)完善项目信息:
    Product Name: pycharm
    Organization Identifier: com.jetbrains
    Bundle identifier: com.jetbrains.pycharm
    Language: Swift
    User Interface: Storyboard
    3)打开Info.plist文件 ,添加Privacy – Camera Usage Description,属性为:Give me my camera access!
    4)打开AppDelegate.swift文件,导入库新增:
    import AVKit
    5)applicationDidFinishLaunching() 函数中,添加代码:
    AVCaptureDevice.requestAccess(for: .video) { _ in }

然后运行项目,OK允许

  1. Iterm2
    系统当前 shell
    $ cat /etc/shells
    当前使用的shell
    echo $SHELL
    切换到zsh
    chsh -s /bin/zsh

bash的配置文件是 -/.bash_profile
zsh的配置文件是-/.zshrc

安装iTerm2
iTerm2下载地址:https://www.iterm2.com/downloads.html
brew cask install iterm2

安装oh my zsh
通过curl安装:
sh -c “$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)”
或通过wget安装:
sh -c “$(wget -O- https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)

‘/Applications/IntelliJ IDEA.app/Contents/MacOS/idea’

python开发工具

pycharm
https://www.jetbrains.com/pycharm/

IDEA加装插件
python
python文件都必须要有明确的程序入口才能执行,不像自己随便写写的一个print一样。也就是说,必须要有

if __name__ == '__main__':

Mac下Python环境搭建、多版本管理

通过brew安装pyenv

1)命令行输入:
$ brew install pyenv(如果一直卡在Updating Homebrew就按ctrl+c一次跳转brew update)

2)在home目录的 .bash_profile文件中添加:
vi ~/.bash_profile 在最后增加
eval "$(pyenv init -)"
根据提示需要添加
==> readline
readline is keg-only, which means it was not symlinked into /usr/local,
because macOS provides BSD libedit.

For compilers to find readline you may need to set:
  export LDFLAGS="-L/usr/local/opt/readline/lib"
  export CPPFLAGS="-I/usr/local/opt/readline/include"

For pkg-config to find readline you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/readline/lib/pkgconfig"

3)命令行输入,更新一下环境变量:
$ source .bash_profile
注意:没有配置的话无法进行python版本间的切换。

$ pyenv
pyenv 1.2.18
Usage: pyenv <command> [<args>]

Some useful pyenv commands are:
   commands    列出所有pyenv可用的命令
   exec        Run an executable with the selected Python version
   local       设置或显示本地应用程序特定的Python版本
   global      设置或显示系统全局的Python版本
   shell       设置或显示shell外壳的Python版本
   install     使用python-build安装指定Python版本
   uninstall   卸载已经安装的Python
   rehash      刷新 pyenv shims (安装之后运行这个)
   version     查看当前使用的版本
   versions    列出已经安装的Python版本,当前激活版本用*号标注
   which       显示的完整路径的可执行文件
   whence      列出包含给定的可执行所有的Python版本

使用pyenv安装Python3
1)查看当前激活的是那个版本的Python
pyenv version

2)安装需要的版本:
$ pyenv install 3.7.4 -v (看有哪一些版本可以安装:pyenv install --list)

3)完成后更新数据库:
$ pyenv rehash

4)查看系统已安装的版本:
$ pyenv versions
*号表示系统当前正在使用的版本

5)切换python版本
$ pyenv global 3.6.2
$ pyenv global system

6)确认python版本
python --version

系统全局用系统默认的Python比较好,不建议直接对其操作
pyenv global system
用local进行指定版本切换,一般开发环境使用。
pyenv local 2.7.10
对当前用户的临时设定Python版本,退出后失效
pyenv shell 3.5.0
取消某版本切换
pyenv local 3.5.0 --unset
优先级关系:shell——local——global

删除python
python3版本查看

$ python3 --version
Python 3.7.1
删除Python 3.7 框架:
$ ls /Library/Frameworks/Python.framework/Versions/
3.7
$ sudo rm -rf /Library/Frameworks/Python.framework/Versions/3.7

 删除Python 3.7 应用目录:
$ cd /Applications
$ sudo rm -rf Python\ 3.7/   #Python 3.7存在空格
查看launchpad中python3的IDLE就被删除了

删除/usr/local/bin 目录下指向的Python3.7 的连接:
$ cd /usr/local/bin/
$ ls -l /usr/local/bin
$ rm Python3.7相关的文件和链接 #Python3.7相关的文件和链接需要你自行确认
Python3.7 对应的文件和链接最好删除干净;无法确认的文件和链接就上网搜一下Bing
bin下面要删除这些,防止下次又找
➜ bin rm pydoc3
➜ bin rm pydoc3.7
➜ bin rm python3
➜ bin rm python3-config
➜ bin rm python3.7
➜ bin rm python3.7-config
➜ bin rm python3.7m
➜ bin rm python3.7m-config
➜ bin rm pyvenv
➜ bin rm pyvenv-3.7
➜ bin rm pip3
➜ bin rm pip3.7
➜ bin rm 2to3
➜ bin rm 2to3-3.7
➜ bin rm easy_install-3.7
➜ bin rm idle3
➜ bin rm idle3.7

删除python的环境路径
$ vi ~/.bash_profile
删除Python3.7设置的环境路径。

确认python是否已经删除
$ python3
-bash: python3: command not found