(1)在urls.py中新增以下url,
(2)在data_mining.html中增加链接到回归分析页面(data_ols),
(3)页面布局如下,
{% extends "base.html" %}
{% load staticfiles %}
{% block main %}
<div class="div_center" style="margin:50px">
<h2>多元線性回歸</h2>
<div id="select">
</div>
<button id='show_var'>顯示變量</button>
<button id='regress'>回歸計算</button>
</div>
{% endblock %}
布局效果:
(4)要实现点击效果,点击变量,出现变量选择框,选择变量后点击,便进行ols回归运算,显示回归结果:
因此编写如下代码:
<script>
var i=0;
$('#show_var').on('click',function(){
if(i==0){
$.get("/data_mining/ols/var",function(data){
$('#select').append("<select id='show_y'> </select>");
$('#select').append("<select id='show_x' multiple='multiple'> </select>");
$.each(data,function(i,j){
$('#show_y').append("<option>"+j+"</option>");
$('#show_x').append("<option>"+j+"</option>");
}
)
});
};
i=i+1;
});
#点击按钮后添加选择因变量、自变量的要素。
$('#regress').on('click',function(){
var y=$("#show_y option:selected").text();
var x=new Array();
$("#show_x option:selected").each(function(){
x.push($(this).text());
xx=x.join(',');
});
#获取选择的自变量、因变量的名称
$.get("/data_mining/ols/res",{'x':xx,'y':y},function(data){
str0=data.y+"=";
for(i=0;i<data.coef.length;i++){
if(i!=(data.coef.length-1)){
str0=str0+data.coef[i]+"*"+data.x[i]+"+"
}else{
str0=str0+data.coef[i]+"*"+data.x[i]
}
}
str0=str0+"+"+data.intercept_;
alert(str0);
}
)
});
#获得回归方程并显示
</script>
(5)在views中,编写视图函数。
首先导入回归模块,from sklearn.linear_model import LinearRegression。
然后,编写模板显示函数,
def ols_show(request):
return render(request, "data_mining/ols.html")
编写显示变量的函数,
base_dir = 'media/data_mining/'
l = os.listdir(base_dir)
l.sort(key=lambda fn: os.path.getmtime(base_dir + fn) if not os.path.isdir(base_dir + fn) else 0)
name = l[-1]
inputfile = base_dir + name
data = pd.read_csv(inputfile, index_col=0, header=0,encoding='gb2312')
columns=list(data.columns)
return JsonResponse(columns,safe=False)
编写计算回归方程的函数,
@csrf_exempt
def ols_res(request):
base_dir = 'media/data_mining/'
l = os.listdir(base_dir)
l.sort(key=lambda fn: os.path.getmtime(base_dir + fn) if not os.path.isdir(base_dir + fn) else 0)
name = l[-1]
inputfile = base_dir + name
data = pd.read_csv(inputfile, index_col=0, header=0,encoding='gbk')
data.dropna()
x=request.GET.get('x','')
y = request.GET.get('y', '')
x=x.split(",")
print(x)
print(y)
x_in=data[x]
y_in=data[y]
print(x_in)
linreg = LinearRegression()
linreg.fit(x_in, y_in)
obj={}
obj['y']=y
obj['x']=x
obj['intercept_'] = linreg.intercept_.tolist()
obj['coef'] = linreg.coef_.tolist()
return HttpResponse(json.dumps(obj),content_type="application/json")
(6)后期对前端界面进行美化。