Yu-shui


  • 首页

  • 关于

  • 标签

  • 分类

  • 归档

  • 日程表

  • 搜索

机器学习2

发表于 2019-03-09
字数统计: | 阅读时长 ≈

python机器学习基础库(numpy,pandas,matplotlib)

1.numpy

NumPy是Python数值计算最重要的基础包,支持高级大量的维度数组与矩阵运算,大多数提供科学计算的包都是使用Numpy的数组作为构建基础。Numpy内部解除了Python的PIL(全局解释器锁),运算效率极好,是大量机器学习框架的基础库。

下面简要介绍numpy的简单使用方法

创建ndarray对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)

1.
object 任何暴露数组接口方法的对象都会返回一个数组或任何(嵌套)序列。
2.
dtype 数组的所需数据类型,可选。
3.
copy 可选,默认为true,对象是否被复制。
4.
order C(按行)、F(按列)或A(任意,默认)。
5.
subok 默认情况下,返回的数组被强制为基类数组。 如果为true,则返回子类。
6.
ndmin 指定返回数组的最小维数。

代码:

1
2
3
4
5
6
7
import numpy as np 

a = np.array([1,2,3])

print a

输出为:[1, 2, 3]

创建一个二维数组

1
2
3
4
5
6
7
import numpy as np 

a = np.array([[1, 2], [3, 4]])

print a

output:[[1, 2] ,[3, 4]]
使用reshape调整数组大小
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import numpy as np 

a = np.array([[1,2,3],[4,5,6]])

b = a.reshape(3,2)

print b

output:
[[1, 2]

[3, 4]

[5, 6]]

切片和索引

ndarray对象的内容可以通过索引或切片来访问和修改,就像 Python 的内置容器对象一样。

如前所述,ndarray对象中的元素遵循基于零的索引。 有三种可用的索引方法类型: 字段访问,基本切片和高级索引。

基本切片是 Python 中基本切片概念到 n 维的扩展。 通过将start,stop和step参数提供给内置的slice函数来构造一个 Python slice对象。 此slice对象被传递给数组来提取数组的一部分。

示例 1
1
2
3
4
import numpy as np
a = np.arange(10)
s = slice(2,7,2)
print a[s]

输出如下:

1
[2  4  6]

在上面的例子中,ndarray对象由arange()函数创建。 然后,分别用起始,终止和步长值2,7和2定义切片对象。 当这个切片对象传递给ndarray时,会对它的一部分进行切片,从索引2到7,步长为2。

通过将由冒号分隔的切片参数(start:stop:step)直接提供给ndarray对象,也可以获得相同的结果。

示例 2
1
2
3
4
import numpy as np
a = np.arange(10)
b = a[2:7:2]
print b

输出如下:

1
[2  4  6]

如果只输入一个参数,则将返回与索引对应的单个项目。 如果使用a:,则从该索引向后的所有项目将被提取。 如果使用两个参数(以:分隔),则对两个索引(不包括停止索引)之间的元素以默认步骤进行切片。

示例 3
1
2
3
4
5
# 对单个元素进行切片  
import numpy as np
a = np.arange(10)
b = a[5]
print b

输出如下:

1
5
示例 4
1
2
3
4
# 对始于索引的元素进行切片  
import numpy as np
a = np.arange(10)
print a[2:]

数学运算

可以对Numpy数组进行加法,减法,乘法,甚至三角运算,可以通过广度映射对不同阵型的数组进行算术运算。

向量

使用np.vectorize(函数)创建标量函数的向量化版本,以Python函数或方法作为参数,输出函数的向量化版本。

1
2
3
4
5
6
7
8
9
10
import numpy as np

def myfunc(a,b):
def myfunc(a,b):
if a>b:
return a-b
else:
return a+b
vfunc=np.vectorize(myfunc)
print(vfunc([1,2,3,4],[4,3,2,1]))

输出为:

1
[5 5 1 3]

多项式函数

ployld接受降幂次序的参数数组作为参数

