簡體   English   中英

Python 從零開始使用 SVM 進行情緒分析

[英]Python Sentiment Analysis using SVM from Scratch

我有一個使用支持向量機 (SVM) 的情感分析學校項目,但我必須從頭開始構建它。 我是 python 的新手,我想問一下我的項目。

所以我正在嘗試做的項目是從頭開始使用 SVM 進行情緒分析。 我從 Twitter 中獲取數據,並標記 x 表示推文數據,標記 y 表示正面 (1) 或負面 (0) 情緒。

然后,使用 countvectorizer 處理推文數據。 在對推文數據 (x) 進行矢量化處理后,我得到數據 x 的形狀 (2411, 5067) 和數據 y 的形狀 (2411,)。 (數據 y 未矢量化)

x.shape
(2411, 5067)

y.shape
(2411,)

然后,我將x和y數據reshape成一維數據,這樣數據就可以進入SVMscratch

x.shape
(12218948, 1)

y.shape
(2411, 1)

之后,我從頭開始研究 SVM 算法並將 x 和 y 擬合在一起。 這是代碼:

class svc:
    def __init__(self , C = 1.0 , n_iters = 100 , learning_rate = 0.1):
 
        self.c = C
        self.iter = n_iters
        self.eta = learning_rate
            
    def fit(self , x , y):
        self.x = x
        self.y = y
        
        w = np.zeros([1 , x.shape[1]])
        b = 0
        
        costs = np.zeros(self.iter)
        for i in range(self.iter):
            cost = x @ w.T + b
            b = b - self.eta * self.c * sum(cost - y) 
            w = w - self.eta * self.c * sum((cost - y)*x) 
            costs[i] = self.c * sum( (y * cost)  + (1 - y)*cost ) + (1/2)* sum(w.T**2)
        
        self.w = w
        self.b = b 
        self.costs = costs
        
    
    def predict(self , x_test):
        pred_y =  []
        svc = x_test @ self.w.T + self.b
        for i in svc:
            if i >= 0:
                pred_y.append(1)
            else:
                pred_y.append(0)
        
        return pred_y
svm = svc(learning_rate=0.001 , C = 1.0)
svm.fit(x , y)

當我做 fit(x, y) 時,我得到這樣的錯誤:

ValueError                                Traceback (most recent call last)
<ipython-input-25-73d1171c68dd> in <module>()
      1 svm = svc(learning_rate=0.001 , C = 1.0)
----> 2 svm.fit(x , y)

<ipython-input-23-6b4dd0109800> in fit(self, x, y)
     16         for i in range(self.iter):
     17             cost = x @ w.T + b
---> 18             b = b - self.eta * self.c * sum(cost - y)
     19             w = w - self.eta * self.c * sum((cost - y)*x)
     20             costs[i] = self.c * sum( (y * cost)  + (1 - y)*cost ) + (1/2)* sum(w.T**2)

ValueError: operands could not be broadcast together with shapes (12218948,1) (2411,1) 

誰能幫我這個?

我什至將數據更改為一維,但仍然出現錯誤。

那么,我該怎么辦?

您的幫助對我來說意義重大!

謝謝 !

這只是一個廣播問題。

請嘗試cost - y.reshape([y.shape[0],-1])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM