Anita Sharma

1628602010

WooCommerce Web-to-print: Simplifying Online Print Business

E-Commerce is one of the cleverest things of modern times; it has changed the way we shop and has improved our way of buying to ten folds. But this change is not just about finding all the things on one platform. It is more about the slight things we enjoy. For example, online payments, 24×7 customer support, or customized product suggestions. Each and every time it impresses us with a remarkable shopping experience. 

For more than two decades now, e-commerce has become an integral part of our lives. People are selling everything on an e-commerce store. Recently someone buying a helicopter on an e-commerce site made global headlines. Similarly, traditional services such as of printing industry are now available online in the same format as an e-commerce store. People just have to log in, select a product, add quantity, choose to customize the product as per their liking, and the product would be delivered to their doorsteps. 

People can use the services for merchandise printing, branding material printing or banners, and other stuff. For the owners, this software helps them in eliminating the repetitive tasks and tasks of the manual work. Once what was considered tedious and time-consuming is now being done within seconds. It also gave the business owners a well-deserved reach. They are no longer a store on the street. They are now global businesses surprising people with their solutions. 

All thanks to technology, be it a business owner or a shopper, it is only possible because we have technologies that have brought our dreams to life. In the last two decades, we have experienced some very powerful technologies that have empowered people to run globally successful businesses. One such technology is WooCommerce. WooCommerce print-on-demand solutions offer everything that’s needed to run a successful web-to-print online store. 

What is WooCommerce? 

WooCommerce is an open-source e-commerce plugin for WordPress which was specifically designed to build large-sized online selling platforms using WordPress. It was launched in 2011, and since then, has improved a lot. It has added more dynamic features and has amazing customizable themes. 

Using WooCommerce, you can simplify your printing business operations across the border, reduce human errors, and offer a class-apart shopping experience. The plugin quickly became popular for simplicity to install and customize free base products. You can even add features that provide a personalized experience to your customers. Such as help them choose the products that match their choice, add artworks such as photos, text, clipart, etc., to be printed on their merchandise, and so much more. 

When it comes to implementing open-source e-commerce solutions, WooCommerce web to print solutions stands unprecedented, top on the chart. It is a lightweight technology that is very user-friendly. It has chic modern themes that you can use, and it is backed with a powerful CMS such as WordPress. Since it is a tool from WordPress, it gives away remarkable SEO benefits. It is a delight for a web designer and a developer both to implement it. 

This WordPress web to print solution has the power to render superior e-commerce experience and personalization at the same time to introduce best-in-class software solutions. If you are thinking about moving your printing business to online print business, WooCommerce is one of the best solution providers. 

Benefits of using WooCommerce with web to print software: 

  • A web to print software would allow you to manage all the products such as T-shirts, photo mugs, banners, greeting cards, custom packaging material, etc. You name it, and you can offer it over a WooCommerce web to print store.
     
  • Usually, store owners redirect the user to another website when people add any customizations. You can avoid it by configuring your own design studio on the WooCommerce website and keep the user experience uniform all over your site.
  • Managing your business becomes fairly easy. You can add hierarchy in the software, which allows you to manage access to the data and other operations such as adding products for personalization within the WooCommerce admin panel. It is very easy to integrate and doesn’t hinder the performance of the site in any manner.
  • One of the biggest benefits of going with WooCommerce is that it allows you to add unlimited products and customization options. For an online print business, it is very important to meet customer expectations, and WooCommerce meets your needs perfectly well.
  • Talking about customer experience, you can add a 3D preview as well as a full 360-degree rotation-view of the finished product; this allows customers to make better decisions and improves their experience multitudinously.
  • Configuring products is very easy. WooCommerce is an e-commerce platform, offers you all the capabilities of a large e-commerce enterprise. It allows users to select the product and customize it as per their liking. You can add as many options as you like in the categories such as size, color, material, and this helps you to take a leap forth in the competition.
  • It all comes down to how easy it makes for people to do a tedious task that is prone to human errors. WooCommerce gives you an opportunity to customize your website as per your idea.
     
  • Read More: https://www.wtpbiz.com/woocommerce-web-to-print-simplifying-online-print-business/

What is GEEK

Buddha Community

WooCommerce Web-to-print: Simplifying Online Print Business

Why Business Cards Printing are essential for your business

No matter how technological advancement helps in communication but business card printing still worth it. Most businesses prefer to have and share business cards to develop a direct relationship with the potential market. It is an important part of the promotional and branding strategy and effectively described the brand’s nature. It gives ease in sharing the business-related information in the public like at conference, workshops and other.

This is image title

Moreover, a quality visiting card printing online provides the impression of products or services. According to the random research, it is stated that most of the customers draw the conclusion about the business and its products from the card quality or its printing. So, a smart business card with the right size and content is essential for the business.

Here are the factors that will help to understand the importance of the business card in the brand promotion or more:

Provide Contact Details:

One of the main reasons behind business card printing is the contact sharing features. The card contains contact details, name, logo, and other related information that helps the client to reach the business. Further, it helps to describe the brand or product nature before approaching the product or services. Other than the technology usage or sharing of the information through devices, business cards are most suitable and a handy item that worth a lot for the customers.

This is image title

The impression of the Brand:

The business card is a source that will deliver the first impression of the brand or business towards the potential buyers. It is something handy with the physical touch that develops a direct relationship with the potential market. While going to print business cards that quality, printing style, and overall outlook matters a lot. Because it works as the first impression of the business and its product or services for the potential market. So, the worthy card made with durable material and have an attractive color combination or layout can capture the interest easily.

It contains the company logo, name, design, and color combination that quickly attain the interest of the audience. On other hand, it is an important factor to pay attention to while making the designing and printing decision about the business card.

Direct Marketing Facility:

