1681128661
Вы можете использовать метод replace() для замены появления символа внутри строки в JavaScript.
Вот пример замены символа в строке другим символом с помощью метода replace() :
const str = 'Hello World!'
const updated = str.replace('l', '!')
console.log(updated)
// He!lo World!
По умолчанию replace() заменяет только первое вхождение указанного символа.
Чтобы заменить все вхождения указанного символа, необходимо использовать регулярное выражение с глобальным модификатором ( g ):
const str = 'Hello World!'
const updated = str.replace(/l/g, '!')
console.log(updated)
// He!!o Wor!d!
Для глобальной замены без учета регистра вы можете комбинировать глобальный модификатор ( g ) с модификатором игнорирования регистра ( i ):
const str = 'HeLLo World!'
const updated = str.replace(/l/gi, '!')
console.log(updated)
// He!!o Wor!d!
В качестве альтернативы вы можете использовать метод replaceAll() для замены всех вхождений символа внутри строки:
const str = 'HelLo World!'
const updated = str.replaceAll(/l/gi, '!')
console.log(updated)
// He!!o Wor!d!
Метод replaceAll () был представлен в ES2021. Он заменяет все вхождения строки поиска замещающим текстом и возвращает новую строку.
Оригинальный источник статьи: https://attacomsian.com/
1681124849
您可以使用replace()方法替换 JavaScript 中字符串中出现的字符。
下面是一个使用replace()方法将字符串中的一个字符替换为另一个字符的示例:
const str = 'Hello World!'
const updated = str.replace('l', '!')
console.log(updated)
// He!lo World!
默认情况下,replace()只会替换第一次出现的指定字符。
要替换所有出现的指定字符,您必须使用带有全局修饰符 ( g ) 的正则表达式:
const str = 'Hello World!'
const updated = str.replace(/l/g, '!')
console.log(updated)
// He!!o Wor!d!
对于全局不区分大小写的替换,您可以将全局修饰符 ( g ) 与忽略大小写修饰符 ( i ) 结合使用:
const str = 'HeLLo World!'
const updated = str.replace(/l/gi, '!')
console.log(updated)
// He!!o Wor!d!
或者,您可以使用replaceAll()方法替换字符串中所有出现的字符:
const str = 'HelLo World!'
const updated = str.replaceAll(/l/gi, '!')
console.log(updated)
// He!!o Wor!d!
replaceAll ()方法是在 ES2021 中引入的。它用替换文本替换所有出现的搜索字符串并返回一个新字符串。
文章原文出处:https: //attacomsian.com/
1681110185
You can use the replace() method to replace the occurrence of a character inside a string in JavaScript.
Here is an example that replaces a character in a string with another character using the replace() method:
const str = 'Hello World!'
const updated = str.replace('l', '!')
console.log(updated)
// He!lo World!
By default, the replace() will only replace the first occurrence of the specified character.
To replace all occurrences of a specified character, you must use a regular expression with the global modifier (g):
const str = 'Hello World!'
const updated = str.replace(/l/g, '!')
console.log(updated)
// He!!o Wor!d!
For a global case-insensitive replacement, you can combine the global modifier (g) with the ignore case modifier (i):
const str = 'HeLLo World!'
const updated = str.replace(/l/gi, '!')
console.log(updated)
// He!!o Wor!d!
Alternatively, you could use the replaceAll() method to replace all occurrences of a character inside a string:
const str = 'HelLo World!'
const updated = str.replaceAll(/l/gi, '!')
console.log(updated)
// He!!o Wor!d!
The replaceAll() method was introduced in ES2021. It replaces all occurrences of the search string with the replacement text and returns a new string.
Original article source at: https://attacomsian.com/
1676368391
This article describes how to find and replace text in Vim / Vi.
Vim is the most popular command-line text editor. It comes preinstalled on macOS and most Linux distributions. Finding and replacing text in Vim is quick and easy.
In Vim, you can find and replace text using the :substitute
(:s
) command.
To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the ‘Esc’ key.
The general form of the substitute command is as follows:
:[range]s/{pattern}/{string}/[flags] [count]
The command searches each line in [range]
for a {pattern}
, and replaces it with a {string}
. [count]
is a positive integer that multiplies the command.
If no [range]
and [count]
are given, only the pattern found in the current line is replaced. The current line is the line where the cursor is placed.
For example, to search for the first occurrence of the string ‘foo’ in the current line and replace it with ‘bar’, you would use:
:s/foo/bar/
To replace all occurrences of the search pattern in the current line, add the g
flag:
:s/foo/bar/g
If you want to search and replace the pattern in the entire file, use the percentage character %
as a range. This character indicates a range from the first to the last line of the file:
:%s/foo/bar/g
If the {string}
part is omitted, it is considered as an empty string, and the matched pattern is deleted. The following command deletes all instances of the string ‘foo’ in the current line:
:s/foo//g
Instead of the slash character (/
), you can use any other non-alphanumeric single-byte character except as a delimiter. This option is useful when you have the ‘/’ character in the search pattern or the replacement string.
:s|foo|bar|
To confirm each substitution, use the c
flag:
:s/foo/bar/gc
replace with bar (y/n/a/q/l/^E/^Y)?
Press y
to replace the match or l
to replace the match and quit. Press n
to skip the match and q
or Esc
to quit substitution. The a
option substitutes the match and all remaining occurrences of the match. To scroll the screen down, use CTRL+Y
, and to scroll up, use CTRL+E
.
You can also use regular expressions as a search pattern. The command bellow replaces all lines starting with ‘foo’ with ‘Vim is the best’:
:%s/^foo.*/Vim is the best/gc
The ^
(caret) symbol matches the beginning of a line and .*
matches any number of any characters.
By default, the search operation is case sensitive; searching for “FOO” will not match “Foo”.
To ignore case for the search pattern, use the i
flag:
:s/Foo/bar/gi
Another way to force ignore case is to append \c
after the search pattern. For example, /Linux\c
performs ignore case search.
If you changed the default case setting and you want to perform case sensitive search, use the I
flag:
:s/foo/bar/gi
Uppercase \C
after the pattern also forces case match search.
When no range is specified the substitute command operates only in the current line.
The range can be either one line or a range between two lines. The line specifiers are separated with the ,
or ;
characters. The range can be specified using the absolute line number or special symbols.
For example, to substitute all occurrences of ‘foo’ to ‘bar’ in all lines starting from line 3 to line 10 you would use:
:3,10s/foo/bar/g
The range is inclusive, which means that the first and last lines are included in the range.
The dot .
character indicates the current line and $
- the dollar sign the last line. To substitute ‘foo’ in all lines starting from the current line to the last one:
:.,$s/foo/bar/
The line specifier can also be set using the ‘+’ or ‘-’ symbol,followed by a number that is added or subtracted from the preceding line number. If the number after the symbol is omitted, it defaults to 1.
For example to substitute each ‘foo’ with ‘bar’ starting from the current line and the four next lines, type:
:.,+4s/foo/bar/g
The substitute command looks for the pattern as a string, not a whole word. If, for example, you were searching for “gnu”, the search find matches where “gnu” is embedded in larger words, such as “cygnus” or “magnum”.
To search for a whole word, type \<
to mark the beginning of a word, enter the search pattern, type \>
to mark the end of a word:
For example, to search for the word “foo” you would use \<foo\>
:
:s/\<foo\>/bar/
Vim keeps track of all the commands you run in the current session. To browse the history for previous substitute commands, enter :s
and use the arrow up/down keys to find a previous substitute operation. To run the command, simply press Enter
. You can also edit the command before performing the operation.
Comment lines (add #
before the line) from 5 to 20:
:5,20s/^/#/
Uncomment lines from 5 to 20, revert the previous changes:
:5,20s/^#//
Replace all instances of ‘apple’, ‘orange’, and ‘mango’ with ‘fruit’:
:%s/apple\|orange\|mango/fruit/g
Remove trailing whitespace at the end of each line:
:%s/\s\+$//e
Searching and replacing is a powerful feature of Vim, which allows you to make changes to your text quickly.
Feel free to leave a comment if you have any questions.
Original article source at: https://linuxize.com/
1669174554
In this article, we will learn how to replace elements in Python NumPy Array. To replace elements in Python NumPy Array, We can follow the following examples.
The following code shows how to replace all elements in the NumPy array equal to 8 with a new value of 20:
#replace all elements equal to 8 with 20
my_array[my_array == 8] = 20
#view updated array
print(my_array)
[ 4 5 5 7 20 20 9 12]
The following code shows how to replace all elements in the NumPy array greater than 8 with a new value of 20:
#replace all elements greater than 8 with 20
my_array[my_array > 8] = 20
#view updated array
print(my_array)
[ 4 5 5 7 8 8 20 20]
The following code shows how to replace all elements in the NumPy array greater than 8 or less than 6 with a new value of 20:
#replace all elements greater than 8 or less than 6 with a new value of 20
my_array[(my_array > 8) | (my_array < 6)] = 20
#view updated array
print(my_array)
[20 20 20 7 8 8 20 20]
1667679960
New Shortcut : "cmd option shift f"
Remembers your settings - Remembers your settings for next time you do a find/replace (doesn't remember find/replace/scope as these will change each time)
Get the Regex Power ! ⚡️
Find
(\w+)\s+(\w+)
Replace with
$2 $1
Result: Smith John.
Find
\s{2,}
Replace with
(one space)
Follow me on twitter for more tips.
https://twitter.com/Autre_planete
If you have any problems, or ideas, please open an issue!
V1 Created by Martin Steven - @mscodemonkey - Thank you Martin.
V2 Created by Thierry Charbonnel - @thierryc.
V2 Maintained and improved by Thierry Charbonnel - @thierryc.
Thanks to Aby Nimbalkar - @abynim - for the SketchPlugin-Remember code to save user settings.
Thanks to Autre Planete - @thierryc - for writing the code to change text within symbol overrides.
Thanks to Vincenzo Petito - @vincenzopetito - for code within Shapr showing how to focus the text field on start and tabbing between input fields found within the dialog.
Thanks to Sean Dellis - @seandellis - for his help, test sketch doc and issues review.
Thanks to @iconmaster - for his test.
I take no responsibility for what you find and replace, or for any changes made unintentionally due to this software erroring. I do test it before I release it so the chances of bugs are minimised, but still, use wisely and completely at your own risk. Remember, cmd-z is your saviour.*
Folow me on twitter to be posted.
Author: Thierryc
Source Code: https://github.com/thierryc/Sketch-Find-And-Replace
License: Apache-2.0 license
1666430340
Replace small numbers with zero, or round numbers
zchop
zchop(x)
replaces numbers in x
that are close to zero with zero.
zchop(x)
returns 0 if abs(x) is smaller than 1e-14, and x otherwise.
zchop(x,eps)
uses eps rather than 1e-14
zchop!(a,eps)
works inplace on Array a.
nchop
The interface and implementation of nchop
was done November 16, 2021 and may change.
nchop(x, args...; kwargs...)
round x
using round
. If x
is a container or nested container, round numbers in the containers.
nchop!
a mutating version of nchop
.
zchop
trims noise only from numbers that should be zero.nchop
trims noise from non-zero numbers as well.zchop
is often more than 10 time faster than nchop
.zchop
and nchop
are meant to be used at the command line or notebook for conveniencezchop
is also meant to be efficient at trimming zeros after creating, but before returning, objects in functions.zchop
See also this Jupyter notebook for more examples.
julia> using FFTW
julia> using ZChop
julia> res = ifft(fft([2,1,1,0,0,0,0]))
7-element Vector{ComplexF64}:
2.0 + 0.0im
1.0 + 0.0im
1.0 + 0.0im
1.527827807198305e-17 + 0.0im
5.727136726909545e-18 + 0.0im
0.0 + 0.0im
-6.344131569286608e-17 + 0.0im
julia> zchop(res)
7-element Vector{ComplexF64}:
2.0 + 0.0im
1.0 + 0.0im
1.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
0.0 + 0.0im
julia> res = exp.((1:4) * im * pi)
4-element Vector{ComplexF64}:
-1.0 + 1.2246467991473532e-16im
1.0 - 2.4492935982947064e-16im
-1.0 + 3.6739403974420594e-16im
1.0 - 4.898587196589413e-16im
julia> zchop(res)
4-element Vector{ComplexF64}:
-1.0 + 0.0im
1.0 + 0.0im
-1.0 + 0.0im
1.0 + 0.0im
julia> using SparseArrays
julia> a = sparse([ [1.0,1e-16] [1e-16, 1.0]])
2×2 SparseMatrixCSC{Float64, Int64} with 4 stored entries:
1.0 1.0e-16
1.0e-16 1.0
julia> zchop(a)
2×2 SparseMatrixCSC{Float64, Int64} with 4 stored entries:
1.0 0.0
0.0 1.0
nchop
julia> x = [7.401486830834377e-17 + 3.700743415417188e-17im
8.26024732898714e-17 + 7.020733317042351e-17im
0.9999999999999997 + 1.0000000000000002im
-1.0177044392397268e-16 - 6.476300976980079e-17im
0.0 - 7.401486830834377e-17im
-4.5595039135699516e-17 - 2.1823706978711105e-16im
1.2952601953960158e-16 + 0.0im
-2.1079998571544233e-16 + 5.303212320736824e-17im
0.0 - 7.401486830834377e-17im
-6.476300976980079e-17 + 2.498001805406602e-16im
7.401486830834377e-17 - 1.4802973661668753e-16im
1.7379255156127046e-16 + 2.0982745100975517e-17im]
julia> nchop(x)
12-element Vector{ComplexF64}:
0.0 + 0.0im
0.0 + 0.0im
1.0 + 1.0im
-0.0 - 0.0im
0.0 - 0.0im
-0.0 - 0.0im
0.0 + 0.0im
-0.0 + 0.0im
0.0 - 0.0im
-0.0 + 0.0im
0.0 - 0.0im
0.0 + 0.0im
The type of the numbers is preserved. For instance, complex numbers with imaginary part near zero are not replaced with real numbers.
zchop works on complex and rational numbers, arrays, and some other structures. The idea is for zchop to descend into structures, chopping numbers, and acting as the the identity on anything that can't be sensibly compared to eps.
julia> a = Any[ [1e-15, "dog", (BigFloat(10.0))^-15, complex(1e-15,1), 1 // 10^15],
[[2,3] [4,1e-15]] ];
julia> zchop(a)
2-element Array{Any,1}:
{0.0,"dog",0e+00 with 256 bits of precision,0.0 + 1.0im,0//1}
2x2 Array{Float64,2}:
2.0 4.0
3.0 0.0
Author: jlapeyre
Source Code: https://github.com/jlapeyre/ZChop.jl
License: View license
1660658280
Bonjour lecteurs, dans cet article nous allons essayer de comprendre ce qu'est l'algorithme LDA. comment cela fonctionne et comment il est implémenté en python. Latent Dirichlet Allocation est un algorithme qui relève principalement du domaine du traitement du langage naturel (NLP).
Il est utilisé pour la modélisation de sujet. La modélisation de sujet est une technique d'apprentissage automatique effectuée sur des données textuelles pour les analyser et trouver un sujet similaire abstrait parmi la collection de documents.
LDA est l'un des algorithmes de modélisation thématique spécialement conçu pour les données textuelles. Cette technique considère chaque document comme un mélange de certains des sujets que l'algorithme produit comme résultat final. Les sujets sont la distribution de probabilité des mots qui apparaissent dans l'ensemble de tous les documents présents dans l'ensemble de données.
Le résultat des données prétraitées fournira un tableau de mots-clés ou de jetons, l'algorithme LDA prendra ces données prétraitées en entrée et essaiera de trouver des sujets cachés/sous-jacents en fonction de la distribution de probabilité de ces mots-clés. Initialement, l'algorithme affectera chaque mot du document à un sujet aléatoire parmi le nombre « n » de sujets.
Par exemple, considérez les données textuelles suivantes
Théoriquement, considérons deux sujets Sports et Covid pour que l'algorithme travaille. L'algorithme peut attribuer le premier mot qui dit "IPL" pour le sujet 2 Covid. Nous savons que cette affectation est erronée, mais l'algorithme essaiera de corriger cela dans la future itération en fonction de deux facteurs, à savoir la fréquence à laquelle le sujet apparaît dans le document et la fréquence à laquelle le mot apparaît dans le sujet. Comme il n'y a pas beaucoup de termes liés à Covid dans le texte 1 et que le mot "IPL" n'apparaîtra pas plusieurs fois dans le sujet 2 Covid, l'algorithme peut attribuer le mot "IPL" au nouveau sujet qui est le sujet 1 (sports). Avec plusieurs itérations de ce type, l'algorithme atteindra une stabilité dans la reconnaissance des sujets et la distribution des mots entre les sujets. Enfin, chaque document peut être représenté comme un mélange de sujets déterminés.
A lire aussi : Recherche bidirectionnelle en Python
Les étapes suivantes sont effectuées dans LDA pour attribuer des sujets à chacun des documents :
1) Pour chaque document, initialiser aléatoirement chaque mot à un thème parmi les K thèmes où K est le nombre de thèmes prédéfinis.
2) Pour chaque pièce d :
Pour chaque mot w du document, calculez :
3) Réaffecter le sujet T' au mot w avec probabilité p(t'|d)*p(w|t') en considérant tous les autres mots et leurs affectations de sujet
La dernière étape est répétée plusieurs fois jusqu'à ce que nous atteignions un état stable où les affectations de sujet ne changent plus. La proportion de sujets pour chaque document est ensuite déterminée à partir de ces affectations de sujets.
Exemple illustratif de LDA :
Disons que nous avons les 4 documents suivants comme corpus et que nous souhaitons effectuer une modélisation thématique sur ces documents.
La modélisation LDA nous aide à découvrir des sujets dans le corpus ci-dessus et à attribuer des mélanges de sujets pour chacun des documents. Par exemple, le modèle peut produire quelque chose comme indiqué ci-dessous :
Sujet 1 : 40 % de vidéos, 60 % de YouTube
Sujet 2 : 95 % de blogs, 5 % de YouTube
Les documents 1 et 2 appartiendraient alors à 100% au Topic 1. Le document 3 appartiendrait à 100% au Topic 2. Le document 4 appartiendrait à 80% au Topic 2 et 20% au Topic 1
Voici les étapes pour mettre en œuvre l'algorithme LDA :
Ici, nous avons les données d'entrée collectées à partir de Twitter et les avons converties en un fichier CSV, car les données sur les réseaux sociaux sont variées et nous pouvons construire un modèle efficace.
import numpy as np
import pandas as pd
import re
import gensim
from gensim import corpora, models, similarities
from gensim.parsing.preprocessing import STOPWORDS
from nltk.corpus import stopwords
def normalize_whitespace(tweet):
tweet = re.sub('[\s]+', ' ', tweet)
return tweet
text = " We are the students of Science. "
print("Text Before: ",text)
text = normalize_whitespace(text)
print("Text After: ",text)
PRODUCTION:
Text Before: We are the students of Science.
Texte après : Nous sommes des étudiants en sciences.
import nltk
nltk.download('stopwords')
import gensim
from gensim.parsing.preprocessing import STOPWORDS
from nltk.corpus import stopwords
stop_words = stopwords.words('english')
def remove_stopwords(text):
final_s=""
text_arr= text.split(" ") #splits sentence when space occurs
print(text_arr)
for word in text_arr:
if word not in stop_words: # if word is not in stopword then append(join) it to string
final_s= final_s + word + " "
return final_s
import nltk
# nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer, SnowballStemmer, PorterStemmer
stemmer = PorterStemmer()
def tokenize_stemming(text):
text = re.sub(r'[^\w\s]','',text)
#replace multiple spaces with one space
text = re.sub(r'[\s]+',' ',text)
#transfer text to lowercase
text = text.lower()
# tokenize text
tokens = re.split(" ", text)
# Remove stop words
result = []
for token in tokens :
if token not in stop_words and len(token) > 1:
result.append(stemmer.stem(token))
return result
Il est l'abréviation de terme fréquence-fréquence inverse des documents, est une statistique numérique destinée à refléter l'importance d'un mot pour un document dans une collection ou un corpus. Il est souvent utilisé comme facteur de pondération.
corpus_doc2bow_vectors = [dictionary.doc2bow(tok_doc) for tok_doc in tokens]
print("# Term Frequency : ")
corpus_doc2bow_vectors[:5]
tfidf_model = models.TfidfModel(corpus_doc2bow_vectors, id2word=dictionary, normalize=False)
corpus_tfidf_vectors = tfidf_model[corpus_doc2bow_vectors]
print("\n# TF_IDF: ")
print(corpus_tfidf_vectors[5])
lda_model = gensim.models.LdaMulticore(corpus_doc2bow_vectors, num_topics=10, id2word=dictionary, passes=2, workers=2)
lda_model_tfidf = gensim.models.LdaMulticore(corpus_tfidf_vectors, num_topics=10, id2word=dictionary, passes=2, workers=4)
for idx, topic in lda_model_tfidf.print_topics(-1):
print('Topic: {} Word: {}'.format(idx, topic))
Évaluation des performances en classant des exemples de documents à l'aide du modèle LDA Bag of Words Nous vérifierons où notre document de test serait classé.
for index, score in sorted(lda_model[corpus_doc2bow_vectors[1]], key=lambda tup: -1*tup[1]):
print("\nScore: {}\t \nTopic: {}".format(score, lda_model.print_topic(index, 10)))
for index, score in sorted(lda_model_tfidf[corpus_doc2bow_vectors[1]], key=lambda tup: -1*tup[1]):
print("\nScore: {}\t \nTopic: {}".format(score, lda_model_tfidf.print_topic(index, 10)))
Dans cet article, nous avons essayé de comprendre l'algorithme le plus couramment utilisé dans le domaine du traitement du langage naturel. LDA est la base de la modélisation thématique - un type de modélisation statistique et d'exploration de données.
Lien : https://www.askpython.com/python/examples/latent-dirichlet-allocation-lda
#python
1660640107
Здравствуйте читатели, в этой статье мы попробуем разобраться что такое алгоритм LDA. как это работает и как это реализовано в python. Скрытое распределение Дирихле — это алгоритм, который в основном относится к области обработки естественного языка (NLP).
Он используется для тематического моделирования. Тематическое моделирование — это метод машинного обучения, выполняемый на текстовых данных для их анализа и поиска абстрактной похожей темы среди коллекции документов.
LDA — это один из алгоритмов тематического моделирования, специально разработанный для текстовых данных. Этот метод рассматривает каждый документ как смесь некоторых тем, которые алгоритм выдает в качестве конечного результата. Темы представляют собой распределение вероятностей слов, встречающихся в наборе всех документов, присутствующих в наборе данных.
Результат предварительно обработанных данных предоставит массив ключевых слов или токенов, алгоритм LDA примет эти предварительно обработанные данные в качестве входных данных и попытается найти скрытые/основные темы на основе распределения вероятностей этих ключевых слов. Первоначально алгоритм будет назначать каждому слову в документе случайную тему из ' n' количества тем.
Например, рассмотрим следующие текстовые данные
Теоретически давайте рассмотрим две темы Sports и Covid, над которыми будет работать алгоритм. Алгоритм может назначить первое слово, которое говорит «IPL», для темы 2 Covid. Мы знаем, что это назначение неверно, но алгоритм попытается исправить это в будущей итерации на основе двух факторов: как часто тема встречается в документе и как часто слово встречается в теме. Поскольку в тексте 1 не так много терминов, связанных с Covid, а слово «IPL» не будет встречаться много раз в теме 2 Covid, алгоритм может назначить слово «IPL» новой теме, которая является темой 1 (спорт). С помощью нескольких таких итераций алгоритм достигнет стабильности в распознавании тем и распределении слов по темам. Наконец, каждый документ может быть представлен как смесь определенных тем.
Читайте также: Двунаправленный поиск в Python
Следующие шаги выполняются в LDA для назначения тем каждому из документов:
1) Для каждого документа случайным образом инициализируйте каждое слово темой среди K тем, где K — количество предопределенных тем.
2) Для каждого документа d:
Для каждого слова w в документе вычислить:
3) Переназначить тему T' слову w с вероятностью p(t'|d)*p(w|t'), учитывая все остальные слова и их назначения тем.
Последний шаг повторяется несколько раз, пока мы не достигнем устойчивого состояния, когда тематические задания больше не меняются. Затем на основе этих тематических заданий определяется доля тем для каждого документа.
Иллюстративный пример LDA:
Допустим, у нас есть следующие 4 документа в качестве корпуса, и мы хотим провести тематическое моделирование по этим документам.
Моделирование LDA помогает нам находить темы в вышеупомянутом корпусе и назначать смеси тем для каждого из документов. Например, модель может вывести что-то, как показано ниже:
Тема 1: 40% видео, 60% YouTube
Тема 2: 95% блоги, 5% YouTube
Документы 1 и 2 тогда будут на 100 % принадлежать Теме 1. Документ 3 будет на 100 % принадлежать Теме 2. Документ 4 будет принадлежать 80 % Теме 2 и 20 % Теме 1.
Ниже приведены шаги для реализации алгоритма LDA:
Здесь у нас есть входные данные, собранные из Twitter и преобразованные в файл CSV, поскольку данные в социальных сетях разнообразны, и мы можем построить эффективную модель.
import numpy as np
import pandas as pd
import re
import gensim
from gensim import corpora, models, similarities
from gensim.parsing.preprocessing import STOPWORDS
from nltk.corpus import stopwords
def normalize_whitespace(tweet):
tweet = re.sub('[\s]+', ' ', tweet)
return tweet
text = " We are the students of Science. "
print("Text Before: ",text)
text = normalize_whitespace(text)
print("Text After: ",text)
ВЫХОД:
Text Before: We are the students of Science.
Текст после: Мы студенты естественных наук.
import nltk
nltk.download('stopwords')
import gensim
from gensim.parsing.preprocessing import STOPWORDS
from nltk.corpus import stopwords
stop_words = stopwords.words('english')
def remove_stopwords(text):
final_s=""
text_arr= text.split(" ") #splits sentence when space occurs
print(text_arr)
for word in text_arr:
if word not in stop_words: # if word is not in stopword then append(join) it to string
final_s= final_s + word + " "
return final_s
import nltk
# nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer, SnowballStemmer, PorterStemmer
stemmer = PorterStemmer()
def tokenize_stemming(text):
text = re.sub(r'[^\w\s]','',text)
#replace multiple spaces with one space
text = re.sub(r'[\s]+',' ',text)
#transfer text to lowercase
text = text.lower()
# tokenize text
tokens = re.split(" ", text)
# Remove stop words
result = []
for token in tokens :
if token not in stop_words and len(token) > 1:
result.append(stemmer.stem(token))
return result
Это сокращение от термина «частотно-обратная частота документа», представляет собой числовую статистику, которая предназначена для отражения того, насколько важно слово для документа в коллекции или корпусе. Его часто используют в качестве весового коэффициента.
corpus_doc2bow_vectors = [dictionary.doc2bow(tok_doc) for tok_doc in tokens]
print("# Term Frequency : ")
corpus_doc2bow_vectors[:5]
tfidf_model = models.TfidfModel(corpus_doc2bow_vectors, id2word=dictionary, normalize=False)
corpus_tfidf_vectors = tfidf_model[corpus_doc2bow_vectors]
print("\n# TF_IDF: ")
print(corpus_tfidf_vectors[5])
lda_model = gensim.models.LdaMulticore(corpus_doc2bow_vectors, num_topics=10, id2word=dictionary, passes=2, workers=2)
lda_model_tfidf = gensim.models.LdaMulticore(corpus_tfidf_vectors, num_topics=10, id2word=dictionary, passes=2, workers=4)
for idx, topic in lda_model_tfidf.print_topics(-1):
print('Topic: {} Word: {}'.format(idx, topic))
Оценка производительности путем классификации образцов документов с использованием модели LDA Bag of Words Мы проверим, где наш тестовый документ будет классифицирован.
for index, score in sorted(lda_model[corpus_doc2bow_vectors[1]], key=lambda tup: -1*tup[1]):
print("\nScore: {}\t \nTopic: {}".format(score, lda_model.print_topic(index, 10)))
for index, score in sorted(lda_model_tfidf[corpus_doc2bow_vectors[1]], key=lambda tup: -1*tup[1]):
print("\nScore: {}\t \nTopic: {}".format(score, lda_model_tfidf.print_topic(index, 10)))
В этой статье мы попытались понять наиболее часто используемый алгоритм в области обработки естественного языка. LDA является основой для тематического моделирования — типа статистического моделирования и интеллектуального анализа данных.
Ссылка: https://www.askpython.com/python/examples/latent-dirichlet-allocation-lda
#python
1660632746
Xin chào các bạn độc giả, trong bài viết này chúng tôi sẽ cố gắng tìm hiểu thuật toán LDA là gì. nó hoạt động như thế nào và nó được triển khai như thế nào trong python. Phân bổ Dirichlet tiềm ẩn là một thuật toán chủ yếu nằm trong miền xử lý ngôn ngữ tự nhiên (NLP).
Nó được sử dụng để mô hình hóa chủ đề. Mô hình hóa chủ đề là một kỹ thuật học máy được thực hiện trên dữ liệu văn bản để phân tích dữ liệu đó và tìm một chủ đề tương tự trừu tượng trong bộ sưu tập các tài liệu.
LDA là một trong những thuật toán mô hình hóa chủ đề được thiết kế đặc biệt cho dữ liệu văn bản. Kỹ thuật này coi mỗi tài liệu là một hỗn hợp của một số chủ đề mà thuật toán tạo ra như một kết quả cuối cùng. Các chủ đề là phân phối xác suất của các từ xuất hiện trong tập hợp tất cả các tài liệu có trong tập dữ liệu.
Kết quả của dữ liệu được xử lý trước sẽ cung cấp một mảng từ khóa hoặc mã thông báo, thuật toán LDA sẽ lấy dữ liệu được xử lý trước này làm đầu vào và sẽ cố gắng tìm các chủ đề ẩn / cơ bản dựa trên phân phối xác suất của các từ khóa này. Ban đầu, thuật toán sẽ gán mỗi từ trong tài liệu cho một chủ đề ngẫu nhiên trong số ' n' số chủ đề.
Ví dụ: hãy xem xét dữ liệu văn bản sau
Về mặt lý thuyết, chúng ta hãy xem xét hai chủ đề Thể thao và Sống động để thuật toán hoạt động. Thuật toán có thể gán từ đầu tiên có nội dung “IPL” cho chủ đề 2 Covid. Chúng tôi biết bài tập này là sai, nhưng thuật toán sẽ cố gắng sửa lỗi này trong lần lặp lại trong tương lai dựa trên hai yếu tố là tần suất xuất hiện của chủ đề trong tài liệu và tần suất xuất hiện của từ trong chủ đề. Vì không có nhiều thuật ngữ liên quan đến Covid trong văn bản 1 và từ “IPL” sẽ không xuất hiện nhiều lần trong chủ đề 2 Covid, thuật toán có thể gán từ “IPL” cho chủ đề mới là chủ đề 1 (thể thao). Với nhiều lần lặp lại như vậy, thuật toán sẽ đạt được sự ổn định trong nhận dạng chủ đề và phân phối từ trên các chủ đề. Cuối cùng, mỗi tài liệu có thể được biểu diễn dưới dạng hỗn hợp các chủ đề đã xác định.
Cũng đọc: Tìm kiếm hai chiều bằng Python
Các bước sau được thực hiện trong LDA để gán chủ đề cho từng tài liệu:
1) Đối với mỗi tài liệu, hãy khởi tạo ngẫu nhiên mỗi từ cho một chủ đề trong số K chủ đề trong đó K là số chủ đề được xác định trước.
2) Đối với mỗi tài liệu d:
Đối với mỗi từ w trong tài liệu, hãy tính:
3) Gán lại chủ đề T 'cho từ w với xác suất p (t' | d) * p (w | t ') xem xét tất cả các từ khác và bài tập chủ đề của chúng
Bước cuối cùng được lặp lại nhiều lần cho đến khi chúng ta đạt đến trạng thái ổn định mà các bài tập về chủ đề không thay đổi thêm. Tỷ lệ chủ đề cho mỗi tài liệu sau đó được xác định từ các bài tập chủ đề này.
Ví dụ minh họa về LDA:
Giả sử chúng tôi có 4 tài liệu sau đây làm kho tài liệu và chúng tôi muốn thực hiện mô hình hóa chủ đề trên các tài liệu này.
Mô hình hóa LDA giúp chúng tôi khám phá các chủ đề trong kho tài liệu trên và chỉ định các hỗn hợp chủ đề cho mỗi tài liệu. Ví dụ, mô hình có thể xuất ra một cái gì đó như được đưa ra bên dưới:
Chủ đề 1: 40% video, 60% YouTube
Chủ đề 2: 95% blog, 5% YouTube
Tài liệu 1 và 2 sẽ thuộc 100% thuộc Chủ đề 1. Tài liệu 3 sẽ thuộc 100% thuộc Chủ đề 2. Tài liệu 4 sẽ thuộc 80% thuộc Chủ đề 2 và 20% thuộc Chủ đề 1
Sau đây là các bước để triển khai Thuật toán LDA:
Tại đây, chúng tôi có dữ liệu đầu vào được thu thập từ Twitter và chuyển đổi thành tệp CSV, vì dữ liệu trên mạng xã hội rất đa dạng và chúng tôi có thể xây dựng một mô hình hiệu quả.
import numpy as np
import pandas as pd
import re
import gensim
from gensim import corpora, models, similarities
from gensim.parsing.preprocessing import STOPWORDS
from nltk.corpus import stopwords
def normalize_whitespace(tweet):
tweet = re.sub('[\s]+', ' ', tweet)
return tweet
text = " We are the students of Science. "
print("Text Before: ",text)
text = normalize_whitespace(text)
print("Text After: ",text)
ĐẦU RA:
Text Before: We are the students of Science.
Văn bản Sau: Chúng tôi là sinh viên của Khoa học.
import nltk
nltk.download('stopwords')
import gensim
from gensim.parsing.preprocessing import STOPWORDS
from nltk.corpus import stopwords
stop_words = stopwords.words('english')
def remove_stopwords(text):
final_s=""
text_arr= text.split(" ") #splits sentence when space occurs
print(text_arr)
for word in text_arr:
if word not in stop_words: # if word is not in stopword then append(join) it to string
final_s= final_s + word + " "
return final_s
import nltk
# nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer, SnowballStemmer, PorterStemmer
stemmer = PorterStemmer()
def tokenize_stemming(text):
text = re.sub(r'[^\w\s]','',text)
#replace multiple spaces with one space
text = re.sub(r'[\s]+',' ',text)
#transfer text to lowercase
text = text.lower()
# tokenize text
tokens = re.split(" ", text)
# Remove stop words
result = []
for token in tokens :
if token not in stop_words and len(token) > 1:
result.append(stemmer.stem(token))
return result
Nó là viết tắt của thuật ngữ tần số nghịch đảo tần số của tài liệu, là một thống kê số nhằm phản ánh tầm quan trọng của một từ đối với một tài liệu trong một bộ sưu tập hoặc kho ngữ liệu. Nó thường được sử dụng như một hệ số trọng số.
corpus_doc2bow_vectors = [dictionary.doc2bow(tok_doc) for tok_doc in tokens]
print("# Term Frequency : ")
corpus_doc2bow_vectors[:5]
tfidf_model = models.TfidfModel(corpus_doc2bow_vectors, id2word=dictionary, normalize=False)
corpus_tfidf_vectors = tfidf_model[corpus_doc2bow_vectors]
print("\n# TF_IDF: ")
print(corpus_tfidf_vectors[5])
lda_model = gensim.models.LdaMulticore(corpus_doc2bow_vectors, num_topics=10, id2word=dictionary, passes=2, workers=2)
lda_model_tfidf = gensim.models.LdaMulticore(corpus_tfidf_vectors, num_topics=10, id2word=dictionary, passes=2, workers=4)
for idx, topic in lda_model_tfidf.print_topics(-1):
print('Topic: {} Word: {}'.format(idx, topic))
Đánh giá hiệu suất bằng cách phân loại các tài liệu mẫu bằng mô hình LDA Bag of Words Chúng tôi sẽ kiểm tra xem tài liệu thử nghiệm của chúng tôi sẽ được phân loại ở đâu.
for index, score in sorted(lda_model[corpus_doc2bow_vectors[1]], key=lambda tup: -1*tup[1]):
print("\nScore: {}\t \nTopic: {}".format(score, lda_model.print_topic(index, 10)))
for index, score in sorted(lda_model_tfidf[corpus_doc2bow_vectors[1]], key=lambda tup: -1*tup[1]):
print("\nScore: {}\t \nTopic: {}".format(score, lda_model_tfidf.print_topic(index, 10)))
Trong bài viết này, chúng tôi đã cố gắng tìm hiểu thuật toán được sử dụng phổ biến nhất trong miền xử lý ngôn ngữ tự nhiên. LDA là cơ sở để lập mô hình chủ đề - một loại mô hình thống kê và khai thác dữ liệu.
Liên kết: https://www.askpython.com/python/examples/latent-dirichlet-allocation-lda
#python
1660625280
各位讀者好,在本文中我們將嘗試了解什麼是 LDA 算法。它是如何工作的以及它是如何在 python 中實現的。潛在狄利克雷分配是一種主要屬於自然語言處理 (NLP) 領域的算法。
它用於主題建模。主題建模是一種對文本數據執行的機器學習技術,用於分析它並在文檔集合中找到一個抽象的相似主題。
LDA 是專為文本數據設計的主題建模算法之一。該技術將每個文檔視為算法生成的一些主題的混合,作為最終結果。主題是出現在數據集中所有文檔集中的單詞的概率分佈。
預處理數據的結果會提供一組關鍵詞或tokens,LDA算法會將這些預處理數據作為輸入,並嘗試根據這些關鍵詞的概率分佈來尋找隱藏/潛在的主題。最初,該算法會將文檔中的每個單詞分配給“ n”個主題中的一個隨機主題。
例如,考慮以下文本數據
從理論上講,讓我們考慮兩個主題 Sports 和 Covid 以供算法研究。該算法可以為主題 2 Covid 分配第一個單詞“IPL”。我們知道這個分配是錯誤的,但是該算法將在未來的迭代中嘗試根據兩個因素來糾正這個問題,即主題在文檔中出現的頻率以及單詞在主題中出現的頻率。由於文本 1 中與 Covid 相關的術語不多,並且“IPL”這個詞在主題 2 Covid 中不會出現很多次,因此算法可以將“IPL”這個詞分配給新主題,即主題 1(體育)。通過多次這樣的迭代,該算法將實現主題識別和跨主題詞分佈的穩定性。最後,每個文檔都可以表示為已確定主題的混合。
另請閱讀:Python 中的雙向搜索
在 LDA 中執行以下步驟以將主題分配給每個文檔:
1)對於每個文檔,將每個單詞隨機初始化為 K 個主題中的一個主題,其中 K 是預定義主題的數量。
2) 對於每個文檔 d:
對於文檔中的每個單詞 w,計算:
3) 考慮所有其他單詞及其主題分配,以概率 p(t'|d)*p(w|t') 將主題 T' 重新分配給單詞 w
最後一步重複多次,直到我們達到主題分配不會進一步變化的穩定狀態。然後根據這些主題分配確定每個文檔的主題比例。
LDA 的說明性示例:
假設我們有以下 4 個文檔作為語料庫,我們希望對這些文檔進行主題建模。
LDA 建模幫助我們發現上述語料庫中的主題並為每個文檔分配主題混合。例如,模型可能會輸出如下所示的內容:
主題 1:40% 視頻,60% YouTube
主題 2:95% 的博客,5% 的 YouTube
文檔 1 和 2 將 100% 屬於主題 1。文檔 3 將 100% 屬於主題 2。文檔 4 將 80% 屬於主題 2,20% 屬於主題 1
以下是實現 LDA 算法的步驟:
在這裡,我們從 Twitter 收集輸入數據並將其轉換為 CSV 文件,因為社交媒體上的數據多種多樣,我們可以建立一個有效的模型。
import numpy as np
import pandas as pd
import re
import gensim
from gensim import corpora, models, similarities
from gensim.parsing.preprocessing import STOPWORDS
from nltk.corpus import stopwords
def normalize_whitespace(tweet):
tweet = re.sub('[\s]+', ' ', tweet)
return tweet
text = " We are the students of Science. "
print("Text Before: ",text)
text = normalize_whitespace(text)
print("Text After: ",text)
輸出:
Text Before: We are the students of Science.
後文:我們是理科學生。
import nltk
nltk.download('stopwords')
import gensim
from gensim.parsing.preprocessing import STOPWORDS
from nltk.corpus import stopwords
stop_words = stopwords.words('english')
def remove_stopwords(text):
final_s=""
text_arr= text.split(" ") #splits sentence when space occurs
print(text_arr)
for word in text_arr:
if word not in stop_words: # if word is not in stopword then append(join) it to string
final_s= final_s + word + " "
return final_s
import nltk
# nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer, SnowballStemmer, PorterStemmer
stemmer = PorterStemmer()
def tokenize_stemming(text):
text = re.sub(r'[^\w\s]','',text)
#replace multiple spaces with one space
text = re.sub(r'[\s]+',' ',text)
#transfer text to lowercase
text = text.lower()
# tokenize text
tokens = re.split(" ", text)
# Remove stop words
result = []
for token in tokens :
if token not in stop_words and len(token) > 1:
result.append(stemmer.stem(token))
return result
它是詞頻-逆文檔頻率的縮寫,是一種數值統計數據,旨在反映一個詞對集合或語料庫中的文檔的重要性。它通常用作加權因子。
corpus_doc2bow_vectors = [dictionary.doc2bow(tok_doc) for tok_doc in tokens]
print("# Term Frequency : ")
corpus_doc2bow_vectors[:5]
tfidf_model = models.TfidfModel(corpus_doc2bow_vectors, id2word=dictionary, normalize=False)
corpus_tfidf_vectors = tfidf_model[corpus_doc2bow_vectors]
print("\n# TF_IDF: ")
print(corpus_tfidf_vectors[5])
lda_model = gensim.models.LdaMulticore(corpus_doc2bow_vectors, num_topics=10, id2word=dictionary, passes=2, workers=2)
lda_model_tfidf = gensim.models.LdaMulticore(corpus_tfidf_vectors, num_topics=10, id2word=dictionary, passes=2, workers=4)
for idx, topic in lda_model_tfidf.print_topics(-1):
print('Topic: {} Word: {}'.format(idx, topic))
通過使用 LDA Bag of Words 模型對樣本文檔進行分類進行性能評估 我們將檢查我們的測試文檔將被分類到哪裡。
for index, score in sorted(lda_model[corpus_doc2bow_vectors[1]], key=lambda tup: -1*tup[1]):
print("\nScore: {}\t \nTopic: {}".format(score, lda_model.print_topic(index, 10)))
for index, score in sorted(lda_model_tfidf[corpus_doc2bow_vectors[1]], key=lambda tup: -1*tup[1]):
print("\nScore: {}\t \nTopic: {}".format(score, lda_model_tfidf.print_topic(index, 10)))
在本文中,我們試圖了解自然語言處理領域下最常用的算法。LDA 是主題建模的基礎——一種統計建模和數據挖掘。
鏈接:https ://www.askpython.com/python/examples/latent-dirichlet-allocation-lda
#python
1659664080
计算机视觉中最常见的工作之一是对象检测。它是理解和与场景互动的基础。
对象检测可用于从检测物品等简单应用到自动驾驶汽车等复杂工作的所有领域,以了解各种场景并根据它们做出判断。安全摄像头甚至当前的手机都内置了类似的功能,可实现多种功能。
如今,YOLO(You Only Look Once)是更好的目标检测模型框架,并且该模型是 YOLO 模型家族的最新成员。YOLO 是第一个将边界框预测和对象分类合并到单个端到端可微网络中的对象检测模型。它是在 Darknet 框架下创建和维护的。YOLOv5 是第一个在 PyTorch 框架上编写的 YOLO 模型,它更轻量级,更易于使用。然而,YOLOv7 在标准基准 COCO 数据集上的表现并没有优于 YOLOv6,因为它没有对 YOLOv6 中的网络进行基本的架构改进。
Yolo v6 有一些缺陷,例如在微小项目上的性能不佳以及对象尺寸不相等时的泛化能力差。
这是原始 YOLO 论文中展示 YOLO 操作的图片。从那时起它已经走了很长一段路,我们现在是第 5 版。尽管它不是由任何原始作者或贡献者编写的,但它遵循相同的基本策略。它是用 PyTorch 编写的,这是一个优点。在这个版本的 Yolo 马赛克中,使用了增强,增强和不同的缩放方法提供了许多增强功能。
要让您的目标检测器启动并运行,您必须首先收集训练照片。您应该仔细考虑您尝试完成的活动,并提前计划您的模型可能发现困难的任务组件。为了提高最终模型的准确性,我建议尽可能减少模型必须处理的域。
对于 YOLOv7 自定义训练,我们需要开发一个数据集。如果您没有任何数据,可以使用openimages数据库。
使用LabelImg或任何注释工具来注释数据集。创建一个与图像和注释文本同名的文件。
准备一个集合,例如,对应于
YOLOv7 接受以下格式的文本 (.txt) 文件中的标签数据:
标记数据后,我们会将其分为训练和测试文件夹。拆分比例将由用户决定,但最常见的拆分是 (80-20)%,这意味着 80% 的数据用于训练,20% 用于测试。*图像和标签存储在规定的文件夹架构中。
*对于数据拆分,请查看 python 库 - 拆分文件夹,它将您的数据随机划分为训练、测试和验证。
以下 pip 命令安装数据拆分库
pip 安装拆分文件夹
输入文件夹的格式应如下:
为了向您提供这个:
将文件分成训练集和验证集(以及可选的测试集)。在进入 YOLOv7 训练之前,最终的数据集文件夹如下所示,
├── yolov7
## └── train
####└── images(包含所有训练图像的文件夹)
####└── labels(包含所有训练标签的文件夹)
## └── test
#### └── images(包含所有测试图像的文件夹)
####└── labels(包含所有测试标签的文件夹)
## └──有效
####└── images(包含所有有效图像的文件夹)
### #└── 标签(包含所有有效标签的文件夹)
我们现在必须开发一个定制的配置文件。(请务必指定正确的目录),因为训练过程将完全依赖于该文件。
在 (yolov7/data) 文件夹中创建一个名为“custom.yaml”的文件。在该文件中,粘贴下面的代码。设置数据集文件夹的正确路径,更改类的数量及其名称,然后保存。
创建一个指定训练配置的文件。在 custom.yaml文件中,编写以下内容:
train: (Complete path to dataset train folder)
test: (Complete path to dataset test folder)
valid: (Complete path to dataset valid folder)
#Classes
nc: 1 # replace classes count
#classes names
#replace all class names list with your custom classes
namesnames: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear']
完成所有预处理程序后,就可以开始训练了。在主“ yolov7 ”中启动终端,激活虚拟环境,然后执行下面列出的命令。
git clone https://github.com/WongKinYiu/yolov7.git # clone
cd yolov7
pip install -r requirements.txt # install modules
wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7.pt # download pretrained weight
官方存储库包含模型的预训练权重。
备注:
根据使用环境,如 Google Colab,GPU 内存可能不足。在这种情况下,您可以通过减少批量大小来学习。
python train.py --weights yolov7.pt --data "data/custom.yaml" --workers 4 --batch-size 4 --img 416 --cfg cfg/training/yolov7.yaml --name yolov7 --hyp data/hyp.scratch.p5.yaml
— img = 模型将训练的图像大小,默认值为 640。
— 批量大小= 用于自定义数据集训练的批量大小。
— epochs = 获得最佳模型的训练 epoch 数
— 数据= 自定义配置文件路径
— 权重= 预训练的 yolov7 权重 ( yolov7.pt )
注意:如果任何图像损坏,训练将不会开始。如果任何标签文件损坏,训练将不会开始,因为 yolov7 将忽略该图像和标签文件。
等待训练完成,然后再使用新形成的权重进行推理。自定义训练的权重将保存在以下文件夹路径中。
[yolov7/runs/train/yolov7/weights/best.pt]
训练结束后,转到终端并执行下面列出的命令以检测自定义权重。
python detect.py --weights runs/train/yolov7/weights/best.pt --source "path to your testing image"
您可以使用 YOLO 为您想要的任何东西设计自己的自定义检测模型。
Yolo v7 在速度和准确性方面取得了重大进步,它可以匹配甚至优于基于 RPN 的模型。该模型快速可靠,现在可以用于任何事情。
这就是“使用自定义数据训练 YOLOv7”的全部内容。您可以使用自己的数据进行试验。YOLOv7 轻量级且易于使用。YOLO v7 训练很快,得出很好的结论,并且表现很好。
上述 YOLOV7 的主要经验总结如下:
1659659400
Uno de los trabajos más comunes en la visión artificial es la detección de objetos. Es la base para comprender e interactuar con la escena.
La detección de objetos se usa en todo, desde aplicaciones simples como la detección de artículos hasta trabajos complicados como automóviles autónomos para comprender diversos escenarios y emitir juicios basados en ellos. Las cámaras de seguridad e incluso los teléfonos celulares actuales tienen características similares integradas para una variedad de funciones.
Hoy en día, YOLO (You Only Look Once) es el mejor marco de modelo de detección de objetos , y este modelo es la última incorporación a la familia de modelos YOLO. YOLO fue el primer modelo de detección de objetos que incorporó la predicción de cuadros delimitadores y la clasificación de objetos en una única red diferenciable de extremo a extremo. Fue creado y se mantiene bajo el marco Darknet. YOLOv5 es el primer modelo de YOLO escrito en el marco PyTorch, y es mucho más ligero y fácil de usar. Sin embargo, YOLOv7 no supera a YOLOv6 en un punto de referencia estándar, el conjunto de datos COCO, porque no realizó mejoras fundamentales en la arquitectura de la red en YOLOv6.
Yolo v6 tiene algunas fallas, como un rendimiento deficiente en elementos pequeños y una generalización deficiente cuando las dimensiones de los objetos no son iguales.
Esta es una imagen del artículo original de YOLO que demuestra la operación de YOLO. Ha recorrido un largo camino desde entonces, y ahora estamos en la versión 5. A pesar de que no fue escrito por ninguno de los autores o colaboradores originales, sigue la misma estrategia básica. Está escrito en PyTorch, lo cual es una ventaja. En esta versión del mosaico de Yolo, se utiliza el aumento, y el aumento y diferentes enfoques de escala proporcionan numerosas mejoras.
Para poner en funcionamiento su detector de objetos, primero debe recopilar fotografías de entrenamiento. Debe pensar detenidamente en la actividad que está intentando completar y planificar con anticipación los componentes de la tarea que su modelo puede encontrar difíciles. Para mejorar la precisión de su modelo final, recomiendo reducir el dominio que debe manejar su modelo tanto como sea posible.
Para el entrenamiento personalizado de YOLOv7, necesitamos desarrollar un conjunto de datos. Si no tiene ningún dato, puede usar la base de datos de imágenes abiertas.
Use LabelImg o cualquier herramienta de anotación para anotar el conjunto de datos. Cree un archivo con el mismo nombre que la imagen y el texto de la anotación.
Prepare un conjunto, por ejemplo, correspondiente a
YOLOv7 acepta datos de etiquetas en archivos de texto (.txt) en el siguiente formato:
Una vez que haya etiquetado sus datos, los dividiremos en carpetas de entrenamiento y prueba. El usuario determinará la relación de división; sin embargo, la división más común es (80-20) por ciento, lo que implica que el 80 por ciento de los datos se utiliza para entrenamiento y el 20 por ciento para pruebas. *Las imágenes y etiquetas se almacenan en la arquitectura de carpetas indicada.
*Para la división de datos, busque en la biblioteca de python - Carpeta dividida, que dividirá aleatoriamente sus datos en entrenamiento, prueba y validación.
El siguiente comando pip para instalar la biblioteca de división de datos
pip instalar carpetas divididas
La carpeta de entrada debe formatearse de la siguiente manera:
Para proporcionarle esto:
Separe los archivos en un conjunto de entrenamiento y validación (y, opcionalmente, un conjunto de prueba). La carpeta del conjunto de datos final se ve a continuación antes de ingresar al entrenamiento de YOLOv7,
├── yolov7
## └── tren
####└── imágenes (carpeta que incluye todas las imágenes de entrenamiento)
####└── etiquetas (carpeta que incluye todas las etiquetas de entrenamiento)
## └── prueba
#### └── imágenes (carpeta que incluye todas las imágenes de prueba)
####└── etiquetas (carpeta que incluye todas las etiquetas de prueba)
## └── valid
####└── imágenes (carpeta que incluye todas las imágenes válidas)
### #└── etiquetas (carpeta que incluye todas las etiquetas válidas)
Ahora debemos desarrollar un archivo de configuración personalizado. (Asegúrese de especificar el directorio adecuado), ya que el proceso de capacitación dependerá completamente de ese archivo.
Cree un archivo con el nombre "custom.yaml" en la carpeta (yolov7/data). En ese archivo, pegue el código a continuación. Establezca la ruta correcta a la carpeta del conjunto de datos, modifique la cantidad de clases y sus nombres, y luego guárdelo.
Cree un archivo que especifique la configuración de entrenamiento. En el archivo custom.yaml , escribe lo siguiente:
train: (Complete path to dataset train folder)
test: (Complete path to dataset test folder)
valid: (Complete path to dataset valid folder)
#Classes
nc: 1 # replace classes count
#classes names
#replace all class names list with your custom classes
namesnames: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear']
Después de que se hayan completado todos los procedimientos de preprocesamiento, está listo para comenzar el entrenamiento. Inicie el terminal en el " yolov7 " principal, active el entorno virtual y ejecute los comandos que se enumeran a continuación.
git clone https://github.com/WongKinYiu/yolov7.git # clone
cd yolov7
pip install -r requirements.txt # install modules
wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7.pt # download pretrained weight
El repositorio oficial contiene pesos preentrenados para tu modelo.
Observaciones:
Según el contexto de uso, como Google Colab, la memoria GPU puede ser insuficiente. Puede aprender reduciendo el tamaño del lote en esa situación.
python train.py --weights yolov7.pt --data "data/custom.yaml" --workers 4 --batch-size 4 --img 416 --cfg cfg/training/yolov7.yaml --name yolov7 --hyp data/hyp.scratch.p5.yaml
— img = tamaño de las imágenes en las que se entrenará el modelo, el valor predeterminado es 640.
— tamaño de lote = tamaño de lote utilizado para el entrenamiento de conjuntos de datos personalizados.
— épocas = número de épocas de entrenamiento para obtener el mejor modelo
— datos = ruta del archivo de configuración personalizada
— pesos = pesos yolov7 preentrenados ( yolov7.pt )
Nota : si alguna imagen está dañada, el entrenamiento no comenzará. Si algún archivo de etiqueta está dañado, el entrenamiento no comenzará porque yolov7 ignorará esa imagen y etiquetará los archivos.
Espere a que finalice el entrenamiento antes de realizar inferencias con pesos recién formados. Los pesos entrenados personalizados se guardarán en la siguiente ruta de la carpeta.
[yolov7/runs/train/yolov7/weights/best.pt]
Cuando finalice el entrenamiento, vaya a la terminal y ejecute el comando que se indica a continuación para la detección de pesos personalizados.
python detect.py --weights runs/train/yolov7/weights/best.pt --source "path to your testing image"
Puede usar YOLO para diseñar su propio modelo de detección personalizado para cualquier cosa que desee.
Yolo v7 es un avance significativo en términos de velocidad y precisión, e iguala o incluso supera a los modelos basados en RPN. El modelo es rápido y confiable, y ahora se puede usar para cualquier cosa.
Eso es todo lo que hay que hacer para "Entrenar a YOLOv7 con datos personalizados". Puede experimentar con sus propios datos. YOLOv7 es liviano y fácil de usar. YOLO v7 entrena rápidamente, saca buenas conclusiones y funciona bien.
Las lecciones clave del mencionado YOLOV7 se resumen a continuación:
1659658440
Um dos trabalhos mais comuns em visão computacional é a detecção de objetos. É a base para compreender e interagir com a cena.
A detecção de objetos é usada em tudo, desde aplicativos simples, como detectar itens, até trabalhos complicados, como automóveis autônomos, para entender diversos cenários e fazer julgamentos com base neles. Câmeras de segurança e até mesmo telefones celulares atuais têm recursos semelhantes integrados para uma variedade de funções.
Atualmente, YOLO (You Only Look Once) é a melhor estrutura de modelo de detecção de objetos , e esse modelo é a mais recente adição à família de modelos YOLO. O YOLO foi o primeiro modelo de detecção de objetos a incorporar previsão de caixa delimitadora e classificação de objetos em uma única rede diferenciável de ponta a ponta. Ele foi criado e é mantido sob a estrutura Darknet. YOLOv5 é o primeiro modelo YOLO escrito no framework PyTorch, e é muito mais leve e fácil de usar. No entanto, o YOLOv7 não supera o YOLOv6 em um benchmark padrão, o conjunto de dados COCO, porque não fez melhorias arquiteturais fundamentais na rede no YOLOv6.
O Yolo v6 tem algumas falhas, como baixo desempenho em itens pequenos e má generalização quando as dimensões dos objetos não são iguais.
Esta é uma imagem do documento YOLO original demonstrando a operação YOLO. Ele percorreu um longo caminho desde então, e agora estamos na versão 5. Apesar de não ter sido escrito por nenhum dos autores ou contribuidores originais, segue a mesma estratégia básica. Está escrito em PyTorch, o que é uma vantagem. Nesta versão do mosaico Yolo, o aumento é usado, e o aumento e diferentes abordagens de dimensionamento fornecem vários aprimoramentos.
Para colocar seu detector de objetos em funcionamento, você deve primeiro coletar fotografias de treinamento. Você deve pensar cuidadosamente sobre a atividade que está tentando concluir e planejar com antecedência os componentes da tarefa que seu modelo pode achar difícil. Para melhorar a precisão de seu modelo final, recomendo reduzir o domínio que seu modelo deve manipular tanto quanto possível.
Para treinamento personalizado YOLOv7, precisamos desenvolver um conjunto de dados. Se você não tiver nenhum dado, poderá usar o banco de dados openimages .
Use LabelImg ou qualquer ferramenta de anotação para anotar o conjunto de dados. Crie um arquivo com o mesmo nome da imagem e do texto da anotação.
Prepare um conjunto, por exemplo, correspondente a
YOLOv7 aceita dados de etiquetas em arquivos de texto (.txt) no seguinte formato:
Depois de marcar seus dados, vamos dividi-los em pastas de treinamento e teste. A proporção de divisão será determinada pelo usuário, porém a divisão mais comum é (80-20) por cento, o que implica que 80 por cento dos dados são utilizados para treinamento e 20 por cento para teste. *As imagens e rótulos são armazenados na arquitetura de pasta indicada.
*Para divisão de dados, procure na biblioteca python – Split Folder, que dividirá aleatoriamente seus dados em treinar, testar e validar.
O seguinte comando pip para instalar a biblioteca de divisão de dados
pip instalar pastas divididas
A pasta de entrada deve ser formatada da seguinte forma:
Para lhe fornecer isso:
Separe os arquivos em um conjunto de treinamento e validação (e opcionalmente um conjunto de teste). A pasta do conjunto de dados final parece abaixo antes de entrar no treinamento YOLOv7,
├── yolov7
## └── train
####└── imagens (pasta incluindo todas as imagens de treinamento)
####└── labels (pasta incluindo todos os rótulos de treinamento)
## └── test
#### └── imagens (pasta incluindo todas as imagens de teste)
####└── labels (pasta incluindo todas as etiquetas de teste)
## └── valid
####└── imagens (pasta incluindo todas as imagens válidas)
### #└── rótulos (pasta incluindo todos os rótulos válidos)
Agora devemos desenvolver um arquivo de configuração personalizado. (Certifique-se de especificar o diretório apropriado), pois o processo de treinamento será totalmente dependente desse arquivo.
Crie um arquivo com o nome “custom.yaml” na pasta (yolov7/data). Nesse arquivo, cole o código abaixo. Defina o caminho correto para a pasta do conjunto de dados, altere o número de classes e seus nomes e salve-o.
Crie um arquivo que especifique a configuração de treinamento. No arquivo custom.yaml , escreva o seguinte:
train: (Complete path to dataset train folder)
test: (Complete path to dataset test folder)
valid: (Complete path to dataset valid folder)
#Classes
nc: 1 # replace classes count
#classes names
#replace all class names list with your custom classes
namesnames: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear']
Depois que todos os procedimentos de pré-processamento forem concluídos, ele estará pronto para iniciar o treinamento. Inicie o terminal no “ yolov7 ” principal, ative o ambiente virtual e execute os comandos listados abaixo.
git clone https://github.com/WongKinYiu/yolov7.git # clone
cd yolov7
pip install -r requirements.txt # install modules
wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7.pt # download pretrained weight
O repositório oficial contém pesos pré-treinados para seu modelo.
Observações:
Dependendo do contexto de uso, como o Google Colab, a memória da GPU pode ser insuficiente. Você pode aprender reduzindo o tamanho do lote nessa situação.
python train.py --weights yolov7.pt --data "data/custom.yaml" --workers 4 --batch-size 4 --img 416 --cfg cfg/training/yolov7.yaml --name yolov7 --hyp data/hyp.scratch.p5.yaml
— img = tamanho das imagens nas quais o modelo será treinado, o valor padrão é 640.
— batch-size = tamanho do lote usado para treinamento de conjunto de dados personalizado.
— épocas = número de épocas de treinamento para obter o melhor modelo
— data = caminho do arquivo de configuração personalizado
— pesos = pesos yolov7 pré-treinados ( yolov7.pt )
Nota : Se alguma imagem estiver corrompida, o treinamento não começará. Se algum arquivo de rótulo estiver corrompido, o treinamento não começará porque o yolov7 ignorará essa imagem e os arquivos de rótulo.
Aguarde o término do treinamento antes de realizar a inferência com pesos recém-formados. Os pesos treinados sob medida serão salvos no seguinte caminho de pasta.
[yolov7/runs/train/yolov7/weights/best.pt]
Quando o treinamento terminar, vá para o terminal e execute o comando listado abaixo para detecção de pesos personalizados.
python detect.py --weights runs/train/yolov7/weights/best.pt --source "path to your testing image"
Você pode usar o YOLO para projetar seu próprio modelo de detecção personalizado para qualquer coisa que desejar.
O Yolo v7 é um avanço significativo em termos de velocidade e precisão e corresponde ou até supera os modelos baseados em RPN. O modelo é rápido e confiável, e agora pode ser usado para qualquer coisa.
Isso é tudo o que há para “Treinar YOLOv7 em dados personalizados”. Você pode experimentar com seus próprios dados.YOLOv7 é leve e simples de usar. O YOLO v7 treina rapidamente, tira boas conclusões e tem um bom desempenho.
As principais lições do YOLOV7 acima mencionado são resumidas da seguinte forma:
1659658320
L'une des tâches les plus courantes en vision par ordinateur est la détection d'objets. C'est la base pour comprendre et interagir avec la scène.
La détection d'objets est utilisée dans tout, des applications simples comme la détection d'objets aux tâches complexes comme les automobiles autonomes pour comprendre divers scénarios et porter des jugements en fonction de ceux-ci. Les caméras de sécurité et même les téléphones portables actuels ont des fonctionnalités similaires intégrées pour une variété de fonctions.
De nos jours, YOLO (You Only Look Once) est le meilleur cadre de modèle de détection d'objets , et ce modèle est le dernier ajout à la famille de modèles YOLO. YOLO a été le premier modèle de détection d'objets à intégrer la prédiction de la boîte englobante et la classification des objets dans un seul réseau différentiable de bout en bout. Il a été créé et est maintenu sous le framework Darknet. YOLOv5 est le premier modèle YOLO écrit sur le framework PyTorch, et il est beaucoup plus léger et plus facile à utiliser. Cependant, YOLOv7 ne surpasse pas YOLOv6 sur un benchmark standard, l'ensemble de données COCO, car il n'a pas apporté d'améliorations architecturales fondamentales au réseau dans YOLOv6.
Yolo v6 présente quelques défauts, tels que de mauvaises performances sur des objets minuscules et une mauvaise généralisation lorsque les dimensions des objets ne sont pas égales.
Ceci est une image de l'article YOLO original démontrant le fonctionnement de YOLO. Il a parcouru un long chemin depuis lors, et nous sommes maintenant sur la version 5. Malgré le fait qu'il n'a été écrit par aucun des auteurs ou contributeurs originaux, il suit la même stratégie de base. Il est écrit en PyTorch, ce qui est un plus. Dans cette version de la mosaïque Yolo, l'augmentation est utilisée, et l'augmentation et différentes approches de mise à l'échelle fournissent de nombreuses améliorations.
Pour que votre détecteur d'objets soit opérationnel, vous devez d'abord collecter des photographies d'entraînement. Vous devez réfléchir attentivement à l'activité que vous tentez de réaliser et planifier à l'avance les composants de la tâche que votre modèle peut trouver difficiles. Pour améliorer la précision de votre modèle final, je vous recommande de réduire autant que possible le domaine que votre modèle doit gérer.
Pour la formation personnalisée YOLOv7, nous devons développer un ensemble de données. Si vous n'avez pas de données, vous pouvez utiliser la base de données openimages .
Utilisez LabelImg ou n'importe quel outil d'annotation pour annoter l'ensemble de données. Créez un fichier portant le même nom que l'image et le texte d'annotation.
Préparez un ensemble, par exemple, correspondant à
YOLOv7 accepte les données d'étiquette dans les fichiers texte (.txt) au format suivant :
Après avoir étiqueté vos données, nous les diviserons en dossiers d'apprentissage et de test. Le rapport de division sera déterminé par l'utilisateur, mais la division la plus courante est (80-20) %, ce qui implique que 80 % des données sont utilisées pour la formation et 20 % pour les tests. *Les images et les étiquettes sont stockées dans l'architecture de dossier indiquée.
* Pour le fractionnement des données, consultez la bibliothèque python - Split Folder, qui divisera au hasard vos données en train, test et validation.
La commande pip suivante pour installer la bibliothèque de fractionnement de données
pip installer des dossiers divisés
Le dossier d'entrée doit être formaté comme suit :
Afin de vous fournir ceci :
Séparez les fichiers en un ensemble d'entraînement et un ensemble de validation (et éventuellement un ensemble de test). Le dossier de l'ensemble de données final ressemble à ci-dessous avant d'entrer dans la formation YOLOv7,
├── yolov7
## └── train
####└── images (dossier contenant toutes les images d'entraînement)
####└── labels (dossier contenant toutes les étiquettes d'entraînement)
## └── test
#### └── images (dossier contenant toutes les images de test)
####└── labels (dossier contenant toutes les étiquettes de test)
## └── valid
####└── images (dossier contenant toutes les images valides)
### #└── étiquettes (dossier contenant toutes les étiquettes valides)
Nous devons maintenant développer un fichier de configuration personnalisé. (Assurez-vous de spécifier le répertoire approprié), car le processus de formation dépendra entièrement de ce fichier.
Créez un fichier avec le nom "custom.yaml" dans le dossier (yolov7/data). Dans ce fichier, collez le code ci-dessous. Définissez le chemin d'accès correct au dossier du jeu de données, modifiez le nombre de classes et leurs noms, puis enregistrez-le.
Créez un fichier qui spécifie la configuration de la formation. Dans le fichier custom.yaml , écrivez ce qui suit :
train: (Complete path to dataset train folder)
test: (Complete path to dataset test folder)
valid: (Complete path to dataset valid folder)
#Classes
nc: 1 # replace classes count
#classes names
#replace all class names list with your custom classes
namesnames: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear']
Une fois toutes les procédures de prétraitement terminées, il est prêt à commencer la formation. Lancez le terminal dans le principal " yolov7 ", activez l'environnement virtuel et exécutez les commandes répertoriées ci-dessous.
git clone https://github.com/WongKinYiu/yolov7.git # clone
cd yolov7
pip install -r requirements.txt # install modules
wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7.pt # download pretrained weight
Le référentiel officiel contient des poids pré-entraînés pour votre modèle.
Remarques :
Selon le contexte d'utilisation, tel que Google Colab, la mémoire GPU peut être insuffisante. Vous pouvez apprendre en réduisant la taille du lot dans cette situation.
python train.py --weights yolov7.pt --data "data/custom.yaml" --workers 4 --batch-size 4 --img 416 --cfg cfg/training/yolov7.yaml --name yolov7 --hyp data/hyp.scratch.p5.yaml
— img = taille des images sur lesquelles le modèle s'entraînera, la valeur par défaut est 640.
— batch-size = taille de lot utilisée pour la formation de l'ensemble de données personnalisé.
— époques = nombre d'époques d'entraînement pour obtenir le meilleur modèle
— data = chemin du fichier de configuration personnalisé
— poids = poids yolov7 pré-entraînés ( yolov7.pt )
Remarque : Si une image est corrompue, la formation ne commencera pas. Si un fichier d'étiquette est corrompu, la formation ne commencera pas car yolov7 ignorera cette image et ces fichiers d'étiquette.
Attendez la fin de l'entraînement avant d'effectuer une inférence avec des poids fraîchement formés. Les poids formés sur mesure seront enregistrés dans le chemin de dossier suivant.
[yolov7/runs/train/yolov7/weights/best.pt]
Une fois l'entraînement terminé, accédez au terminal et exécutez la commande ci-dessous pour la détection sur les poids personnalisés.
python detect.py --weights runs/train/yolov7/weights/best.pt --source "path to your testing image"
Vous pouvez utiliser YOLO pour concevoir votre propre modèle de détection personnalisé pour tout ce que vous désirez.
Yolo v7 est une avancée significative en termes de vitesse et de précision, et il correspond ou même surpasse les modèles basés sur RPN. Le modèle est rapide et fiable, et il peut maintenant être utilisé pour n'importe quoi.
C'est tout ce qu'il y a à faire pour "former YOLOv7 sur des données personnalisées". Vous pouvez expérimenter avec vos propres données.YOLOv7 est léger et simple à utiliser. YOLO v7 s'entraîne rapidement, tire de bonnes conclusions et fonctionne bien.
Les principaux enseignements tirés du YOLOV7 susmentionné sont résumés comme suit :