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

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