糖尿病预测(*小二乘回归)

糖尿病预测(*小二乘回归)

import numpy as np
from sklearn.datasets import load_diabetes
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd

feature,label = load_diabetes(return_X_y=True)
bias = np.ones(feature.shape[0]).reshape(-1,1)
feature = np.hstack((bias,feature))
pData = np.hstack((feature,label.reshape(-1,1)))
data = pd.DataFrame(pData)
data = data.sample(len(data),random_state=0)

def mean_square_error(prediction,real):
real = real.flatten()
return np.sum((prediction – real) ** 2)/len(real)

def r2_score(prediction,real):
real = real.flatten()
mean = np.mean(real)
Z = np.sum((prediction – real) ** 2)
M = np.sum((real – mean) ** 2)
return 1 – Z/M

class Regression:
def fit(self,X,y):
X = np.matrix(X)
y = np.matrix(y).reshape(-1,1)
self.w = (X.T * X).I * X.T * y

def predict(self,X):
X = np.matrix(X)
return np.array(X * self.w).flatten()

train_len = 350
train_X = data.iloc[:train_len,:-1]
train_y = data.iloc[:train_len,-1]
test_X = data.iloc[train_len:,:-1]
test_y = data.iloc[train_len:,-1]
test_y = np.array(test_y)

model = Regression()
model.fit(train_X,train_y)
result = model.predict(test_X)

MSE = mean_square_error(result,test_y)
R2 = r2_score(result,test_y)

print(“MSE: ” + str(MSE) + “\nR2: ” + str(R2))
plt.figure(figsize=(50,50))
plt.plot(result,”go–“,label = “prediction”,lw = 15,ms = 35)
plt.plot(test_y,”ro-“,label = “real”,lw = 10,ms = 25)
plt.xlabel(“Samples”,fontsize = 40)
plt.ylabel(“Value”,fontsize = 40)
plt.tick_params(labelsize = 25)
plt.legend(prop={‘size’: 60})
plt.savefig(‘diabets.png’)
plt.show()

%title插图%num

正则表达式的学习笔记

正则表达式的学习笔记

. 的用法,匹配任意一个字符 ,比如 我和你、我信你、我讨厌你 ,用 ‘我.你’ 可以匹配前两个,不能匹配第三个
* ,匹配 * 前面的那个字符一次或者0次,比如 笑起、笑起来哈、笑起来哈哈哈哈、笑起来哈呵呵呵,‘笑起来*’可以匹配所有的,‘笑起来哈*’匹配不到*个
?,匹配前面的那个字符的0次或者一次
\ 反斜杠 转义
/d 数字
()可以把表达式中的内容提取出来
match()从头开始匹配,返回一个对象
Findall()将所有匹配的结果返回,列表
.*是贪婪匹配,将满足条件的*长表达式返回
.*? 是将满足条件的*短的结果返回
Search()扫描整个字符串,返回*个匹配的正则表达式对象,用.group()获取内容
如果表达式中有多个括号,group(1)代表*个括号内容,类推

 

 

区别:match是从头开始匹配,匹配失败直接返回None。匹配成功返回一个匹配对象。(Search是从整个文本中寻找匹配,匹配失败直接返回None。找到*个匹配的直接返回一个匹配对象,不会继续往后匹配。Findall是整个文本匹配,会将所有满足匹配的数据返回,返回类型是列表,匹配不成功返回[ ])。

比如说匹配邮箱,匹配手机号

Phone=input(“请输入你的手机号:”)

Res=re.match(r‘^1[35789][0-9]{9}$’,phone)

Mail= input(“请输入你的邮箱:”)

Res=re.match(r‘^[0-9a-zA-Z_]{1,13}@[0-9a-zA-Z_]{1,5}\.[com,cn]{2,3}$)

windows下安装调试pip

windows下安装调试pip

windows7操作系统下面,git cmd命令行模式下,执行pip报错

C:\Users\Administrator>pip install lxml
‘pip’ 不是内部或外部命令,也不是可运行的程序
或批处理文件。

C:\Users\Administrator>
 

先去找下python的执行路径

C:\Users\Administrator>where python
C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python.exe

C:\Users\Administrator>

C:\Users\Administrator>where python
C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python.exe

C:\Users\Administrator>cd C:\Users\Administrator\AppData\Local\Programs\Python\P
ython37\Scripts

