Melatih model bahasa yang besar untuk mengetahui cara mengekstrak entitas, dan memberikan informasi penting tentang entitas tersebut (URL Wikipedia-nya)
Ketika mesin pencari merayapi situs web, mereka mencoba yang terbaik untuk mendapatkan informasi sebanyak mungkin dari halaman-halaman tersebut. Meskipun telah ada perkembangan besar-besaran dalam hal ini, mereka masih membuat tebakan terbaik, menggunakan probabilitas tentang informasi yang mereka gali.
Menyediakan mesin pencari (atau aplikasi lain yang menggunakan halaman web kami) dengan data terstruktur akan membuat segalanya menjadi lebih mudah, dan memungkinkan aplikasi yang sangat menarik dan penggunaan data kami.
Dalam banyak kasus, kita dihadapkan pada situasi di mana kita memiliki banyak halaman yang tidak berisi data terstruktur, tetapi hal itu perlu dilakukan. Tentu saja kita dapat mengambil rute manual dan mengklasifikasikan/menandai konten kita satu per satu. Kita juga dapat mengeksplorasi kemajuan terbaru menggunakan model bahasa besar, dan melatihnya untuk tugas khusus mengekstrak data tertentu dari halaman kita, dan membuat markup tambahan yang diinginkan dalam bentuk skrip JSON-LD. Namun kita tidak terbatas pada format tersebut, setelah kita memiliki akses ke data, kita dapat memformatnya dengan cara apa pun yang kita inginkan.
Berikut ini adalah ikhtisar singkat tentang masalah yang mungkin kita hadapi dan langkah-langkah yang disarankan untuk mengatasinya:
- Kami memiliki situs web besar dengan (puluhan atau ratusan) ribu halaman yang tidak memiliki markup terstruktur (JSON-LD, Twitter, OpenGraph misalnya).
- Kami ingin membuat markup terstruktur untuk halaman-halaman tersebut.
- Kami ingin melakukan hal ini dalam skala besar.
- Kami akan melatih LLM untuk mengekstrak entitas dari artikel, dan memberikan tautan ke halaman Wikipedia untuk setiap entitas.
Untuk memperjelas, kami akan memberikan ChatGPT masukan seperti berikut, yang merupakan bagian ringkasan dari sebuah halaman Wikipedia, dalam hal ini "Bola Basket". Hanya beberapa baris pertama yang ditampilkan, dan kita akan membahas contoh lengkapnya nanti:
Basketball is a team sport in which two teams, most commonly of five players each, opposing one another on a rectangular court, compete with the primary objective of shooting a basketball (approximately 9.4 inches (24 cm) in diameter) through the defender’s hoop (a basket 18 inches (46 cm) in diameter mounted 10 feet (3.048 m) high to a backboard at each end of the court), while preventing the opposing team from shooting through their own hoop. A field goal is worth two points, unless made from behind the three-point line, when it is worth three…
Dan kami ingin mendapatkan tanggapan sebagai berikut:
idx | entitas | url |
0 | James Naismith | https://en.wikipedia.org/wiki/James_Naismith |
1 | Springfield, Massachusetts | https://en.wikipedia.org/wiki/Springfield,_Massachusetts |
2 | National Basketball Association | https://en.wikipedia.org/wiki/National_Basketball_Association |
3 | NBA | https://en.wikipedia.org/wiki/National_Basketball_Association |
4 | EuroLeague | https://en.wikipedia.org/wiki/EuroLeague |
5 | Basketball Champions League Americas | https://en.wikipedia.org/wiki/Basketball_Champions_League_Americas |
6 | FIBA Basketball World Cup | https://en.wikipedia.org/wiki/FIBA_Basketball_World_Cup |
7 | EuroBasket | https://en.wikipedia.org/wiki/EuroBasket |
8 | FIBA AmeriCup | https://en.wikipedia.org/wiki/FIBA_AmeriCup |
9 | FIBA Women’s Basketball World Cup | https://en.wikipedia.org/wiki/FIBA_Women%27s_Basketball_World_Cup |
10 | WNBA | https://en.wikipedia.org/wiki/Women%27s_National_Basketball_Association |
11 | NCAA Women’s Division I Basketball Championship | https://en.wikipedia.org/wiki/NCAA_Division_I_women%27s_basketball_tournament |
12 | EuroLeague Wanita | https://en.wikipedia.org/wiki/EuroLeague_Women |
Ini adalah tujuan yang cukup ambisius untuk mengotomatiskan proses ekstraksi entitas, dan tidak hanya itu, kita juga akan mendapatkan URL Wikipedia masing-masing.
Setelah kita memiliki URL tersebut, akan lebih mudah untuk mendapatkan lebih banyak informasi tentang setiap entitas, karena kita dapat mengulik halaman tersebut, mencari di Google, dan seterusnya. Tapi pertama-tama kita membutuhkan halaman awal awal. Kita tidak akan membahas lebih jauh tentang langkah tersebut dalam artikel ini, dan kita akan fokus pada prosesnya hingga saat ini.
Sebelum memulai pengkodean, pertama-tama mari kita bedakan antara petunjuk biasa dan model yang telah disesuaikan. Prompt biasa adalah instruksi atau pertanyaan sederhana, yang memerintahkan model untuk menyelesaikan tugas tertentu, menjawab pertanyaan, atau membuat konten. Ini bertujuan untuk menjadi mesin tanya-jawab universal yang dapat berfungsi sebagai asisten pribadi Anda. Di sisi lain, ketika kami menyempurnakan model, kami melatih LLM untuk tugas tertentu yang akan bekerja jauh lebih baik daripada prompt biasa, dengan batasan mengetahui cara melakukan tugas itu saja. Ini seperti perbedaan antara mobil biasa (prompt normal) dan kereta metro (model yang disetel dengan baik). Mobil Anda dapat digunakan untuk berbagai tugas, dan dapat memenuhi hampir semua kebutuhan transportasi kita. Kereta metro hanya dapat melakukan satu hal, pergi dari titik A ke titik B dan kembali. Ini sangat terbatas, tetapi melakukan tugas ini dengan sangat baik, jauh lebih baik daripada mobil, dan dalam skala yang jauh lebih besar. Berikut ini adalah perbandingan singkat antara kedua pendekatan ini:
Area | Petunjuk normal | Model yang disempurnakan dengan baik |
Cakupan | Umum | Spesifik |
Proses pelatihan | Termasuk dalam prompt | Dilakukan dengan memberikan banyak contoh serupa yang konsisten |
Keumuman | Jagoan dari semua perdagangan | Alat yang sangat spesifik |
Anda mungkin sudah pernah bereksperimen dengan petunjuk normal, dan untuk tugas di atas, akan terlihat seperti berikut ini:
"Extract the main entities of the following text, and provide the Wikipedia URL for each, format the response as a table:
FULL TEXT GOES HERE
Dewasa ini, Anda terjebak dalam situasi paradoks di sini, yang muncul akibat keterbatasan pada panjang prompt. Jika Anda ingin mendapatkan respons yang bagus, Anda harus memberikan prompt yang sangat rinci dengan contoh, dan instruksi yang jelas. Tetapi, semakin banyak contoh dan instruksi yang Anda berikan, semakin sedikit ruang yang Anda miliki untuk menyediakan konten yang perlu diproses. Hal yang sebaliknya juga benar. Dengan model yang telah disetel dengan baik, Anda hanya mengirimkan sepotong teks yang akan berfungsi sebagai prompt. Model kami yang terlatih tidak akan memikirkannya, atau mencoba hal lain selain untuk apa ia dilatih (tugas di atas).
Mari kita segera membahas proses sederhana untuk melatih LLM dengan model yang sudah disetel dengan baik:
cepat | tanggapan |
biru | menjadi |
bunga | fr |
buku | bk |
laut | sa |
jendela | ww |
mobil | cr |
tas | ?? |
Setelah membaca contoh di atas, mungkin mudah bagi Anda untuk mengetahui cara melengkapi prompt "bag" terakhir, karena contoh-contoh sebelumnya sudah konsisten dan jelas. Tiap jawaban hanya memiliki dua huruf, dan apabila dikaitkan dengan prompt masing-masing, Anda bisa melihat secara jelas, bahwa pada dasarnya, ini adalah karakter pertama dan terakhir dari prompt tersebut. Semakin banyak contoh yang kami berikan, semakin yakinlah Anda bahwa ini memang pola yang kita cari. Kuncinya di sini, adalah menyediakan banyak, jelas, dan yang paling penting, pasangan prompt:response yang konsisten.
Ini adalah bagaimana kita akan melatih ChatGPT untuk mengekstrak entitas yang diperlukan. "Perintah" kita hanya berupa sebuah artikel dan ia akan mencari tahu apa yang harus dilakukan dengannya (asalkan kita melakukan pekerjaan yang baik dalam fase pelatihan).
Dalam hal ini, petunjuk kami akan sangat mudah. Mereka tidak akan berisi instruksi atau klarifikasi apa pun. Namun kesulitannya adalah dalam memberikan contoh yang cukup banyak sehingga LLM dapat dengan jelas mendapatkan pola yang kita cari.
Daftar Isi
Rencana Pelatihan
Kami perlu menyediakan dataset dengan ketentuan sebagai berikut:
- Sejumlah besar artikel (ratusan)
- Artikel-artikel tersebut harus memiliki entitas yang diidentifikasi dan diekstraksi oleh manusia
- Kita tidak hanya ingin mendapatkan entitasnya, kita juga membutuhkan URL Wikipedia masing-masing entitas
Di mana kita dapat menemukan dataset seperti itu? Di Wikipedia itu sendiri. Itu memenuhi semua persyaratan tersebut. Itu mudah. Sekarang implementasinya. Untungnya, API Wikipedia menyediakan beberapa fitur yang memudahkan pekerjaan kita. Untuk setiap artikel, kita dapat mengunduh teks beserta berbagai elemen menarik. Kami akan fokus pada dua di antaranya:
- Ringkasan: Ini adalah beberapa paragraf pertama yang kita lihat di awal setiap artikel.
- Tautan: Daftar semua tautan dalam artikel, dengan
import re
import json
import advertools as adv
import pandas as pd
import wikipediaapi
pd.options.display.max_columns = None
from IPython.display import display_html, display_markdown, IFrame
import openai
openai.api_key = 'YOUR OPEN AI API KEY'
Mendapatkan data dari API Wikipedia
Pertama-tama kita akan membahas prosesnya selangkah demi selangkah untuk satu artikel Wikipedia, dan kemudian menggeneralisasikannya.
Pertama-tama kami memulai program Wikipedia
dan kemudian menggunakannya untuk mendapatkan data untuk halaman mana pun. Untuk menentukan halaman, kita membutuhkan slug-nya, folder terakhir dari bagian path dari URL https://en.wikipedia.org/wiki/Article_title
"Artikel_judul" dalam kasus ini. Hal ini sangat penting karena tidak selalu mudah untuk menyimpulkan bagian URL ini. Dalam beberapa kasus, hal ini sangat mudah, seperti /Pizza
atau /Music
namun dalam banyak kasus tidak demikian, seperti /FIBA_Women's_Basketball_World_Cup
Sekarang kita membuat variabel untuk halaman yang kita inginkan:
wiki_wiki = wikipediaapi.Wikipedia('en')
page_basketball = wiki_wiki.page('Basketball')
print(page_basketball.summary[:1500])
Basketball is a team sport in which two teams, most commonly of five players each, opposing one another on a rectangular court, compete with the primary objective of shooting a basketball (approximately 9.4 inches (24 cm) in diameter) through the defender's hoop (a basket 18 inches (46 cm) in diameter mounted 10 feet (3.048 m) high to a backboard at each end of the court), while preventing the opposing team from shooting through their own hoop. A field goal is worth two points, unless made from behind the three-point line, when it is worth three. After a foul, timed play stops and the player fouled or designated to shoot a technical foul is given one, two or three one-point free throws. The team with the most points at the end of the game wins, but if regulation play expires with the score tied, an additional period of play (overtime) is mandated.
Players advance the ball by bouncing it while walking or running (dribbling) or by passing it to a teammate, both of which require considerable skill. On offense, players may use a variety of shots – the layup, the jump shot, or a dunk; on defense, they may steal the ball from a dribbler, intercept passes, or block shots; either offense or defense may collect a rebound, that is, a missed shot that bounces from rim or backboard. It is a violation to lift or drag one's pivot foot without dribbling the ball, to carry it, or to hold the ball with both hands then resume dribbling.
The five players on each side fall into five playing posi
Seperti yang Anda lihat, kami dapat meminta summary
atribut objek tersebut ke teks ringkasan. Di atas kita memiliki beberapa paragraf pertama dari ringkasan.
Atribut menarik lainnya yang bisa kita dapatkan adalah link
atribut. Ini memberi kita teks dari setiap tautan, serta informasi tambahan tentang setiap tautan. Di sini kita dapat melihat beberapa tautan pertama, dan kita juga mencetak jumlah total tautan untuk mendapatkan gambaran.
Mendapatkan tautan artikel
print(len(page_basketball.links))
list(page_basketball.links.items())[:20]
1309
[('16-inch softball', 16-inch softball (id: ??, ns: 0)),
('1936 Summer Olympics', 1936 Summer Olympics (id: ??, ns: 0)),
('1979 NBL Season', 1979 NBL Season (id: ??, ns: 0)),
('1992 Summer Olympics', 1992 Summer Olympics (id: ??, ns: 0)),
("1992 United States men's Olympic basketball team",
1992 United States men's Olympic basketball team (id: ??, ns: 0)),
('1998 NBL Season', 1998 NBL Season (id: ??, ns: 0)),
('1998–99 NBL season', 1998–99 NBL season (id: ??, ns: 0)),
('1–2–1–1 zone press', 1–2–1–1 zone press (id: ??, ns: 0)),
('1–3–1 defense and offense', 1–3–1 defense and offense (id: ??, ns: 0)),
('2000–01 FIBA SuproLeague', 2000–01 FIBA SuproLeague (id: ??, ns: 0)),
('2004 Summer Olympics', 2004 Summer Olympics (id: ??, ns: 0)),
('2006 FIBA World Championship for Women',
2006 FIBA World Championship for Women (id: ??, ns: 0)),
('2007 Asian Indoor Games', 2007 Asian Indoor Games (id: ??, ns: 0)),
("2008 United States men's Olympic basketball team",
2008 United States men's Olympic basketball team (id: ??, ns: 0)),
('2009 Asian Youth Games', 2009 Asian Youth Games (id: ??, ns: 0)),
('2010 FIBA World Championship',
2010 FIBA World Championship (id: ??, ns: 0)),
('2010 Youth Olympics', 2010 Youth Olympics (id: ??, ns: 0)),
('2011 FIBA 3x3 Youth World Championships',
2011 FIBA 3x3 Youth World Championships (id: ??, ns: 0)),
('2012 FIBA 3x3 World Championships',
2012 FIBA 3x3 World Championships (id: ??, ns: 0)),
('2014 FIBA Basketball World Cup',
2014 FIBA Basketball World Cup (id: ??, ns: 0))]
Tautan-tautan tersebut tersebar di seluruh artikel, dan yang kita inginkan sekarang adalah menemukan tautan yang ada di bagian ringkasan artikel. Kita dapat melakukannya dengan ekspresi reguler sederhana.
Membuat ekspresi reguler untuk mengekstrak tautan yang merupakan entitas penting
Karena kita memiliki teks jangkar dari setiap tautan pada artikel, regex hanya akan menjadi gabungan dari semua teks tautan, dipisahkan oleh operator pipa "atau". Satu-satunya hal lain yang perlu kita penuhi adalah mengurutkan tautan berdasarkan panjangnya. Berikut ini adalah contoh sederhana untuk mengilustrasikan hal ini. Anggaplah kita ingin mengekstrak semua contoh kata "menang" atau "luar biasa" dari sebuah teks. Pertama-tama mari kita uji regex won|wonderful
:
import re
text="I won the game at the wonderful tournament"
re.findall('won|wonderful', text)
['won', 'won']
Apa yang baru saja terjadi?
Contoh pertama dari "won", yang merupakan kata kedua dalam kalimat diekstraksi dengan benar, tetapi yang kedua tidak. Sebenarnya benar, tetapi bukan itu yang kita maksudkan. Karena kita pertama kali menentukan "won", mesin regex mulai mencari pola tersebut, jika tidak menemukannya, mesin regex akan mencari opsi lainnya. Dalam kasus kami, mesin regex menemukan contoh kedua dari "won" tepat sebelum "derful". Setelah mesin regex mengekstrak "satu" yang kedua, ia sekarang berada di "d", dan dari sana tidak ada lagi contoh lain dari "won". Mari kita coba regex yang sama, tetapi letakkan pola yang lebih panjang sebelum pola yang lebih pendek:
re.findall('wonderful|won', text)
['won', 'wonderful']
Sekarang berfungsi sebagaimana mestinya. Untuk itu, kita akan membuat regex ekstraksi tautan kita diurutkan berdasarkan panjangnya, untuk menghindari situasi ini.
Hal lain yang ingin kami pastikan adalah bahwa kami ingin mengekstrak seluruh kata. Asumsikan kita ingin mengekstrak pola "istirahat". Jika mesin regex menemukan kata "restoran" dalam teks yang disediakan, mesin regex akan mengekstrak kata tersebut sebagai kecocokan yang sah untuk pola tersebut. Tetapi kita tidak menginginkan hal itu. Kita hanya menginginkan "rest" sebagai kata yang lengkap. Untuk itu, kita dapat menggunakan pola batas kata dalam ekspresi reguler \b
. Karena backslack adalah karakter khusus dalam regex, kita menghindarinya dengan menambahkan karakter lain. Regex kita akan terlihat seperti ini:
pattern_1\\b|\\bpattern_2\\b|\\bpattern_3
dan seterusnya.
Kode berikut ini membuat regex yang diinginkan oleh:
- Menggabungkan semua teks jangkar dari tautan kami
- Menyortirnya berdasarkan panjangnya, dalam urutan menurun (pola yang lebih panjang sebelum yang lebih pendek)
- Bergabung dengan mereka melalui pipa
|
serta kata karakter batas kata\\b
dari kedua sisi
page_basketball_linksregex = '\\b|\\b'.join(sorted(page_basketball.links.keys(), key=len, reverse=True))
page_basketball_linksregex[:400]
"List of U.S. high school basketball national player of the year awards\\b|\\bList of basketball players who have scored 100 points in a single game\\b|\\bYoung Men's Christian Association Building (Albany, New York)\\b|\\bCategory:Articles with dead external links from February 2021\\b|\\bCategory:Articles with disputed statements from January 2019\\b|\\bCategory:Articles with disputed statements from Janua"
Berikut adalah beberapa baris pertama dari teks ringkasan kami, dengan teks jangkar entitas yang disorot sehingga Anda dapat memperoleh gambaran tentang bagaimana hal ini akan bekerja:
Basketball is a team sport in which two teams, most commonly of five players each, opposing one another on a rectangular court, compete with the primary objective of shooting a basketball (approximately 9.4 inches (24 cm) in diameter) through the defender’s hoop (a basket 18 inches (46 cm) in diameter mounted 10 feet (3.048 m) high to a backboard at each end of the court), while preventing the opposing team from shooting through their own hoop. A field goal is worth two points, unless made from behind the three-point line, when it is worth three. After a foul, timed play stops and the player fouled or designated to shoot a technical foul is given one, two or three one-point free throws. The team with the most points at the end of the game wins, but if regulation play expires with the score tied, an additional period of play (overtime) is mandated. Players advance the ball by bouncing it while walking or running (dribbling) or by passing it to a teammate, both of which require considerable skill. On offense, players may use a variety of shots – the layup, the jump shot, or a dunk; on defense, they may steal the ball from a dribbler, intercept passes, or block shots; either offense or defense may collect a rebound, that is, a missed shot that bounces from rim or backboard. It is a violation to lift or drag one’s pivot foot without dribbling the ball, to carry it, or to hold the ball with both hands then resume dribbling. The five players on each side fall into five playing positions. The tallest player is usually the center, the second-tallest and strongest is the power forward, a slightly shorter but more agile player is the small forward, and the shortest players or the best ball handlers are the shooting guard and the point guard, who implements the coach’s game plan by managing the execution of offensive and defensive plays (player positioning). Informally, players may play three-on-three, two-on-two, and one-on-one. Invented in 1891 by Canadian-American gym teacher James Naismith in Springfield, Massachusetts, in the United States, basketball has evolved to become one of the world’s most popular and widely viewed sports. The National Basketball Association (NBA) is the most significant professional basketball league in the world in terms of popularity, salaries, talent, and level of competition (drawing most of its talent from U.S. college basketball). Outside North America, the top clubs from national leagues qualify to continental championships such as the EuroLeague and the Basketball Champions League Americas. The FIBA Basketball World Cup and Men’s Olympic Basketball Tournament are the major international events of the sport and attract top national teams from around the world. Each continent hosts regional competitions for national teams, like EuroBasket and FIBA AmeriCup. The FIBA Women’s Basketball World Cup and Women’s Olympic Basketball Tournament feature top national teams from continental championships. The main North American league is the WNBA (NCAA Women’s Division I Basketball Championship is also popular), whereas the strongest European clubs participate in the EuroLeague Women.
Sekarang kita ingin mendapatkan teks tautan yang memiliki kecocokan dalam ringkasan artikel kita, dan menempatkannya dalam kamus sederhana. Kuncinya adalah teks jangkar yang cocok. Nilainya adalah halaman permintaan dari Wikipedia (berisi semua data yang relevan).
Saat mengatur nilai, kami akan mengirimkan permintaan ke Wikipedia untuk mendapatkan data baru tentang halaman yang cocok. Hasil akhirnya, yang merupakan links_wikis
akan berisi informasi lengkap dari setiap kecocokan yang diekstrak. Kita terutama tertarik pada nama entitas dan URL-nya, sehingga kita dapat membuat DataFrame sederhana untuk menunjukkan hasil akhir yang kita cari.
links_wikis = {}
for match in re.finditer(page_basketball_linksregex, page_basketball.summary):
links_wikis[match.group()] = wiki_wiki.page(match.group())
Menyusun entit dan tautannya (diekstrak dari ringkasan aritkel)
ent_link = pd.DataFrame({
'entitas': tautan_wiki.kunci(),
'url': [link.fullurl untuk tautan di links_wikis.values()]})
ent_link.style.set_caption('
<h3>Entitas di bagian ringkasan dari <code data-no-auto-translation="">/Basketball</code> wiki</h3>
<p>‘)</p>
Entitas di bagian ringkasan dari /Basketball
wiki
entitas | url | |
0 | James Naismith | https://en.wikipedia.org/wiki/James_Naismith |
1 | Springfield, Massachusetts | https://en.wikipedia.org/wiki/Springfield,_Massachusetts |
2 | National Basketball Association | https://en.wikipedia.org/wiki/National_Basketball_Association |
3 | NBA | https://en.wikipedia.org/wiki/National_Basketball_Association |
4 | EuroLeague | https://en.wikipedia.org/wiki/EuroLeague |
5 | Basketball Champions League Americas | https://en.wikipedia.org/wiki/Basketball_Champions_League_Americas |
6 | FIBA Basketball World Cup | https://en.wikipedia.org/wiki/FIBA_Basketball_World_Cup |
7 | EuroBasket | https://en.wikipedia.org/wiki/EuroBasket |
8 | FIBA AmeriCup | https://en.wikipedia.org/wiki/FIBA_AmeriCup |
9 | FIBA Women’s Basketball World Cup | https://en.wikipedia.org/wiki/FIBA_Women%27s_Basketball_World_Cup |
10 | WNBA | https://en.wikipedia.org/wiki/Women%27s_National_Basketball_Association |
11 | NCAA Women’s Division I Basketball Championship | https://en.wikipedia.org/wiki/NCAA_Division_I_women%27s_basketball_tournament |
12 | EuroLeague Wanita | https://en.wikipedia.org/wiki/EuroLeague_Women |
Dengan adanya halaman "Bola Basket", kita akan mendapatkan sebuah DataFrame yang berisi entitas pada bagian ringkasannya, bersama dengan setiap URL yang dimiliki oleh setiap entitas.
Langkah selanjutnya adalah memformat tanggapan ini dengan cara yang konsisten sehingga ChatGPT dapat mengetahui dengan tepat bagaimana memformat tanggapan untuk kita. Formatnya adalah sebagai berikut.
Memformat penyelesaian GPT dengan cara yang jelas dan konsisten
Entity_1: https://en.wikipedia.org/wiki/Entity_1
Entity_2: https://en.wikipedia.org/wiki/Entity_2
Entity_3: https://en.wikipedia.org/wiki/Entity_3
...
completion = '@@'.join([': '.join(entity) for entity in ent_link.values])
print(*completion.split('@@'), sep='\n')
James Naismith: https://en.wikipedia.org/wiki/James_Naismith
Springfield, Massachusetts: https://en.wikipedia.org/wiki/Springfield,_Massachusetts
National Basketball Association: https://en.wikipedia.org/wiki/National_Basketball_Association
NBA: https://en.wikipedia.org/wiki/National_Basketball_Association
EuroLeague: https://en.wikipedia.org/wiki/EuroLeague
Basketball Champions League Americas: https://en.wikipedia.org/wiki/Basketball_Champions_League_Americas
FIBA Basketball World Cup: https://en.wikipedia.org/wiki/FIBA_Basketball_World_Cup
EuroBasket: https://en.wikipedia.org/wiki/EuroBasket
FIBA AmeriCup: https://en.wikipedia.org/wiki/FIBA_AmeriCup
FIBA Women's Basketball World Cup: https://en.wikipedia.org/wiki/FIBA_Women%27s_Basketball_World_Cup
WNBA: https://en.wikipedia.org/wiki/Women%27s_National_Basketball_Association
NCAA Women's Division I Basketball Championship: https://en.wikipedia.org/wiki/NCAA_Division_I_women%27s_basketball_tournament
EuroLeague Women: https://en.wikipedia.org/wiki/EuroLeague_Women
Kita sekarang ingin menempatkan pasangan prompt/penyelesaian dalam format JSON standar yang dibutuhkan ChatGPT, yaitu
{"prompt": "prompt text goes here", "completion": "completion text goes here"}
Gabungkan permintaan dan penyelesaiannya dalam format JSON yang disimpan dalam file jsonlines (ini adalah "pelatihan" kami)
print(json.dumps({"prompt":page_basketball.summary,"completion":completion}))
{"prompt": "Basketball is a team sport in which two teams, most commonly of five players each, opposing one another on a rectangular court, compete with the primary objective of shooting a basketball (approximately 9.4 inches (24 cm) in diameter) through the defender's hoop (a basket 18 inches (46 cm) in diameter mounted 10 feet (3.048 m) high to a backboard at each end of the court), while preventing the opposing team from shooting through their own hoop. A field goal is worth two points, unless made from behind the three-point line, when it is worth three. After a foul, timed play stops and the player fouled or designated to shoot a technical foul is given one, two or three one-point free throws. The team with the most points at the end of the game wins, but if regulation play expires with the score tied, an additional period of play (overtime) is mandated.\nPlayers advance the ball by bouncing it while walking or running (dribbling) or by passing it to a teammate, both of which require considerable skill. On offense, players may use a variety of shots \u2013 the layup, the jump shot, or a dunk; on defense, they may steal the ball from a dribbler, intercept passes, or block shots; either offense or defense may collect a rebound, that is, a missed shot that bounces from rim or backboard. It is a violation to lift or drag one's pivot foot without dribbling the ball, to carry it, or to hold the ball with both hands then resume dribbling.\nThe five players on each side fall into five playing positions. The tallest player is usually the center, the second-tallest and strongest is the power forward, a slightly shorter but more agile player is the small forward, and the shortest players or the best ball handlers are the shooting guard and the point guard, who implements the coach's game plan by managing the execution of offensive and defensive plays (player positioning). Informally, players may play three-on-three, two-on-two, and one-on-one.\nInvented in 1891 by Canadian-American gym teacher James Naismith in Springfield, Massachusetts, in the United States, basketball has evolved to become one of the world's most popular and widely viewed sports. The National Basketball Association (NBA) is the most significant professional basketball league in the world in terms of popularity, salaries, talent, and level of competition (drawing most of its talent from U.S. college basketball). Outside North America, the top clubs from national leagues qualify to continental championships such as the EuroLeague and the Basketball Champions League Americas. The FIBA Basketball World Cup and Men's Olympic Basketball Tournament are the major international events of the sport and attract top national teams from around the world. Each continent hosts regional competitions for national teams, like EuroBasket and FIBA AmeriCup.\nThe FIBA Women's Basketball World Cup and Women's Olympic Basketball Tournament feature top national teams from continental championships. The main North American league is the WNBA (NCAA Women's Division I Basketball Championship is also popular), whereas the strongest European clubs participate in the EuroLeague Women.", "completion": "James Naismith: https://en.wikipedia.org/wiki/James_Naismith@@Springfield, Massachusetts: https://en.wikipedia.org/wiki/Springfield,_Massachusetts@@National Basketball Association: https://en.wikipedia.org/wiki/National_Basketball_Association@@NBA: https://en.wikipedia.org/wiki/National_Basketball_Association@@EuroLeague: https://en.wikipedia.org/wiki/EuroLeague@@Basketball Champions League Americas: https://en.wikipedia.org/wiki/Basketball_Champions_League_Americas@@FIBA Basketball World Cup: https://en.wikipedia.org/wiki/FIBA_Basketball_World_Cup@@EuroBasket: https://en.wikipedia.org/wiki/EuroBasket@@FIBA AmeriCup: https://en.wikipedia.org/wiki/FIBA_AmeriCup@@FIBA Women's Basketball World Cup: https://en.wikipedia.org/wiki/FIBA_Women%27s_Basketball_World_Cup@@WNBA: https://en.wikipedia.org/wiki/Women%27s_National_Basketball_Association@@NCAA Women's Division I Basketball Championship: https://en.wikipedia.org/wiki/NCAA_Division_I_women%27s_basketball_tournament@@EuroLeague Women: https://en.wikipedia.org/wiki/EuroLeague_Women"}
# for link, name in links_wikis.items():
# display_markdown(f'### {link}', raw=True)
# display_markdown(name.summary, raw=True)
# print()
Sekarang kita telah melakukan ini untuk satu halaman Wikipedia, kita siap untuk menggabungkan semua langkah ini ke dalam satu fungsi. Fungsi ini akan mengambil halaman Wikipedia sebagai masukan, dan mengembalikan objek JSON seperti yang kita lakukan di langkah terakhir.
Catatan penting mengenai pemformatan permintaan dan respons: Harus ada indikasi yang jelas tentang di mana pertanyaan berakhir, dan di mana jawaban berakhir. Hal ini dapat berupa apa saja, dan pola teks yang sangat tidak mungkin untuk digunakan adalah pilihan yang baik, misalnya dua karakter newlin yang diikuti oleh sekelompok tanda dolar.
Membuat fungsi yang mengambil siput Wikipedia, misalnya /Basketball
dan mengembalikan string JSON yang diinginkan
Ini menggabungkan semua langkah yang diambil sejauh ini. Dalam fungsi "ner" adalah singkatan dari "pengenalan entitas bernama".
prompt_end = '\n\n%%%%%\n'
completion_end = '\n\n^^^^^\n'
def wikipedia_ner(page):
wikipage = wiki_wiki.page(page)
page_links_regex = '\\b|\\b'.join(sorted(wikipage.links.keys(), key=len, reverse=True))
links_wikis = {}
for match in re.finditer(page_links_regex, wikipage.summary):
links_wikis[match.group()] = wiki_wiki.page(match.group())
ent_link = pd.DataFrame({
'entity': links_wikis.keys(),
'url': [link.fullurl for link in links_wikis.values()]})
completion = ' ' + '@@'.join([': '.join(entity) for entity in ent_link.values])
training_dict = {
'prompt': wikipage.summary + prompt_end,
'completion': completion + completion_end}
return json.dumps(training_dict)
Mengujinya lagi dengan /Basketball
Sekarang kita telah menyarikan semua langkah ke dalam satu perintah, mari kita lihat bagaimana cara kerjanya dengan halaman yang sama dengan yang kita mulai.
basketball = wikipedia_ner('Basketball')
print(json.loads(basketball)['prompt'])
Basketball is a team sport in which two teams, most commonly of five players each, opposing one another on a rectangular court, compete with the primary objective of shooting a basketball (approximately 9.4 inches (24 cm) in diameter) through the defender's hoop (a basket 18 inches (46 cm) in diameter mounted 10 feet (3.048 m) high to a backboard at each end of the court), while preventing the opposing team from shooting through their own hoop. A field goal is worth two points, unless made from behind the three-point line, when it is worth three. After a foul, timed play stops and the player fouled or designated to shoot a technical foul is given one, two or three one-point free throws. The team with the most points at the end of the game wins, but if regulation play expires with the score tied, an additional period of play (overtime) is mandated.
Players advance the ball by bouncing it while walking or running (dribbling) or by passing it to a teammate, both of which require considerable skill. On offense, players may use a variety of shots – the layup, the jump shot, or a dunk; on defense, they may steal the ball from a dribbler, intercept passes, or block shots; either offense or defense may collect a rebound, that is, a missed shot that bounces from rim or backboard. It is a violation to lift or drag one's pivot foot without dribbling the ball, to carry it, or to hold the ball with both hands then resume dribbling.
The five players on each side fall into five playing positions. The tallest player is usually the center, the second-tallest and strongest is the power forward, a slightly shorter but more agile player is the small forward, and the shortest players or the best ball handlers are the shooting guard and the point guard, who implements the coach's game plan by managing the execution of offensive and defensive plays (player positioning). Informally, players may play three-on-three, two-on-two, and one-on-one.
Invented in 1891 by Canadian-American gym teacher James Naismith in Springfield, Massachusetts, in the United States, basketball has evolved to become one of the world's most popular and widely viewed sports. The National Basketball Association (NBA) is the most significant professional basketball league in the world in terms of popularity, salaries, talent, and level of competition (drawing most of its talent from U.S. college basketball). Outside North America, the top clubs from national leagues qualify to continental championships such as the EuroLeague and the Basketball Champions League Americas. The FIBA Basketball World Cup and Men's Olympic Basketball Tournament are the major international events of the sport and attract top national teams from around the world. Each continent hosts regional competitions for national teams, like EuroBasket and FIBA AmeriCup.
The FIBA Women's Basketball World Cup and Women's Olympic Basketball Tournament feature top national teams from continental championships. The main North American league is the WNBA (NCAA Women's Division I Basketball Championship is also popular), whereas the strongest European clubs participate in the EuroLeague Women.
%%%%%
print(*json.loads(basketball)['completion'].split('@@'), sep='\n')
James Naismith: https://en.wikipedia.org/wiki/James_Naismith
Springfield, Massachusetts: https://en.wikipedia.org/wiki/Springfield,_Massachusetts
National Basketball Association: https://en.wikipedia.org/wiki/National_Basketball_Association
NBA: https://en.wikipedia.org/wiki/National_Basketball_Association
EuroLeague: https://en.wikipedia.org/wiki/EuroLeague
Basketball Champions League Americas: https://en.wikipedia.org/wiki/Basketball_Champions_League_Americas
FIBA Basketball World Cup: https://en.wikipedia.org/wiki/FIBA_Basketball_World_Cup
EuroBasket: https://en.wikipedia.org/wiki/EuroBasket
FIBA AmeriCup: https://en.wikipedia.org/wiki/FIBA_AmeriCup
FIBA Women's Basketball World Cup: https://en.wikipedia.org/wiki/FIBA_Women%27s_Basketball_World_Cup
WNBA: https://en.wikipedia.org/wiki/Women%27s_National_Basketball_Association
NCAA Women's Division I Basketball Championship: https://en.wikipedia.org/wiki/NCAA_Division_I_women%27s_basketball_tournament
EuroLeague Women: https://en.wikipedia.org/wiki/EuroLeague_Women
^^^^^
Sekarang, mari kita lakukan ini dalam skala besar.
Dapatkan seribu URL/slug Wikipedia dari halaman populer, ekstrak entitas dan tautan
Kita ingin menemukan daftar acak URL Wikipedia dan mendapatkan ringkasan teksnya, bersama dengan entitas yang diekstrak (dan URL-nya). Untuk itu, kita akan menggunakan advertools, yang merupakan paket Python yang di dalamnya terdapat perayap SEO.
Kami lebih memilih untuk mendapatkan data dari halaman Wikipedia yang populer. Alasannya adalah semakin populer sebuah halaman, semakin banyak orang yang bekerja untuk menyuntingnya, dan oleh karena itu kualitas entitas yang diekstrak akan lebih baik. Kode berikut ini dimulai dengan daftar dua puluh lima halaman Wikipedia yang paling banyak dilihat, dan mengikuti tautan-tautan dari sana. Saya telah menyertakan komentar pada setiap baris yang menjelaskan lebih banyak tentang apa yang dilakukannya.
adv.crawl(
url_list="https://en.wikipedia.org/wiki/Wikipedia:Top_25_Report",
output_file="wiki_crawl.jl",
# for each crawled page, should the crawler follow discovered links?
# this is also known as "spider mode" as opposed to "list mode" where
# only the given URLs are crawled
follow_links=True,
# out of the disovered links, which ones should the crawler follow?
# follow links that match the following regex:
include_url_regex='https://en.wikipedia.org/wiki/[A-Z].+',
# same as the previous parameter, but for exclusion, this is to prevent
# following fragments
exclude_url_regex='#',
# further customization of the crawling process
custom_settings={
# stop crawling after a certain number of pages
'CLOSESPIDER_PAGECOUNT': 1500,
# save the logs of the crawl process in this file (good for debugging)
'LOG_FILE': 'wiki_crawl.jl',
# save the details of the current crawl job to a folder, so we can
# pause/resume the crawl without having to re-crawl the same pages again
'JOBDIR': 'wikicrawl_job'
})
Ikhtisar dataset perayapan:
wiki_crawl = pd.read_json('wiki_crawl.jl', lines=True)
wiki_crawl.head(3)
url | judul | viewport | charset | h1 | h2 | h3 | kanonik | alt_href | og:title | ... | jsonld_1_author.name | jsonld_1_publisher.@type | jsonld_1_publisher.name | jsonld_1_publisher.logo.@type | jsonld_1_publisher.logo.url | resp_headers_set-cookie | request_header_referer | h4 | img_usemap | h5 | |
0 | https://en.wikipedia.org/wiki/Wikipedia:Top_25_Report | Wikipedia:Laporan 25 Besar - Wikipedia bahasa Indonesia, ensiklopedia bebas | width=1000 | UTF-8 | Wikipedia:Laporan 25 Besar | Artikel Wikipedia Terpopuler Minggu Ini (16-22 April 2023)[sunting] | Pengecualian[sunting] | https://en.wikipedia.org/wiki/Wikipedia:Top_25_Report | //en.m.wikipedia.org/wiki/Wikipedia:Top_25_Report@@/w/index.php?title=Wikipedia:Top_25_Report&action=edit@@/w/index.... | Wikipedia:Laporan 25 Besar - Wikipedia bahasa Indonesia, ensiklopedia bebas | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
1 | https://en.wikipedia.org/wiki/ChatGPT | ChatGPT - Wikipedia bahasa Indonesia, ensiklopedia bebas | width=1000 | UTF-8 | ChatGPT | Isi@@Pelatihan@@Fitur dan keterbatasan@@Layanan@@Penerimaan@@Implikasi@@Kekhawatiran etis@@Dampak budaya@@C... | Fitur@@Pembatasan@@Layanan dasar@@Layanan premium@@Dukungan pengembang perangkat lunak@@Pembobolan keamanan Maret 2023@@Lainnya... | https://en.wikipedia.org/wiki/ChatGPT | //en.m.wikipedia.org/wiki/ChatGPT@@/w/index.php?title=Special:RecentChanges&feed=atom | ChatGPT - Wikipedia bahasa Indonesia, ensiklopedia bebas | ... | Kontributor untuk proyek-proyek Wikimedia | Organisasi | Wikimedia Foundation, Inc. | ImageObject | https://www.wikimedia.org/static/images/wmf-hor-googpub.png | WMF-DP=46f;Path=/;HttpOnly;secure;Expires=Mon, 01 May 2023 00:00:00 GMT | https://en.wikipedia.org/wiki/Wikipedia:Top_25_Report | NaN | NaN | NaN |
2 | https://en.wikipedia.org/wiki/Wikipedia:Humor | Wikipedia:Humor - Wikipedia bahasa Indonesia, ensiklopedia bebas | width=1000 | UTF-8 | Wikipedia:Humor | Daftar isi@@Indikator kebutuhan humor[sunting]@@Mengapa humor yang bertanggung jawab itu penting[sunting]@@Humor dalam artikel[sunting]@@Humor dalam... | Bagaimana humor dapat dimasukkan[sunting] | https://en.wikipedia.org/wiki/Wikipedia:Humor | //en.m.wikipedia.org/wiki/Wikipedia:Humor@@/w/index.php?title=Wikipedia:Humor&action=edit@@/w/index.php?title=Specia... | Wikipedia:Humor - Wikipedia bahasa Indonesia, ensiklopedia bebas | ... | NaN | NaN | NaN | NaN | NaN | NaN | https://en.wikipedia.org/wiki/Wikipedia:Top_25_Report | NaN | NaN | NaN |
3 baris × 107 kolom
Ekstrak slug URL dari halaman yang dirayapi.
wikipedia_slugs = wiki_crawl[~wiki_crawl['url'].str.contains('[a-zA-Z]:[a-zA-Z]')]['url'].str.rsplit('/').str[-1].tolist()
wikipedia_slugs[:30]
['ChatGPT',
'Mario',
'Netflix',
'GPT-3',
'Language_models',
'LLaMA',
'Meta_AI',
'Bard_(chatbot)',
'Ambedkar_Jayanti',
'The_Greatest_Indian',
'The_Matrix',
'Dalai_Lama',
'Academic_plagiarism',
'Hyderabad',
'B._R._Ambedkar',
'Bon_Jovi',
'Mahatma_Gandhi',
'Mario_Bros.',
'Satoru_Iwata',
'San_Diego_Comic-Con',
'A_Perfect_Crime_(TV_series)',
'If',
'V_Wars',
'When_They_See_Us',
'AJ_and_the_Queen',
'Unbelievable_(miniseries)',
'Trinkets_(TV_series)',
'Trailer_Park_Boys:_The_Animated_Series',
'Twelve_Forever',
'Turn_Up_Charlie']
Telusuri siput, dan ekstrak entitas dan tautan
entity_responses = []
errors = []
for i, slug in enumerate(wikipedia_slugs):
try:
print(f'{i:>4}Getting: /{slug}', end='\r')
wikipage = wikipedia_ner(slug)
entity_responses.append(wikipage)
except Exception as e:
err = (slug, str(e))
errors.append(err)
print('Error: ', err)
Membuat file pelatihan
with open('training_data_wikipedia_ner.jsonl', 'w') as file:
for resp in entity_responses:
prompt = json.loads(resp)['prompt']
completion = json.loads(resp)['completion']
if prompt:
print(json.dumps({'prompt': prompt, 'completion': completion}), file=file)
Dengan ini, model pelatihan kami telah siap, yang merupakan satu set sederhana dari pasangan prompt/penyelesaian yang dapat diunggah dan digunakan dengan ChatGPT.
Anda bisa mengujinya di aplikasi ekstraksi entitas langsung ini, dan melihat cara kerjanya.