No doubt there are multiple marketing and promotional tools are available for the product or business promotion. But engraved business cards online is something incredible and handy that provide the physical touch experience. It works as the marketing or promotional element that helps in sharing the details directly to the potential market. With the more physical interaction that the business cards offer to the buyers and business.

The important thing that has to be considered in making the custom business cards, related to the content adjustment, design, and color combination. It helps to capture the buyer’s interest and deliver the right impression towards them.

This is image title

Appreciated in Different Cultures:

The business cards preferably deliver the right knowledge and impression about the product or services. It described the brand position, nature of the products or services, and other relevant skills. In most cultures, it is appreciated to have and share physical business cards as an information-sharing tool. In face-to-face interaction, develops a network and promotes sharing the business information in a circle.

Ease to Provide a Business Reference:

In business cards, online people find multiple opportunities in designing and Printing Services with a significant impression. It helps to make an easy referral related to particular services and a person with a skill set. The business car not only contains the address, contact information, or brand-related knowledge. It provides details about the particular person and reflects the skill set. Multiple factors truly help to describe the right impression of the brand through color, text, and images.

A tool to Develop Trust:

For business growth and development, it is important to gain the trust level of the customers. With the custom business cards, it is easier to attain the trust of the customers. in the competitive business atmosphere for a business survival trust is the only key, that can be over the product or on a company as well. Through the business card, it is easier to exchange and share personal warmth feelings.

With Business Cards Printing, it is easier to show more graphical representation through colors and design. Moreover, with the physical touch, it is easier to give trust feelings or more.

This is image title

Final Consideration!

In the competitive business world, the business card is a source to deliver information and capture the interest of potential buyers. It helps to impress the audience and provide relevant product details and skills that build trust or act as the direct promotional tool.

#business cards printing #visiting card printing online #go print business cards #engraved business cards online #custom business cards #business cards online

Carmen  Grimes

Carmen Grimes

1595491178

Best Electric Bikes and Scooters for Rental Business or Campus Facility

The electric scooter revolution has caught on super-fast taking many cities across the globe by storm. eScooters, a renovated version of old-school scooters now turned into electric vehicles are an environmentally friendly solution to current on-demand commute problems. They work on engines, like cars, enabling short traveling distances without hassle. The result is that these groundbreaking electric machines can now provide faster transport for less — cheaper than Uber and faster than Metro.

Since they are durable, fast, easy to operate and maintain, and are more convenient to park compared to four-wheelers, the eScooters trend has and continues to spike interest as a promising growth area. Several companies and universities are increasingly setting up shop to provide eScooter services realizing a would-be profitable business model and a ready customer base that is university students or residents in need of faster and cheap travel going about their business in school, town, and other surrounding areas.

Electric Scooters Trends and Statistics

In many countries including the U.S., Canada, Mexico, U.K., Germany, France, China, Japan, India, Brazil and Mexico and more, a growing number of eScooter users both locals and tourists can now be seen effortlessly passing lines of drivers stuck in the endless and unmoving traffic.

A recent report by McKinsey revealed that the E-Scooter industry will be worth― $200 billion to $300 billion in the United States, $100 billion to $150 billion in Europe, and $30 billion to $50 billion in China in 2030. The e-Scooter revenue model will also spike and is projected to rise by more than 20% amounting to approximately $5 billion.

And, with a necessity to move people away from high carbon prints, traffic and congestion issues brought about by car-centric transport systems in cities, more and more city planners are developing more bike/scooter lanes and adopting zero-emission plans. This is the force behind the booming electric scooter market and the numbers will only go higher and higher.

Companies that have taken advantage of the growing eScooter trend develop an appthat allows them to provide efficient eScooter services. Such an app enables them to be able to locate bike pick-up and drop points through fully integrated google maps.

List of Best Electric Bikes for Rental Business or Campus Facility 2020:

It’s clear that e scooters will increasingly become more common and the e-scooter business model will continue to grab the attention of manufacturers, investors, entrepreneurs. All this should go ahead with a quest to know what are some of the best electric bikes in the market especially for anyone who would want to get started in the electric bikes/scooters rental business.

We have done a comprehensive list of the best electric bikes! Each bike has been reviewed in depth and includes a full list of specs and a photo.

Billy eBike

mobile-best-electric-bikes-scooters https://www.kickstarter.com/projects/enkicycles/billy-were-redefining-joyrides

To start us off is the Billy eBike, a powerful go-anywhere urban electric bike that’s specially designed to offer an exciting ride like no other whether you want to ride to the grocery store, cafe, work or school. The Billy eBike comes in 4 color options – Billy Blue, Polished aluminium, Artic white, and Stealth black.

Price: $2490

Available countries

Available in the USA, Europe, Asia, South Africa and Australia.This item ships from the USA. Buyers are therefore responsible for any taxes and/or customs duties incurred once it arrives in your country.

Features

  • Control – Ride with confidence with our ultra-wide BMX bars and a hyper-responsive twist throttle.
  • Stealth- Ride like a ninja with our Gates carbon drive that’s as smooth as butter and maintenance-free.
  • Drive – Ride further with our high torque fat bike motor, giving a better climbing performance.
  • Accelerate – Ride quicker with our 20-inch lightweight cutout rims for improved acceleration.
  • Customize – Ride your own way with 5 levels of power control. Each level determines power and speed.
  • Flickable – Ride harder with our BMX /MotoX inspired geometry and lightweight aluminum package

Specifications

  • Maximum speed: 20 mph (32 km/h)
  • Range per charge: 41 miles (66 km)
  • Maximum Power: 500W
  • Motor type: Fat Bike Motor: Bafang RM G060.500.DC
  • Load capacity: 300lbs (136kg)
  • Battery type: 13.6Ah Samsung lithium-ion,
  • Battery capacity: On/off-bike charging available
  • Weight: w/o batt. 48.5lbs (22kg), w/ batt. 54lbs (24.5kg)
  • Front Suspension: Fully adjustable air shock, preload/compression damping /lockout
  • Rear Suspension: spring, preload adjustment
  • Built-in GPS

