一、boston房價預測
1. 讀取數據集
from sklearn.datasets import load_boston boston = load_boston() boston.keys() print(boston.DESCR) boston.data.shape import pandas as pd pd.DataFrame(boston.data)
運行結果:

2. 訓練集與測試集划分
from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test = train_test_split(boston.data,boston.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('線性回歸模型:')
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("多項式回歸模型:")
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.獲取文件,寫文件
import os
import numpy as np
import sys
from datetime import datetime
import gc
path = 'E:\\E\\Pycharm\\12.6期末作業\\147'
import jieba
with open(r'E:\\stopsCN.txt',encoding='utf-8') as f: # 打開停用詞文本,將無用的詞讀入進去
stopwords = f.read().split('\n')
2.除去噪聲,如:格式轉換,去掉符號,整體規范化
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
3.遍歷每個個文件夾下的每個文本文件,使用jieba分詞將中文文本切割
tokenList = []
targetList = []
for root,dirs,files in os.walk(path):
for f in files:
filePath = os.path.join(root,f)
with open(filePath,encoding='gb18030',errors='ignore') as f:
content = f.read()
target = filePath.split('\\')[-2]
targetList.append(target)
tokenList.append(processing(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.3,train_size=0.7)
vectorizer = TfidfVectorizer()
X_train = vectorizer.fit_transform(x_train)
X_test = vectorizer.transform(x_test)
from sklearn.naive_bayes import MultinomialNB
# 多項式朴素貝葉斯
mnb = MultinomialNB()
module = mnb.fit(X_train,y_train)
y_predict = module.predict(X_test)
# 對數據進行5次分割
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))
運行結果:

4.
targetList.append(target) print(targetList[0:10]) tokenList.append(processing(content)) tokenList[0:10]
運行結果:(很顯然,結果不理想,說明前面的代碼有問題,改正之后再更新)

