Ether-J 2023-06-21 22:32 采纳率: 100%
浏览 69
已结题

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
  • 写回答

2条回答 默认 最新

  • PhoenixRiser 2023-06-21 22:38
    关注

    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为不通过),以及他们的考试分数。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月30日
  • 已采纳回答 6月22日
  • 创建了问题 6月21日