Why Should You Buy This?

  • Riding fun and excitement
  • Better climbing ability and faster acceleration.
  • Ride with confidence
  • Billy folds for convenient storage and transportation.
  • Shorty levers connect to disc brakes ensuring you stop on a dime
  • belt drives are maintenance-free and clean (no oil or lubrication needed)

**Who Should Ride Billy? **

Both new and experienced riders

**Where to Buy? **Local distributors or ships from the USA.

Genze 200 series e-Bike

genze-best-electric-bikes-scooters https://www.genze.com/fleet/

Featuring a sleek and lightweight aluminum frame design, the 200-Series ebike takes your riding experience to greater heights. Available in both black and white this ebike comes with a connected app, which allows you to plan activities, map distances and routes while also allowing connections with fellow riders.

Price: $2099.00

Available countries

The Genze 200 series e-Bike is available at GenZe retail locations across the U.S or online via GenZe.com website. Customers from outside the US can ship the product while incurring the relevant charges.

Features

  • 2 Frame Options
  • 2 Sizes
  • Integrated/Removable Battery
  • Throttle and Pedal Assist Ride Modes
  • Integrated LCD Display
  • Connected App
  • 24 month warranty
  • GPS navigation
  • Bluetooth connectivity

Specifications

  • Maximum speed: 20 mph with throttle
  • Range per charge: 15-18 miles w/ throttle and 30-50 miles w/ pedal assist
  • Charging time: 3.5 hours
  • Motor type: Brushless Rear Hub Motor
  • Gears: Microshift Thumb Shifter
  • Battery type: Removable Samsung 36V, 9.6AH Li-Ion battery pack
  • Battery capacity: 36V and 350 Wh
  • Weight: 46 pounds
  • Derailleur: 8-speed Shimano
  • Brakes: Dual classic
  • Wheels: 26 x 20 inches
  • Frame: 16, and 18 inches
  • Operating Mode: Analog mode 5 levels of Pedal Assist Thrott­le Mode

Norco from eBikestore

norco-best-electric-bikes-scooters https://ebikestore.com/shop/norco-vlt-s2/

The Norco VLT S2 is a front suspension e-Bike with solid components alongside the reliable Bosch Performance Line Power systems that offer precise pedal assistance during any riding situation.

Price: $2,699.00

Available countries

This item is available via the various Norco bikes international distributors.

Features

  • VLT aluminum frame- for stiffness and wheel security.
  • Bosch e-bike system – for their reliability and performance.
  • E-bike components – for added durability.
  • Hydraulic disc brakes – offer riders more stopping power for safety and control at higher speeds.
  • Practical design features – to add convenience and versatility.

Specifications

  • Maximum speed: KMC X9 9spd
  • Motor type: Bosch Active Line
  • Gears: Shimano Altus RD-M2000, SGS, 9 Speed
  • Battery type: Power Pack 400
  • Battery capacity: 396Wh
  • Suspension: SR Suntour suspension fork
  • Frame: Norco VLT, Aluminum, 12x142mm TA Dropouts

Bodo EV

bodo-best-electric-bikes-scootershttp://www.bodoevs.com/bodoev/products_show.asp?product_id=13

Manufactured by Bodo Vehicle Group Limited, the Bodo EV is specially designed for strong power and extraordinary long service to facilitate super amazing rides. The Bodo Vehicle Company is a striking top in electric vehicles brand field in China and across the globe. Their Bodo EV will no doubt provide your riders with high-level riding satisfaction owing to its high-quality design, strength, breaking stability and speed.

Price: $799

Available countries

This item ships from China with buyers bearing the shipping costs and other variables prior to delivery.

Features

  • Reliable
  • Environment friendly
  • Comfortable riding
  • Fashionable
  • Economical
  • Durable – long service life
  • Braking stability
  • LED lighting technology

Specifications

  • Maximum speed: 45km/h
  • Range per charge: 50km per person
  • Charging time: 8 hours
  • Maximum Power: 3000W
  • Motor type: Brushless DC Motor
  • Load capacity: 100kg
  • Battery type: Lead-acid battery
  • Battery capacity: 60V 20AH
  • Weight: w/o battery 47kg

#android app #autorent #entrepreneurship #ios app #minimum viable product (mvp) #mobile app development #news #app like bird #app like bounce #app like lime #autorent #best electric bikes 2020 #best electric bikes for rental business #best electric kick scooters 2020 #best electric kickscooters for rental business #best electric scooters 2020 #best electric scooters for rental business #bird scooter business model #bird scooter rental #bird scooter rental cost #bird scooter rental price #clone app like bird #clone app like bounce #clone app like lime #electric rental scooters #electric scooter company #electric scooter rental business #how do you start a moped #how to start a moped #how to start a scooter rental business #how to start an electric company #how to start electric scooterrental business #lime scooter business model #scooter franchise #scooter rental business #scooter rental business for sale #scooter rental business insurance #scooters franchise cost #white label app like bird #white label app like bounce #white label app like lime

坂本  篤司

坂本 篤司

1633767300

Pythonのトランスフォーマーを備えた会話型AIチャットボット

チャットボットは近年多くの人気を博しており、ビジネスでのチャットボットの使用への関心が高まるにつれ、研究者は会話型AIチャットボットの進歩にも素晴らしい仕事をしました。

このチュートリアルでは、Huggingfaceトランスフォーマーライブラリを使用して、事前にトレーニングされたDialoGPTモデルを使用して会話型応答を生成します。

DialoGPTは、Redditから抽出された1億4700万の会話でトレーニングされた、大規模で調整可能なニューラル会話応答生成モデルです。データセットで微調整して、最初からトレーニングするよりも優れたパフォーマンスを実現できるのは良いことです。

開始するには、トランスフォーマーをインストールしましょう:

$ pip3 install transformers

新しいPythonファイルまたはノートブックを開き、次の手順を実行します。

from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# model_name = "microsoft/DialoGPT-large"
model_name = "microsoft/DialoGPT-medium"
# model_name = "microsoft/DialoGPT-small"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)

DialoGPTには3つのバージョンがあります。小、中、大。もちろん、大きいほど良いのですが、これをマシンで実行している場合は、中小規模でも問題なくメモリに収まると思います。また、GoogleColabを使用して大きなものを試すこともできます。

欲張り検索による応答の生成

このセクションでは、欲張り検索アルゴリズムを使用して応答を生成します。つまり、各タイムステップで選択される可能性が最も高いチャットボット応答を選択します。

欲張り検索を使用してAIとチャットするためのコードを作成しましょう:

# chatting 5 times with greedy search
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        pad_token_id=tokenizer.eos_token_id,
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

このコードのコアを説明しましょう:

  • まず、チャットのためにユーザーからの入力を受け取ります。
  • input_idsDialoGPTトークナイザーを使用してテキストをエンコードし、文字列トークンの末尾を追加して、Pytorchテンソルとして返します。
  • ボットとのチャットが初めての場合は、input_idsモデルに直接フィードして世代を超えます。それ以外の場合は、torch.cat()メソッドを使用して連結を使用してチャット履歴を追加します。
  • その後model.generate()、チャットボット応答を生成する方法を使用します。
  • 最後に、返される出力もトークン化されたシーケンスであるため、を使用tokenizer.decode()してシーケンスをデコードし、に設定skip_special_tokensTrueて、などの迷惑な特別なトークンが表示されないようにし<|endoftext|>ます。また、モデルはシーケンス全体を返すため、以前のチャット履歴をスキップし、新しく生成されたチャットボットの回答のみを出力します。

以下は、ボットとのディスカッションの例です。

>> You:How can you be rich so quickly?
DialoGPT: I'm not rich, I'm just a rich man.
>> You:Ok, you don't make sense, how old are you ?
DialoGPT: I'm not a rich man, I'm just a rich man.
>> You:How can you be happy ?
DialoGPT: I'm not happy, I'm just a rich man.
>> You:But they say money buys happiness!
DialoGPT: Money buys happiness, but not happiness itself.
>> You:You don't make sense again!
DialoGPT: I'm not happy, I'm just a rich man.

モデルは多くの応答を繰り返すことがわかります。これらは最も高い確率であり、毎回それを選択しているためです。

デフォルトでmodel.generate()は、他のパラメーターが設定されていない場合は欲張り検索アルゴリズムを使用します。次のセクションでは、このメソッドにいくつかの引数を追加して、生成を改善できるかどうかを確認します。

ビーム検索による応答の生成

ビーム検索でnum_beams、各タイムステップで最も可能性の高い仮説を保持し、全体的に最も確率の高いシーケンスを取得することで、高確率シーケンスを見逃すリスクを減らすことができます。以下のコードは、ビーム検索でチャットボット応答を生成します。

# chatting 5 times with beam search
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        num_beams=3,
        early_stopping=True,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

inメソッドに設定num_beamsする場合、各タイムステップで3つの単語を選択し、それらを開発して、シーケンスの全体的な確率が最も高くなるようにします。1に設定することは、欲張り検索と同じです。3model.generate()num_beams

以下は、ビーム検索を使用したチャットボットとのディスカッションの例です。

>> You:How can I be rich?
DialoGPT: You can't.
>> You:Why not?
DialoGPT: Because you can't.
>> You:Then how am I supposed to live well?
DialoGPT: You can't.
>> You:So basically, you want me to be a poor guy?
DialoGPT: No, I want you to be a rich guy.
>> You:Ok how to be rich, then?
DialoGPT: I don't know.

サンプリングによる応答の生成

前のセクションでは、ビーム検索と欲張り検索を使用して、最も確率の高いシーケンスを生成しました。これは、出力が予測可能な機械翻訳やテキスト要約などのタスクに最適です。ただし、チャットボットのように、オープンエンド世代には最適なオプションではありません。

より良い生成のために、確率に基づいて広範囲の候補配列からサンプリングするランダム性を導入する必要があります。

# chatting 5 times with sampling
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        do_sample=True,
        top_k=0,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

今回は、サンプリング用に設定do_sampleTrue、可能なすべての確率を選択していることtop_k0示すように設定しましたtop_k。後でパラメーターについて説明します。

これらのパラメータを使用したチャットは次のとおりです。

>> You:Hello, how can I be rich?
DialoGPT: You can't
>> You:Really? then how others get rich?
DialoGPT: They work as money artists
>> You:How to be a money artist?
DialoGPT: I don't know, I don't have enough knowledge on artists
>> You:Alright, thank you!
DialoGPT: No problem, if you need tips pm me.
>> You:Great, you're my savior!
DialoGPT: Thank you for helping a stranger out like me!

明らかにいくつかの改善があります。ただし、確率の低いシーケンスの幅広いリストでサンプリングすると、ランダムに生成される可能性があります(最後の文で見られるように)。

それをさらに改善するために、次のことができます。

  • サンプリングをtemperature低くすると、確率の低い単語を選択する可能性が低くなり、確率の高い単語を選択する可能性が高くなります。
  • 発生する可能性のあるすべての単語を選択する代わりに、Top-kサンプリングを使用します。これにより、確率の低い単語が選択されないようにすることができます。
