期末大做業

1、boston房價預測app

1. 讀取數據集性能

2. 訓練集與測試集劃分測試

3. 線性迴歸模型:創建13個變量與房價之間的預測模型,並檢測模型好壞。spa

4. 多項式迴歸模型:創建13個變量與房價之間的預測模型,並檢測模型好壞。3d

5. 比較線性模型與非線性模型的性能,並說明緣由。code

#數據讀取
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)
print(x_train.shape,y_train.shape)
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))

 

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))

 

 

 

2、中文文本分類orm

 

import os
path = r'C:\Users\Administrator\Desktop\0369'
data = []
target = []
fileList = os.listdir(path)
for f in fileList:
    file = os.path.join(path,f)
    print(file)

import os
import numpy as np
import sys
from datetime import datetime #引入datetime包裏的datetime類
import gc
path = 'E:\\0369'
import jieba #導入jieba和停用詞
with open(r'E:\\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獲取須要的變量,並拼接文件路徑再打開每個文件
#root是當前正在遍歷的這個文件夾的自己地址,dirs,files是一個list,dirs內容是
#該文件夾中全部的目錄的名字,files內容是該文件夾中全部的文件
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)
#把各種別追加到乾淨的tarList = []列表
        tokenList.append(processing(content))
#把預處理事後的文本追加到乾淨的txtList = [] 列表
 
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.3,stratify=targetList)
#轉化爲特徵向量,這裏選擇TfidfVectorizer的方式創建特徵向量。不一樣新聞的詞語使用會有較大不一樣
vectorizer = TfidfVectorizer()
X_train = vectorizer.fit_transform(x_train)
#對部分X訓練集數據先擬合,找到這部分的總體指標後,用transform進行轉換,實現數據的標準化、歸一化
X_test = vectorizer.transform(x_test)#對X測試集進行轉化
from sklearn.naive_bayes import MultinomialNB
#創建模型,這裏用多項式樸素貝葉斯,由於樣本特徵的分佈大部分是多元離散值
mnb = MultinomialNB() 
module
= mnb.fit(X_train,y_train)#擬合x,y訓練集數據
y_predict = module.predict(X_test) #進行預測,預測測試集
#驗證模型在訓練集上的穩定性,輸出5個預測精度,把初始訓練樣本分紅5份,其中4份用做訓練集,1份用做評估集,一共能夠對分類器作k次訓練,而且獲得k個訓練結果
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))

 

 

 

 

#獲取新聞類別標籤,並處理該新聞
targetList.append(target) print(targetList[
0:10]) tokenList.append(processing(content)) tokenList[0:10]

 

 

import collections
# 統計測試集和預測集的各種新聞個數
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)

 

相關文章
相關標籤/搜索