一、boston房价预测
#1. 读取数据集 from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split data = load_boston() #2. 训练集与测试集划分 x_train,x_test,y_train,y_test = train_test_split(data.data,data.target,test_size=0.3) print(x_train.shape,y_train.shape)
#3. 线性回归模型:建立13个变量与房价之间的预测模型,并检测模型好坏。 from sklearn.linear_model import LinearRegression mlr = LinearRegression() mlr.fit(x_train,y_train) print('系数',mlr.coef_,"\n截距",mlr.intercept_) from sklearn.metrics import regression y_predict = mlr.predict(x_test) # 检测模型好坏 print("预测的均方误差:", regression.mean_squared_error(y_test,y_predict)) print("预测的平均绝对误差:", regression.mean_absolute_error(y_test,y_predict)) # 计算模型的预测指标 print("模型的分数:",mlr.score(x_test, y_test))
运行结果:
#4. 多项式回归模型:建立13个变量与房价之间的预测模型,并检测模型好坏。 from sklearn.preprocessing import PolynomialFeatures poly2 = PolynomialFeatures(degree=2) x_poly_train = poly2.fit_transform(x_train) x_poly_test = poly2.transform(x_test) # 多项式化 mlrp = LinearRegression() mlrp.fit(x_poly_train, y_train) # 建立模型 y_predict2 = mlrp.predict(x_poly_test) # 预测 print("预测的均方误差:", regression.mean_squared_error(y_test,y_predict2)) print("预测的平均绝对误差:", regression.mean_absolute_error(y_test,y_predict2)) # 计算模型的预测指标 print("模型的分数:",mlrp.score(x_poly_test, y_test))
运行结果:
5. 比较线性模型与非线性模型的性能,并说明原因。
线性回归模型和非线性回归模型的区别是:
线性就是每个变量的指数都是1,而非线性就是至少有一个变量的指数不是1。
通过指数来进行判断即可。
线性回归模型:是利用数理统计中回归分析,来确定两种或两种以上变量间相互依赖的定量关系的一种统计分析方法,运用十分广泛。其表达形式为y = w'x+e,e为误差服从均值为0的正态分布。线性回归模型是利用称为线性回归方程的最小平方函数对一个或多个自变量和因变量之间关系进行建模的一种回归分析。这种函数是一个或多个称为回归系数的模型参数的线性组合。只有一个自变量的情况称为简单回归,大于一个自变量情况的叫做多元回归。
非线性回归模型:是在掌握大量观察数据的基础上,利用数理统计方法建立因变量与自变量之间的回归关系函数表达式(称回归方程式)。回归分析中,当研究的因果关系只涉及因变量和一个自变量时,叫做一元回归分析;当研究的因果关系涉及因变量和两个或两个以上自变量时,叫做多元回归分析。
二、中文文本分类
import os import numpy as np import sys from datetime import datetime import gc path = 'C:\\Users\\Administrator\\Desktop\\0369' import jieba with open(r'C:\Users\Administrator\Desktop\stopsCN.txt', encoding='utf-8') as f: #导入停用词 stopwords = f.read().split('\n') def processing(tokens): tokens = "".join([char for char in tokens if char.isalpha()]) # 去掉非字母汉字的字符 tokens = [token for token in jieba.cut(tokens,cut_all=True) if len(token) >=2] #结巴分词 tokens = " ".join([token for token in tokens if token not in stopwords]) #去掉停用词 return tokens tokenList = [] targetList = [] for root,dirs,files in os.walk(path): for f in files: filePath = os.path.join(root,f) with open(filePath, encoding='utf-8') as f: content = f.read() # 用os.walk获取需要的变量,并拼接文件路径再打开每一个文件 target = filePath.split('\\')[-2] targetList.append(target) tokenList.append(processing(content))# 获取新闻类别标签,并处理该新闻 print(tokenList) print(targetList)
运行结果:
# 划分训练集测试集并建立特征向量,为建立模型做准备 from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB,MultinomialNB from sklearn.model_selection import cross_val_score from sklearn.metrics import classification_report x_train,x_test,y_train,y_test = train_test_split(tokenList,targetList,test_size=0.2,stratify=targetList) # 划分训练集测试集 vectorizer = TfidfVectorizer() X_train = vectorizer.fit_transform(x_train) X_test = vectorizer.transform(x_test) # 转化为特征向量,这里选择TfidfVectorizer的方式建立特征向量。不同新闻的词语使用会有较大不同。 mnb = MultinomialNB() module = mnb.fit(X_train, y_train) y_predict = module.predict(X_test) #进行预测 scores=cross_val_score(mnb,X_test,y_test,cv=5) print("Accuracy:%.3f"%scores.mean()) # 输出模型精确度 print("classification_report:\n",classification_report(y_predict,y_test)) # 输出模型评估报告
运行结果:
# 将预测结果和实际结果进行对比 import collections import matplotlib.pyplot as plt from pylab import mpl mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体 mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 testCount = collections.Counter(y_test) predCount = collections.Counter(y_predict) print('实际:',testCount,'\n', '预测', predCount) # 统计测试集和预测集的各类新闻个数 nameList = list(testCount.keys()) testList = list(testCount.values()) predictList = list(predCount.values()) x = list(range(len(nameList))) print("新闻类别:",nameList,'\n',"实际:",testList,'\n',"预测:",predictList) # 建立标签列表,实际结果列表,预测结果列表, plt.figure(figsize=(7,5)) total_width, n = 0.6, 2 width = total_width / n plt.bar(x, testList, width=width,label='实际',fc = 'g') for i in range(len(x)): x[i] = x[i] + width plt.bar(x, predictList,width=width,label='预测',tick_label = nameList,fc='b') plt.grid() plt.title('实际和预测对比图',fontsize=17) plt.xlabel('新闻类别',fontsize=17) plt.ylabel('频数',fontsize=17) plt.legend(fontsize =17) plt.tick_params(labelsize=15) plt.show() # 画图
运行结果: