五了赌、分類(lèi)代碼

邏輯回歸梯度下降法
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report
from sklearn import preprocessing
# 數(shù)據(jù)是否需要標(biāo)準(zhǔn)化
# 數(shù)據(jù)標(biāo)準(zhǔn)化有利于梯度下降法的優(yōu)化
scale = False

data = np.genfromtxt('LR-testSet.csv' ,delimiter=',')
x_data = data[: ,:-1]
y_data = data[: ,-1]

def plot():
    x0 = []
    x1 = []
    y0 = []
    y1 = []
    # 切分不同類(lèi)別的數(shù)據(jù)
    for i in range(len(x_data)):
        if y_data[i] == 0:
            x0.append(x_data[i ,0])
            y0.append(x_data[i ,1])
        else:
            x1.append(x_data[i ,0])
            y1.append(x_data[i ,1])
    # 畫(huà)圖
    scatter0 = plt.scatter(x0 ,y0 ,c='b' ,marker='o')
    scatter1 = plt.scatter(x1 ,y1 ,c='r' ,marker='x')
    # 畫(huà)圖例
    plt.legend(handles = [scatter0 ,scatter1] ,labels = ['label0' ,'label1'] ,loc = 'best')

plot()
plt.show()

# 數(shù)據(jù)處理,添加偏置項(xiàng)
x_data = data[: ,:-1]
y_data = data[: ,-1 ,np.newaxis]
print(x_data)
print(y_data)

print(np.mat(x_data).shape)
print(np.mat(y_data).shape)
# 給樣本添加偏置項(xiàng)
X_data = np.concatenate((np.ones((100 ,1)) ,x_data) ,axis=1)
print(X_data.shape)

def sigmoid(x):
    return  1.0 / (1 + np.exp(-x))

def cost(xMat ,yMat ,ws):
    left = np.multiply(yMat ,np.log(sigmoid(xMat*ws)))
    # multiply按位相乘
    right = np.multiply(1 - yMat ,np.log(1 - sigmoid(xMat*ws)))
    return np.sum(left + right) / -(len(xMat))

def gradAscent(xArr ,yArr):
    if scale == True:
        xArr = preprocessing.scale(xArr)
    xMat = np.mat(xArr)
    yMat = np.mat(yArr)

    lr = 0.001
    epochs = 10000
    costList = []
    # 計(jì)算數(shù)據(jù)行列數(shù)
    # 行代表數(shù)據(jù)個(gè)數(shù),列代表權(quán)值個(gè)數(shù)
    m ,n = np.shape(xMat)
    # 初始化權(quán)值
    ws = np.mat(np.ones((n ,1)))

    for i in range(epochs + 1):
        # xMat和weights矩陣相乘
        h = sigmoid(xMat * ws)
        # 計(jì)算誤差
        ws_grad = xMat.T * (h - yMat) / m
        ws = ws - lr * ws_grad

        if i % 50 == 0:
            costList.append(cost(xMat ,yMat ,ws))
    return ws,costList

# 訓(xùn)練模型,得到權(quán)值和cost值的變化
ws,costList = gradAscent(X_data ,y_data)
print(ws)

if scale == False:
    # 畫(huà)圖決策邊界
    plot()
    x_test = [[-4] ,[3]]
    y_test = (-ws[0] - x_test * ws[1])/ws[2]
    plt.plot(x_test ,y_test ,'k')
    plt.show()

# 畫(huà)圖loss值的變化
x = np.linspace(0 ,10000 ,201)
plt.plot(x ,costList ,c='r')
plt.title('Train')
plt.xlabel('Epochs')
plt.ylabel('Cost')
plt.show()

# 預(yù)測(cè)
def predict(x_data ,ws):
    if scale == True:
        x_data = preprocessing.scale(x_data)
    xMat = np.mat(x_data)
    ws = np.mat(ws)
    return [1 if x >= 0.5 else 0 for x in sigmoid(xMat * ws)]

predictions = predict(X_data ,ws)
print(classification_report(y_data ,predictions))
sklearn邏輯回歸梯度下降法
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report
from sklearn import preprocessing
from sklearn import linear_model

scale = False

data = np.genfromtxt('LR-testSet.csv' ,delimiter=',')
x_data = data[: ,:-1]
y_data = data[: ,-1]

def plot():
    x0 = []
    x1 = []
    y0 = []
    y1 = []
    # 切分不同類(lèi)別的數(shù)據(jù)
    for i in range(len(x_data)):
        if y_data[i] == 0:
            x0.append(x_data[i ,0])
            y0.append(x_data[i ,1])
        else:
            x1.append(x_data[i ,0])
            y1.append(x_data[i ,1])
    # 畫(huà)圖
    scatter0 = plt.scatter(x0 ,y0 ,c='b' ,marker='o')
    scatter1 = plt.scatter(x1 ,y1 ,c='r' ,marker='x')
    # 畫(huà)圖例
    plt.legend(handles = [scatter0 ,scatter1] ,labels = ['label0' ,'label1'] ,loc = 'best')

plot()
plt.show()

logistic = linear_model.LogisticRegression()
logistic.fit(x_data ,y_data)

if scale == False:
    plot()
    x_test = np.array([[-4] ,[3]])
    y_test = (-logistic.intercept_ - x_test * logistic.coef_[0][0]) / logistic.coef_[0][1]
    plt.plot(x_test ,y_test ,'k')
    plt.show()

predictions = logistic.predict(x_data)
print(classification_report(y_data ,predictions))
邏輯回歸非線性問(wèn)題梯度下降法
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report
from sklearn import preprocessing
from sklearn.preprocessing import PolynomialFeatures

scale = False

data = np.genfromtxt('LR-testSet2.txt' ,delimiter=',')
x_data = data[: ,:-1]
y_data = data[: ,-1 ,np.newaxis]
print(y_data)


def plot():
    x0 = []
    x1 = []
    y0 = []
    y1 = []
    # 切分不同類(lèi)別的數(shù)據(jù)
    for i in range(len(x_data)):
        if y_data[i] == 0:
            x0.append(x_data[i ,0])
            y0.append(x_data[i ,1])
        else:
            x1.append(x_data[i ,0])
            y1.append(x_data[i ,1])
    # 畫(huà)圖
    scatter0 = plt.scatter(x0 ,y0 ,c='b' ,marker='o')
    scatter1 = plt.scatter(x1 ,y1 ,c='r' ,marker='x')
    # 畫(huà)圖例
    plt.legend(handles = [scatter0 ,scatter1] ,labels = ['label0' ,'label1'] ,loc = 'best')

plot()
plt.show()

# 定義多項(xiàng)式回歸伍绳,degree的值可以調(diào)節(jié)多項(xiàng)式的特征
poly_reg= PolynomialFeatures(degree=3)
# 特征處理
x_poly = poly_reg.fit_transform(x_data)

def sigmoid(x):
    return 1.0 / (1 + np.exp(-x))

def cost(xMat ,yMat ,ws):
    left = np.multiply(yMat ,np.log(sigmoid(xMat*ws)))
    right = np.multiply(1 - yMat ,np.log(1 - sigmoid(xMat*ws)))
    return np.sum(left + right) / -(len(xMat))

def gradAscent(xArr ,yArr):
    if scale == True:
        xArr = preprocessing.scale(xArr)
    xMat = np.mat(xArr)
    yMat = np.mat(yArr)

    lr = 0.03
    epochs = 50000
    costList = []
    # 計(jì)算數(shù)據(jù)行列數(shù)
    # 行代表數(shù)據(jù)個(gè)數(shù),列代表權(quán)值個(gè)數(shù)
    m, n = np.shape(xMat)
    # 初始化權(quán)值
    ws = np.mat(np.ones((n, 1)))

    for i in range(epochs + 1):
        # xMat和weights矩陣相乘
        h = sigmoid(xMat * ws)
        # 計(jì)算誤差
        ws_grad = xMat.T * (h - yMat) / m
        ws = ws - lr * ws_grad

        if i % 50 == 0:
            costList.append(cost(xMat, yMat, ws))
    return ws, costList

# 訓(xùn)練模型乍桂,得到權(quán)值和cost值的變化
ws ,costList = gradAscent(x_poly ,y_data)
print(ws)
# 基本完成


# 獲取數(shù)據(jù)值所在的范圍
x_min ,x_max = x_data[: ,0].min() ,x_data[: ,0].max() + 1
y_min ,y_max = x_data[: ,1].min() ,x_data[: ,1].max() + 1

# 生成網(wǎng)絡(luò)矩陣
xx ,yy = np.meshgrid(np.arange(x_min ,x_max ,0.02) ,
                     np.arange(y_min ,y_max ,0.02))


z = sigmoid(poly_reg.fit_transform(np.c_[xx.ravel() ,yy.ravel()]).dot(np.array(ws)))
# ravel與flatten類(lèi)似冲杀,多維數(shù)據(jù)轉(zhuǎn)一維效床,flatten不會(huì)改變數(shù)據(jù)原始數(shù)據(jù),ravel會(huì)改變?cè)紨?shù)據(jù)
for i in range(len(z)):
    if z[i] > 0.5:
        z[i] = 1
    else:
        z[i] = 0
z = z.reshape(xx.shape)

# 等高線圖
cs = plt.contour(xx ,yy ,z)
plot()
plt.show()

# 預(yù)測(cè)
def predict(x_data ,ws):
    if scale == True:
        x_data = preprocessing.scale(x_data)
    xMat = np.mat(x_data)
    ws = np.mat(ws)
    return [1 if x >= 0.5 else 0 for x in sigmoid(xMat * ws)]

