機(jī)器學(xué)習(xí)筆記(6)

個(gè)人自己創(chuàng)建數(shù)據(jù),實(shí)現(xiàn)分類任務(wù)

本次組隊(duì)學(xué)習(xí)不太設(shè)計(jì)特征工程內(nèi)容,只是學(xué)習(xí)算法的內(nèi)容骆姐,對(duì)數(shù)據(jù)簡單的歸一化就行

創(chuàng)建數(shù)據(jù)示例如圖所示:

'''
Logistic Regression算法練習(xí)
'''

#第一步:數(shù)據(jù)準(zhǔn)備:生成數(shù)據(jù)和訓(xùn)練數(shù)據(jù)/測試數(shù)據(jù)劃分

import numpy as np
import matplotlib.pyplot as plt
#生成數(shù)據(jù)
def generate_data(seed):
    np.random.seed(seed)
    data_size_1 = 500
    x1_1 = np.random.normal(loc=1.0, scale=1.0, size=data_size_1)
    x2_1 = np.random.normal(loc=2.0, scale=1.0, size=data_size_1)
    y_1 = [0 for _ in range(data_size_1)]
    data_size_2 = 400
    x1_2 = np.random.normal(loc=6.0, scale=2.0, size=data_size_2)
    x2_2 = np.random.normal(loc=8.0, scale=2.0, size=data_size_2)
    y_2 = [1 for _ in range(data_size_2)]
    x1 = np.concatenate((x1_1, x1_2), axis=0)
    x2 = np.concatenate((x2_1, x2_2), axis=0)

    x = np.hstack((x1.reshape(-1, 1), x2.reshape(-1, 1)))
    y = np.concatenate((y_1, y_2), axis=0)
    data_size_all = data_size_1 + data_size_2
    shuffled_index = np.random.permutation(data_size_all)
    x = x[shuffled_index]
    y = y[shuffled_index]
    return x, y

#數(shù)據(jù)劃分
def train_test_split(x, y):
    split_index = int(len(y) * 0.7)
    x_train = x[:split_index]
    y_train = y[:split_index]
    x_test = x[split_index:]
    y_test = y[split_index:]
    return x_train, y_train, x_test, y_test

class LogisticRegression(object):

    def __init__(self, learning_rate=0.1, max_iter=100, seed=None):
        self.seed = seed
        self.lr = learning_rate
        self.max_iter = max_iter

    def fit(self, x, y):   #初始化x,y,w,b
        np.random.seed(self.seed)
        self.w = np.random.normal(loc=0.0, scale=1.0, size=x.shape[1])
        self.b = np.random.normal(loc=0.0, scale=1.0)
        self.x = x
        self.y = y
        for i in range(self.max_iter):
            self._update_step()

    def _sigmoid(self, z):    # f(C1/x) = 1 / (1 + exp(-z))
        return 1.0 / (1.0 + np.exp(-z))

    def _f(self, x, w, b):    # z = wx+b
        z = x.dot(w) + b
        return self._sigmoid(z)

    def predict_proba(self, x=None):
        if x is None:
            x = self.x
        y_pred = self._f(x, self.w, self.b)
        return y_pred

    def predict(self, x=None):
        if x is None:
            x = self.x
        y_pred_proba = self._f(x, self.w, self.b)
        y_pred = np.array([0 if y_pred_proba[i] < 0.5 else 1 for i in range(len(y_pred_proba))])
        return y_pred

    def score(self, y_true=None, y_pred=None):   #預(yù)測正確率
        if y_true is None or y_pred is None:
            y_true = self.y
            y_pred = self.predict()
        acc = np.mean([1 if y_true[i] == y_pred[i] else 0 for i in range(len(y_true))])
        return acc

    def loss(self, y_true=None, y_pred_proba=None):   #計(jì)算損失函數(shù)
        if y_true is None or y_pred_proba is None:
            y_true = self.y
            y_pred_proba = self.predict_proba()
        return np.mean(-1.0 * (y_true * np.log(y_pred_proba) + (1.0 - y_true) * np.log(1.0 - y_pred_proba)))

    def _calc_gradient(self):   #計(jì)算梯度
        y_pred = self.predict()
        d_w = (y_pred - self.y).dot(self.x) / len(self.y)
        d_b = np.mean(y_pred - self.y)
        return d_w, d_b

    def _update_step(self):   #計(jì)算梯度下降
        d_w, d_b = self._calc_gradient()
        self.w = self.w - self.lr * d_w
        self.b = self.b - self.lr * d_b
        return self.w, self.b


x, y = generate_data(seed=20190603)    #設(shè)置seed為20190603
x_train, y_train, x_test, y_test = train_test_split(x, y)

x_train = (x_train - np.min(x_train, axis=0)) / (np.max(x_train, axis=0) - np.min(x_train, axis=0))
x_test = (x_test - np.min(x_test, axis=0)) / (np.max(x_test, axis=0) - np.min(x_test, axis=0))

# Logistic regression classifier
clf = LogisticRegression(learning_rate=0.1, max_iter=500, seed=272)
clf.fit(x_train, y_train)

# plot the result
split_boundary_func = lambda x: (-clf.b - clf.w[0] * x) / clf.w[1]
xx = np.arange(0.1, 0.6, 0.1)
cValue = ['g','b'] 
plt.scatter(x_train[:,0], x_train[:,1], c=[cValue[i] for i in y_train], marker='o')
plt.plot(xx, split_boundary_func(xx), c='red')
plt.show()

# loss on test set
y_test_pred = clf.predict(x_test)
y_test_pred_proba = clf.predict_proba(x_test)
print(clf.score(y_test, y_test_pred))
print(clf.loss(y_test, y_test_pred_proba))
# print(y_test_pred_proba)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末滤钱,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子斩萌,更是在濱河造成了極大的恐慌缝裤,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,590評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件颊郎,死亡現(xiàn)場離奇詭異憋飞,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)姆吭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門榛做,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人内狸,你說我怎么就攤上這事检眯。” “怎么了昆淡?”我有些...
    開封第一講書人閱讀 169,301評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵锰瘸,是天一觀的道長。 經(jīng)常有香客問我昂灵,道長避凝,這世上最難降的妖魔是什么舞萄? 我笑而不...
    開封第一講書人閱讀 60,078評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮恕曲,結(jié)果婚禮上鹏氧,老公的妹妹穿的比我還像新娘。我一直安慰自己佩谣,他們只是感情好把还,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著茸俭,像睡著了一般吊履。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上调鬓,一...
    開封第一講書人閱讀 52,682評(píng)論 1 312
  • 那天艇炎,我揣著相機(jī)與錄音,去河邊找鬼腾窝。 笑死缀踪,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的虹脯。 我是一名探鬼主播驴娃,決...
    沈念sama閱讀 41,155評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼循集!你這毒婦竟也來了唇敞?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,098評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤咒彤,失蹤者是張志新(化名)和其女友劉穎疆柔,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體镶柱,經(jīng)...
    沈念sama閱讀 46,638評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡旷档,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了歇拆。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片鞋屈。...
    茶點(diǎn)故事閱讀 40,852評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖查吊,靈堂內(nèi)的尸體忽然破棺而出谐区,到底是詐尸還是另有隱情湖蜕,我是刑警寧澤逻卖,帶...
    沈念sama閱讀 36,520評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站昭抒,受9級(jí)特大地震影響评也,放射性物質(zhì)發(fā)生泄漏炼杖。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評(píng)論 3 335
  • 文/蒙蒙 一盗迟、第九天 我趴在偏房一處隱蔽的房頂上張望坤邪。 院中可真熱鬧,春花似錦罚缕、人聲如沸艇纺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽黔衡。三九已至,卻和暖如春腌乡,著一層夾襖步出監(jiān)牢的瞬間盟劫,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評(píng)論 1 274
  • 我被黑心中介騙來泰國打工与纽, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留侣签,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,279評(píng)論 3 379
  • 正文 我出身青樓急迂,卻偏偏與公主長得像影所,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子袋毙,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評(píng)論 2 361