from matplotlib.font_manager import FontProperties
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
def loaddata():
data = np.loadtxt('data1.txt',delimiter=',')
n = data.shape[1] - 1
X = data[:, 0:n]
y = data[:, -1].reshape(-1, 1)
return X, y
def plot(X,y):
pos = np.where(y==1)
neg = np.where(y==0)
plt.scatter(X[pos[0],0],X[pos[0],1],marker='x')
plt.scatter(X[neg[0], 0], X[neg[0], 1], marker='o')
plt.xlabel('Exam 1 score')
plt.ylabel('Exam 2 score')
plt.show()
X,y = loaddata()
plot(X,y)
def sigmoid(z):
r = 1/(1+np.exp(-z))
return r
def hypothesis(X,theta):
z=np.dot(X,theta)
return sigmoid(z)
def computeCost(X,y,theta):
m = X.shape[0]
z = -y * np.log(hypothesis(X,theta) + 1e-6) - (1 - y) * np.log(1 - hypothesis(X,theta) + 1e-6)
return np.sum(z)/m
diff = []
def gradientDescent(X,y,theta,iterations,alpha):
m = X.shape[0]
X = np.hstack((np.ones((m, 1)), X))
for i in range(iterations):
theta_temp = theta - alpha * np.dot(X.T,hypothesis(X,theta) - y) / m
theta = theta_temp
if(i%10000==0):
diff.append([i,computeCost(X,y,theta)])
print('第',i,'次迭代,当前损失为:',computeCost(X,y,theta),'theta=',theta)
return theta
def predict(X):
c = np.ones(X.shape[0]).transpose()
X = np.insert(X, 0, values=c, axis=1)
h = hypothesis(X,theta)
h[h>=0.5]=1
h[h<0.5]=0
return h
X,y = loaddata()
n = X.shape[1]
theta = np.zeros(n+1).reshape(n+1, 1)
theta_temp = np.zeros(n+1).reshape(n+1, 1)
iterations = 250000
alpha = 0.008
theta = gradientDescent(X,y,theta,iterations,alpha)
print('theta=\n',theta)
def plotDescisionBoundary(X,y,theta):
cm_dark = mpl.colors.ListedColormap(['g', 'r'])
plt.xlabel('Exam 1 score')
plt.ylabel('Exam 2 score')
plt.scatter(X[:,0],X[:,1],c=np.array(y).squeeze(),cmap=cm_dark,s=30)
x1 = np.linspace(0,150,500)
x2 = (-theta[0] - theta[1] * x1) / theta[2]
plt.plot(x1,x2)
plt.show()
def plotLoss():
d = np.array(diff)
x = d[:,0]
y = d[:,1]
plt.plot(x,y)
plt.title("损失函数变化图",fontsize = 20,fontproperties = "kaiti")
plt.show()
def plotPred():
test_x = []
for i in range(233):
tx = np.random.uniform(0.0,100.0)
ty = np.random.uniform(0.0,100.0)
test_x.append([tx,ty])
test_x = np.array(test_x)
test_y = predict(test_x)
cm_dark = mpl.colors.ListedColormap(['b', 'pink'])
plt.scatter(test_x[:, 0], test_x[:, 1], c=np.array(test_y).squeeze(), cmap=cm_dark, s=30)
x1 = np.linspace(0, 150, 500)
x2 = (- theta[0] - theta[1] * x1) / theta[2]
plt.plot(x1,x2)
plt.title("预测",fontproperties = 'kaiti',fontsize = 20)
plt.show()
plotDescisionBoundary(X,y,theta)
plotLoss()
plotPred()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?