创建多项式
1
2
3
4
5
6
7
8
import  numpy as np
p=np.poly1d([2,3,4])
print(np.poly1d(p))


output:
2
2 x + 3 x + 4

python爬虫1

发表于 2019-03-05
字数统计: | 阅读时长 ≈

python爬虫(1)

(注:代码使用的IP代理不稳定,运行时极有可能失效,建议取免费IP代理网站上寻找代理IP,替换代码中的IP)

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
mport re
import time
import chardet
import requests
import urllib.robotparser
from fake_useragent import UserAgent

def get_headers():
ua=UserAgent()
user_agent=ua.random
headers={'User-Agent':user_agent}
return headers


def get_proxies():
proxies={
"http":"111.43.70.58",
"http": "117.90.1.102",
"http": "111.177.186.120",
"http": "58.210.94.242",
"http": "122.234.206.52"
}
return proxies

#robot检测
def robot_check(robotstxt_url,headers,url):
rp=urllib.robotparser.RobotFileParser()
rp.set_url(robotstxt_url)
rp.read()
result=rp.can_fetch(headers['User-Agent'],url)
return result

def get_data(url,num_retries=3,proxies=None):
try:
data=requests.get(url,headers=headers)
print(data.status_code)
except requests.exceptions.ConnectionError as e:
print("请求错误,url:",url)
print("错误详情",e)
data=None
except:
print("未知错误,url:",url)
data=None


if(data!=None)and(500<=data.status_code<600):
if(num_retries>0):
print("服务器错误,正在重试.......")
time.sleep(1)
num_retries-=1
get_data(url,num_retries,proxies=proxies)
return data

def parse_data(data):
if(data==None):
return None
charset=chardet.detect(data.content)
data.encoding=charset['encoding']
html_text=data.text
t=re.findall('<a>(.*?)</a444>',html_text)
return t

if __name__=='__main__':
headers=get_headers()
proxies=get_proxies()
data=get_data("http://www.baidu.com",num_retries=3,proxies=proxies)
t=parse_data(data)
print(t)

机器学习1

发表于 2019-03-04
字数统计: | 阅读时长 ≈

机器学习周记<1>

1.基础知识点
1
2
3
1. 机器学习的核心是“使用算法解析数据,从中学习,然后对世界上的某件事情做出决定或预测”

2. 机器学习分为监督学习,无监督学习,强化学习
2.机器学习算法分类
1
2
3
4
5
6
7
1. 回归算法
2. 基于实例的算法
3. 决策树算法
4. 贝叶斯算法
5. 聚类算法
6. 深度学习和神经网络算法
7. 其他算法
3.基础机器学习代码实现
1
1.区分橘子与苹果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
rom sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

def main():
iris = datasets.load_iris()
iris_feature = iris.data
iris_target = iris.target
#print(iris_target)
#print('***********')
#print(iris_feature)

feature_train, feature_test, target_train, target_test = train_test_split(iris_feature, iris_target,test_size=0.33,random_state=42)
dt_model=DecisionTreeClassifier()
dt_model.fit(feature_train,target_train)
predict_results=dt_model.predict(feature_test)
print(predict_results)

main()
1
2.识别鸢尾花类别
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
26
27
28
29
30
31
32
33
34
35
36
from sklearn import datasets#导入内置数据集模块
from sklearn.neighbors import KNeighborsClassifier#导入sklear.neughbors模板中的KNN类
import numpy as np
np.random.seed(0)#设置随机种子

#数据集梳理
iris=datasets.load_iris()#导入鸢尾花样本数据
iris_x=iris.data
iris_y=iris.target
indices=np.random.permutation(len(iris_x))#对样本数据进行打乱(150)
iris_x_train=iris_x[indices[:-10]]#选取140个数据集作为训练集
iris_y_train=iris_y[indices[:-10]]
iris_x_test=iris_x[indices[-10:]]
#剩下的十个样本作为测试集
iris_y_test=iris_y[indices[-10:]]

knn=KNeighborsClassifier()
knn.fit(iris_x_train,iris_y_train)
iris_y_predict=knn.predict(iris_x_test)
#测试数据集
probility=knn.predict_proba(iris_x_test)
#计算各测试样本基于概率的预测
neighbor=knn.kneighbors(iris_x_test[-1],5,False)
#计算与最后一个样本距离最近的五个点,返回的是这些样本的序号组成的数组
score=knn.score(iris_x_test,iris_y_test,sample_weight=None)
#计算准确率


print('iris_y_predict=')
print(iris_y_predict)

print('iris_y_test:')
print(iris_y_test)
print("准确率:",score)
print("邻近对象数据为:",neighbor)
print("基于概率的预测:",probility)

安卓实现动画生成

发表于 2019-03-01
字数统计: | 阅读时长 ≈

安卓实现动画界面

1.MainActivity.java文件

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.example.project53;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.*;
import java.util.*;
public class MainActivity extends Activity {
private Button button;
private ImageView imageview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.bt);
imageview=(ImageView)findViewById(R.id.ig);
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Animation animation=AnimationUtils.loadAnimation(MainActivity.this, R.anim.re);
imageview.startAnimation(animation);
}

});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

2.activity_main.xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.project53.MainActivity" >

<ImageView
android:id="@+id/ig"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"/>

<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ig"
android:layout_marginTop="26px"
android:text="按钮"/>
</RelativeLayout>

在project文件下的res文件中创建一个anim文件夹,在文件夹中新建一个re.xml文件夹作为动画的布局文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="10000"/>
<scale
android:fromXScale="1.0"
android:toXScale="0.0"
android:fromYScale="1.0"
android:toYScale="0.0"
android:duration="10000"
android:pivotX="50%"
android:pivotY="50%"/>
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="10000"/>
</set>

MySQL的基本语法 1:对表和数据库的基本操作

发表于 2019-01-29
字数统计: | 阅读时长 ≈

[1].数据库的创建查找和删除

  1. 创建数据库:

    1
    CREATE DATABASE DATABASENAME
  2. 展示已经存在在的数据库

    1
    SHOW DATABASES
  3. 展示创建了的数据库

    1
    SHOW CREATE DATABASE DTABASENAME
  4. 删除数据库
    DROP DATABASE DATABASENAME

[2]表

  • 使用当前数据库
    1
    USE DATABASENAME
  • 创建表
    1
    CREAT TABLE ......
  1. 主键

    • 列后面写PRIMARY KEY
    • 在CREATE 语句后面写PRIMARY KEY(….,…..,…..)
    • 可以为多个表项的合并
  2. 外键

    • CONSTRAINT 外键名 FOREIGN KEY(本表中的表项名) REFERENCES 表名(主键)
    • constraint 约束名 unique (name)
  3. 约束

    • 不为空 not null

    • 唯一性约束 unique(……unique)

    • 默认约束
      default 默认值
    • 属性值自动增加
      初始值为1,默认自动增加1:一般为主键项中的一项设置为,只能有一项设置为属性自动增加:auto_increment

[3].表的基本操作

  1. desc 表名
  2. select * from 表名
  3. alter table 表名 rename to 新表名
  4. alter table 表名 modify 字段名 字段类型(修改字段的数据类型)
  5. alter table 表名 change 旧字段名 新字段名 新数据类型(可以同时修改字段名和数据类型)
  6. alter table 表名 add 新字段名 数据类型 约束条件 [first|after 已存在字段名]
    (first将该字段放在第一位,after放在指定字段名的后面)添加字段
  7. alter table 表名 drop 字段名
  8. alter table 表名 modify 字段1 数据类型 first|after 字段2修改字段的位置
  9. alter table 表名 drop foreign key 外键名删除外键
  10. drop table 表名删除表

Hello World

发表于 2019-01-22
字数统计: | 阅读时长 ≈

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment

1…45

Yu-shui

46 日志
GitHub
© 2019 Yu-shui | Site words total count:
由 Hexo 强力驱动
|
主题 — NexT.Pisces v5.1.4