- 算法是核心,数据和计算是基础
-
数据类型
1、离散数据类型
2、连续数据类型
-
机器学习算法分类
监督学习:特征值+目标值
无监督学习:只有特征值,无目标值
分类:目标值离散型
回归:目标值连续型
-
分类算法
k-近邻算法:根据你的邻居来判断你的类别
k-近邻算法的计算公式:
注意:k-近邻算法,需要做标准化处理 -
sklearn k-近邻算法API
k-近邻算法的例子:
from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import pandas as pd def knncls(): """ K-近邻预测用户签到位置 """ # 1、读取数据 data = pd.read_csv("./data/FBlocation/train.csv") # print(data.head(10)) # 打印前十行 # 2、处理数据 # 2.1 缩小数据,查询数据筛选 data = data.query("x>1.0 & x<1.25 & y>2.5 & y<2.75") # 2.2 处理时间 time_value = pd.to_datatime(data['time'], unit='s') # print(time_value) # 2.3 把日期格式转换成字典格式 time_value = pd.DatetimeIndex(time_value) # 2.4 构造一些特征 data['day'] = time_value.day data['hour'] = time_value.hour data['weekday'] = time_value.weekday # 2.5 把时间特征删除 data = data.drop(['time'], axis=1) # 按列删除 # 2.6 把签到数量少于n个目标位置删除 place_count = data.groupby('place_id').count() tf = place_count[place_count.row_id > 3].reset_index() data = data[data['place_id'].isin(tf.place_id)] # 2.7 取出数据中的特征值和目标值 y = data['place_id'] x = data.drop(['place_id'], axis=1) # 2.8 进行数据分割,训练集与测试集 x_train, x_test, y_train, x_test = train_test_split(x, y, test_size=0.25) # 3、特征工程(标准化) std = StandardScaler() # 对测试集与训练集的特征值做标准化 x_train = std.fit_transform(x_train) x_test = std.transform(x_test) # 4、进行算法流程 knn = KNeighborsClassifier(n_neighbors=5) knn.fit(x_train, y_train) # 得出预测结果 y_predict = knn.predict(x_test) print("预测的目标签到位置为:", y_predict) # 得出准确率 print("预测准确率:", knn.score(x_test. x_)) return None if __name__ == "__main__": knncls()
-
朴素贝叶斯算法
概率想关知识:
朴素贝叶斯算法:适用特征独立的数据
- API:
sklearn.naive_bayes.MultinomialNB(alpha=1.0)
朴素贝叶斯算法例子:from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB def naviebayes(): """ 朴素贝叶斯进行文本分类 """ # 获取数据 news = fetch_20newsgroups(subset='all') # 进行数据分割 x_train, x_test, y_train, y_test = train_test_split(new.data, news.target, test_size=0.25) # 对数据集进行特征抽取 tf = TfidfVectorizer() # 以训练集当中词的列表进行每篇文章重要性统计 x_train = tf.fit_transform(x_train) print(tf.get_feature_names()) x_test = tf.fit_transform(x_test) # 进行朴素贝叶斯算法预测 mlt = MultinomialNB(alpha=1.0) print(x_train.toarry()) mlt.fit(x_train, y_train) y_predict = mlt.predict(x_test) print("预测文章的类别为:", y_predict) # 得出准确率 print("准确率为:", mlt.score(x_test, y_test)) return None if __name__ == "__main__": naviebayes()
总结朴素贝叶斯分类:
-
分类模型效果评估标准:
1、准确率
2、精确率
3、召回率
- 分类模型评估API
API:sklearn.metrics.classification_report
- 模型的选优
1、交叉验证,将训练集数据分成训练集与验证集,数据不包括测试集
2、超参数搜索-网格搜索API
API:sklearn.model_selection.GridSearchCV
from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.preprocessing import StandardScaler import pandas as pd def knncls(): """ K-近邻预测用户签到位置 """ # 1、读取数据 data = pd.read_csv("./data/FBlocation/train.csv") # print(data.head(10)) # 打印前十行 # 2、处理数据 # 2.1 缩小数据,查询数据筛选 data = data.query("x>1.0 & x<1.25 & y>2.5 & y<2.75") # 2.2 处理时间 time_value = pd.to_datatime(data['time'], unit='s') # print(time_value) # 2.3 把日期格式转换成字典格式 time_value = pd.DatetimeIndex(time_value) # 2.4 构造一些特征 data['day'] = time_value.day data['hour'] = time_value.hour data['weekday'] = time_value.weekday # 2.5 把时间特征删除 data = data.drop(['time'], axis=1) # 按列删除 # 2.6 把签到数量少于n个目标位置删除 place_count = data.groupby('place_id').count() tf = place_count[place_count.row_id > 3].reset_index() data = data[data['place_id'].isin(tf.place_id)] # 2.7 取出数据中的特征值和目标值 y = data['place_id'] x = data.drop(['place_id'], axis=1) # 2.8 进行数据分割,训练集与测试集 x_train, x_test, y_train, x_test = train_test_split(x, y, test_size=0.25) # 3、特征工程(标准化) std = StandardScaler() # 对测试集与训练集的特征值做标准化 x_train = std.fit_transform(x_train) x_test = std.transform(x_test) # 4、进行算法流程 knn = KNeighborsClassifier() # 构造一些参数值进行搜索 param = {"n_neighbors": [3, 5, 10]} # 进行网格搜索 gc = GridSearchCV(knn, param_grid=param, cv=10) gc.fit(x_train, y_train) # 预测准确率 print("在测试集上的准确率:", gc.score) print("在交叉验证当中最好的结果:", gc.best_score_) print("选择最好的模型是:", gc.best_estimator_) print("每个超参数每次交叉验证的精确率与召回率:", gc.cv_results_) return None if __name__ == "__main__": knncls()
-
决策树
-
决策树的划分依据
1、信息增益:当得知一个特征条件之后,减少的信息熵的大小
例子:
基尼系数:划分更加仔细 -
API
from sklearn.tree import DecisionTreeClassifier from sklearn.feature_extraction import DictVectorizer from sklearn.model_selection import train_test_split import pandas as pd def decision(): """ 决策树对泰坦尼克号进行预测生死 """ # 1、获取数据 titan = pd.read_csv("http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titan.txt") # 2、处理数据,找出特征值和目标值 x = titan[['pclass', 'age', 'sex']] y = titan['survived'] # 2.1 缺失值处理 x['age'] = .fillna(x['age'].mean(), inplace=True) # 2.2 分割数据集到训练集和测试集 x_train, x_test, y_train, x_test = train_test_split(x, y, test_size=0.25) # 3、进行处理(特征工程)特征-> 类别 one_hot编码 dict = DictVectorizer(sparse=False) x_train = dict.fit_transform(x_train.to_dict(orient="records")) x_test = dict.tansform(x_test.to_dict(orient="records")) # 4、用决策数进行预测 dec = DecisionTreeClassifier() dec.fit(x_train, y_train) # 4、1 预测准确率 print("预测的准确率:", dec.score(x_test, y_test)) return None if __name__ == "__main__": decision()
-