大作业

一、boston房价预测

1. 读取数据集

2. 训练集与测试集划分

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

4. 多项式回归模型:建立13个变量与房价之间的预测模型,并检测模型好坏。

5. 比较线性模型与非线性模型的性能,并说明原因。

 

二、中文文本分类

按学号未位下载相应数据集。

147:财经、彩票、房产、股票、

258:家居、教育、科技、社会、时尚、

0369:时政、体育、星座、游戏、娱乐

分别建立中文文本分类模型,实现对文本的分类。基本步骤如下:

1.各种获取文件,写文件

2.除去噪声,如:格式转换,去掉符号,整体规范化

3.遍历每个个文件夹下的每个文本文件。

4.使用jieba分词将中文文本切割。

中文分词就是将一句话拆分为各个词语,因为中文分词在不同的语境中歧义较大,所以分词极其重要。

可以用jieba.add_word('word')增加词,用jieba.load_userdict('wordDict.txt')导入词库。

维护自定义词库

5.去掉停用词。

维护停用词表

6.对处理之后的文本开始用TF-IDF算法进行单词权值的计算

7.贝叶斯预测种类

8.模型评价

9.新文本类别预测

 

#1.回归模型预测波士顿房价
#导入load_boston数据
from sklearn.datasets import load_boston
data = load_boston()
#多元线性回归模型

from sklearn.model_selection import train_test_split

# 训练集与测试集划分为7:3
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)

#线性回归模型:建立13个变量与房价之间的预测模型,并检测模型好
#线性回归模型公式:y=^bx+^a
from sklearn.linear_model import LinearRegression
mlr = LinearRegression()
mlr.fit(x_train,y_train)
print('系数b',mlr.coef_,"\n截距a",mlr.intercept_)

#检测模型的好坏
from sklearn.metrics import regression
y_predict = mlr.predict(x_test)
#计算模型的预测指标
print('线性回归模型判断指数')
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))

#多项式回归模型:建立13个变量与房价之间的预测模型,并检测模型好坏。
# 多项式回归模型公式y = a0 + a1 * x + a2 * (x**2) + ... + an * (x ** n) + e
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("多项式回归模型判断指数")
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))

 

import os
import numpy as np
import sys
from datetime import datetime
import gc
path = 'F:\\nz258'


# 导入结巴库,并将需要用到的词库加进字典
import jieba
# 导入停用词:
with open(r'F:\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 = []
# 用os.walk获取需要的变量,并拼接文件路径再打开每一个文件
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()
            # 获取新闻类别标签,并处理该新闻
        target = filePath.split('\\')[-2]
        targetList.append(target)
        tokenList.append(processing(content))


#划分训练集和测试,用TF-IDF算法进行单词权值的计算
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
vectorizer= TfidfVectorizer()
x_train,x_test,y_train,y_test=train_test_split(tokenList,targetList,test_size=0.2)
X_train=vectorizer.fit_transform(x_train)
X_test=vectorizer.transform(x_test)


#构建贝叶斯模型
from sklearn.naive_bayes import MultinomialNB #用于离散特征分类,文本分类单词统计,以出现的次数作为特征值
mulp=MultinomialNB ()
mulp_NB=mulp.fit(X_train,y_train)
#对模型进行预测
y_predict=mulp.predict(X_test)
# # 从sklearn.metrics里导入classification_report做分类的性能报告
from sklearn.metrics import classification_report
print('模型的准确率为:', mulp.score(X_test, y_test))
print('classification_report:\n',classification_report(y_test, y_predict))

# 将预测结果和实际结果进行对比
import collections
import matplotlib.pyplot as plt

# 统计测试集和预测集的各类新闻个数
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)

posted on 2018-12-21 10:22  阿占  阅读(170)  评论(0编辑  收藏  举报

导航