打卡day9 logistic分類

2021-10-05 18:43:38 字數 4299 閱讀 7898

一、logistic回歸之資料載入、視覺化

#_*_coding:utf-8_*_

import numpy as np

import matplotlib.pyplot as plt

defloaddataset

(filename =

'testset.txt'):

dataset =

labels =

fr =

open

(filename)

#每次取出一行

二、logis分類完整**

import numpy as np

import matplotlib.pyplot as plt

defloaddataset

(filename =

'testset.txt'):

fr =

open

(filename)

dataset =

labels =

for line in fr.readlines():

a = line.strip(

).split()[

1.0,

float

(a[0])

,float

(a[1])

])int(a[2]

))fr.close(

)return dataset,labels

defsigmiod

(inx)

:return

1.0/(1

+ np.exp(

-inx)

)def

gradascent

(datamatin,classlabels)

: datamatin = np.mat(datamatin)

classlabels = np.mat(classlabels)

.transpose(

) m,n = np.shape(datamatin)

lr =

0.001

epochs =

500 weight = np.ones(

(n,1))

for i in

range

(epochs)

: h = sigmiod(datamatin * weight)

error = classlabels - h

weight = weight + lr * datamatin.transpose(

)* error

return weight.geta(

)def

plotfigure

(weight)

: dataset,label = loaddataset(

) dataset = np.array(dataset)

xtrue =

;ytrue =

;xfalse =

;yfalse =

m = dataset.shape[0]

for i in

range

(m):

if label[i]==1

:1])

2])else:1

])2]

) plt.figure(

'logistic二分類'

三、隨機梯度下降演算法

由於上文中梯度演算法導致運算量大

改進後:

def

stocgradascent1

(datamatrix, classlabels, numiter=

150)

: m, n = np.shape(datamatrix)

# 返回datamatrix的大小。m為行數,n為列數。

weights = np.ones(n)

# 引數初始化

for j in

range

(numiter)

: dataindex =

list

(range

(m))

for i in

range

(m):

alpha =4/

(1.0

+ j + i)

+0.01

# 降低alpha的大小,每次減小1/(j+i)。

randindex =

int(random.uniform(0,

len(dataindex)))

# 隨機選取樣本

h = sigmoid(

sum(datamatrix[dataindex[randindex]

]* weights)

)# 選擇隨機選取的乙個樣本,計算h

error = classlabels[dataindex[randindex]

]- h # 計算誤差

weights = weights + alpha * error * datamatrix[dataindex[randindex]

]# 更新回歸係數

del(dataindex[randindex]

)# 刪除已經使用的樣本

return weights # 返回

Day9 打卡acwing 429 獎學金

某小學最近得到了一筆贊助,打算拿出其中一部分為學習成績優秀的前 5 5 5 名學生發獎學金。期末,每個學生都有 3 3 3 門課的成績 語文 數學 英語。先按總分從高到低排序,如果兩個同學總分相同,再按語文成績從高到低排序,如果兩個同學總分和語文成績都相同,那麼規定學號小的同學排在前面,這樣,每個學...

leetcode打卡day02 二分查詢

之前寫過二分查詢的模板,參見部落格二分查詢模板 leetcode744 解題思路 此題為找到大於目標字元的第乙個字元,及0000011111問題查詢第乙個1,利用模板即可。另外注意特殊情況,當目標值比最後乙個字元都大的時候,返回第乙個字串。class solution while l r else ...

每日打卡 Day9 被圍繞的區域 C 實現

給定乙個二維的矩陣,包含 x 和 o 字母 o 找到所有被 x 圍繞的區域,並將這些區域裡所有的 o 用 x 填充。示例 x x x x x o o x x x o x x o x x執行你的函式後,矩陣變為 x x x x x x x x x x x x x o x x解釋 被圍繞的區間不會存在於...