File size: 5,545 Bytes
0da9ad7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# 返回图片测试
from sklearn.linear_model import LinearRegression
from sklearn.neural_network import MLPRegressor
import lightgbm as lgb
from xgboost import XGBRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import pandas as pd
from fastapi.middleware.cors import CORSMiddleware  # 跨域
from fastapi import FastAPI, Response, BackgroundTasks
import json
import matplotlib.pyplot as plt
import io
import matplotlib
matplotlib.use('AGG')

app = FastAPI()

# 配置跨域白名单
origins = [
    "http://127.0.0.1:5500"
]

# 图片测试
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["POST"],
    allow_headers=["*"],
)

def create_img():
    plt.rcParams['figure.figsize'] = [7.50, 3.50]
    plt.rcParams['figure.autolayout'] = True
    plt.plot([1, 2])
    img_buf = io.BytesIO()
    plt.savefig(img_buf, format='png')
    plt.close()
    return img_buf

@app.get('/png')
async def get_img(background_tasks: BackgroundTasks):
    img_buf = create_img()
    # get the entire buffer content
    # because of the async, this will await the loading of all content
    bufContents: bytes = img_buf.getvalue()
    background_tasks.add_task(img_buf.close)
    headers = {'Content-Disposition': 'inline; filename="out.png"'}
    return Response(bufContents, headers=headers, media_type='image/png')


# 机器学习测试
# 多元线性回归
@app.post("/mlr")
async def mlr():
    # 引入excel数据
    # 可能存在空行问题,dropna(axis=0)删除空行
    df = pd.read_csv("./1.csv").dropna(axis=0)
    # 取xy
    x = df.iloc[:, :12]
    # y = df.loc[:, "BSR"]
    y = df.loc[:, "SBR"]
    # 划分数据集
    x_train, x_test, y_train, y_test = train_test_split(
        x, y, test_size=0.3, random_state=0)

    # 标准化
    standardscaler = StandardScaler()
    standardscaler.fit(x_train)
    x_train = standardscaler.transform(x_train)
    x_test = standardscaler.transform(x_test)

    # 多元线性回归
    model = LinearRegression()
    model.fit(x_train, y_train)

    # 测试样本预测
    y_pred = model.predict(x_test)
    return json.dumps(y_pred.tolist())

# 随机森林
@app.post("/rf")
async def rf():
    # 引入excel数据
    # 可能存在空行问题,dropna(axis=0)删除空行
    df = pd.read_csv("./1.csv").dropna(axis=0)
    # 取xy
    x = df.iloc[:, :12]
    # y = df.loc[:, "BSR"]
    y = df.loc[:, "SBR"]
    # 划分数据集
    x_train, x_test, y_train, y_test = train_test_split(
        x, y, test_size=0.3, random_state=0)

    # 标准化
    standardscaler = StandardScaler()
    standardscaler.fit(x_train)
    x_train = standardscaler.transform(x_train)
    x_test = standardscaler.transform(x_test)

    # 随机森林
    model = RandomForestRegressor()
    model.fit(x_train, y_train)

    # 测试样本预测
    y_pred = model.predict(x_test)
    return json.dumps(y_pred.tolist())

# BP神经网络
@app.post("/bpn")
async def rf():
    # 引入excel数据
    # 可能存在空行问题,dropna(axis=0)删除空行
    df = pd.read_csv("./1.csv").dropna(axis=0)
    # 取xy
    x = df.iloc[:, :12]
    # y = df.loc[:, "BSR"]
    y = df.loc[:, "SBR"]
    # 划分数据集
    x_train, x_test, y_train, y_test = train_test_split(
        x, y, test_size=0.3, random_state=0)

    # 标准化
    standardscaler = StandardScaler()
    standardscaler.fit(x_train)
    x_train = standardscaler.transform(x_train)
    x_test = standardscaler.transform(x_test)

    # BP神经网络
    model = MLPRegressor(hidden_layer_sizes=(10,), random_state=10,learning_rate_init=0.1)  # BP神经网络回归模型
    model.fit(x_train,y_train)  # 训练模型

    # 测试样本预测
    y_pred = model.predict(x_test)
    return json.dumps(y_pred.tolist())

# XGBoost
@app.post("/xgboost")
async def rf():
    # 引入excel数据
    # 可能存在空行问题,dropna(axis=0)删除空行
    df = pd.read_csv("./1.csv").dropna(axis=0)
    # 取xy
    x = df.iloc[:, :12]
    # y = df.loc[:, "BSR"]
    y = df.loc[:, "SBR"]
    # 划分数据集
    x_train, x_test, y_train, y_test = train_test_split(
        x, y, test_size=0.3, random_state=0)

    # 标准化
    standardscaler = StandardScaler()
    standardscaler.fit(x_train)
    x_train = standardscaler.transform(x_train)
    x_test = standardscaler.transform(x_test)

    # XGBoost
    model = XGBRegressor(max_depth=5, learning_rate=0.1, n_estimators=160, objective='reg:gamma')
    model.fit(x_train, y_train)

    # 测试样本预测
    y_pred = model.predict(x_test)
    return json.dumps(y_pred.tolist())

# LightGBM
@app.post("/lightgbm")
async def rf():
    # 引入excel数据
    # 可能存在空行问题,dropna(axis=0)删除空行
    df = pd.read_csv("./1.csv").dropna(axis=0)
    # 取xy
    x = df.iloc[:, :12]
    # y = df.loc[:, "BSR"]
    y = df.loc[:, "SBR"]
    # 划分数据集
    x_train, x_test, y_train, y_test = train_test_split(
        x, y, test_size=0.3, random_state=0)

    # 标准化
    standardscaler = StandardScaler()
    standardscaler.fit(x_train)
    x_train = standardscaler.transform(x_train)
    x_test = standardscaler.transform(x_test)

    # LightGBM
    model = lgb.LGBMRegressor(objective='regression',num_leaves=31,learning_rate=0.05,n_estimators=20)
    model.fit(x_train, y_train)

    # 测试样本预测
    y_pred = model.predict(x_test)
    return json.dumps(y_pred.tolist())