predictions = predict(x_poly ,ws)
print(classification_report(y_data ,predictions))
![QQ截圖20200409162541.png](https://upload-images.jianshu.io/upload_images/21212888-5aca5100936cf253.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
sklearn邏輯回歸非線性
import  numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.datasets import make_gaussian_quantiles
from sklearn.preprocessing import PolynomialFeatures

# 生成2維正態(tài)分布漠趁,生成的數(shù)據(jù)按分位數(shù)分為兩類(lèi)扁凛,500個(gè)樣本,2個(gè)樣本特征
# 可以生成兩類(lèi)或多類(lèi)數(shù)據(jù)
x_data ,y_data = make_gaussian_quantiles(n_samples=500 ,n_features=2 ,n_classes=2)

plt.scatter(x_data[: ,0] ,x_data[: ,1] ,c = y_data)
plt.show()

# 定義多項(xiàng)式回歸闯传,degree的值可以調(diào)節(jié)多項(xiàng)式的特征
poly_reg = PolynomialFeatures(degree=5)
# 特征處理
x_poly = poly_reg.fit_transform(x_data)

logistic = linear_model.LogisticRegression()
logistic.fit(x_poly ,y_data)

# 獲取數(shù)據(jù)值所在的范圍
x_min ,x_max = x_data[: ,0].min() ,x_data[: ,0].max() + 1
y_min ,y_max = x_data[: ,1].min() ,x_data[: ,1].max() + 1

# 生成網(wǎng)絡(luò)矩陣
xx ,yy = np.meshgrid(np.arange(x_min ,x_max ,0.02) ,
                     np.arange(y_min ,y_max ,0.02))

z = logistic.predict(poly_reg.fit_transform(np.c_[xx.ravel() ,yy.ravel()]))
z = z.reshape(xx.shape)
# 等高線圖
cs = plt.contourf(xx ,yy ,z)
# 樣本點(diǎn)數(shù)圖
plt.scatter(x_data[: ,0] ,x_data[: ,1] ,c = y_data)
plt.show()

print('score' ,logistic.score(x_poly ,y_data))
KNN算法
import matplotlib.pyplot as plt
import numpy as np
import operator

# 已知分類(lèi)的數(shù)據(jù)
x1 = np.array([3 ,2 ,1])
y1 = np.array([104 ,100 ,81])
x2 = np.array([101 ,99 ,98])
y2 = np.array([10 ,5 ,2])
scatter1 = plt.scatter(x1 ,y1 ,c = 'r')
scatter2 = plt.scatter(x2 ,y2 ,c = 'b')

# 未知數(shù)據(jù)
x = np.array([18])
y = np.array([90])
scatter3 = plt.scatter(x ,y ,c = 'k')

# 畫(huà)圖例
plt.legend(handles = [scatter1 ,scatter2 ,scatter3] ,labels = ['labelA' ,'labelB' ,'X'] ,loc = 'best')
plt.show()

# 已知分類(lèi)的數(shù)據(jù)
x_data = np.array([[3,104],
                   [2,100],
                   [1,81],
                   [101,10],
                   [99,5],
                   [81,2]])
y_data = np.array(['A','A','A','B','B','B'])
x_test = np.array([18,90])
# 計(jì)算樣本數(shù)量
x_data_size = x_data.shape[0]
x_data_size
# 復(fù)制x_test
np.tile(x_test ,(x_data_size ,1))
# 計(jì)算x_test與每一個(gè)樣本的差值
diffMat = np.tile(x_test ,(x_data_size ,1)) - x_data
diffMat

# 計(jì)算差值的平方
sqDiffMat = diffMat**2
sqDiffMat

# 求和
sqDistances = sqDiffMat.sum(axis = 1)
sqDistances
#開(kāi)方
distances = sqDistances**0.5
distances
# 從小到大排序
sortedDistances = distances.argsort()

classCount = {}
# 設(shè)置k
k = 5
for i in range(k):
    #獲取標(biāo)簽
    votelabel = y_data[sortedDistances[i]]
    # 統(tǒng)計(jì)標(biāo)簽數(shù)量
    classCount[votelabel] = classCount.get(votelabel ,0) + 1

classCount
# 根據(jù)operator.itemgetter(1)-第1個(gè)值對(duì)classCount排序谨朝,然后再取倒序
sortedClassCount = sorted(classCount.items() ,key=operator.itemgetter(1) ,reverse=True)
sortedClassCount

# 獲取數(shù)量最多的標(biāo)簽
knnclass = sortedClassCount[0][0]
knnclass

圖片:


QQ截圖20200409163053.png
KNN鳶尾花
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report,confusion_matrix
import operator
import random

# 鳶尾花,數(shù)據(jù)屬性:萼片長(zhǎng)度(sepal length)甥绿,萼片寬度字币,花瓣長(zhǎng)度(petal length),花瓣寬度
# 類(lèi)別:Iris setosa,lris versicolor,Iris virginica
def knn(x_test ,x_data ,y_data ,k):
    #計(jì)算樣本數(shù)量
    x_data_size = x_data.shape[0]
    # 復(fù)制x_test
    np.tile(x_test ,(x_data_size ,1))
    # 計(jì)算x_test與每一個(gè)樣本的差值
    diffMat = np.tile(x_test ,(x_data_size ,1)) - x_data
    # 計(jì)算差值的平方
    sqDiffMat = diffMat**2
    # 求和
    sqDistances = sqDiffMat.sum(axis=1)
    # 開(kāi)方
    distances = sqDistances**0.5
    # 從小到大排序
    sortedDistances = distances.argsort()
    classCount = {}
    for i in range(k):
        # 獲取標(biāo)簽
        votelabel = y_data[sortedDistances[i]]
        # 統(tǒng)計(jì)標(biāo)簽數(shù)量
        classCount[votelabel] = classCount.get(votelabel, 0) + 1

    # 根據(jù)operator.itemgetter(1)-第1個(gè)值對(duì)classCount排序共缕,然后再取倒序
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    # 獲取數(shù)量最多的標(biāo)簽
    return sortedClassCount[0][0]
# 載入數(shù)據(jù)
iris = datasets.load_iris()
# 打亂數(shù)據(jù)
data_size = iris.data.shape[0]
index = [i for i in range(data_size)]
random.shuffle(index)
iris.data = iris.data[index]
iris.target = iris.target[index]
# 切分?jǐn)?shù)據(jù)集
test_size = 40
x_train = iris.data[test_size:]
x_test = iris.data[:test_size]
y_train = iris.target[test_size:]
y_test = iris.target[:test_size]

predictions = []
for i in range(x_test.shape[0]):
    predictions.append(knn(x_test[i] ,x_train ,y_train ,5))
print(classification_report(y_test ,predictions))
QQ截圖20200409163319.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末洗出,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子图谷,更是在濱河造成了極大的恐慌翩活,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件便贵,死亡現(xiàn)場(chǎng)離奇詭異菠镇,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)承璃,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)利耍,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人盔粹,你說(shuō)我怎么就攤上這事隘梨。” “怎么了舷嗡?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵轴猎,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我进萄,道長(zhǎng)税稼,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任垮斯,我火速辦了婚禮,結(jié)果婚禮上只祠,老公的妹妹穿的比我還像新娘兜蠕。我一直安慰自己,他們只是感情好抛寝,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布熊杨。 她就那樣靜靜地躺著曙旭,像睡著了一般。 火紅的嫁衣襯著肌膚如雪晶府。 梳的紋絲不亂的頭發(fā)上桂躏,一...
    開(kāi)封第一講書(shū)人閱讀 51,692評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音川陆,去河邊找鬼剂习。 笑死,一個(gè)胖子當(dāng)著我的面吹牛较沪,可吹牛的內(nèi)容都是我干的鳞绕。 我是一名探鬼主播,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼尸曼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼们何!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起控轿,我...
    開(kāi)封第一講書(shū)人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤冤竹,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后茬射,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體鹦蠕,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年躲株,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了片部。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡霜定,死狀恐怖档悠,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情望浩,我是刑警寧澤辖所,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站磨德,受9級(jí)特大地震影響缘回,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜典挑,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一酥宴、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧您觉,春花似錦拙寡、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)般堆。三九已至,卻和暖如春诚啃,著一層夾襖步出監(jiān)牢的瞬間淮摔,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工始赎, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留和橙,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓极阅,卻偏偏與公主長(zhǎng)得像胃碾,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子筋搏,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 在小白我的第一篇文里就提出過(guò)一個(gè)問(wèn)題仆百,就是現(xiàn)在的教程都太“分散”太“板塊”,每一個(gè)知識(shí)點(diǎn)都單獨(dú)用一個(gè)例子奔脐,機(jī)器學(xué)習(xí)...
    猴小白閱讀 14,181評(píng)論 0 4
  • 本文包含了五個(gè)知識(shí)點(diǎn): 1.數(shù)據(jù)挖掘與機(jī)器學(xué)習(xí)技術(shù)簡(jiǎn)介 2.Python數(shù)據(jù)預(yù)處理實(shí)戰(zhàn) 3.常見(jiàn)分類(lèi)算法介紹 ...
    星丶雲(yún)閱讀 4,363評(píng)論 1 12
  • 最近發(fā)現(xiàn)自己的一個(gè)缺點(diǎn)髓迎,很多原理雖然從理論上或著數(shù)學(xué)上理解了峦朗,但是難以用一種簡(jiǎn)潔的偏于溝通的方式表達(dá)出來(lái)。所以合上...
    給力桃閱讀 1,712評(píng)論 0 0
  • 春風(fēng) 吹散的不只是頭發(fā) 更是那絲絲的情懷 夏雨 淋濕的不光是那衣服 更是那如夏日般的熱情 秋霧 蒙住的不再是眼睛 ...
    會(huì)走貓步的魚(yú)閱讀 162評(píng)論 0 3
  • 思想日記46 道-〉德-〉仁-〉義-〉禮-〉智(世智辯聰排龄,知識(shí)波势,而非智慧)-〉法-〉信,猶如十維空間橄维。 上德下德尺铣,...
    幸福人生世界閱讀 129評(píng)論 0 0