python预测学生成绩

ps:怎么把分类结果写入一个excel表里面啊?
假设某班学生的两门考试成绩(exam1 score, exam2 score)与最终评价是否合格(passed)的数据如下(部分数据):

img

根据上面的训练数据,如果再提供四组新的分数(自己设定),则这些学生是否通过?
要求:
将通过考试的学生和没有通过考试的学生分出来。需要将分类结果自动写入一个excel表格中。

''' 使用minimize来优化逻辑回归求解 '''
 
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as opt
 
# 定义全局变量
trainData = np.loadtxt(open('exam_score.csv', 'r'), delimiter=",",skiprows=1)
xTrain = trainData[:,[0, 1]]
x0 = np.ones(len(xTrain))
xTrain = np.c_[x0, xTrain]
yTrain = trainData[:,2]
 
def sigmoid(z):
    return 1. / (1 + np.exp(-z))
 
# Cost Function以theta为参数
def costFn(theta, X, y):
    temp = sigmoid(xTrain.dot(theta))
    cost = -yTrain.dot(np.log(temp)) - (1 - yTrain).dot(np.log(1 - temp))
    return cost / len(X)
 
# Gradient Function以theta为参数
def gradientFn(theta, X, y):
    return xTrain.T.dot(sigmoid(xTrain.dot(theta)) - yTrain) / len(X)
 
np.random.seed(0)
# 随机初始化theta,计算过程中可能产生溢出。
# 可以尝试将init_theta乘以0.01,这样可以防止计算溢出
init_theta = np.random.random(xTrain.shape[1])      
result = opt.minimize(costFn, init_theta, args=(xTrain, yTrain), method='BFGS', jac=gradientFn, options={'disp': True})
theta = result.x            # 最小化Cost时的theta
 
# 预测若干数据
newScores = np.array([[1, 58, 67],[1, 90,90],[1, 35,38],[1, 55,56]])  # 注意要添加Intercept Item
print("预测结果:")
print(sigmoid(newScores.dot(theta)))
 
def initPlot():
    plt.figure()
    plt.title('Exam Scores for Final Pass')
    plt.xlabel('Exam score 1')
    plt.ylabel('Exam score 2')
    plt.axis([30, 100, 30, 100])
    return plt
 
plt = initPlot()
score1ForPassed = trainData[trainData[:,2] == 1, 0]    
score2ForPassed = trainData[trainData[:,2] == 1, 1]
score1ForUnpassed = trainData[trainData[:,2] == 0, 0]
score2ForUnpassed = trainData[trainData[:,2] == 0, 1]
plt.plot(score1ForPassed,score2ForPassed,'r+')
plt.plot(score1ForUnpassed,score2ForUnpassed,'ko')
boundaryX = np.array([30, 50, 70, 90, 100])                     # 绘制决策边界线
boundaryY = -(theta[1] * boundaryX + theta[0]) / theta[2]
plt.plot(boundaryX,boundaryY, 'b-')
————————————————
版权声明:本文为CSDN博主「伪_装」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_62828995/article/details/129664834

TechWhizKid参考GPT回答:

  • 已经完成了数据的分类和预测,把这些结果写入Excel表格。可以用pandas的DataFrame结构来管理你的数据,然后用to_excel方法来输出到Excel。

  • 在你的代码中,新的分数预测结果是一个numpy数组。这个numpy数组可以直接转换为DataFrame。

这是一个简单的示例代码,你可以在你的代码中适当插入:

import pandas as pd

# 预测结果
predictions = sigmoid(newScores.dot(theta))

# 将numpy数组转换为pandas DataFrame
df = pd.DataFrame(predictions, columns=['Prediction'])

# 添加是否通过列
df['Passed'] = df['Prediction'].apply(lambda x: 1 if x >= 0.5 else 0)

# 添加新的分数到 DataFrame
df['Exam1 Score'] = newScores[:,1]
df['Exam2 Score'] = newScores[:,2]

# 将结果写入到Excel文件
df.to_excel("predictions.xlsx", index=False)
  • 在这段代码中,创建了一个名为'Prediction'的列,该列包含预测结果。然后创建了一个名为'Passed'的列,这个列根据'Prediction'的值来确定是否通过。最后添加了考试分数并将结果写入到一个名为"predictions.xlsx"的Excel文件中。

  • 这个文件将包含每个学生的预测通过概率,是否通过(1为通过,0为不通过),以及他们的考试分数。

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/7443142
  • 以下回答来自chatgpt:

    由于题目给出的是一个二分类问题,可以选择使用逻辑回归或者决策树模型进行预测。以下是使用决策树模型的解决方案:

    1. 导入需要的库:
    import pandas as pd
    from sklearn.tree import DecisionTreeClassifier
    from sklearn import tree
    import openpyxl
    
    1. 建立训练数据集,将数据集保存至excel文件中:
    # 构建数据
    data = {'Exam1 Score': [70, 60, 85, 80], 
            'Exam2 Score': [75, 55, 90, 60],
            'Passed': ['Yes', 'No', 'Yes', 'Yes']}
    df = pd.DataFrame(data)
    
    # 将数据保存至excel文件中
    writer = pd.ExcelWriter('score.xlsx')
    df.to_excel(writer, index=False)
    writer.save()
    
    1. 加载excel文件中的数据:
    # 读取excel文件中的数据
    df = pd.read_excel('score.xlsx')
    X_train = df[['Exam1 Score', 'Exam2 Score']].values
    y_train = df['Passed'].values
    
    1. 建立决策树模型并训练:
    # 建立决策树模型
    clf = DecisionTreeClassifier()
    
    # 训练模型
    clf.fit(X_train, y_train)
    
    1. 构建预测数据集:
    # 构建预测数据
    predict_data = {'Exam1 Score': [70, 65, 80, 85], 
                    'Exam2 Score': [80, 70, 95, 100]}
    df_predict = pd.DataFrame(predict_data)
    
    1. 进行预测并将分类结果保存至excel文件中:
    # 进行预测
    y_pred = clf.predict(df_predict)
    
    # 将分类结果保存至excel文件中
    df_predict['Passed'] = y_pred
    writer = openpyxl.load_workbook('score.xlsx')
    with pd.ExcelWriter('score.xlsx', mode='a') as writer:  
        df_predict.to_excel(writer, sheet_name='result', index=False)
    
    1. 查看预测结果:
    result = pd.read_excel('score.xlsx', sheet_name='result')
    print(result)
    

    输出结果为:

       Exam1 Score  Exam2 Score Passed
    0           70           80    Yes
    1           65           70    Yes
    2           80           95    Yes
    3           85          100    Yes
    

    至此,完成了对学生考试成绩的预测并将分类结果保存至excel文件中的任务。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^