# chatting 5 times with Top K sampling & tweaking temperature
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        do_sample=True,
        top_k=100,
        temperature=0.75,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

ここで、確率で降順にソートされた上位の単語からサンプリングtop_kする100ように設定しました100。またtemperature0.75(デフォルトは1.0)に設定して、確率の高い単語を選択する可能性を高めます。温度を0.0貪欲検索と同じに設定し、無限大に設定すると、完全にランダムと同じになります。

これらのパラメータについての説明は次のとおりです。

>> You:How can I get rich?
DialoGPT: I'd also like to know this.
>> You:So you don't know it?
DialoGPT: I know it, but it doesn't matter.
>> You:Really? money matters, man!
DialoGPT: Well, money is money and I gotta get my money.
>> You:Yeah how to get them?
DialoGPT: Well, that's a question. I'd like to know more, just for curiosity's sake, to know what other people have said about how I should get rich.
>> You:Some robots like you told me you have to buy gold, silver or stocks.
DialoGPT: I think my wallet is empty.

ご覧のとおり、今でははるかに優れています。パラメータを自由に調整してtemperaturetop_k改善できるかどうかを確認してください。

核サンプリング

核サンプリングまたはTop-pサンプリングは、累積確率がp設定したパラメーターを超える可能な限り小さい単語から選択します。

以下は、Top-pサンプリングを使用した例です。

# chatting 5 times with nucleus sampling & tweaking temperature
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        do_sample=True,
        top_p=0.95,
        top_k=0,
        temperature=0.75,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

Top-kサンプリングを無効にするtop_kよう0に設定しましたが、どちらの方法も使用できるため、より効果的に機能する傾向があります。これがチャットです:

>> You:How can I be rich fast?
DialoGPT: Inflation and free money
>> You:lol, but that takes time, I need fast money.
DialoGPT: Your post makes no sense. You just need a lot of money to be rich fast
>> You:Ok how to get a lot of money?
DialoGPT: Buy gold and then trade it for money.
>> You:Hmm, I got your point, thanks.
DialoGPT: No problem. You have to have money to buy gold, but its only good for trading it.
>> You:Yeah, I understand, thank you so much.
DialoGPT: Ok, let me know if you need help

現在、チャットボットは多くの場合明らかに意味があります。

次に、複数のチャットボット応答を生成するコードを追加して、次の入力に含める応答を選択します。

