Fri May 19 07:45:00 UTC 2023 inscode

上级 7e3da906
{ {
"cells": [ "cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"今天的日期是: 2023-05-11\n"
]
}
],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"\n",
"def sigmoid(z):\n",
" return 1 / (1 + np.exp(-z))\n",
"\n",
"def costFunction(theta, X, y):\n",
" m = len(y)\n",
" \n",
" J = 0\n",
" grad = np.zeros(theta.shape)\n",
" \n",
" h = sigmoid(np.dot(X, theta))\n",
" J = (-1/m) * np.sum(y*np.log(h) + (1-y)*np.log(1-h))\n",
" grad = (1/m) * np.dot(X.T, (h-y))\n",
" \n",
" return J, grad\n",
"\n",
"def gradientDescent(X, y, theta, alpha, num_iters):\n",
" m = len(y)\n",
" J_history = np.zeros(num_iters)\n",
" \n",
" for i in range(num_iters):\n",
" J_history[i], grad = costFunction(theta, X, y)\n",
" theta = theta - alpha*grad\n",
" \n",
" return theta, J_history\n",
"\n",
"# 生成样本数据\n",
"np.random.seed(0)\n",
"X = np.random.randn(100, 2)\n",
"ones = np.ones((100, 1))\n",
"X = np.hstack((ones, X))\n",
"y = np.random.randint(0, 2, size=(100,1))\n",
"\n",
"# 初始化theta\n",
"initial_theta = np.zeros((X.shape[1], 1))\n",
"\n",
"# 梯度下降\n",
"alpha = 0.1\n",
"num_iters = 1000\n",
"theta, J_history = gradientDescent(X, y, initial_theta, alpha, num_iters)\n",
"\n",
"# 绘制决策边界\n",
"x1 = np.arange(-3, 3, 0.1)\n",
"x2 = -(theta[0]+theta[1]*x1)/theta[2]\n",
"plt.plot(x1, x2, label='Decision Boundary')\n",
"plt.scatter(X[:, 1], X[:, 2], c=y.flatten())\n",
"plt.legend()\n",
"plt.show()\n"
]
},
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 1, "execution_count": 1,
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册