簡單的線性回歸預測房價
#!/usr/bin/env python # encoding: utf-8 """ @version: @author: --*--. @file: LinearRegression.py @time: 2018/11/1 11:05 @desc: """ # Required Packages import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model def get_data(): """ 生成隨機的線性數據集 :return: """ x = 100 * np.random.rand(100, 1).astype(np.float32) y = 2 * x + 10 # 直線 # y = 7 * x ** 5 + 3 * x + 10 # 曲線 y += 50 * np.random.rand(100, 1).astype(np.float32) return x, y # Function for Fitting our data to Linear model def linear_model_main(X_parameters, Y_parameters, predict_value): # Create linear regression object regr = linear_model.LinearRegression() regr.fit(X_parameters, Y_parameters,sample_weight=None) # 權重 predict_outcome = regr.predict(predict_value) predictions = {} predictions['intercept'] = regr.intercept_ predictions['coefficient'] = regr.coef_ predictions['predicted_value'] = predict_outcome return predictions # Function to show the resutls of linear fit model def show_linear_line(X_parameters, Y_parameters, predictvalue): # Create linear regression object regr = linear_model.LinearRegression() regr.fit(X_parameters, Y_parameters) fig = plt.figure() ax1 = fig.add_subplot(111) # 設置標題 ax1.set_title('Housing Forecast') ax1.scatter(X_parameters, Y_parameters, color='blue', marker='*') ax1.plot(X_parameters, regr.predict(X_parameters), color='c', linewidth=1) # 畫點 ax1.scatter(predictvalue, regr.predict(predictvalue), color='red') # 畫水平虛線 plt.axvline(x=predictvalue, ls='dotted', color='y') plt.axhline(y=regr.predict(predictvalue), ls='dotted', color='y') plt.xlabel('x:area') plt.ylabel('y:price') plt.show() if __name__ == "__main__": X, Y = get_data() predictvalue = 90 # 面積 # 新版必須2維哦 predictvalue = np.array(predictvalue,dtype=np.int32).reshape(1, -1) result = linear_model_main(X, Y, predictvalue) print("截距-Intercept value ", result['intercept']) print("回歸系數-coefficient", result['coefficient']) print("y-Predicted value: ", result['predicted_value']) print("面積 %d 的價格預測為 %d" % (predictvalue, result['predicted_value'])) show_linear_line(X, Y, predictvalue)
輸出結果為:
/usr/bin/python3.5 /home/think-hxr/PycharmProjects/MachineLearningAlgorithms/LinearRegression.py Intercept value [ 38.77058411] coefficient [[ 1.92119944]] Predicted value: [[ 211.67853379]] 面積 90 的價格預測為 211
畫圖: