一、boston房價預測
#1. 讀取數據集 from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split data = load_boston() #2. 訓練集與測試集划分 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)
#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("預測的均方誤差:", 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("預測的均方誤差:", 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,而非線性就是至少有一個變量的指數不是1。
通過指數來進行判斷即可。
線性回歸模型:是利用數理統計中回歸分析,來確定兩種或兩種以上變量間相互依賴的定量關系的一種統計分析方法,運用十分廣泛。其表達形式為y = w'x+e,e為誤差服從均值為0的正態分布。線性回歸模型是利用稱為線性回歸方程的最小平方函數對一個或多個自變量和因變量之間關系進行建模的一種回歸分析。這種函數是一個或多個稱為回歸系數的模型參數的線性組合。只有一個自變量的情況稱為簡單回歸,大於一個自變量情況的叫做多元回歸。
非線性回歸模型:是在掌握大量觀察數據的基礎上,利用數理統計方法建立因變量與自變量之間的回歸關系函數表達式(稱回歸方程式)。回歸分析中,當研究的因果關系只涉及因變量和一個自變量時,叫做一元回歸分析;當研究的因果關系涉及因變量和兩個或兩個以上自變量時,叫做多元回歸分析。
二、中文文本分類
import os import numpy as np import sys from datetime import datetime import gc path = 'C:\\Users\\Administrator\\Desktop\\0369' import jieba with open(r'C:\Users\Administrator\Desktop\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 = [] 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() # 用os.walk獲取需要的變量,並拼接文件路徑再打開每一個文件 target = filePath.split('\\')[-2] targetList.append(target) tokenList.append(processing(content))# 獲取新聞類別標簽,並處理該新聞 print(tokenList) print(targetList)
運行結果:
# 划分訓練集測試集並建立特征向量,為建立模型做准備 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) # 划分訓練集測試集 vectorizer = TfidfVectorizer() X_train = vectorizer.fit_transform(x_train) X_test = vectorizer.transform(x_test) # 轉化為特征向量,這里選擇TfidfVectorizer的方式建立特征向量。不同新聞的詞語使用會有較大不同。 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() # 畫圖
運行結果: