Отказ от ответственности: эта статья носит чисто экспериментальный характер, и вы не можете найти твердую теорию экспериментов.

В 20-м году у нас есть много вариантов, начиная от простой модели пропуска грамматики, такой как Word2Vec, до сложной архитектуры кодера-декодера, такой как трансформаторы. Это не было похоже на ту архитектуру кодировщика-декодера, какой не было раньше, и, как вы знаете, это LSTM и RNN или причудливый механизм внимания, который реализован в трансформаторах. Мы также могли бы реализовать внимание в RNN, но вместо передачи вектора контекста мы можем передать взвешенную сумму.

Transformers также используют стековую архитектуру кодировщика-декодера, которая имеет 6 уровней и реализует концепцию самовнимания. Этот механизм самовнимания делает этот механизм настолько мощным. Есть несколько постов и авторов, которые могут объяснить трансформаторы лучше, чем я, поэтому позвольте мне перейти к экспериментальной части.

Несколько недель назад я работал над очень техническим набором данных, и мне нужно было поэкспериментировать, какое вложение лучше всего подходит для использования в архитектуре, и набор данных был таким, в котором каждый абзац содержал около 45% технических слов. И, как вы уже догадались, создать вложение с использованием предварительно обученных весов практически невозможно.

Я использовал Transformers -XL и универсальный кодировщик предложений Google для сравнения встраивания, и эта статья представляет собой мою точку зрения на сгенерированное встраивание. Прежде чем перейти к результатам, давайте разберемся с некоторыми ключевыми моментами, связанными с transformer-xl.

Transformers Xl был выпущен около года назад, и основным мотивом его создания было улучшение по сравнению с ванильными трансформерами. Transformers XL был создан для решения проблемы фрагментации контекста. Это серьезная проблема, которая возникает, когда обрабатываются длинные последовательности, и, как обычно, LSTM, RNN и даже трансформаторы начинают давать сбой, поскольку он пытается построить скрытые состояния каждого нового сегмента из предыдущего контекста, и, следовательно, более длинные зависимости могут быть разумно обработаны в XL

Для этого эксперимента я бы использовал очень известную библиотеку hugging-face:

from transformers import TransfoXLTokenizer, TransfoXLModelimport 
torchtokenizer_transformer_xl=TransfoXLTokenizer.from_pretrained('transfo-xl-wt103')
model_transformer_xl = TransfoXLModel.from_pretrained('transfo-xl-wt103')
#INPUT SENTENCE
text = """Education is the process of facilitating learning, or the acquisition of knowledge, skills, values, beliefs, and habits. Educational methods include teaching, training, storytelling, discussion and directed research. Education frequently takes place under the guidance of educators, however learners can also educate themselves.[1] Education can take place in formal or informal settings and any experience that has a formative effect on the way one thinks, feels, or acts may be considered educational. The methodology of teaching is called pedagogy.Formal education is commonly divided formally into such stages as preschool or kindergarten, primary school, secondary school and then college, university, or apprenticeship.A right to education has been recognized by some governments and the United Nations.[2] In most regions, education is compulsory up to a certain age. There is a movement for education reform, and in particular for evidence-based education."""
text2 = "Education is not at all important, only skill matters"

Давайте сгенерируем встраивание для текста и текста2 и получим сравнительную оценку

result_USE : 0.6578701138496399
result_transformer_xl : 0.5666961073875427

Пример 2:

text = """Education is the process of facilitating learning, or the acquisition of knowledge, skills, values, beliefs, and habits. Educational methods include teaching, training, storytelling, discussion and directed research. Education frequently takes place under the guidance of educators, however learners can also educate themselves.[1] Education can take place in formal or informal settings and any experience that has a formative effect on the way one thinks, feels, or acts may be considered educational. The methodology of teaching is called pedagogy.Formal education is commonly divided formally into such stages as preschool or kindergarten, primary school, secondary school and then college, university, or apprenticeship. A right to education has been recognized by some governments and the United Nations.[2] In most regions, education is compulsory up to a certain age. There is a movement for education reform, and in 
particular for evidence-based education."""
text2 = "Education is very important, only then we can be civilized"

Давайте сгенерируем встраивание для текста и текста2 и получим сравнительную оценку

result_USE : 0.5801218748092651
result_transformer_xl : 0.6045575141906738

Пример 3:

text = """The Airbus A320 family are narrow-body airliners designed and produced by Airbus. The A320 was launched in March 1984, first flew on 22 February 1987, and was introduced in April 1988 by Air France. The first member of the family was followed by the longer A321 (first delivered in January 1994), the shorter A319 (April 1996), and the even shorter A318 (July 2003). Final assembly takes place in Toulouse in France; Hamburg in Germany; Tianjin in China since 2009; and in Mobile, Alabama in the United States since April 2016.The twinjet has a six-abreast cross-section and is powered by either CFM56 or IAE V2500 turbofans, except the CFM56/PW6000 powered A318. The family pioneered the use of digital fly-by-wire and side-stick flight controls in airliners. Variants offer maximum take-off weights from 68 to 93.5 t (150,000 to 206,000 lb), to cover a 5,740–6,940 km (3,100–3,750 nmi) range. The 31.4 m (103 ft) long A318 typically accommodates 107 to 132 passengers. The 124-156 seats A319 is 33.8 m (111 ft) long. The A320 is 37.6 m (123 ft) long and can accommodate 150 to 186 passengers. The 44.5 m (146 ft) A321 offers 185 to 230 seats. The Airbus Corporate Jets are business jet versions.In December 2010, Airbus announced the re-engined A320neo (new engine option), which entered service with Lufthansa in January 2016. With more efficient turbofans and improvements including sharklets, it offers up to 15% better fuel economy. Earlier A320s are now called A320ceo (current engine option).In October 2019, it surpassed the Boeing 737 to become the highest-selling airliner. As of January 2020, a total of 9,273 aircraft have been delivered to more than 330 operators including low-cost carriers, with 8,814 aircraft in service. American Airlines is the largest operator with 414 aircraft.[b] Orders pending were 6,068, for a total of 15,315 orders. The A320ceo initially competed with the MD-80 and the 737 Classic, then the MD-90 and the 737 Next Generation, while the 737 MAX is Boeing's response to the A320neo."""
text2 =  """When Airbus designed the Airbus A300 during the late 1960s and early 1970s, it envisaged a broad family of airliners with which to compete against Boeing and Douglas, two established US aerospace manufacturers. From the moment of formation, Airbus had begun studies into derivatives of the Airbus A300B in support of this long-term goal.[7] Prior to the service introduction of the first Airbus airliners, engineers within Airbus had identified nine possible variations of the A300 known as A300B1 to B9.[8] A 10th variation, conceived in 1973, later the first to be constructed, was designated the A300B10.[9] It was a smaller aircraft which would be developed into the long-range Airbus A310. Airbus then focused its efforts on the single-aisle market, which was dominated by the 737 and McDonnell Douglas DC-9.Plans from a number of European aircraft manufacturers called for a successor to the relatively successful BAC One-Eleven, and to replace the 737-200 and DC-9.[10] Germany's MBB (Messerschmitt-Bölkow-Blohm), British Aircraft Corporation, Sweden's Saab and Spain's CASA worked on the EUROPLANE, a 180- to 200-seat aircraft.[10][11] It was abandoned after intruding on A310 specifications.[11] VFW-Fokker, Dornier and Hawker Siddeley worked on a number of 150-seat designs.[10]The design within the JET study that was carried forward was the JET2 (163 passengers), which then became the Airbus S.A1/2/3 series (Single Aisle), before settling on the A320 name for its launch in 1984. Previously, Hawker Siddeley had produced a design called the HS.134 "Airbus" in 1965, an evolution of the HS.121 (formerly DH.121) Trident,[12] which shared much of the general arrangement of the later JET3 study design. The name "Airbus" at the time referred to a BEA requirement, rather than to the later international programme."""

Давайте сгенерируем встраивание для текста и текста2 и получим сравнительную оценку

result_USE : 0.8522822856903076
result_xl : 0.5586667359182176

Пример 4:

text = 'Hello world! '
text2 = 'Bring me some money '

Давайте сгенерируем встраивание для текста и текста2 и получим сравнительную оценку

result_USE : 0.4378304183483124
result_transformer_xl : 0.2658374607563019

Заключение:

Я думал об этом эксперименте, чтобы доказать, что XL может работать лучше, чем USE, и поэтому мои примеры были восприняты как таковые. Выше вы можете наблюдать примеры длинных и длинных, коротких и коротких, и, следовательно, я был неправ.

Этот эксперимент может показаться неправильным, так как вложения xl, которые я использовал, производили вложения слов, которые были усреднены, тогда как в USE использовалась методика, называемая сетями глубокого усреднения, где берется двойное среднее и передается через сеть с прямой связью, которая смотрит на похожие предложения и вычисляет потери. соответственно.

Привет, меня зовут Прияншу, и я активно участвую в создании Vision.ml, платформы для обмена опытом с разработчиками искусственного интеллекта, которые решают ряд проблем при проектировании и строительстве. сложные алгоритмы для выполнения определенных задач.

Vision.ml - это платформа с открытым исходным кодом, позволяющая делиться неотразимым захватывающим контентом, с которым мы сталкиваемся при разработке моделей искусственного интеллекта. Неважно, простая проблема или слишком сложная. Мы поделились темами, которые, возможно, активно ищут большинство разработчиков / исследователей. Мы стараемся охватить темы от машинного обучения до языков программирования. Мы пишем, чем мы занимались, и, что более важно, как мы подошли к этой проблеме.

Если вам нравится идея vision.ml, подписывайтесь на меня, чтобы увидеть больше таких статей.