1.决策树
2.随机森林
3.jupyter notebook
4.贝叶斯公式
5.朴素贝叶斯
4.周测
1.决策树
决策树.py
from sklearn.tree import DecisionTreeClassifier
#创建分类器对象
tree=DecisionTreeClassifier(criterion="entropy")
#训练数据fit
tree.fit([[0],[1],[2],[3]],["a","a","b","c"])
#预测新数据
target=tree.predict([[2]])
#模型评估,打分,验证方法,评估方式
print(target)
print(tree.score([[2]],target))
决策树–鸢尾花.py
#用决策树对鸢尾花进行分类
from sklearn.tree import DecisionTreeClassifier,plot_tree
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
#获取数据集
iris=load_iris()
print(iris)
#划分数据集(传入特征值,目标值,划分的比例以及随机种子)
X_train, X_test, y_train, y_test=train_test_split(iris.data,iris.target,test_size=0.3,random_state=30)
#创建决策树预估器(利用决策树对象学习训练集,预测测试集)
tree=DecisionTreeClassifier(criterion="gini",max_depth=2)
tree.fit(X_train,y_train)
target=tree.predict(X_test)
#模型评估,(使用测试集中特征和目标对决策树打分)
print("预测结果:",target)
print("对比",target==y_test)
print("打分结果:",tree.score(X_test,y_test))
plt.figure(figsize=(12,11),dpi=80)
plot_tree(tree,feature_names=iris.feature_names)
plt.show()
决策树–鸢尾花–网格交叉搜索.py
#用决策树对鸢尾花进行分类
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split,GridSearchCV
#获取数据集
iris=load_iris()
print(iris)
#划分数据集(传入特征值,目标值,划分的比例以及随机种子)
X_train, X_test, y_train, y_test=train_test_split(iris.data,iris.target,test_size=0.3,random_state=30)
#创建决策树预估器(利用决策树对象学习训练集,预测测试集)
tree=DecisionTreeClassifier(criterion="gini",max_depth=2)
#创建网格交叉搜索的对象,传入分类器对象,param_grid用于指定分类器对象tree可以调整的参数,字典格式
gsc=GridSearchCV(tree,param_grid={"criterion":["gini","entropy","cart"],'max_depth':range(1,21),"min_samples_split":range(1,11)})
#学习、训练数据
gsc.fit(X_train,y_train)
#预测
target=gsc.predict(X_test)
#模型评估,(使用测试集中特征和目标对决策树打分)
print("预测结果:",target)
print("对比结果:",target==y_test)
print("打分结果:",gsc.score(X_test,y_test))
print("最优参数:",gsc.best_params_)
print("最优分数:",gsc.best_score_)
print("最优分类器:",gsc.best_estimator_)
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction import DictVectorizer
from sklearn.tree import DecisionTreeClassifier,export_graphviz
import pydotplus
titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')
#选取一些特征作为我们划分的依据
x = titanic[['pclass', 'age', 'sex']]
y = titanic['survived']
# print(x)
#缺失值处理
x['age'].fillna(x['age'].mean(), inplace=True)
#分割数据集到训练集合测试集
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25)
#进行处理(特征工程)特征-》类别-》one_hot编码
dict=DictVectorizer(sparse=False)
x_train = dict.fit_transform(x_train.to_dict(orient="records"))
print(dict.get_feature_names())
x_test = dict.fit_transform(x_test.to_dict(orient="records"))
# print(x_train)
#用决策树进行预测
dec=DecisionTreeClassifier()
dec.fit(x_train,y_train)
print("预测的准确率:",dec.score(x_test,y_test))
#导出决策树的结构
# export_graphviz(dec,out_file='./tree1.pdf',feature_names=['年龄', 'pclass=1st', 'pclass=2nd', 'pclass=3rd', '女性', 'sex=male'])
dot_data = export_graphviz(dec, out_file=None)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf("tree2.pdf")
决策树–乳腺癌.py
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split,GridSearchCV
import pandas as pd
pd.set_option("max_columns",None) #显示所有列
# pd.set_option("max_rows",None) #显示所有行
#加载数据
df=pd.read_csv("wisc_bc_data.csv")
print(df)
#特征列切出来
data=df.loc[:,"radius_mean":].copy()
# print(data)
#标准化
scaler=StandardScaler()
data=scaler.fit_transform(data)
# print(data)
#特征值和目标值划分
X_train, X_test, y_train, y_test=train_test_split(data,df["diagnosis"],test_size=0.3,random_state=42)
#训练算法
tree=DecisionTreeClassifier()
#创建网格交叉搜索的对象,传入分类器对象,param_grid用于指定分类器对象tree可以调整的参数,字典格式
gsc=GridSearchCV(tree,param_grid={"criterion":["gini","entropy","cart"],'max_depth':range(1,21),"min_samples_split":range(1,11)})
#网格交叉搜索
tree.fit(X_train,y_train)
gsc.fit(X_train,y_train)
#预测
# target=tree.predict(X_test)
target=gsc.predict(X_test)
# print(target)
print("预测结果:",target)
print("对比结果:",target==y_test)
print("打分结果:",gsc.score(X_test,y_test))
print("最优参数:",gsc.best_params_)
print("最优分数:",gsc.best_score_)
结果:
2.随机森林
随机森林-乳腺癌.py
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import MinMaxScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split,GridSearchCV
import pandas as pd
from sklearn.datasets import load_breast_cancer
pd.set_option("max_columns",None) #显示所有列
# pd.set_option("max_rows",None) #显示所有行
#加载数据
cancer=load_breast_cancer()
print(cancer)
#处理数据
scaler=MinMaxScaler()
data=scaler.fit_transform(cancer.data)
#划分数据集
X_train, X_test, y_train, y_test=train_test_split(data,cancer.target,test_size=0.3,random_state=42)
#训练算法
random=RandomForestClassifier()
#创建网格交叉搜索的对象,传入分类器对象,param_grid用于指定分类器对象tree可以调整的参数,字典格式
gsc=GridSearchCV(random,param_grid={"criterion":["gini","entropy","cart"],'max_depth':[3,5,7,10,15],"n_estimators":[10,20,30,100,150]})
#预测
gsc.fit(X_train,y_train)
target=gsc.predict(X_test)
#打分
print("打分结果:",gsc.score(X_test,y_test))
print("最优参数:",gsc.best_params_)
print("最优分数:",gsc.best_score_)
结果:
3.jupyter notebook
注意:如果pip升级不成功的话有两种方法:
问题来源:pip 20.1.1升级20.2.2升级不成功?
第一种:
第一步:先删除pip 命令: python -m pip uninstall pip
第二步: python -m ensurepip
第三步: python -m pip install --upgrade pip -i https://pypi.douban.com/simple 一定要加上镜像才能成功
此时pip升级成功,若进入pycharm中,发现pip版本依旧是老版本,在Terminal中执行第三步即可
第二种:
执行命令:python -m pip install -U --force-veinstall pip
4.贝叶斯公式
5.朴素贝叶斯
朴素贝叶斯.py
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.datasets import fetch_20newsgroups,load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
news=fetch_20newsgroups()
print(news.keys())#news.data 特征数据 new.target 类别(目标值) news.target_name 类别名称
tf=TfidfVectorizer(stop_words=["she","you"])
new_data=tf.fit_transform(news.data)
X_train, X_test, y_train, y_test=train_test_split(new_data,news.target,test_size=0.3,random_state=42)
nb=MultinomialNB()
nb.fit(X_train,y_train)
#预测的类别
target=nb.predict(X_test)
#对比
print(target==y_test)
#打分
print(nb.score(X_test,y_test))
结果:
4.周测
1、当前有棒球运动员的体脂数据(baseballs.csv),训练算法。给定一个球员(体重74,身高191),判
断属于哪一种体脂(<18为A,1823为B,2328为C,28以上的为D),是否合格
提示:数据目标值不一定准确,需要先处理,再学习
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
#1.加载数据集
data=pd.read_csv("baseballs.csv")
#BMI的取值范围划分: <20 是A,20-25 是b 25-30是C 30以上是D
#BMI=“体重指数的计算方法是体质指数(BMI)=体重(kg)÷身高^2(m),例如身高1.6m、体重50kg,其体重
# 指数BMI=50÷1.6²=19.53。”
# 原数据集中目标值不太准备,重新计算目标值
data["BMI"]=np.round(data["weight"]/(data["height"]/100*data["height"]/100),1)
print(data)
def change(x):
if x<20:
return "A"
elif x>=20 and x<=25:
return "B"
elif x>25 and x<=30:
return "C"
else:
return "D"
# 目标值离散化
data["bfat"]=data["BMI"].apply(lambda x:change(x))
print("修正后的数据是:",data)
x=data[["weight","height"]].values #特征值
y=data["bfat"].values #目标值
#划分数据集
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42
)
#特征工程:做数据标准化,实现无量纲化
std=StandardScaler()
x_train=std.fit_transform(x_train)
x_test=std.transform(x_test)
#模型训练:1)创建分类器对象 2)调用fit()
knnClasser=KNeighborsClassifier(n_neighbors=3)
knnClasser.fit(x_train, y_train)
#模型验证:
y_pred=knnClasser.predict(x_test)
print("比较预测值和真实值:")
print(y_pred==y_test)
print("对测试集预测的准确率是:", knnClasser.score(x_test, y_test))
# 给定一个球员(体重74,身高191),判断属于哪一种体脂,是否合格
obj1=[[74,191]]
obj1=std.transform(obj1)
print("对给定数据的预测结果是:",knnClasser.predict(obj1))
2、分析所学分类算法中,哪一个算法预测乳腺癌是最准确的算法?
df=pd.read_csv("wisc_bc_data.csv")
print(df)
#特征列切出来
data=df.loc[:,"radius_mean":].copy()
# print(data)
#标准化
scaler=StandardScaler()
data=scaler.fit_transform(data)
# print(data)
#特征值和目标值划分
X_train, X_test, y_train, y_test=train_test_split(data,df["diagnosis"],test_size=0.3,random_state=42)
#训练算法
tree=DecisionTreeClassifier()
#创建网格交叉搜索的对象,传入分类器对象,param_grid用于指定分类器对象tree可以调整的参数,字典格式
gsc=GridSearchCV(tree,param_grid={"criterion":["gini","entropy","cart"],'max_depth':range(1,21),"min_samples_split":range(1,11)})
#网格交叉搜索
tree.fit(X_train,y_train)
gsc.fit(X_train,y_train)
#预测
# target=tree.predict(X_test)
target=gsc.predict(X_test)
# print(target)
print("打分结果:",gsc.score(X_test,y_test))
print("最优参数:",gsc.best_params_)
print("最优分数:",gsc.best_score_)
3、根据银行贷款数据,训练算法,要求在0.98分以上。给定一个客户信息(无公积金,存款30万,无房
子,无信用污点),预测银行是否审批
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.preprocessing import StandardScaler,LabelEncoder
plt.rcParams['font.sans-serif'] = ['SimHei'] #避免中文乱码
plt.rcParams['axes.unicode_minus'] = False #避免符号乱码
#加载数据集
data=pd.read_csv("loans.csv")
print(data)
#数据预处理
encoder= LabelEncoder()
data["公积金"]=encoder.fit_transform(data["公积金"])
data["信用污点"]=encoder.fit_transform(data["信用污点"])
print(data)
x=data[["公积金","存款","房子数量","信用污点"]]
y=data["审批结果"].values
#划分数据集
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42
)
#特征工程
#模型训练:1)创建分类器对象 2)调用fit()
treeClasser=DecisionTreeClassifier(max_depth=5)
treeClasser.fit(x_train,y_train)
#模型验证:
y_pred=treeClasser.predict(x_test)
print("比较预测值和真实值:")
print(y_pred==y_test)
print("对测试集预测的准确率是:",treeClasser.score(x_test,y_test))
#可视化
plt.figure(figsize=(70,70),dpi=40) #设置画布大小和分辨率
plot_tree(treeClasser,feature_names=x.columns)
plt.show()
obj1=[[0,300000,2,0]] #指定给定数据
print("对给定数据的预测结果是:\n",treeClasser.predict(obj1))