期末大作业

boston房价预测

1. 读取数据集

from   sklearn.datasets import load_boston

2. 训练集与测试集划分

boston = load_boston()
x = boston.data
y = boston.target
print(x.shape)
print(y.shape)

3. 线性回归模型:建立13个变量与房价之间的预测模型,并检测模型好坏。

# 建立多元线性回归模型
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个变量与房价之间的预测模型,并检测模型好坏。

# 多元多项式回归模型
# 多项式化
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. 比较线性模型与非线性模型的性能,并说明原因。

一个模型如果是线性的,就意味着它的参数项要么是常数,要么是原参数和要预测的特征之间的乘积加和就是我们要预测的值。

如果一个回归等式是线性的,那么它的相对于参数就必须也是线性的。

如果相对于参数是线性,那么即使性对于样本变量的特征是二次方或者多次方,这个回归模型也是线性的 

最简单的判断一个模型是不是非线性,就是关注非线性本身,判断它的参数是不是非线性的。

与线性模型不一样的是,非线性模型的特征因子对应的参数不止一个。

 

 

 

 

 

 

 

————————————————————————————————————————————————————————————————————————————————————————————

 5.中文文本分类

import os    #调用os

import numpy as np #调用numpy并命名为np按条件截取

import jieba #调用jieba
texts=r'C:\Users\xiaochunjie\Desktop\258'  #导入要进行分词的文件,命名为texts

wordList = jieba.cut(texts)    #进行分词

tokens=list(wordList) #以列表形式输出

tokens

path=r'C:\Users\xiaochunjie\Desktop\stopsCN.txt'   #导入无用字词文件
stops=np.loadtxt(path,dtype=str,delimiter=r'\t',encoding='utf-8')  #读取文件,字符型(str),用\t分隔,编码为utf-8

stops.shape #查看矩阵或是列表的维数

tokens=[token for token in tokens if token not in stops]  #如果tokens不在stops中,便让token 赋值给tokens,

#   格式规范化
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]     # 结巴分词,长度大于等于2
    tokens = " ".join([token for token in tokens if token not in path])     # 去掉停用词
    return tokens
tokenList = []
targetList = []
# 遍历每个个文件夹下的每个文本文件。
# 用os.walk获取需要的变量,并拼接文件路径再打开每一个文件
for root,dirs,files in os.walk(texts):
    for f in files:
        filePath = os.path.join(root,f) #链接文件路径
        with open(filePath, encoding='utf-8') as f: #用utf-8的形式打开文件 filePath 作为f
            content = f.read() #读取 f
            # 获取新闻类别标签,并处理该新闻
        target = filePath.split('\\')[-2] #取出类别 \\指定边界
       targetList.append(target)
        tokenList.append(processing(content))
#print(content)
# 划分训练集测试集并建立特征向量,为建立模型做准备
# 划分训练集测试集
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)
# text_size 样本占比测试集占数据集的比重 训练集 测试集划分
# 转化为特征向量,这里选择TfidfVectorizer的方式建立特征向量。不同新闻的词语使用会有较大不同。
vectorizer = TfidfVectorizer()
X_train = vectorizer.fit_transform(x_train) #拟合 数据标准化
X_test = vectorizer.transform(x_test)
# 建立模型,这里用多项式朴素贝叶斯,因为样本特征的a分布大部分是多元离散值
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) #输出5个预测精度,初始训练样本为5份,4份被用作训练集,1份做评估集,共做5次训练,得到5个训练结果
print("Accuracy:%.3f"%scores.mean())
# 输出模型评估报告
print("classification_report:\n",classification_report(y_predict,y_test)) #\n换行
# 将预测结果和实际结果进行对比
import collections
import matplotlib.pyplot as plt
from pylab import mpl
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))) #输出nameList的每个文字
print("新闻类别:",nameList,'\n',"实际:",testList,'\n',"预测:",predictList)

 

 

 

posted @ 2018-12-21 01:22  与冰  阅读(231)  评论(0编辑  收藏  举报