大作业

1、回归模型预测波士顿房价

代码:

 

# 多元线性回归模型
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split

# 波士顿房价数据集
data = load_boston()

# 划分数据集
x_train, x_test, y_train, y_test = train_test_split(data.data,data.target,test_size=0.3)

# 建立多元线性回归模型
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))

# 多元多项式回归模型
# 多项式化
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))

 

 

截图:

 

性能比较:

多项式回归做出来的模型显然会好一点。因为多项式模型不仅仅是一条直线,它是一条平滑的曲线,更贴合样本点的分布。并且多项式回归模型的误差也明显比线性的小。

 

2、新闻文本分类:

定义函数:读数据,清洗,分词。标签存入target_list,文本存入content_list

代码:

import os
import numpy as np
import sys
from datetime import datetime
import gc
path = 'F:\\计算机\\python\\挖掘\\data'

# 导入结巴库,并将需要用到的词库加进字典
import jieba
# 导入停用词:
with open(r'data\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))

 

截图:

 

 将content_list列表向量化再建模,将模型用于预测并评估模型

代码:

# 划分训练集测试集并建立特征向量,为建立模型做准备
# 划分训练集测试集
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)
# 转化为特征向量,这里选择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)
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()

截图:

 

转载于:https://www.cnblogs.com/traces2018/p/10101480.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
sqringboot大作业是一个基于springboot框架开发的项目,主要目的是实现一个完整的企业级应用程序。在这个项目中,我们需要使用springboot的特性来构建一个稳健、高效、可扩展的后端系统,同时还需要考虑与前端页面的无缝集成。 在sqringboot大作业中,我们首先需要对项目的架构进行设计和规划,确定后端的技术选型和数据库设计。然后我们需要编写各种模块的业务逻辑,包括用户管理、权限控制、数据管理等功能。同时,我们还需要考虑如何保证系统的安全性和稳定性,例如错误处理、日志记录、缓存优化等方面。 另外,在sqringboot大作业中,我们还需要实现与前端页面的交互,可以选择使用RESTful API或者GraphQL等方式来提供数据接口。我们需要确保后端系统的性能不受前端页面的影响,并且能够处理大量的并发请求。 除此之外,sqringboot大作业还需要考虑项目的测试和部署。我们需要编写各种单元测试和集成测试来保证系统的稳定性和功能的正确性。最后,我们还需要考虑系统的部署和运维,确保项目能够正常运行并且能够及时处理和修复各种问题。 总的来说,sqringboot大作业是一个综合性很强的项目,需要考虑的方面非常广泛,对团队成员的技术水平和团队协作能力都提出了很高的要求。因此,完成sqringboot大作业将会是一个非常有挑战性和收获丰富的项目。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值