使用kNN算法对红酒进行分类

第1关 分析红酒数据

1
2
3
4
5
6
7
8
9
10
11
12
13
  

import numpy as np

def alcohol_mean(data):
    '''
    返回红酒数据中红酒的酒精平均含量
    :param data: 红酒数据对象
    :return: 酒精平均含量,类型为float
    '''
    #********* Begin *********#
    return data.data[:,0].mean()
    #********* End **********#

第2关 对数据进行标准化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from sklearn.preprocessing import StandardScaler

def scaler(data):
    '''
    返回标准化后的红酒数据
    :param data: 红酒数据对象
    :return: 标准化后的红酒数据,类型为ndarray
    '''

    #********* Begin *********#
    scaler=StandardScaler()
    after_scaler=scaler.fit_transform(data['data'])
    return after_scaler
    #********* End **********#

第3关 使用kNN算法进行预测

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler

def classification(train_feature, train_label, test_feature):
    '''
    对test_feature进行红酒分类
    :param train_feature: 训练集数据,类型为ndarray
    :param train_label: 训练集标签,类型为ndarray
    :param test_feature: 测试集数据,类型为ndarray
    :return: 测试集数据的分类结果
    '''

    #********* Begin *********#
    scaler=StandardScaler()
    train_feature=scaler.fit_transform(train_feature)
    test_feature=scaler.transform(test_feature)
    clf=KNeighborsClassifier()
    clf.fit(train_feature,train_label)
    return clf.predict(test_feature)

    #********* End **********#

机器学习-线性回归

第1关 数据载入与分析

1
2
3
4
5
6
7
8
9
10
11
#encoding=utf8
import os
import pandas as pd

if __name__ == "__main__":
    path = os.getcwd() + '/ex1data1.txt'
    #利用pandas读入数据data,并将数据属性分别命名为'Population'和'Profit'
    #********* begin *********#
    data = pd.read_csv(path,header=None,names=['Population','Profit'])
    #********* end *********#
    print(data.shape)

第2关 计算损失函数

1
2
3
4
5
6
7
8
9
10
11
12
#encoding=utf8

import numpy as np

def computeCost(X, y, theta):
    #根据公式编写损失函数计算函数
    #********* begin *********#
    inner = np.power(((X * theta.T) - y), 2)
    cost=np.sum(inner) / (2 * len(X))
    cost=round(cost,10)
    #********* end *********#
    return cost

第3关 进行梯度下降得到线性模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#encoding=utf8
import numpy as np

def computeCost(X, y, theta):
    inner = np.power(((X * theta.T) - y), 2)
    return np.sum(inner) / (2 * len(X))

def gradientDescent(X, y, theta, alpha, iters):
    temp = np.matrix(np.zeros(theta.shape))
    parameters = int(theta.ravel().shape[1])
    cost = np.zeros(iters)
    for i in range(iters):
        error = (X * theta.T) - y
        for j in range(parameters):
            #********* begin *********#
            term = np.multiply(error, X[:,j])
            temp[0,j] = theta[0,j] - ((alpha / len(X)) * np.sum(term))    
            #********* end *********#
        theta = temp
        cost[i] = computeCost(X, y, theta)
    return theta, cost

第4关 建立完整线性回归模型

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
#encoding=utf8

import os
import numpy as np
import pandas as pd

#载入数据并进行数据处理
path = os.getcwd() + '/ex1data1.txt'
#********* begin *********#
data=pd.read_csv(path,header=None,names=['Population','Profit'])

#********* end *********#
data.insert(0, 'Ones', 1)
cols = data.shape[1]
X = data.iloc[:,0:cols-1]
y = data.iloc[:,cols-1:cols]

#初始化相关参数
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))
alpha = 0.01
iters = 1000

#定义损失函数

def computeCost(X, y, theta):
    #********* begin *********#
    inner = np.power(((X * theta.T) - y), 2)
    cost=np.sum(inner) / (2 * len(X))

    #********* end *********#
    return cost

#定义梯度下降函数
def gradientDescent(X, y, theta, alpha, iters):
    temp = np.matrix(np.zeros(theta.shape))
    parameters = int(theta.ravel().shape[1])
    cost = np.zeros(iters)
    for i in range(iters):
        error = (X * theta.T) - y
        for j in range(parameters):
            #********* begin *********#
            term = np.multiply(error, X[:,j])
            temp[0,j] = theta[0,j] - ((alpha / len(X)) * np.sum(term))

            #********* end *********#            
        theta = temp
        cost[i] = computeCost(X, y, theta)        
    return theta, cost

#根据梯度下架算法得到最终线性模型参数
g, cost = gradientDescent(X, y, theta, alpha, iters)

print("模型参数为:", g)