This commit is contained in:
shoney 2023-06-28 20:54:23 +00:00
parent b838faf8a7
commit 55a1b9f552
6 changed files with 76 additions and 17 deletions

View file

@ -621,6 +621,42 @@
" print ('epoch - %d (%d%%) train loss - %.2f test loss - %.2f accuracy - %.4f'\\\n",
" % (epoch, epoch/150 * 10 , loss.data.item(), loss_test.data.item(), accuracy))"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"ename": "ValueError",
"evalue": "empty vocabulary; perhaps the documents only contain stop words",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[13], line 4\u001b[0m\n\u001b[1;32m 2\u001b[0m tf \u001b[39m=\u001b[39m TfidfVectorizer(token_pattern\u001b[39m=\u001b[39m\u001b[39mu\u001b[39m\u001b[39m'\u001b[39m\u001b[39m(?ui)\u001b[39m\u001b[39m\\b\u001b[39;00m\u001b[39m\\\u001b[39m\u001b[39mw*[a-z]+\u001b[39m\u001b[39m\\\u001b[39m\u001b[39mw*\u001b[39m\u001b[39m\\b\u001b[39;00m\u001b[39m'\u001b[39m)\n\u001b[1;32m 3\u001b[0m text \u001b[39m=\u001b[39m [\u001b[39m\"\u001b[39m\u001b[39mThis is v000 Sparta!\u001b[39m\u001b[39m\"\u001b[39m]\n\u001b[0;32m----> 4\u001b[0m tfidf_matrix \u001b[39m=\u001b[39m tf\u001b[39m.\u001b[39;49mfit_transform(text)\n\u001b[1;32m 5\u001b[0m feature_names \u001b[39m=\u001b[39m tf\u001b[39m.\u001b[39mget_feature_names_out() \n\u001b[1;32m 6\u001b[0m \u001b[39mprint\u001b[39m(feature_names)\n",
"File \u001b[0;32m~/dev/.venv/lib/python3.10/site-packages/sklearn/feature_extraction/text.py:2133\u001b[0m, in \u001b[0;36mTfidfVectorizer.fit_transform\u001b[0;34m(self, raw_documents, y)\u001b[0m\n\u001b[1;32m 2126\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39m_check_params()\n\u001b[1;32m 2127\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39m_tfidf \u001b[39m=\u001b[39m TfidfTransformer(\n\u001b[1;32m 2128\u001b[0m norm\u001b[39m=\u001b[39m\u001b[39mself\u001b[39m\u001b[39m.\u001b[39mnorm,\n\u001b[1;32m 2129\u001b[0m use_idf\u001b[39m=\u001b[39m\u001b[39mself\u001b[39m\u001b[39m.\u001b[39muse_idf,\n\u001b[1;32m 2130\u001b[0m smooth_idf\u001b[39m=\u001b[39m\u001b[39mself\u001b[39m\u001b[39m.\u001b[39msmooth_idf,\n\u001b[1;32m 2131\u001b[0m sublinear_tf\u001b[39m=\u001b[39m\u001b[39mself\u001b[39m\u001b[39m.\u001b[39msublinear_tf,\n\u001b[1;32m 2132\u001b[0m )\n\u001b[0;32m-> 2133\u001b[0m X \u001b[39m=\u001b[39m \u001b[39msuper\u001b[39;49m()\u001b[39m.\u001b[39;49mfit_transform(raw_documents)\n\u001b[1;32m 2134\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39m_tfidf\u001b[39m.\u001b[39mfit(X)\n\u001b[1;32m 2135\u001b[0m \u001b[39m# X is already a transformed view of raw_documents so\u001b[39;00m\n\u001b[1;32m 2136\u001b[0m \u001b[39m# we set copy to False\u001b[39;00m\n",
"File \u001b[0;32m~/dev/.venv/lib/python3.10/site-packages/sklearn/feature_extraction/text.py:1388\u001b[0m, in \u001b[0;36mCountVectorizer.fit_transform\u001b[0;34m(self, raw_documents, y)\u001b[0m\n\u001b[1;32m 1380\u001b[0m warnings\u001b[39m.\u001b[39mwarn(\n\u001b[1;32m 1381\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mUpper case characters found in\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 1382\u001b[0m \u001b[39m\"\u001b[39m\u001b[39m vocabulary while \u001b[39m\u001b[39m'\u001b[39m\u001b[39mlowercase\u001b[39m\u001b[39m'\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 1383\u001b[0m \u001b[39m\"\u001b[39m\u001b[39m is True. These entries will not\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 1384\u001b[0m \u001b[39m\"\u001b[39m\u001b[39m be matched with any documents\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 1385\u001b[0m )\n\u001b[1;32m 1386\u001b[0m \u001b[39mbreak\u001b[39;00m\n\u001b[0;32m-> 1388\u001b[0m vocabulary, X \u001b[39m=\u001b[39m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_count_vocab(raw_documents, \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mfixed_vocabulary_)\n\u001b[1;32m 1390\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mbinary:\n\u001b[1;32m 1391\u001b[0m X\u001b[39m.\u001b[39mdata\u001b[39m.\u001b[39mfill(\u001b[39m1\u001b[39m)\n",
"File \u001b[0;32m~/dev/.venv/lib/python3.10/site-packages/sklearn/feature_extraction/text.py:1294\u001b[0m, in \u001b[0;36mCountVectorizer._count_vocab\u001b[0;34m(self, raw_documents, fixed_vocab)\u001b[0m\n\u001b[1;32m 1292\u001b[0m vocabulary \u001b[39m=\u001b[39m \u001b[39mdict\u001b[39m(vocabulary)\n\u001b[1;32m 1293\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39mnot\u001b[39;00m vocabulary:\n\u001b[0;32m-> 1294\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m(\n\u001b[1;32m 1295\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mempty vocabulary; perhaps the documents only contain stop words\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 1296\u001b[0m )\n\u001b[1;32m 1298\u001b[0m \u001b[39mif\u001b[39;00m indptr[\u001b[39m-\u001b[39m\u001b[39m1\u001b[39m] \u001b[39m>\u001b[39m np\u001b[39m.\u001b[39miinfo(np\u001b[39m.\u001b[39mint32)\u001b[39m.\u001b[39mmax: \u001b[39m# = 2**31 - 1\u001b[39;00m\n\u001b[1;32m 1299\u001b[0m \u001b[39mif\u001b[39;00m _IS_32BIT:\n",
"\u001b[0;31mValueError\u001b[0m: empty vocabulary; perhaps the documents only contain stop words"
]
}
],
"source": [
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
"tf = TfidfVectorizer(token_pattern=u'(?ui)\\b\\w*[a-z]+\\w*\\b')\n",
"text = [\"This is v000 Sparta!\"]\n",
"tfidf_matrix = tf.fit_transform(text)\n",
"feature_names = tf.get_feature_names_out() \n",
"print(feature_names)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {

View file

@ -36,6 +36,7 @@ class DataFrame:
text =soup.get_text()
text = (re.sub('[-\W]+', ' ', text))
text = (re.sub('(?<=\d) (?=\d)', '', text))
text = (re.sub("([a-z]\d+)|(\d+)", '', text))
return ''.join(
c for c in unicodedata.normalize('NFD', text)
if unicodedata.category(c) != 'Mn')

View file

@ -12,16 +12,16 @@ class RNN(nn.Module):
self.i2h = nn.Linear(input_size + hidden_size, hidden_size)
self.i2o = nn.Linear(input_size + hidden_size, output_size)
self.h2o = nn.Linear(hidden_size, output_size)
self.softmax = nn.LogSoftmax(dim=1)
def forward(self, input, hidden):
combined = torch.cat((input, hidden), 1)
compbined = torch.cat((input, hidden), 1)
hidden = self.i2h(combined)
hidden = self.i2h(compbined)
output = self.i2o(combined)
output = self.h2o(hidden)
output = self.softmax(output)
return output, hidden

View file

@ -27,7 +27,9 @@ class Train():
self.rnn.zero_grad()
output, hidden = self.rnn(name_tensor, hidden)
for i in range(name_tensor.size()[0]):
output, hidden = self.rnn(name_tensor[i], hidden)
loss = self.criterion(output, category_tensor)
loss.backward()
@ -35,6 +37,12 @@ class Train():
# for p in self.rnn.parameters():
# p.data.add_(-self.learning_rate, p.grad.data)
# Add parameters' gradients to their values, multiplied by learning rate
for p in self.rnn.parameters():
p.data.add_(p.grad.data, alpha=-self.learning_rate)
return output, loss.item()
@ -51,8 +59,14 @@ class Train():
name =self.df_en.iloc[index]["name"]
category_tensor = torch.tensor([self.all_category.index(randcategory)], dtype=torch.long)
name_tensor=torch.zeros(1, self.inputSize)
name_tensor[0][np.where(ngramNameArray==1)[0]] = 1
ngramOnceArray = np.where(ngramNameArray==1)[0]
name_tensor=torch.zeros(len(ngramOnceArray),1, self.inputSize)
for i in range(ngramOnceArray.size):
name_tensor[i][0][ngramOnceArray[i]] = 1
return randcategory, name, category_tensor, name_tensor
@ -75,7 +89,7 @@ class Train():
output, loss = self.train(category_tensor, name_tensor)
self.current_loss += loss
if epoch % 100 == 0:
if epoch % 5000 == 0:
guess, guess_i = self.categoryFromOutput(output)
correct = '✓' if guess == category else '✗ (%s)' % category

View file

@ -1,7 +1,9 @@
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
class Vectorize():
def __init__(self,ngram_min,ngram_max):
self.vectorizer = CountVectorizer(ngram_range=(ngram_min, ngram_max))
self.TfidV = TfidfVectorizer(token_pattern=u'(?ui)\\b\\w*[a-z]+\\w*\\b')
def fit(self,doc):
self.vectorizer.fit(doc)
@ -19,4 +21,10 @@ class Vectorize():
return self.transformedVector.shape[1]
def setTfidFitTransform(self,doc):
self.TfidVectorized=self.TfidV.fit_transform(doc)
def getTfidFitTransform(self):
return self.TfidVectorized

View file

@ -14,23 +14,23 @@ def main():
[df_en, df_de]=df.create()
vectorizer = Vectorize(1,1)
# vectorizer.setTfidFitTransform(df_en["name"])
# x =vectorizer.getTfidFitTransform()
# print(x.shape)
vectorizer.fit(doc=df_en["name"])
vectorizer.transform(df_en["name"])
vectorizer.transform(df_en["category"])
# df_eng["category"].astype("category")
# df =df_eng["category"].isnull()
# bool_name_series = pd.notnull(df_eng["name"])
# bool_cat_series = pd.isnull(df_eng["name"])
# print(df_eng[bool_cat_series])
inputSize=vectorizer.getTransformedVectorSize()
n_hidden = 256
n_hidden = 256*3
df_category = df_en.groupby('category')
all_category = list(df_category.groups.keys())
n_category = len(all_category)
@ -38,7 +38,7 @@ def main():
train = Train(vectorizer,df_en,all_category,rnn)
train.run(10000)
train.run(200000)