from matplotlib import pyplot as plt
import numpy as np
import pandas as pd


"""
:param filename:
excel文件名
:return:
xArr - x数据集
yArr - y数据集
"""

m=30
for l in range(m):
    def loaddataset(filename):  # 导入EXCEL数据集
        data = pd.read_excel(filename)
        new_data = np.array(data)
        n = len(new_data)  # 矩阵的行
        x_vals = []
        y_vals = []
        for j in range(n):
            x_valss = np.array([new_data[j][i] for i in range(1)])  # 20是样本的特征（列），取的是随机样本的特征
            y_valss = np.array(new_data[j][l+1])
            print(y_valss)
            x_vals.append(x_valss)
            y_vals.append(y_valss)
        x_vals = np.array(x_vals)
        y_vals = np.array(y_vals)
        # print(x_vals)
        # print(y_vals)
        return x_vals, y_vals


    if __name__ == '__main__':
        abX, abY = loaddataset('1.xlsx')
        # plotDataSet_and_preset(abX , abY)

    from sklearn import linear_model
    from sklearn.preprocessing import PolynomialFeatures

    length = len(abX)
    # 将datasets_X转化为数组， 并变为二维，以符合线性回归拟合函数输入参数要求
    datasets_X = np.array(abX).reshape([length, 1])
    # 将datasets_Y转化为数组
    datasets_Y = np.array(abY)

    # degree=3表示建立datasets_X的二次多项式特征X_poly。
    poly_reg = PolynomialFeatures(degree=3)
    X_ploy = poly_reg.fit_transform(datasets_X)
    lin_reg_2 = linear_model.LinearRegression()
    lin_reg_2.fit(X_ploy, datasets_Y)

    # 查看回归方程系数
    print('系数：', lin_reg_2.coef_)
    # 查看回归方程截距
    print('截距：', lin_reg_2.intercept_)
    plt.scatter(datasets_X, datasets_Y, color='red')
    plt.plot(abX, lin_reg_2.predict(poly_reg.fit_transform(abX)), color='blue')
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.show()
    n = 19  # 输入数据x
    arr = lin_reg_2.coef_
    YYY = lin_reg_2.intercept_ + (arr[1]) * n + (arr[2]) * (n ** 2) + (arr[3]) * (n ** 3)
    print("第",l+1,"个省份：",YYY)