C:\Users\Administrator\AppData\Local\Programs\Python\Python37\Scripts>pip3.exe i
nstall lxml
Collecting lxml
Downloading https://files.pythonhosted.org/packages/9e/5e/171ee9d40a600f565fe6
91ec5bf7596247ec62cfb2edc00c91afe8ea837b/lxml-4.6.3-cp37-cp37m-win_amd64.whl (3.
5MB)
35% |███████████▌ | 1.2MB 6.8MB/s eta 0:00:01
35% |███████████▌ | 1.3MB 6.8MB/s eta 0:00:01
36% |███████████▌ | 1.3MB 6.0MB/s eta 0:00:01
36% |████████████ | 1.3MB 6.0MB/s eta 0:00:01
36% |████████████ | 1.3MB 5.7MB/s eta 0:00:01
37% |████████████ | 1.3MB 5.1MB/s eta 0:00:01
37% |████████████ | 1.3MB 5.4MB/s eta 0:00:01
37% |████████████ | 1.3MB 4.9MB/s eta 0:00:01
38% |████████████ | 1.3MB 4.9MB/s eta 0:00:01
38% |████████████ | 1.3MB 6.0MB/s eta 0:00:01
38% |████████████▌ | 1.4MB 6.0MB/s eta 0:00:0
38% |████████████▌ | 1.4MB 6.0MB/s eta 0:00:0
39% |████████████▌ | 1.4MB 6.0MB/s eta 0:00:0
39% |████████████▌ | 1.4MB 6.0MB/s eta 0:00:0
39% |█████████████ | 1.4MB 6.8MB/s eta 0:00:0
40% |█████████████ | 1.4MB 5.7MB/s eta 0:00:0
40% |█████████████ | 1.4MB 5.7MB/s eta 0:00:0
40% |█████████████ | 1.4MB 5.7MB/s eta 0:00:0
40% |█████████████ | 1.4MB 5.7MB/s eta 0:00:0
41% |█████████████ | 1.4MB 2.9MB/s eta 0:00:0
41% |█████████████ | 1.5MB 2.9MB/s eta 0:00:0
41% |█████████████▌ | 1.5MB 2.8MB/s eta 0:00:
42% |█████████████▌ | 1.5MB 3.0MB/s eta 0:00:
42% |█████████████▌ | 1.5MB 3.0MB/s eta 0:00:
42% |██████████████ | 1.5MB 2.9MB/s eta 0:00:
43% |██████████████ | 1.5MB 3.1MB/s eta 0:00:
43% |██████████████ | 1.5MB 3.0MB/s eta 0:00:
43% |██████████████ | 1.5MB 3.1MB/s eta 0:00:
43% |██████████████ | 1.5MB 3.1MB/s eta 0:00:
44% |██████████████ | 1.5MB 6.4MB/s eta 0:00:
44% |██████████████ | 1.6MB 6.4MB/s eta 0:00:
44% |██████████████ | 1.6MB 7.3MB/s eta 0:00:
45% |██████████████▌ | 1.6MB 6.0MB/s eta 0:00
45% |██████████████▌ | 1.6MB 5.1MB/s eta 0:00
45% |██████████████▌ | 1.6MB 5.1MB/s eta 0:00
45% |███████████████ | 1.6MB 5.4MB/s eta 0:00
46% |███████████████ | 1.6MB 5.7MB/s eta 0:00
46% |███████████████ | 1.6MB 5.7MB/s eta 0:00
46% |███████████████ | 1.6MB 5.7MB/s eta 0:00
47% |███████████████ | 1.6MB 5.4MB/s eta 0:00
47% |███████████████ | 1.7MB 5.1MB/s eta 0:00
47% |███████████████ | 1.7MB 5.1MB/s eta 0:00
47% |███████████████▌ | 1.7MB 5.7MB/s eta 0:0
48% |███████████████▌ | 1.7MB 6.8MB/s eta 0:0
48% |███████████████▌ | 1.7MB 4.1MB/s eta 0:0
48% |███████████████▌ | 1.7MB 4.1MB/s eta 0:0
49% |████████████████ | 1.7MB 4.1MB/s eta 0:0
49% |████████████████ | 1.7MB 3.9MB/s eta 0:0
49% |████████████████ | 1.7MB 3.9MB/s eta 0:0
50% |████████████████ | 1.8MB 4.1MB/s eta 0:0
50% |████████████████ | 1.8MB 4.1MB/s eta 0:0
50% |████████████████ | 1.8MB 4.1MB/s eta 0:0
50% |████████████████ | 1.8MB 4.5MB/s eta 0:0
51% |████████████████▌ | 1.8MB 4.7MB/s eta 0:
51% |████████████████▌ | 1.8MB 10.2MB/s eta 0
51% |████████████████▌ | 1.8MB 12.8MB/s eta 0
52% |█████████████████ | 1.8MB 14.6MB/s eta 0
52% |█████████████████ | 1.8MB 6.8MB/s eta 0:
52% |█████████████████ | 1.8MB 7.3MB/s eta 0:
52% |█████████████████ | 1.9MB 7.9MB/s eta 0:
53% |█████████████████ | 1.9MB 9.3MB/s eta 0:
53% |█████████████████ | 1.9MB 10.2MB/s eta 0
53% |█████████████████ | 1.9MB 5.1MB/s eta 0:
54% |█████████████████ | 1.9MB 5.1MB/s eta 0:
54% |█████████████████▌ | 1.9MB 5.1MB/s eta 0
54% |█████████████████▌ | 1.9MB 5.1MB/s eta 0
55% |█████████████████▌ | 1.9MB 5.1MB/s eta 0
55% |██████████████████ | 1.9MB 10.2MB/s eta
55% |██████████████████ | 1.9MB 5.1MB/s eta 0
55% |██████████████████ | 2.0MB 5.1MB/s eta 0
56% |██████████████████ | 2.0MB 5.1MB/s eta 0
56% |██████████████████ | 2.0MB 3.4MB/s eta 0
56% |██████████████████ | 2.0MB 5.1MB/s eta 0
57% |██████████████████ | 2.0MB 5.1MB/s eta 0
57% |██████████████████▌ | 2.0MB 5.1MB/s eta
57% |██████████████████▌ | 2.0MB 3.4MB/s eta
57% |██████████████████▌ | 2.0MB 3.4MB/s eta
58% |██████████████████▌ | 2.0MB 3.4MB/s eta
58% |███████████████████ | 2.0MB 5.1MB/s eta
58% |███████████████████ | 2.1MB 5.1MB/s eta
59% |███████████████████ | 2.1MB 3.4MB/s eta
59% |███████████████████ | 2.1MB 5.1MB/s eta
59% |███████████████████ | 2.1MB 5.1MB/s eta
59% |███████████████████ | 2.1MB 5.1MB/s eta
60% |███████████████████ | 2.1MB 5.1MB/s eta
60% |███████████████████▌ | 2.1MB 5.1MB/s eta
60% |███████████████████▌ | 2.1MB 5.1MB/s eta
61% |███████████████████▌ | 2.1MB 5.1MB/s eta
61% |███████████████████▌ | 2.2MB 5.1MB/s eta
61% |████████████████████ | 2.2MB 5.1MB/s eta
62% |████████████████████ | 2.2MB 5.1MB/s eta
62% |████████████████████ | 2.2MB 5.1MB/s eta
62% |████████████████████ | 2.2MB 5.1MB/s eta
62% |████████████████████ | 2.2MB 5.1MB/s eta
63% |████████████████████ | 2.2MB 5.1MB/s eta
63% |████████████████████ | 2.2MB 10.2MB/s et
63% |████████████████████▌ | 2.2MB 10.2MB/s e
64% |████████████████████▌ | 2.2MB 5.1MB/s et
64% |████████████████████▌ | 2.3MB 5.1MB/s et
64% |█████████████████████ | 2.3MB 5.1MB/s et
64% |█████████████████████ | 2.3MB 10.2MB/s e
65% |█████████████████████ | 2.3MB 5.1MB/s et
65% |█████████████████████ | 2.3MB 5.1MB/s et
65% |█████████████████████ | 2.3MB 5.1MB/s et
66% |█████████████████████ | 2.3MB 5.1MB/s et
66% |█████████████████████ | 2.3MB 5.1MB/s et
66% |█████████████████████▌ | 2.3MB 3.4MB/s e
67% |█████████████████████▌ | 2.3MB 5.1MB/s e
67% |█████████████████████▌ | 2.4MB 5.1MB/s e
67% |█████████████████████▌ | 2.4MB 5.1MB/s e
67% |██████████████████████ | 2.4MB 5.1MB/s e
68% |██████████████████████ | 2.4MB 10.2MB/s
68% |██████████████████████ | 2.4MB 5.1MB/s e
68% |██████████████████████ | 2.4MB 5.1MB/s e
69% |██████████████████████ | 2.4MB 5.1MB/s e
69% |██████████████████████ | 2.4MB 5.1MB/s e
69% |██████████████████████ | 2.4MB 10.2MB/s
69% |██████████████████████▌ | 2.4MB 10.2MB/s
70% |██████████████████████▌ | 2.5MB 5.1MB/s
70% |██████████████████████▌ | 2.5MB 5.1MB/s
70% |██████████████████████▌ | 2.5MB 5.1MB/s
71% |███████████████████████ | 2.5MB 5.1MB/s
71% |███████████████████████ | 2.5MB 10.2MB/s
71% |███████████████████████ | 2.5MB 10.2MB/s
71% |███████████████████████ | 2.5MB 5.1MB/s
72% |███████████████████████ | 2.5MB 5.1MB/s
72% |███████████████████████ | 2.5MB 5.1MB/s
72% |███████████████████████ | 2.5MB 5.1MB/s
73% |███████████████████████▌ | 2.6MB 10.2MB/
73% |███████████████████████▌ | 2.6MB 5.1MB/s
73% |███████████████████████▌ | 2.6MB 5.1MB/s
74% |████████████████████████ | 2.6MB 5.1MB/s
74% |████████████████████████ | 2.6MB 5.1MB/s
74% |████████████████████████ | 2.6MB 5.1MB/s
74% |████████████████████████ | 2.6MB 5.1MB/s
75% |████████████████████████ | 2.6MB 5.1MB/s
75% |████████████████████████ | 2.6MB 5.1MB/s
75% |████████████████████████ | 2.7MB 5.1MB/s
76% |████████████████████████▌ | 2.7MB 5.1MB/
76% |████████████████████████▌ | 2.7MB 10.2MB
76% |████████████████████████▌ | 2.7MB 10.2MB
76% |████████████████████████▌ | 2.7MB 5.1MB/
77% |█████████████████████████ | 2.7MB 5.1MB/
77% |█████████████████████████ | 2.7MB 5.1MB/
77% |█████████████████████████ | 2.7MB 10.2MB
78% |█████████████████████████ | 2.7MB 10.2MB
78% |█████████████████████████ | 2.7MB 10.2MB
78% |█████████████████████████ | 2.8MB 5.1MB/
79% |█████████████████████████ | 2.8MB 5.1MB/
79% |█████████████████████████▌ | 2.8MB 5.1MB
79% |█████████████████████████▌ | 2.8MB 5.1MB
79% |█████████████████████████▌ | 2.8MB 10.2M
80% |█████████████████████████▌ | 2.8MB 10.2M
80% |██████████████████████████ | 2.8MB 5.1MB
80% |██████████████████████████ | 2.8MB 5.1MB
81% |██████████████████████████ | 2.8MB 5.1MB
81% |██████████████████████████ | 2.8MB 5.1MB
81% |██████████████████████████ | 2.9MB 10.2M
81% |██████████████████████████ | 2.9MB 10.2M
82% |██████████████████████████ | 2.9MB 10.2M
82% |██████████████████████████▌ | 2.9MB 5.1M
82% |██████████████████████████▌ | 2.9MB 5.1M
83% |██████████████████████████▌ | 2.9MB 3.4M
83% |███████████████████████████ | 2.9MB 5.1M
83% |███████████████████████████ | 2.9MB 5.1M
83% |███████████████████████████ | 2.9MB 5.1M
84% |███████████████████████████ | 2.9MB 5.1M
84% |███████████████████████████ | 3.0MB 3.4M
84% |███████████████████████████ | 3.0MB 3.4M
85% |███████████████████████████ | 3.0MB 3.4M
85% |███████████████████████████▌ | 3.0MB 5.1
85% |███████████████████████████▌ | 3.0MB 5.1
86% |███████████████████████████▌ | 3.0MB 5.1
86% |███████████████████████████▌ | 3.0MB 5.1
86% |████████████████████████████ | 3.0MB 5.1
86% |████████████████████████████ | 3.0MB 5.1
87% |████████████████████████████ | 3.1MB 5.1
87% |████████████████████████████ | 3.1MB 10.
87% |████████████████████████████ | 3.1MB 10.
88% |████████████████████████████ | 3.1MB 5.1
88% |████████████████████████████ | 3.1MB 5.1
88% |████████████████████████████▌ | 3.1MB 5.
88% |████████████████████████████▌ | 3.1MB 10
89% |████████████████████████████▌ | 3.1MB 10
89% |████████████████████████████▌ | 3.1MB 10
89% |█████████████████████████████ | 3.1MB 5.
90% |█████████████████████████████ | 3.2MB 5.
90% |█████████████████████████████ | 3.2MB 5.
90% |█████████████████████████████ | 3.2MB 5.
91% |█████████████████████████████ | 3.2MB 10
91% |█████████████████████████████ | 3.2MB 5.
91% |█████████████████████████████ | 3.2MB 5.
91% |█████████████████████████████▌ | 3.2MB 5
92% |█████████████████████████████▌ | 3.2MB 5
92% |█████████████████████████████▌ | 3.2MB 5
92% |██████████████████████████████ | 3.2MB 1
93% |██████████████████████████████ | 3.3MB 5
93% |██████████████████████████████ | 3.3MB 5
93% |██████████████████████████████ | 3.3MB 5
93% |██████████████████████████████ | 3.3MB 5
94% |██████████████████████████████ | 3.3MB 1
94% |██████████████████████████████ | 3.3MB 1
94% |██████████████████████████████▌ | 3.3MB
95% |██████████████████████████████▌ | 3.3MB
95% |██████████████████████████████▌ | 3.3MB
95% |██████████████████████████████▌ | 3.3MB
95% |███████████████████████████████ | 3.4MB
96% |███████████████████████████████ | 3.4MB
96% |███████████████████████████████ | 3.4MB
96% |███████████████████████████████ | 3.4MB
97% |███████████████████████████████ | 3.4MB
97% |███████████████████████████████ | 3.4MB
97% |███████████████████████████████ | 3.4MB
98% |███████████████████████████████▌| 3.4MB
98% |███████████████████████████████▌| 3.4MB
98% |███████████████████████████████▌| 3.5MB
98% |███████████████████████████████▌| 3.5MB
99% |████████████████████████████████| 3.5MB
99% |████████████████████████████████| 3.5MB
99% |████████████████████████████████| 3.5MB
100% |████████████████████████████████| 3.5M
B 1.7MB/s
Installing collected packages: lxml
Successfully installed lxml-4.6.3
You are using pip version 19.0.3, however version 21.0.1 is available.
You should consider upgrading via the ‘python -m pip install –upgrade pip’ comm
and.

C:\Users\Administrator\AppData\Local\Programs\Python\Python37\Scripts>

然后在C:\Users\Administrator\AppData\Local\Programs\Python\Python37\Scripts路径,找到pip3.exe

 

参考文档地址:https://blog.csdn.net/miss85246/article/details/81069276

Flask的安装

Flask的安装

1,创建应用目录:

$mkdir flasky
$cd flasky

2,创建虚拟环境:
(在Python3中创建虚拟环境)
如果使用的是Ubuntu Linux系统预装的Python3,那么标准库中没有venv包。则输入以下命令安装python-venv包:

$sudo apt-get instatll python3-venv

创建虚拟环境的命令:

$pthon3 -m venv virtual-environment-name

确保当前目录是flasky,在此目录下创建一个虚拟环境,该虚拟环境命名为venv(也可以自定义):

$python3 -m venv venv

此时,flasky目录中出现一个名为venv的子目录,这是一个全新的虚拟环境,包含这个项目专用的Python解释器

(在Python2中创建虚拟环境):
由于Python2中没有继承venv包,所以要使用第三方工具virtualenv创建虚拟环境:
确保当前目录是flasky,输入:

$sudo pip install virtualenv

virtualenv命令的参数是虚拟环境的名称,确保当前目录是flasky,执行以下命令:

$virtualenv venv

这个命令在当前目录中创建一个名为venv的子目录,虚拟环境相关的文件都在这个子目录中

3,使用虚拟环境
1,激活虚拟环境:

$source venv/bin/activate

如果在Windows系统:

$venv\Script\activate

激活后,为了提示用户已经激活了虚拟环境,命令提示符前会加入环境名:

(venv)$

激活虚拟环境后,在命令提示符中输入python,将调用虚拟环境中的解释器,而不是系统全局解释器(打开多个窗口,每个窗口中都要激活)
2、还原:
工作结束后,输入deactivate,将还原当前终端回话的PATH环境变量

deactivate

4、使用pip安装python包
确保venv虚拟环境已经激活,执行以下命令:

(venv) $ pip install flask

这一命令不仅安装Flask自身,还会安装它所有的依赖,使用以下命令可以查看虚拟环境中安装了哪些包:

(venv) $ pip freeze

验证Flask是否正确安装,可以启动python解释器,尝试导入Flask,如果没有错误提示,则成功

(venv) $ python
>>>import flask

使用 xpath 选择元素

使用 xpath 选择元素

前面学习了 CSS 选择元素的方法,用起来十分灵活。

但有时候使用 xpath 更加方便,爬虫 Scrapy 和 Appium APP 自动化都支持 Xpath 元素选择。

学习的时候可以参考这个简单的页面:https://git-jhy.github.io/snake,右键检查,在 Elements 中 Ctrl+F 可以搜索元素

1. 路径
*对路径

/ 可以表示根节点,也可以用在标签后表示直接子节点的关系,类似 CSS 中的 >

如 /html 和 /html/body/div,后者等价于 html>body>html,通过 xpath 查找元素方法如下:

elements = driver.find_elements_by_xpath(“/html/body/div”)
1

相对路径

使用 // 表示相对路径,它表示从当前节点向后查找元素,不管出现在什么位置:

elements = driver.find_elements_by_xpath(“//div//li”)
1
它等价于 CSS 选择器 div li

同理,//div/li 等价于 div > li

通配符

使用 * 选择所有元素,如:

elements = driver.find_elements_by_xpath(“//div/ul/li”)
for element in elements:
print(element.get_attribute(‘outerHTML’))

2. 属性选择
语法格式:

[@attributeName=’attributeValue’]
1

ID 属性

选择 ID 为 fruits 的元素:

//*[@id=’fruits’]
1

class 属性

选择 class 为 green 的元素

//*[@class=’green’]
1
选择 class 为 like tomato 的元素(所有 class 都要列写出来)

//*[@class=’like tomato’]
1

contains

选择 class 包含 tomato 属性的元素

//*[contains(@class, ‘tomato’)]
1
选择 style 包含 color 字符串的元素

//*[contains(@style, ‘color’)]
1
选择 style 属性值以 color 开头的元素(结束使用 ends-with)

//*[starts-with(@style, ‘color’)]
1

3. 次序选择
第 k 个子元素

选择满足条件的第二个子元素:

//div[@id=’fruits’]//ul//li[2]
1
此时在 页面 选中的是第二个水果

倒数第 k 个子元素

选择*后一个、倒数第 2 个 li 标签:

//li[last()]
//li[last()-1]
1
2

范围选择

选择前 3 个 li 元素

//li[position()<=3]
1

4. 组选择、父节点和兄弟节点
组选择

CSS 可以使用逗号分隔多个表达式,进行多个匹配,xpath 可以使用 | 实现组选择:

//div | //strong
1
等价于 CSS 选择:

div, strong
1

父节点

可以使用 /.. 向上查找父节点,如查找 id 为 fruits 的 div 标签的父节点的父节点:

//div[@id=’fruits’]/../..
1

兄弟节点

CSS 选择兄弟节点用 + ,而 xpath 中:

前兄弟节点:/preceding-sibling::

后兄弟节点:/following-sibling::

如选择第 3 个 li 标签前面为 li 标签的兄弟节点:

//div[@id=’fruits’]//li[3]/precedding-sibling::li
1

5. 实战小测试
运行下面的代码:

import time
from selenium import webdriver

driver = webdriver.Chrome()
driver.get(‘https://git-jhy.github.io/snake’)
driver.implicitly_wait(8)

# 选择 class 包含 tomato 的元素
tomato = driver.find_element_by_xpath(‘//*[contains(@class, “tomato”)]’)
print(tomato.get_attribute(‘outerHTML’), ‘\n’)

# 选择前 3 种水果
fruits = driver.find_elements_by_xpath(‘//div[@id=”fruits”]//li[position()<=3]’)
for fruit in fruits:
print(fruit.text, end=’, ‘)

# 选择第 2 种蔬菜
print(‘\n’)
vegetable = driver.find_element_by_xpath(‘//div[@id=”vegetable”]//li[2]’)
print(vegetable.get_attribute(‘outerHTML’))

time.sleep(1)
driver.quit()

结果为:

<li class=”like tomato”>tomato</li>

apple, banana, cherry,

<li class=”dislike”>been</li>

***Repl Closed***

REFERENCE:

https://git-jhy.github.io/snake
https://developer.mozilla.org/zh-CN/docs/Web/XPath
http://www.python3.vip/tut/auto/selenium/xpath_1/

 

sqlalchemy动态生成model模型

sqlalchemy动态生成model模型

因业务需要从不同时期的sqlite数据库中取数据,不同时期的数据库字段是不同的,但是以往用sqlalchemy管理数据库时的model是写死的,就会导致有些字段错误而报错,这时我们就要根据版本动态生成model

众所周知python里的 type() 函数是可以查看一个实例的class类型,但其实 type() 也可以用来创建一个class类,我们可以利用这一点动态创建model,下面放出例子

#model.py
from sqlalchemy import Column, String, Integer,DateTime
from sqlalchemy.ext.declarative import declarative_base

# 创建对象的基类:
Base = declarative_base()

def test(version):

def to_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}

if version == “1.0”:
field_dict = {
“__tablename__” : ‘student’,
“id”:Column(Integer, primary_key=True, autoincrement=True),
“name”:Column(String(25)),
“to_dict”:to_dict
}
elif version == “2.0”:
field_dict = {
“__tablename__” : ‘student’,
“id”:Column(Integer, primary_key=True, autoincrement=True),
“name”:Column(String(25)),
“class”:Column(String(25)),
“gender”:Column(String(25)),
“to_dict”:to_dict
}
return type(“Student”,(Base,),field_dict)

#view.py
from model import test
from sqlalchemy.orm import sessionmaker
import pymysql

pymysql.install_as_MySQLdb()

# 初始化数据库连接:
sengine = create_engine(‘mysql+pymysql://账号:密码@地址:3306/数据库名?charset=utf8’)
# 创建Session类型:
s_db = sessionmaker(bind=sengine)

def testDynamicGetModel():
dynamicStudentClass = test(‘2.0′)
db = s_db()
result = db.query(dynamicStudentClass).filter_by(class=’6班’).first()
db.close()

student_dict = result.to_dict()

 

macOS下conda的安装和基本使用

macOS下conda的安装和基本使用

安装
在conda官网下载安装conda.

打开terminal输入conda -V,回车显示conda的版本说明安装成功。

将conda更新到*新版本
conda update conda可将conda更新到*新版本。

查看已存在的虚拟环境
conda env list可查看已存在的虚拟环境。

这些虚拟环境都存储在Anaconda根目录下的env文件夹中。

创建一个虚拟环境
conda create -n env_name python=python_version,其中env_name是你想创建的虚拟环境的名称,pythpn_version是要搭建的虚拟环境的python版本。

例如:conda create -n my_station python=3.8,这样就建立了一个pythpn版本为3.8,名称为my_station的虚拟环境,然后存储在Anaconda的根目录下。

搭建之后就可以使用conda env list查看到新创建的虚拟环境。

激活一个虚拟环境
conda env list查看已经存在的虚拟环境。假设现在要激活一个名叫my_station的虚拟环境,则conda activate my_station.

激活之后所有的与python的操作都是在这个虚拟环境中进行的。

这里的激活是指在terminal下激活的,当退出terminal后在打开激活的虚拟环境就失效了。

关闭虚拟环境
conda deactivate即可关闭虚拟环境,这里不需要指定具体的虚拟环境名称。

在conda中查看已安装的库以及库的安装/删除
查看在conda中已安装的库:
conda list 即可查看在conda中已经安装的库

安装/删除库:
安装:conda install [package]

删除:conda uninstall [package]

在虚拟环境中安装/删除库
conda安装/删除库
安装:conda install -n env_name [package],其中 **[package]**是要安装的库的名称。

例如:一个虚拟环境叫做my_station,则conda install -n my_station pymysql就在my_station这个虚拟环境中安装了一个叫做pymysql的库。

删除:conda remove –name env_name package_name
例如:
要删除my_station中的pyqt5库,则执行conda remove –name my_station pymysql

pip安装/删除库
首先激活要安装库的虚拟环境,conda activate env_name

安装:pip install [package]

删除:pip uninstall [package]

这两种安装方式的区别
conda是一种通用包管理系统。

pip是Python包的通用管理器;

换句话说就是:这两个包的区别就是包的管理方式不同。

在conda中安装包和在虚拟环境中安装包的区别
在conda中安装,安装的包并没有安装在具体的某一个虚拟环境中。

当创建虚拟环境或者用conda向某一个虚拟环境安装包的时候,首先检查的就是conda中是否已经安装这个包了,如果conda中已经安装了这个包,就不必再次通过网络下载了。

通过向conda中安装一些非常常用的包可以节省一些时间。

删除一个虚拟环境
conda remove -n env_name –all,例如要将一个名叫my_station的虚拟环境删除,则执行conda remove -n my_station –all

与他人分享虚拟环境的配置
例如现在要与他人分享my_station这个虚拟环境。

首先激活这个虚拟环境conda activate my_station,之后执行conda env export命令即可看到环境的相关配置。这里可以重定向输出流,例如conda env export > my_station_config.yml即可在当前目录下创建一个名叫my_station_config.yml的文件。

当他人获得这个文件之后,执行conda env create -f my_station_config.yml就可以得到一模一样的环境了。

切换conda源
清华源:
conda config –add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config –add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
conda config –add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/msys2/

中科大源:
conda config –add channels https://mirrors.ustc.edu.cn/anaconda/pkgs/main/
conda config –add channels https://mirrors.ustc.edu.cn/anaconda/pkgs/free/
conda config –add channels https://mirrors.ustc.edu.cn/anaconda/cloud/conda-forge/
conda config –add channels https://mirrors.ustc.edu.cn/anaconda/cloud/msys2/
conda config –add channels https://mirrors.ustc.edu.cn/anaconda/cloud/bioconda/
conda config –add channels https://mirrors.ustc.edu.cn/anaconda/cloud/menpo/

切换回默认源
conda config –remove-key channels

python:类对象之间的内存复用问题

python:类对象之间的内存复用问题

问题描述
在定义python类时,把参数的初始化写在了__init__函数外面:

class test:
list_t=[]
num=0

def __init__(self,num):
self.num=num

def add(self,subject):
self.list_t.append(subject)
print(“此时的列表长度:”,len(self.list_t))

于是在给不同的对象add的时候出现了问题:

subject01=test(10)
subject02=test(11)

subject01.add(2)
subject02.add(3)

结果输出为:
此时的列表长度:1
此时的列表长度:2

正确的结果应该是:
此时的列表长度:1
此时的列表长度:1

此时就是发生了对象之间的内存复用,怀疑是在__init__函数外初始化的参数,因为在每一次创造对象的时候都没有初始化,所以实际上每个对象内的list指向的内存都是同一个,于是导致了这种情况。

解决方法
注意把变量初始化写在__init__函数内:

class test:

def __init__(self,num):
self.num=num
self.list_t=[]

def add(self,subject):
self.list_t.append(subject)
print(“此时的列表长度:”,len(self.list_t))

更新
python中,在__init__函数内定义的为实例变量,__init__外定义的为类变量。

神经网络对鸢尾花分类

神经网络对鸢尾花分类

import numpy as np
from sklearn import datasets
import tensorflow as tf
from matplotlib import pyplot as plt

iris = datasets.load_iris()

data = iris.data
target = iris.target

# shuffling dataset
seed = 116 # using same seed in order to data match target
np.random.seed(seed)
np.random.shuffle(data)
np.random.seed(seed)
np.random.shuffle(target)
tf.random.set_seed(seed)

# partitioning dataset
train_data = data[:-30]
train_target = target[:-30]
test_data = data[-30:]
test_target = target[-30:]

# casting
train_data = tf.cast(train_data, tf.float32)
test_data = tf.cast(test_data, tf.float32)

# one hot
train_target = tf.one_hot(train_target, depth=3)

# packaging data
batch = 32
train_slices = tf.data.Dataset.from_tensor_slices((train_data, train_target)).batch(batch)
test_slices = tf.data.Dataset.from_tensor_slices((test_data, test_target)).batch(batch)

# defining trainable variable
weight = tf.Variable(tf.random.truncated_normal((4, 3), stddev=.1))
biases = tf.Variable(tf.random.truncated_normal((3, ), stddev=.1))

# iteration
epoch = 500
learning_rate = .1
recorded_loss = []
recorded_accuracy = []
for epoch in range(epoch):
# training
total_loss = 0
for data, target in train_slices:
with tf.GradientTape() as tape:
prediction = tf.matmul(data, weight) + biases # forward propagation in the network
prediction = tf.nn.softmax(prediction) # make the results distributed according to probability
loss = tf.reduce_mean(tf.square(target-prediction))
total_loss += float(loss)
grads = tape.gradient(loss, [weight, biases])
weight.assign_sub(learning_rate*grads[0])
biases.assign_sub(learning_rate*grads[1])
recorded_loss.append(total_loss)

# testing
total_correct, total_number = 0, 0
for data, target in test_slices:
prediction = tf.matmul(data, weight) + biases
prediction = tf.nn.softmax(prediction)
prediction = tf.argmax(prediction, axis=1) # get the index of result with the highest probability in each row
prediction = tf.cast(prediction, dtype=target.dtype)
correct = tf.cast(tf.equal(prediction, target), dtype=tf.int32)
correct = tf.reduce_sum(correct)
total_number += data.shape[0]
total_correct += int(correct)
accuracy = total_correct/total_number
recorded_accuracy.append(accuracy)

print(‘Epoch: {}, Loss: {}, Accuracy: {}’.format(epoch, total_loss, accuracy))

# output
plt.subplot(121)
plt.title(‘Loss Function Curve’)
plt.xlabel(‘Epoch’)
plt.ylabel(‘Loss’)
plt.plot(recorded_loss, label=’$Loss$’)
plt.legend()
plt.subplot(122)
plt.title(‘Accuracy Curve’)
plt.xlabel(‘Epoch’)
plt.ylabel(‘Accuracy’)
plt.plot(recorded_accuracy, label=’$Accuracy$’)
plt.legend()
plt.show()

 

Web服务器,Web容器和应用服务器的区别

1、什么是服务器?

2、Web服务器,Web容器和应用服务器的区别?
3、Apache和Tomcat的区别?
4、都是服务器,那么我们经常还听到Nginx这样的服务器,和Apache的区别?

1、什么是服务器
查看Apache的定义时,会发现,Apache为Web server,也就是Web服务器。

Web服务器是指能够为发出请求的 浏览器 提供文档的程序。服务器是一种被动程序,只有浏览器发出请求的时候才会响应。应用层使用的是HTTP协议。

2、Web服务器,Web容器和应用服务器的区别
Web Server,Web container和Application Server区别。

Web Server,Web服务器,同上面所说,Web服务器是指能够为发出请求的浏览器提供文档的程序。服务器是一种被动程序,只有浏览器发出请求的时候才会响应。应用层使用的是HTTP协议。目前*主流的三个Web服务器是Apache Nginx IIS。

Web容器是一种服务器程序,在服务器端口就有一个提供相应服务的程序。所以现在知道为什么Tomcat有默认的端口——8080。一个服务器可以有多个容器。

如Tomcat,收到浏览器的请求之后还会解析Servlet,然后再把Servlet处理后的结果返回给浏览器。其实Tomcat既是Web服务器也是Web容器。为什么这样说,第三点会讲到。

而应用服务器,这里有个区分它与Web服务器的答案:
What is the difference between application server and web server?
Web服务器设计服务于HTTP内容,应用服务器不只限于HTTP。Web服务器服务于静态内容,有插件支持动态语言,
应用服务器也具有Web服务器的这些东西,除此它还支持程序级的服务,如连接池,事务支持,信息服务等。

至于Tomcat是不是应用服务器,那就不好说了。

3、Apache和Tomcat的区别
Apache指的是Apache HTTP Server。
stackoverflow里面的这个问题虽然被关闭了,但是有一个评论写的博客挺好的。
What is Tomcat? Is it a Web Server? What can Tomcat do? How is it different than Apache Web Server?
里面就讲到:

Tomcat是一个Servlet/Jsp容器,它同时也作为一个web服务器使用。

Tomcat = ( Web Server + Servlet container + JSP environment ),因为我们知道JSP也是转译为Servlet的,Tomcat接收请求之后,如果是JSP页面的话,Tomcat里面的JSP引擎可以将JSP转换为Servlet类。

从这里也可以看到,其实Tomcat既是Web服务器也是Web容器。

如果是Servlet类的话,直接就是Servlet引擎加载Servlet类并且执行,然后以HTML的格式输出,再返回给浏览器。

而Apache是设计服务于静态web页面的web服务器。如果是Apache来接收 jsp 请求,它根本就不知道这是什么东西,所以返回的并不是我们想要的结果,但是静态页面的话,如http://www.apache.com/index.html这样的请求的时候,Apache就直接将这个页面返回给请求的浏览器了。

4、都是服务器,那么我们经常还听到Nginx这样的服务器,和Apache的区别
Nginx是engine x的缩写,与Apache不同的是,Nginx是一款高性能的HTTP和反向代理服务器。
其实这块我是接触很少的,
但是之前见过他人的博客挂掉的时候出了这个Nginx,就一直很好奇这是什么东西,
还有一个师兄用R asp berry Pi加Nginx加 PHP 发了个Helloworld的时候,也让我感觉很是神奇。