# chatting 5 times with nucleus & top-k sampling & tweaking temperature & multiple
# sentences
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids_list = model.generate(
        bot_input_ids,
        max_length=1000,
        do_sample=True,
        top_p=0.95,
        top_k=50,
        temperature=0.75,
        num_return_sequences=5,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the outputs
    for i in range(len(chat_history_ids_list)):
      output = tokenizer.decode(chat_history_ids_list[i][bot_input_ids.shape[-1]:], skip_special_tokens=True)
      print(f"DialoGPT {i}: {output}")
    choice_index = int(input("Choose the response you want for the next input: "))
    chat_history_ids = torch.unsqueeze(chat_history_ids_list[choice_index], dim=0)

一度に5つの文を返すように設定num_return_sequences5ました。次のシーケンスに含まれる文を選択する必要があります。これがどのように進んだかです:

>> You:Hello, friend.
DialoGPT 0: Hey there!
DialoGPT 1: I am your friend, and I am also your friend.
DialoGPT 2: Hello. :
DialoGPT 3: Hiya! How are you?
DialoGPT 4: Hello. I like your username.
Choose the response you want for the next input: 3
>> You:Fine, thanks, what about you?
DialoGPT 0: Good. Not much to do.
DialoGPT 1: Not much, you?
DialoGPT 2: Fine, thanks.
DialoGPT 3: I'm okay, thank you for asking.
DialoGPT 4: I'm fine too.
Choose the response you want for the next input: 2
>> You:Can you tell me how can I get rich quickly?
DialoGPT 0: Yes, I can!
DialoGPT 1: Yes, just look up how to get rich on Google.
DialoGPT 2: Just keep doing your thing. You'll get rich.
DialoGPT 3: No, I can't.
DialoGPT 4: no, i have no money
Choose the response you want for the next input: 1
>> You:Yeah, but I thought you have an answer...
DialoGPT 0: I'm getting married in the morning.
DialoGPT 1: How do you get rich?
DialoGPT 2: I think there are many good answers, but I could send you one, if you want.
DialoGPT 3: I will, thanks!
DialoGPT 4: I thought you have an answer.
Choose the response you want for the next input: 2
>> You:Yes, please send me.
DialoGPT 0: You can send me link.
DialoGPT 1: I am very interested
DialoGPT 2: I sent you a PM
DialoGPT 3: I'll send you a PM
DialoGPT 4: I am always interested in new ideas.
Choose the response you want for the next input: 2

結論

このチュートリアルが、DialoGPTおよび同様のモデルでテキストを生成する方法に役立つことを願っています。テキストを生成する方法の詳細については、「Transformersを使用してテキストを生成する方法」ガイドを読むことを強くお勧めします。

ボットのパフォーマンスを向上させることができるかどうかを確認するために、パラメーターを微調整しておきます。

また、これをテキスト読み上げおよび音声読み上げのチュートリアルと組み合わせて、AlexaSiriCortanaなどの仮想アシスタントを構築することもできます

リンク: https://www.thepythoncode.com/article/conversational-ai-chatbot-with-huggingface-transformers-in-python

#python 

Hoang  Kim

Hoang Kim

1635843812

Chatbot AI hội thoại với Máy biến áp được đào tạo trước bằng Python

Tìm hiểu cách sử dụng thư viện máy biến áp Huggingface để tạo phản hồi hội thoại bằng mô hình DialoGPT được đào tạo trước bằng Python.

Chatbots đã trở nên phổ biến trong những năm gần đây và khi mối quan tâm ngày càng tăng trong việc sử dụng chatbots cho kinh doanh, các nhà nghiên cứu cũng đã làm rất tốt trong việc phát triển các chatbot AI đàm thoại.

Trong hướng dẫn này, chúng tôi sẽ sử dụng thư viện máy biến áp Huggingface để sử dụng mô hình DialoGPT đã được đào tạo trước để tạo phản hồi hội thoại.

DialoGPT là một mô hình tạo phản hồi hội thoại thần kinh có thể điều chỉnh quy mô lớn được đào tạo trên 147 triệu cuộc hội thoại được trích xuất từ ​​Reddit và điều tốt là bạn có thể tinh chỉnh nó với bộ dữ liệu của mình để đạt được hiệu suất tốt hơn so với đào tạo từ đầu.

Để bắt đầu, hãy cài đặt máy biến áp :

$ pip3 install transformers

Mở tệp hoặc sổ ghi chép Python mới và thực hiện như sau:

from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# model_name = "microsoft/DialoGPT-large"
model_name = "microsoft/DialoGPT-medium"
# model_name = "microsoft/DialoGPT-small"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)

Có ba phiên bản của DialoGPT; nhỏ, vừa và lớn. Tất nhiên, càng lớn càng tốt, nhưng nếu bạn chạy điều này trên máy của mình, tôi nghĩ nhỏ hoặc trung bình phù hợp với bộ nhớ của bạn mà không có vấn đề gì. Bạn cũng có thể sử dụng Google Colab để thử cái lớn.

Tạo phản hồi bằng Tìm kiếm tham lam

Trong phần này, chúng tôi sẽ sử dụng thuật toán tìm kiếm tham lam để tạo phản hồi. Đó là, chúng tôi chọn phản hồi chatbot có xác suất cao nhất được chọn trên mỗi bước thời gian.

Hãy tạo mã để trò chuyện với AI của chúng tôi bằng cách sử dụng tìm kiếm tham lam:

# chatting 5 times with greedy search
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        pad_token_id=tokenizer.eos_token_id,
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

Hãy giải thích cốt lõi của mã này:

  • Đầu tiên chúng tôi lấy thông tin đầu vào từ người dùng để trò chuyện.
  • Chúng tôi mã hóa văn bản input_idsbằng cách sử dụng trình mã hóa DialoGPT, chúng tôi cũng nối vào cuối chuỗi mã thông báo và trả về nó dưới dạng bộ căng Pytorch.
  • Nếu đây là lần đầu tiên trò chuyện với bot, thì chúng tôi sẽ trực tiếp cung cấp input_idscho mô hình của mình trong một thế hệ. Nếu không, chúng tôi nối lịch sử trò chuyện bằng cách nối với sự trợ giúp của torch.cat()phương thức.
  • Sau đó, chúng tôi sử dụng model.generate()phương pháp tạo phản hồi chatbot.
  • Cuối cùng, như sản lượng trở lại là một chuỗi tokenized quá, chúng tôi giải mã trình tự sử dụng tokenizer.decode()và thiết lập skip_special_tokensđể Trueđảm bảo chúng tôi không thấy bất kỳ đặc biệt gây phiền nhiễu mã thông báo như <|endoftext|>. Ngoài ra, vì mô hình trả về toàn bộ chuỗi, chúng tôi bỏ qua lịch sử trò chuyện trước đó và chỉ in câu trả lời chatbot mới được tạo.

Dưới đây là một cuộc thảo luận mẫu với bot:

>> You:How can you be rich so quickly?
DialoGPT: I'm not rich, I'm just a rich man.
>> You:Ok, you don't make sense, how old are you ?
DialoGPT: I'm not a rich man, I'm just a rich man.
>> You:How can you be happy ?
DialoGPT: I'm not happy, I'm just a rich man.
>> You:But they say money buys happiness!
DialoGPT: Money buys happiness, but not happiness itself.
>> You:You don't make sense again!
DialoGPT: I'm not happy, I'm just a rich man.

Bạn thấy mô hình lặp lại rất nhiều phản hồi, vì đây là xác suất cao nhất và nó luôn chọn nó.

Theo mặc định, model.generate()sử dụng thuật toán tìm kiếm tham lam khi không có tham số nào khác được đặt, trong các phần tiếp theo, chúng tôi sẽ thêm một số đối số vào phương thức này để xem liệu chúng tôi có thể cải thiện việc tạo không.

Tạo phản hồi với Tìm kiếm chùm

Tìm kiếm theo chùm cho phép chúng tôi giảm nguy cơ bỏ lỡ các chuỗi có xác suất cao bằng cách giữ lại num_beamscác giả thuyết có khả năng xảy ra nhất ở mỗi bước thời gian và sau đó lấy các chuỗi có xác suất cao nhất tổng thể, đoạn mã dưới đây sẽ tạo ra các phản hồi của chatbot với tìm kiếm theo chùm:

# chatting 5 times with beam search
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        num_beams=3,
        early_stopping=True,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

Khi đặt num_beamsthành 3trong model.generate()phương thức, chúng tôi sẽ chọn 3 từ ở mỗi bước và phát triển chúng để tìm xác suất tổng thể cao nhất của chuỗi, đặt num_beamsthành 1 cũng giống như tìm kiếm tham lam.

Dưới đây là một cuộc thảo luận mẫu với chatbot bằng cách sử dụng tìm kiếm chùm:

>> You:How can I be rich?
DialoGPT: You can't.
>> You:Why not?
DialoGPT: Because you can't.
>> You:Then how am I supposed to live well?
DialoGPT: You can't.
>> You:So basically, you want me to be a poor guy?
DialoGPT: No, I want you to be a rich guy.
>> You:Ok how to be rich, then?
DialoGPT: I don't know.

Tạo phản hồi bằng lấy mẫu

Trong các phần trước, chúng tôi đã sử dụng tìm kiếm chùm và tham lam để tạo ra chuỗi xác suất cao nhất. Giờ đây, điều đó thật tuyệt vời cho các tác vụ như dịch máy hoặc tóm tắt văn bản trong đó kết quả đầu ra có thể dự đoán được. Tuy nhiên, nó không phải là lựa chọn tốt nhất cho thế hệ kết thúc mở như trong chatbots.

Để có một thế hệ tốt hơn, chúng tôi cần đưa ra một số ngẫu nhiên trong đó chúng tôi lấy mẫu từ một loạt các trình tự ứng viên dựa trên xác suất:

# chatting 5 times with sampling
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        do_sample=True,
        top_k=0,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

Lần này, chúng tôi đặt do_sampleđể Truelấy mẫu và chúng tôi đặt top_kđể 0chỉ ra rằng chúng tôi đang chọn tất cả các xác suất có thể xảy ra, sau đó chúng ta sẽ thảo luận về top_ktham số.

Đây là một cuộc trò chuyện với các thông số này:

>> You:Hello, how can I be rich?
DialoGPT: You can't
>> You:Really? then how others get rich?
DialoGPT: They work as money artists
>> You:How to be a money artist?
DialoGPT: I don't know, I don't have enough knowledge on artists
>> You:Alright, thank you!
DialoGPT: No problem, if you need tips pm me.
>> You:Great, you're my savior!
DialoGPT: Thank you for helping a stranger out like me!

Rõ ràng là có một số cải tiến. Tuy nhiên, việc lấy mẫu trên một danh sách rộng các chuỗi với xác suất thấp có thể dẫn đến việc tạo ngẫu nhiên (như bạn thấy trong câu cuối cùng).

Để cải thiện nó hơn nữa, chúng tôi có thể:

  • Hạ thấp mẫu temperature, điều đó giúp chúng tôi giảm khả năng chọn các từ có xác suất thấp và tăng khả năng chọn các từ có xác suất cao.
  • Sử dụng lấy mẫu Top-k thay vì chọn tất cả các lần xuất hiện có thể xảy ra, điều này sẽ giúp chúng tôi loại bỏ các từ có xác suất thấp để được chọn.
# chatting 5 times with Top K sampling & tweaking temperature
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        do_sample=True,
        top_k=100,
        temperature=0.75,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

Bây giờ, chúng ta thiết lập top_kđể 100lấy mẫu từ đỉnh 100từ được sắp xếp descendingly bởi xác suất. Chúng tôi cũng đặt temperaturethành 0.75(mặc định là 1.0) để có cơ hội chọn các từ có xác suất cao hơn, đặt nhiệt độ 0.0giống như tìm kiếm tham lam, đặt nhiệt độ thành vô cùng giống như hoàn toàn ngẫu nhiên.

Đây là một cuộc thảo luận với các thông số này:

>> You:How can I get rich?
DialoGPT: I'd also like to know this.
>> You:So you don't know it?
DialoGPT: I know it, but it doesn't matter.
>> You:Really? money matters, man!
DialoGPT: Well, money is money and I gotta get my money.
>> You:Yeah how to get them?
DialoGPT: Well, that's a question. I'd like to know more, just for curiosity's sake, to know what other people have said about how I should get rich.
>> You:Some robots like you told me you have to buy gold, silver or stocks.
DialoGPT: I think my wallet is empty.

Như bạn có thể thấy, bây giờ nó đã tốt hơn nhiều, hãy thoải mái tinh chỉnh temperaturetop_kcác thông số và xem liệu nó có thể cải thiện nó hay không.

Lấy mẫu hạt nhân

Lấy mẫu hạt nhân hoặc lấy mẫu Top-p chọn từ các từ nhỏ nhất có thể có xác suất tích lũy vượt quá tham số pchúng tôi đặt.

Dưới đây là một ví dụ sử dụng lấy mẫu Top-p:

# chatting 5 times with nucleus sampling & tweaking temperature
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids = model.generate(
        bot_input_ids,
        max_length=1000,
        do_sample=True,
        top_p=0.95,
        top_k=0,
        temperature=0.75,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the output
    output = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    print(f"DialoGPT: {output}")

Chúng tôi đặt top_kđể 0tắt lấy mẫu Top-k, nhưng bạn có thể sử dụng cả hai phương pháp có xu hướng hoạt động tốt hơn. Đây là một cuộc trò chuyện:

>> You:How can I be rich fast?
DialoGPT: Inflation and free money
>> You:lol, but that takes time, I need fast money.
DialoGPT: Your post makes no sense. You just need a lot of money to be rich fast
>> You:Ok how to get a lot of money?
DialoGPT: Buy gold and then trade it for money.
>> You:Hmm, I got your point, thanks.
DialoGPT: No problem. You have to have money to buy gold, but its only good for trading it.
>> You:Yeah, I understand, thank you so much.
DialoGPT: Ok, let me know if you need help

Giờ đây, chatbot rõ ràng có ý nghĩa trong nhiều trường hợp.

Bây giờ, hãy thêm một số mã để tạo nhiều hơn một phản hồi chatbot và sau đó chúng tôi chọn phản hồi nào sẽ bao gồm trong đầu vào tiếp theo:

# chatting 5 times with nucleus & top-k sampling & tweaking temperature & multiple
# sentences
for step in range(5):
    # take user input
    text = input(">> You:")
    # encode the input and add end of string token
    input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors="pt")
    # concatenate new user input with chat history (if there is)
    bot_input_ids = torch.cat([chat_history_ids, input_ids], dim=-1) if step > 0 else input_ids
    # generate a bot response
    chat_history_ids_list = model.generate(
        bot_input_ids,
        max_length=1000,
        do_sample=True,
        top_p=0.95,
        top_k=50,
        temperature=0.75,
        num_return_sequences=5,
        pad_token_id=tokenizer.eos_token_id
    )
    #print the outputs
    for i in range(len(chat_history_ids_list)):
      output = tokenizer.decode(chat_history_ids_list[i][bot_input_ids.shape[-1]:], skip_special_tokens=True)
      print(f"DialoGPT {i}: {output}")
    choice_index = int(input("Choose the response you want for the next input: "))
    chat_history_ids = torch.unsqueeze(chat_history_ids_list[choice_index], dim=0)

Tôi đã thiết lập num_return_sequencesđể 5trả lại 5 câu cùng một lúc, chúng ta phải chọn một câu sẽ có trong chuỗi tiếp theo. Dưới đây là làm thế nào nó đi:

>> You:Hello, friend.
DialoGPT 0: Hey there!
DialoGPT 1: I am your friend, and I am also your friend.
DialoGPT 2: Hello. :
DialoGPT 3: Hiya! How are you?
DialoGPT 4: Hello. I like your username.
Choose the response you want for the next input: 3
>> You:Fine, thanks, what about you?
DialoGPT 0: Good. Not much to do.
DialoGPT 1: Not much, you?
DialoGPT 2: Fine, thanks.
DialoGPT 3: I'm okay, thank you for asking.
DialoGPT 4: I'm fine too.
Choose the response you want for the next input: 2
>> You:Can you tell me how can I get rich quickly?
DialoGPT 0: Yes, I can!
DialoGPT 1: Yes, just look up how to get rich on Google.
DialoGPT 2: Just keep doing your thing. You'll get rich.
DialoGPT 3: No, I can't.
DialoGPT 4: no, i have no money
Choose the response you want for the next input: 1
>> You:Yeah, but I thought you have an answer...
DialoGPT 0: I'm getting married in the morning.
DialoGPT 1: How do you get rich?
DialoGPT 2: I think there are many good answers, but I could send you one, if you want.
DialoGPT 3: I will, thanks!
DialoGPT 4: I thought you have an answer.
Choose the response you want for the next input: 2
>> You:Yes, please send me.
DialoGPT 0: You can send me link.
DialoGPT 1: I am very interested
DialoGPT 2: I sent you a PM
DialoGPT 3: I'll send you a PM
DialoGPT 4: I am always interested in new ideas.
Choose the response you want for the next input: 2

Phần kết luận

Và bạn hiểu rồi, tôi hy vọng hướng dẫn này đã giúp bạn cách tạo văn bản trên DialoGPT và các mô hình tương tự. Để biết thêm thông tin về cách tạo văn bản, tôi thực sự khuyên bạn nên đọc hướng dẫn Cách tạo văn bản bằng Transformers .

Tôi sẽ để bạn điều chỉnh các thông số để xem liệu bạn có thể làm cho bot hoạt động tốt hơn hay không.

Ngoài ra, bạn có thể kết hợp điều này với các hướng dẫn chuyển văn bản thành giọng nói và chuyển lời nói thành văn bản để xây dựng một trợ lý ảo như Alexa , Siri , Cortana , v.v.

#python #ai #chatbot 

渚  直樹

渚 直樹

1636598700

Pythonでリストを昇順および降順でソートする

リストを昇順および降順でソートするためのPythonプログラム。このPythonチュートリアルでは、リストの要素をPythonで昇順と降順で並べ替える方法を紹介します。

pythonの組み込みメソッド名sort()を使用します。これは、リストの要素/オブジェクトを昇順および降順で並べ替えるために使用されます。

ソートメソッドの基本構文:

 list.sort()

リストを昇順および降順でソートするためのPythonプログラム

  • リスト要素を昇順でソートするPythonプログラム
  • リスト要素を降順でソートするPythonプログラム

リスト要素を昇順でソートするPythonプログラム

# List of integers
num = [100, 200, 500, 600, 300]
 
# sorting and printing 
num.sort()
 
#print
print(num)
 
# List of float numbers
fnum = [100.43, 50.72, 90.65, 16.00, 04.41]
 
# sorting and printing
fnum.sort()
 
#print
print(fnum)
 
# List of strings 
str = ["Test", "My", "Word", "Tag", "Has"]
 
# sorting and  printing
str.sort()
 
#print
print(str)

Pythonプログラムを実行すると、出力は次のようになります。

[100、200、300、500、600]
[4.41、16.0、50.72、90.65、100.43]
['Has'、 'My'、 'Tag'、 'Test'、 'Word']

上で知っているように、リスト要素を昇順で並べ替える方法。次に、sort()メソッドを使用してリストを降順で並べ替える方法を説明します。

sort()メソッドを使用して引数としてreverse = Trueを渡し、リスト要素を降順で並べ替えます。

リスト要素を降順でソートする次のプログラムを見ることができます。

リスト要素を降順でソートするPythonプログラム

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# List of integers
num = [100, 200, 500, 600, 300]
 
# sorting and printing 
num.sort(reverse=True)
 
#print
print(num)
 
# List of float numbers
fnum = [100.43, 50.72, 90.65, 16.00, 04.41]
 
# sorting and printing
fnum.sort(reverse=True)
 
#print
print(fnum)
 
# List of strings 
str = ["Test", "My", "Word", "Tag", "Has"]
 
# sorting and  printing
str.sort(reverse=True)
 
#print
print(str)

プログラムの実行後、出力は次のようになります。

[600、500、300、200、100] 
[100.43、90.65、50.72、16.0、4.41] 
['Word'、 'Test'、 'Tag'、 'My'、 'Has']

リンク: https://www.tutsmake.com/python-program-to-sort-list-in-ascending-and-descending-order/

#python