参考学生成绩预测_Mr_Bo_的博客-CSDN博客_学生成绩预测,使用了Anaconda3下的Spyder工具进行代码撰写、测试,最后附上数据文件以供下载。
代码(直接粘贴运行)
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import pandas as pd
import numpy as np
import json
data_features = pd.read_csv('SP_train.csv',
usecols=['gender','race/ethnicity',
'parental level of education',
'lunch','test preparation course' ])
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse = False)
data_features = encoder.fit_transform(data_features)
data=pd.DataFrame(data_features,
columns=['gender_1','gender_2',
'race_1','race_2',
'race_3','race_4',
'race_5','edu_1',
'edu_2','edu_3',
'edu_4','edu_5',
'edu_6','lunch_1',
'lunch_2','test_1',
'test_2'
],dtype=float)
x=data[['gender_1','gender_2','race_1','race_2',
'race_3','race_4','race_5','edu_1',
'edu_2','edu_3','edu_4','edu_5',
'edu_6','lunch_1','lunch_2','test_1',
'test_2']]
y=pd.read_csv('SP_train.csv',
usecols=['math score','reading score','writing score'])
from sklearn import linear_model
regr=linear_model.LinearRegression()
regr.fit(x,y)
coef = regr.coef_
intercept = regr.intercept_
R2 = regr.score(x,y)
print(regr.coef_)
#打印常数
print(regr.intercept_)
#预测单个学生成绩
z=regr.predict([[1,0,0,0,1,
0,0,0,0,0,
0,0,1,0,1,
1,0]])
print('score:' + str(z))
#处理测试集
data_test_features=pd.read_csv('SP_test.csv',
usecols=['gender', 'race/ethnicity','parental level of education','lunch','test preparation course'])
data_test_features=encoder.fit_transform(data_test_features)
data_test=pd.DataFrame(data_test_features,
columns=['gender_1','gender_2',
'race_1','race_2',
'race_3','race_4',
'race_5','edu_1',
'edu_2','edu_3',
'edu_4','edu_5',
'edu_6','lunch_1',
'lunch_2','test_1',
'test_2'],dtype=float)
x_test=data_test[['gender_1','gender_2',
'race_1','race_2',
'race_3','race_4',
'race_5','edu_1',
'edu_2','edu_3',
'edu_4','edu_5',
'edu_6','lunch_1',
'lunch_2','test_1',
'test_2']]
#预测测试集中学生成绩
y_test_pre=regr.predict(x_test)
y_test_pre=np.round(y_test_pre)
#y_test_pre=np.array(y_test_pre,dtype=np.int32)
#print (y_test_pre)
#print(type(y_test_pre))
list=[]
for i in range(1000):
list.append(str(i))
#print(list)
#生成字典
dict1={}
dict1=dict(zip(list,y_test_pre))
#重写json类
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
np.int16, np.int32, np.int64, np.uint8,
np.uint16, np.uint32, np.uint64)):
return int(obj)
elif isinstance(obj, (np.float_, np.float16, np.float32,
np.float64)):
return float(obj)
elif isinstance(obj,(np.ndarray,)): #### This is the fix
return obj.tolist()
return json.JSONEncoder.default(self, obj)
submission1=json.dumps(dict1,cls=NumpyEncoder)
预测结果:
测试数据下载: