Explore all Artificial Intelligence open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Artificial Intelligence

mycroft-core

v21.2.2

DALLE-pytorch

1.5.2

skulpt

Internal updates and breaking changes

AI-on-the-edge-device

10.5.0 - Stability Increase

python-chess

Popular Libraries in Artificial Intelligence

mycroft-core

by MycroftAI doticonpythondoticon

star image 5695 doticonApache-2.0

Mycroft Core, the Mycroft Artificial Intelligence platform.

DALLE-pytorch

by lucidrains doticonpythondoticon

star image 4058 doticonMIT

Implementation / replication of DALL-E, OpenAI's Text to Image Transformer, in Pytorch

skulpt

by skulpt doticonpythondoticon

star image 3137 doticonNOASSERTION

Skulpt is a Javascript implementation of the Python programming language

susi_server

by fossasia doticonjavadoticon

star image 2282 doticonLGPL-2.1

SUSI.AI server backend - the Artificial Intelligence server for personal assistants https://api.susi.ai

sunfish

by thomasahle doticonpythondoticon

star image 2169 doticonGPL-3.0

Sunfish: a Python Chess Engine in 111 lines of code

susi.ai

by fossasia doticonjavascriptdoticon

star image 1939 doticonLGPL-2.1

SUSI.AI Web Client https://susi.ai

AI-on-the-edge-device

by jomjol doticonc++doticon

star image 1912 doticon

susi_iOS

by fossasia doticonswiftdoticon

star image 1694 doticonApache-2.0

SUSI AI iOS app http://susi.ai

python-chess

by niklasf doticonpythondoticon

star image 1648 doticonGPL-3.0

A chess library for Python, with move generation and validation, PGN parsing and writing, Polyglot opening book reading, Gaviota tablebase probing, Syzygy tablebase probing, and UCI/XBoard engine communication

Trending New libraries in Artificial Intelligence

DALLE-pytorch

by lucidrains doticonpythondoticon

star image 4058 doticonMIT

Implementation / replication of DALL-E, OpenAI's Text to Image Transformer, in Pytorch

AI-on-the-edge-device

by jomjol doticonc++doticon

star image 1912 doticon

AI-System

by microsoft doticonpythondoticon

star image 1514 doticonNOASSERTION

System for AI Education Resource.

performer-pytorch

by lucidrains doticonpythondoticon

star image 776 doticonMIT

An implementation of Performer, a linear attention-based transformer, in Pytorch

Lhy_Machine_Learning

by Fafa-DL doticonjupyter notebookdoticon

star image 773 doticon

李宏毅2021春季机器学习课程课件及作业

A-Hackers-AI-Voice-Assistant

by LearnedVector doticonpythondoticon

star image 537 doticonMIT

A hackers AI voice assistant, built using Python and PyTorch.

self-attention-cv

by The-AI-Summer doticonpythondoticon

star image 424 doticonMIT

Implementation of various self-attention mechanisms focused on computer vision. Ongoing repository.

pianotrans

by azuwis doticonpowershelldoticon

star image 353 doticon

Simple GUI for ByteDance's Piano Transcription with Pedals

Aragorn

by njzydark doticontypescriptdoticon

star image 265 doticonMIT

A tool to upload or manage files by object storage sdk

Top Authors in Artificial Intelligence

1

serverless-components

14 Libraries

star icon233

2

lucidrains

10 Libraries

star icon5636

3

fossasia

7 Libraries

star icon11046

4

dialogflow

6 Libraries

star icon153

5

mbaske

5 Libraries

star icon47

6

tencentyun

5 Libraries

star icon285

7

PacktPublishing

4 Libraries

star icon107

8

MarekMarchlewicz

4 Libraries

star icon20

9

IBM

4 Libraries

star icon154

10

TencentCloud

4 Libraries

star icon717

1

14 Libraries

star icon233

2

10 Libraries

star icon5636

3

7 Libraries

star icon11046

4

6 Libraries

star icon153

5

5 Libraries

star icon47

6

5 Libraries

star icon285

7

4 Libraries

star icon107

8

4 Libraries

star icon20

9

4 Libraries

star icon154

10

4 Libraries

star icon717

Trending Kits in Artificial Intelligence

AI-generated artwork wins the top prize in a U.S. art competition! Jason Allen's "Théâtre D'opéra Spatial" or 'Space Opera Theater' won the top prize at the Colorado State Fair's fine art competition in the "digital arts/digitally-manipulated photography" category. While the category allowed digital art, this issue has ignited fierce debate on A.I. generated content. We have all been accustomed to chatbots talking to us in natural language or text editors used in blogs. Creativity is the hallmark of human evolution! The ability to create art is one of the defining characteristics of evolution. The past generation of automation technologies went after repetitive manual tasks and wasn't seen as much of a threat. Generative A.I. technologies promise higher-level cognitive task capabilities such as writing, coding, video, and art. So naturally, this will usher in industrial revolution scale debates on the balance of using A.I. vs human economic value add. The other dimension that is also playing out is copyright. There are at least three parties involved in making A.I. art. The millions of images and their authors, the model's technology provider, and the user who generated the art. In August, a U.S. appeals court affirmed that an artificial intelligence system could not be an inventor under United States patent law, noting that the inventor must be a natural person. Authors of licenses such as CreativeML Open RAIL-M claim no rights on user-generated outputs. Though the product created by the engine is not patentable, it is unique. How unique can derivative work be, and can it be considered innovative? That is the maturity curve that generative A.I. has to scale. After all, we humans learn from instruction, infer from different sources and then reflect those in our innovation! While this journey evolves, here are interesting open source libraries that will help you generate art using A.I.

JavaScript Artificial Intelligence are used to create smarter and more advanced web apps. In 2022, the JavaScript Artificial Intelligence libraries will be in everyone’s mind. The reason being is that the JavaScript is going to be more popular for the AI development. Artificial intelligence (AI) is becoming increasingly important as we move into an automated world. Artificial intelligence is a part of computer science concerned with making computers work like humans. In the world of programming, there are many JavaScript AI frameworks and libraries that can help to create applications with artificial intelligence. These libraries have tools for machine learning, deep learning, computer vision, and more. Popular JavaScript Artificial Intelligence open source libraries among developers include: warriorjs - exciting game of programming and Artificial Intelligence; screeps - Artificial intelligence for screeps; vindinium - Artificial Intelligence Challenge scala game server.

Artificial Intelligence has gained a lot of attention from both developers and investors. In many different industries, artificial intelligence (AI) has already been implemented to automate simple tasks and processes. Artificial Intelligence has the ability to learn from data and improve over time. These libraries cover a wide range of functionality for interacting with and creating data from databases, scraping, and serving web pages. It has a large suite of tools to help for creating own neural nets. It is easy for beginners because the interface makes it easy to get started. Some of the most widely used open source libraries for Ruby Artificial Intelligence among developers include: ruby-warrior - Game written in Ruby for learning Ruby; akiva - simple natural language processing; paipr - Paradigms of Artificial Intelligence Programming; fuzzy-associative-memory - Fuzzy Logic "Fuzzy Associative Memory" for fuzzy control systems.

Artificial intelligence is one of the most promising technologies in 2021. The AI industry has grown tremendously over the past couple of years. Artificial Intelligence is progressively present in our lives. It has now become more accessible to developers and increasingly used in everyday applications. Artificial intelligence is on the rise and this fact is evident in the numerous AI-powered apps and devices. An Artificial Intelligence Library is a set of predefined functions or methods available within a given programming language. These methods allow developers to add AI features to their applications without having to code the AI algorithms from scratch. A few of the most popular C# Artificial Intelligence open source libraries for developers are: AForge.NET - NET Framework is a C# framework designed; BrainSimulator - Brain Simulator is a platform for visual prototyping; aima-csharp - Artificial Intelligence A Modern Approach.

Python is one of the best programming languages for artificial intelligence. It is a general-purpose programming language with libraries that allows to do complex mathematics, analytics, and visualizations. It has easy-to-use syntax, large community support, and tons of open-source libraries. Artificial Intelligence is the latest trend in the tech market and rapidly growing technology in software development. Artificial Intelligence is used in different fields including healthcare, machine learning, and trading. Python libraries and frameworks have made the task of a programmer easy and fast. Python libraries are already written code which we can easily import whenever needed in the code with simple import statements. Some of the most popular Python Artificial Intelligence Open Source libraries among developers are: mycroft-core - Mycroft Core, the Mycroft Artificial Intelligence platform; serenata-de-amor - Artificial Intelligence for social control; muzic - Muzic: Music Understanding and Generation with Artificial Intelligence.

Go is one of the most popular programming languages for building AI applications. It is a statically typed, compiled programming language. Go is the new wave of artificial intelligence programming and is already being used by Google, Facebook, IBM and others. The language has been designed to be simple, easy to learn and super effective. The Go language is growing fast, and the Artificial Intelligence libraries are becoming more and more useful. It also has a lot of great features for artificial intelligence programming includes support for neural networks, deep learning and genetic algorithms. Developers tend to use some of the following Go Artificial Intelligence open source libraries: robotgo - RobotGo, Go Native crossplatform GUI automation @vcaesar; gobot - Golang framework for robotics, drones, and the Internet of Things; gort - Command Line Interface for RobotOps.

C++ is an object-oriented programming language developed by Bjarne Stroustrup in 1983 at Bell Labs. C++ is one of the most popular programming languages in the world and has been around since the early days of computer science. It’s an old language and has seen a lot of different iterations over the years. C++ language has a lot of libraries, with the main focus being on games, software and also large selection of Artificial Intelligence (AI) libraries. Artificial intelligence (AI) is a set of algorithms that allow computers to perform various tasks. AI tools are included in a range of software products and services. This helps to solve numerous real-life problems, including self-driving cars, speech recognition, and robotics. Popular C++ Artificial Intelligence open source libraries for developers include: mrpt - The Mobile Robot Programming Toolkit; gtsam - GTSAM is a library of C classes that implement smoothing and mapping in robotics and vision, using factor graphs and Bayes networks as the underlying; chrono - High-performance C++ library for multiphysics and multibody dynamics simulations.

Java is a powerful, high-level language that enables programmers to create anything from a simple mobile app to the most advanced artificial intelligence software. The Java AI library is a set of functions and classes that allow developers to program on their own. It contains algorithms for machine learning, neural networks, and deep learning. Java has a wide range of artificial intelligence libraries available to developers. Artificial Intelligence is changing the world. It is used in a variety of areas, from a personal assistant to industrial robots. The Java Artificial Intelligence is the intelligence which is demonstrated by machines, in contrast to the natural intelligence displayed by humans and other animals. Many developers depend on the following Java Artificial Intelligence open source libraries: malmo - Project Malmo; gdx-ai - Artificial Intelligence framework for games based; aifh -Artificial Intelligence for Humans.

Should you have a say in your social feed algorithms? In the recent past, Elon Musk had been very vocal in suggesting that Twitter algorithms should be made public. He even added that the algorithms be made open source and are driven by the community like Linux or Signal. This could set a new precedent in social media and tech platforms. We will have to wait and see if and how he drives this change in Twitter. Interestingly Koo had shared the workings of their algorithms at https://info.kooapp.com/algorithms-at-koo/. This page gives a high-level view of how the feed is influenced by your following, trending content, reactions, type of media, etc. It, however, doesn't share the weights. It also explains how trending topics are surfaced based on keywords and hashtags, how creators are recommended, and how followers receive relevant notifications. It is a step in the right direction, but a long way to get to the Web3 ideologies of decentralization and fairness controlled by the users. While we all navigate through this, today's technology offers Explainability and Interpretability to better understand and control model behaviors. You could use these to enable users to understand and tweak algorithms in your applications and contribute to this transformation. Explainability is the extent to which a system's behavior can be traced back to its underlying causes, such as the parameters in use by the algorithm and the data used during training. It shows how significant each of these parameters and nodes contributes to the final decision. This helps debug and improve model performance and understand the model's behavior. Interpretability communicates the extent to which a cause and effect can be observed within a system. i.e. the extent to which you can predict what will happen, given a change in input or algorithmic parameters. For example, if you have a model that predicts whether someone will buy your product based on their age and income, then interpretability would let you know how much each of these factors actually contributes to predicting whether they'll buy your product or not (i.e., it could show that age only contributes 25% to predicting whether someone will buy your product). In contrast, explainability would let you know that age might be important because there's an interaction between age and income - meaning that it's more likely for people who have high incomes Together, they help understand how the model arrived at a decision and how each step contributed to that. Here's a list of open source libraries that can help you experiment on Explainability and Interpretability.

Will you trust a potential global war threat decision with AI? Reuters reported that Deputy Secretary of Defense Kathleen Hicks was briefed on a new software created by US military commanders in the Pacific that can predict Chinese reaction to US actions in the region. The tool looks at data since early 2020. It predicts response across various activities such as congressional visits to Taiwan, arms sales to allies in the region, or when several US ships sail through the Taiwan Strait. It is heartening to see AI mature into strategic roles, especially in the backdrop of Zillow iBuying algorithms causing a loss of more than $300m a few weeks ago and costing over 2000 jobs and an unsold inventory of 7000 homes! Well, the answer lies in strategic oversight. Algorithmic decisions reflect data quality, rigorous training, and introduced biases, among other factors. Both these situations reflect on the maturity of AI as a technology and the need for better design and review. With AI becoming almost a black box to most engineers given the complexity of the high number of parameters and nodes, Explainable AI brings a set of tools and frameworks to help understand predictions made by machine learning models. Explainability shows how significant each of the parameters and nodes contribute to the final decision. This helps debug and improve model performance and understand the model's behavior. Interpretability communicates the extent to which a cause and effect can be observed within a system. i.e. the extent to which you can predict what will happen, given a change in input or algorithmic parameters. Together, they help understand how the model arrived at a decision and how each step contributed to that. Try over 100s of Explainability and Interpretability solutions on kandi to make your next big decision.

Trending Discussions on Artificial Intelligence

Space Complexity in Breadth First Search (BFS) Algorithm

Process fast api multi-user

I'm having a problem with lists in my basic quiz software

Discretize continuous target variable using sklearn

Webpage starts zoomed out on mobile devices

Pyttsx3 not working, process finished with exit code 0

Expandable input and output in neural network

How to group elements of loop in a single list index

Render image with json data | ReactJs

Searching for a word/phrase in a string with all the possible approximations of the phrase

QUESTION

Space Complexity in Breadth First Search (BFS) Algorithm

Asked 2022-Apr-11 at 08:08

According to Artificial Intelligence A Modern Approach - Stuart J. Russell , Peter Norvig (Version 4), space complexity of BFS is O(b^d), where 'b' is branching factor and 'd' is depth.

Complexity of BFS is obtained by this assumption: we store all nodes till we arrive to target node, in other word: 1 + b + b^2 + b^3 + ... + b^d => O(b^d)

But why should we store all nodes? don't we use queue for implementation?

If we use queue, don't need to store all nodes, because we enqueue and dequeue some nodes in steps, then when we find target node(s), we can say some nodes are in queue (but not all of them).

Is my understanding wrong?

ANSWER

Answered 2022-Apr-10 at 06:16

At any moment while we apply BFS, the queue would have at most two levels of nodes, for example if we just started searching in depth d, then the queue now contains all nodes at depth d and as we proceed the queue would finish all nodes at depth d and have all nodes at depth d+1, so at any moment we have O(b^d) space.

Also 1+b+b^2+...+b^d = (b^(d+1)-1)/(b-1).

Source https://stackoverflow.com/questions/71814173

QUESTION

Process fast api multi-user

Asked 2022-Mar-28 at 02:20

I'm studying the process of distributing artificial intelligence modules through fastapi.

I'm going to take a load test

I created an api that answers questions through fastapi using a pre-learned model.

In this case, it is not a problem for one user to use it, but when multiple users use it at the same time, the response may be too slow.

So when multiple users enter a question, is there any way to copy the model and put it in at once?

1
2class sentencebert_ai():
3    def __init__(self) -> None:
4        super().__init__()
5
6 def ask_query(self,query, topN):
7        startt = time.time()
8
9        ask_result = []
10        score = []
11        result_value = []  
12        embedder = torch.load(model_path)
13        corpus_embeddings = embedder.encode(corpus, convert_to_tensor=True)
14        query_embedding = embedder.encode(query, convert_to_tensor=True)
15        cos_scores = util.pytorch_cos_sim(query_embedding, corpus_embeddings)[0] #torch.Size([121])121개의 말뭉치에 대한 코사인 유사도 값이다.
16        cos_scores = cos_scores.cpu()
17
18        top_results = np.argpartition(-cos_scores, range(topN))[0:topN]
19
20        for idx in top_results[0:topN]:        
21            ask_result.append(corpusid[idx].item())
22            #.item()으로 접근하는 이유는 tensor(5)에서 해당 숫자에 접근하기 위한 방식이다.
23            score.append(round(cos_scores[idx].item(),3))
24
25        #서버에 json array 형태로 내보내기 위한 작업
26        for i,e in zip(ask_result,score):
27            result_value.append({"pred_id":i,"pred_weight":e})
28        endd = time.time()
29        print('시간체크',endd-startt)
30        return result_value
31        # return ','.join(str(e) for e in ask_result),','.join(str(e) for e in score)
32
33
34
35class Item_inference(BaseModel):
36    text : str
37    topN : Optional[int] = 1
38
39@app.post("/retrieval", tags=["knowledge recommendation"])
40async def Knowledge_recommendation(item: Item_inference):
41  
42    # db.append(item.dict())
43    item.dict()
44    results = _ai.ask_query(item.text, item.topN)
45
46    return results
47
48
49if __name__ == "__main__":
50    parser = argparse.ArgumentParser()
51    parser.add_argument("--port", default='9003', type=int)
52    # parser.add_argument("--mode", default='cpu', type=str, help='cpu for CPU mode, gpu for GPU mode')
53    args = parser.parse_args()
54
55    _ai = sentencebert_ai()
56    uvicorn.run(app, host="0.0.0.0", port=args.port,workers=4)
57

corrected version

1
2class sentencebert_ai():
3    def __init__(self) -> None:
4        super().__init__()
5
6 def ask_query(self,query, topN):
7        startt = time.time()
8
9        ask_result = []
10        score = []
11        result_value = []  
12        embedder = torch.load(model_path)
13        corpus_embeddings = embedder.encode(corpus, convert_to_tensor=True)
14        query_embedding = embedder.encode(query, convert_to_tensor=True)
15        cos_scores = util.pytorch_cos_sim(query_embedding, corpus_embeddings)[0] #torch.Size([121])121개의 말뭉치에 대한 코사인 유사도 값이다.
16        cos_scores = cos_scores.cpu()
17
18        top_results = np.argpartition(-cos_scores, range(topN))[0:topN]
19
20        for idx in top_results[0:topN]:        
21            ask_result.append(corpusid[idx].item())
22            #.item()으로 접근하는 이유는 tensor(5)에서 해당 숫자에 접근하기 위한 방식이다.
23            score.append(round(cos_scores[idx].item(),3))
24
25        #서버에 json array 형태로 내보내기 위한 작업
26        for i,e in zip(ask_result,score):
27            result_value.append({"pred_id":i,"pred_weight":e})
28        endd = time.time()
29        print('시간체크',endd-startt)
30        return result_value
31        # return ','.join(str(e) for e in ask_result),','.join(str(e) for e in score)
32
33
34
35class Item_inference(BaseModel):
36    text : str
37    topN : Optional[int] = 1
38
39@app.post("/retrieval", tags=["knowledge recommendation"])
40async def Knowledge_recommendation(item: Item_inference):
41  
42    # db.append(item.dict())
43    item.dict()
44    results = _ai.ask_query(item.text, item.topN)
45
46    return results
47
48
49if __name__ == "__main__":
50    parser = argparse.ArgumentParser()
51    parser.add_argument("--port", default='9003', type=int)
52    # parser.add_argument("--mode", default='cpu', type=str, help='cpu for CPU mode, gpu for GPU mode')
53    args = parser.parse_args()
54
55    _ai = sentencebert_ai()
56    uvicorn.run(app, host="0.0.0.0", port=args.port,workers=4)
57@app.post("/aaa") def your_endpoint(request: Request, item:Item_inference): start = time.time() model = request.app.state.model item.dict() #커널 실행시 필요 _ai = sentencebert_ai() results = _ai.ask_query(item.text, item.topN,model) end = time.time() print(end-start) return results ``` 
58

ANSWER

Answered 2022-Mar-25 at 09:09

Firstly, you should not load your model every time a request arrives, but rahter have it loaded once at startup (you could use the startup event for this) and store it on the app instance, which you can later retrieve, as described here and here. For instance:

1
2class sentencebert_ai():
3    def __init__(self) -> None:
4        super().__init__()
5
6 def ask_query(self,query, topN):
7        startt = time.time()
8
9        ask_result = []
10        score = []
11        result_value = []  
12        embedder = torch.load(model_path)
13        corpus_embeddings = embedder.encode(corpus, convert_to_tensor=True)
14        query_embedding = embedder.encode(query, convert_to_tensor=True)
15        cos_scores = util.pytorch_cos_sim(query_embedding, corpus_embeddings)[0] #torch.Size([121])121개의 말뭉치에 대한 코사인 유사도 값이다.
16        cos_scores = cos_scores.cpu()
17
18        top_results = np.argpartition(-cos_scores, range(topN))[0:topN]
19
20        for idx in top_results[0:topN]:        
21            ask_result.append(corpusid[idx].item())
22            #.item()으로 접근하는 이유는 tensor(5)에서 해당 숫자에 접근하기 위한 방식이다.
23            score.append(round(cos_scores[idx].item(),3))
24
25        #서버에 json array 형태로 내보내기 위한 작업
26        for i,e in zip(ask_result,score):
27            result_value.append({"pred_id":i,"pred_weight":e})
28        endd = time.time()
29        print('시간체크',endd-startt)
30        return result_value
31        # return ','.join(str(e) for e in ask_result),','.join(str(e) for e in score)
32
33
34
35class Item_inference(BaseModel):
36    text : str
37    topN : Optional[int] = 1
38
39@app.post("/retrieval", tags=["knowledge recommendation"])
40async def Knowledge_recommendation(item: Item_inference):
41  
42    # db.append(item.dict())
43    item.dict()
44    results = _ai.ask_query(item.text, item.topN)
45
46    return results
47
48
49if __name__ == "__main__":
50    parser = argparse.ArgumentParser()
51    parser.add_argument("--port", default='9003', type=int)
52    # parser.add_argument("--mode", default='cpu', type=str, help='cpu for CPU mode, gpu for GPU mode')
53    args = parser.parse_args()
54
55    _ai = sentencebert_ai()
56    uvicorn.run(app, host="0.0.0.0", port=args.port,workers=4)
57@app.post("/aaa") def your_endpoint(request: Request, item:Item_inference): start = time.time() model = request.app.state.model item.dict() #커널 실행시 필요 _ai = sentencebert_ai() results = _ai.ask_query(item.text, item.topN,model) end = time.time() print(end-start) return results ``` 
58@app.on_event("startup")
59async def startup_event():
60    app.state.model = torch.load(model_path)
61
62from fastapi import Request
63
64@app.post("/")
65def your_endpoint(request: Request):
66        model = request.app.state.model
67        # then pass it to your ask_query function
68

Secondly, if you do not have to await for coroutines in your route, then you should rather define your route with def instead of async def. In this way, FastAPI will process the requests concurrently (each will run in a separate thread), whereas async def routes run on the main thread, i.e., the server processes the requests sequentially (as long as there is no await call to I/O-bound operations inside such routes). Please have a look at the answers here and here, as well as all the references included in them, to understand the concept of async/await, and the difference between using def and async def.

Source https://stackoverflow.com/questions/71613305

QUESTION

I'm having a problem with lists in my basic quiz software

Asked 2022-Mar-11 at 01:38

I am running the code block written below:

1class Question:
2    
3    def __init__(self,text,choices,answer):
4        self.text = text
5        self.choices = choices
6        self.answer = answer
7        
8    def checkAnswer(self, answer):
9        return self.answer == answer
10 class Quiz:
11    
12    def __init__(self, questions):
13        self.questions = questions
14        self.score = 0
15        self.questionsIndex = 0
16        
17    def getQuestion(self):
18        return self.questions[self.questionsIndex]
19    
20    def displayQuestion(self):
21        question = self.getQuestion()
22        print(f"Question: {self.questionsIndex +1}: {question.text}")   
23        for q in question.choices:
24            print("-"+ q)
25        answer = input("Your Answer:  ")
26        self.guess(answer)
27        self.loadQuestion()
28        
29    def guess(self, answer):
30        question = self.getQuestion()
31        if question.checkAnswer(answer):
32            self.score += 1
33        self.questionsIndex += 1
34        self.displayQuestion()
35        
36    def loadQuestion(self):
37        if len(self.questions) == self.questionsIndex:
38            self.showScore()
39        else:
40            self.displayProgress()
41            self.displayQuestion()
42            
43    def showScore(self):
44        print("Score: ", self.score)
45        
46    def displayProgress(self):
47        totalQuestion = len(self.questions)
48        questionNumber = self.questionsIndex + 1
49        if questionNumber > totalQuestion:
50            print("Quiz Finished")
51        else:
52            print(f"*************************Question {questionNumber} of {totalQuestion}***********************************")
53           
54
55q1 = Question("Which programming language is the most profitable?["C#","Python","Java","HTML"],"Python")
56q2 = Question("Which is the easiest programming language?", ["C#","Python","Java","HTML"],"Python")
57q3 = Question("What is the most popular programming language?", ["C#","Python","Java","HTML"],"Python")
58questions = [q1,q2,q3]
59quiz = Quiz(questions)
60quiz.loadQuestion()
61

And I am facing the following problem:

1class Question:
2    
3    def __init__(self,text,choices,answer):
4        self.text = text
5        self.choices = choices
6        self.answer = answer
7        
8    def checkAnswer(self, answer):
9        return self.answer == answer
10 class Quiz:
11    
12    def __init__(self, questions):
13        self.questions = questions
14        self.score = 0
15        self.questionsIndex = 0
16        
17    def getQuestion(self):
18        return self.questions[self.questionsIndex]
19    
20    def displayQuestion(self):
21        question = self.getQuestion()
22        print(f"Question: {self.questionsIndex +1}: {question.text}")   
23        for q in question.choices:
24            print("-"+ q)
25        answer = input("Your Answer:  ")
26        self.guess(answer)
27        self.loadQuestion()
28        
29    def guess(self, answer):
30        question = self.getQuestion()
31        if question.checkAnswer(answer):
32            self.score += 1
33        self.questionsIndex += 1
34        self.displayQuestion()
35        
36    def loadQuestion(self):
37        if len(self.questions) == self.questionsIndex:
38            self.showScore()
39        else:
40            self.displayProgress()
41            self.displayQuestion()
42            
43    def showScore(self):
44        print("Score: ", self.score)
45        
46    def displayProgress(self):
47        totalQuestion = len(self.questions)
48        questionNumber = self.questionsIndex + 1
49        if questionNumber > totalQuestion:
50            print("Quiz Finished")
51        else:
52            print(f"*************************Question {questionNumber} of {totalQuestion}***********************************")
53           
54
55q1 = Question("Which programming language is the most profitable?["C#","Python","Java","HTML"],"Python")
56q2 = Question("Which is the easiest programming language?", ["C#","Python","Java","HTML"],"Python")
57q3 = Question("What is the most popular programming language?", ["C#","Python","Java","HTML"],"Python")
58questions = [q1,q2,q3]
59quiz = Quiz(questions)
60quiz.loadQuestion()
61runfile('C:/Users/Onur/Desktop/Artificial Intelligence A-Z/sorularclass.py', wdir='C:/Users/Onur/Desktop/Artificial Intelligence A-Z')
62*************************Question 1 of 3***********************************
63Question: 1: Which programming language is the most profitable?
64-C#
65-Python
66-Java
67-HTML
68 Your Answer:  a
69Question: 2: Which is the easiest programming language?
70-C#
71-Python
72-Java
73-HTML
74Your Answer:  a
75Question: 3: What is the most popular programming language?
76-C#
77-Python
78-Java
79-HTML
80Your Answer:  a
81Traceback (most recent call last):
82File "C:\Users\Onur\Desktop\Artificial Intelligence A-Z\sorularclass.py", line 63, in <module>
83    quiz.loadQuestion()
84File "C:\Users\Onur\Desktop\Artificial Intelligence A-Z\sorularclass.py", line 44, in loadQuestion
85    self.displayQuestion()
86File "C:\Users\Onur\Desktop\Artificial Intelligence A-Z\sorularclass.py", line 29, in displayQuestion
87    self.guess(answer)
88File "C:\Users\Onur\Desktop\Artificial Intelligence A-Z\sorularclass.py", line 37, in guess
89    self.displayQuestion()
90File "C:\Users\Onur\Desktop\Artificial Intelligence A-Z\sorularclass.py", line 29, in displayQuestion
91    self.guess(answer)
92File "C:\Users\Onur\Desktop\Artificial Intelligence A-Z\sorularclass.py", line 37, in guess
93    self.displayQuestion()
94File "C:\Users\Onur\Desktop\Artificial Intelligence A-Z\sorularclass.py", line 29, in displayQuestion
95    self.guess(answer)
96File "C:\Users\Onur\Desktop\Artificial Intelligence A-Z\sorularclass.py", line 37, in guess
97    self.displayQuestion()
98File "C:\Users\Onur\Desktop\Artificial Intelligence A-Z\sorularclass.py", line 24, in displayQuestion
99    question = self.getQuestion()
100File "C:\Users\Onur\Desktop\Artificial Intelligence A-Z\sorularclass.py", line 21, in getQuestion
101    return self.questions[self.questionsIndex]
102
103IndexError: list index out of range
104

Can you tell me the reason for this? Why is there a problem with lists? I'm adding this because stackoverflow wants me to add more details: I tried to build a quiz using basic class methods in this software, but I ran into a problem.

ANSWER

Answered 2022-Mar-11 at 01:38

In the displayQuestion method you call the guess method. In the guess method you increase the questionsIndex value, and call displayQuestion method again.

This process repeats and repeats infinitely until the questionIndex goes out of range. It seems that you need to remove calling the displayQuestion method from the guess method.

Source https://stackoverflow.com/questions/71431066

QUESTION

Discretize continuous target variable using sklearn

Asked 2022-Jan-30 at 23:08

I have to discretize into at least 5 bins a continuous target variable in order to lower the complexity of a classification model using the sklearn library

In order to do this, I've used the KBinsDiscretizer but I don't know how can I split in balanced parts the dataset now that I've discretized the target variable. This is my code:

1X = df.copy()
2y = X.pop('shares') 
3
4# scaling the dataset so all data in the same range
5scaler = preprocessing.MinMaxScaler()
6X = scaler.fit_transform(X)
7
8discretizer = preprocessing.KBinsDiscretizer(n_bins=5,  encode='ordinal', strategy='uniform')
9y_discretized = discretizer.fit_transform(y.values.reshape(-1, 1))
10
11# is this correct?
12X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, shuffle=True, stratify=y_discretized) 
13

For completeness, I'm trying to recreate a less complex model than the one showed in: [1] K. Fernandes, P. Vinagre and P. Cortez. A Proactive Intelligent Decision Support System for Predicting the Popularity of Online News. Proceedings of the 17th EPIA 2015 - Portuguese Conference on Artificial Intelligence, September, Coimbra, Portugal

ANSWER

Answered 2022-Jan-23 at 20:35

Your y_train and y_test are parts of y, which has (it seems) the original continuous values. So you're ending up fitting multiclass classification models, with probably lots of different classes, which likely causes the crashes.

I assume what you wanted is

1X = df.copy()
2y = X.pop('shares') 
3
4# scaling the dataset so all data in the same range
5scaler = preprocessing.MinMaxScaler()
6X = scaler.fit_transform(X)
7
8discretizer = preprocessing.KBinsDiscretizer(n_bins=5,  encode='ordinal', strategy='uniform')
9y_discretized = discretizer.fit_transform(y.values.reshape(-1, 1))
10
11# is this correct?
12X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, shuffle=True, stratify=y_discretized) 
13X_train, X_test, y_train, y_test = train_test_split(X, y_discretized, test_size=0.33, shuffle=True, stratify=y_discretized)
14

Whether discretizing a continuous target to turn a regression into a classification is a topic for another site, see e.g. https://datascience.stackexchange.com/q/90297/55122

Source https://stackoverflow.com/questions/70821138

QUESTION

Webpage starts zoomed out on mobile devices

Asked 2022-Jan-15 at 20:33

I have created a website for desktop and mobile, and it has to be responsive. My problem is that when I resize the browser all the content gets zoomed out instead of adapting. I also have an issue with the HTML. why is it only taking up 1/3 of the page according to dev tools and when I add width:1100px to my sections it renders the desktop version, but when I take it away it floats to the left side? Why is this happening?

Images of the problem:

1* {
2     margin: 0;
3     padding: 0;
4     box-sizing: border-box;
5}
6 body {
7     font-family: 'Source Sans Pro', sans-serif;
8     background-color: black;
9     color: white;
10     line-height: 30px;
11}
12 html {
13     width:100%;
14}
15 img {
16     width: 100%;
17}
18 h1 {
19     font-weight: 700;
20     font-size: 44px;
21     margin-bottom: 40px;
22     line-height: 50px;
23}
24 h3 {
25     width: 100%;
26}
27/* header */
28 header {
29     display: flex;
30     background-color: black;
31     height: 80px;
32     min-width: 1100px;
33     justify-content: right;
34     align-items: center;
35     margin-bottom: 50px;
36     border-bottom: 1px solid white;
37}
38 nav ul li {
39     display: inline-block;
40     list-style-type: none;
41     margin-right: 20px;
42}
43 .nav-links{
44     color: white;
45     font-size: 18px;
46}
47/* Banner */
48 .banner {
49     display: flex;
50     justify-content: space-around;
51     align-items: center;
52     min-height: 500px;
53     width: 100%;
54}
55 .banner-text-container {
56     max-width: 30%;
57     font-size: 22px;
58}
59 span {
60     color: #11cc9e;
61}
62 .consultation-link{
63     color: #11cc9e;
64     text-decoration: none;
65     margin-top: 30px;
66     font-weight: 900;
67     display: block;
68     border: 1px solid white;
69     max-width: 40%;
70     text-align: center;
71     padding: 5px;
72}
73 .consultation-link:hover{
74     background-color: #fff;
75}
76/* About */
77 .about {
78     display: flex;
79     justify-content: space-around;
80     align-items: center;
81     min-height: 600px;
82     min-width: 1100px;
83}
84 .about-text-container {
85     max-width: 40%;
86     font-size: 22px;
87     margin-left: 20px;
88}
89 .about-img{
90     width: 400px;
91     margin-right: 22px;
92}
93 .about-title {
94     margin-bottom: 40px;
95}
96 .about-us-link{
97     color: #11cc9e;
98     text-decoration: none;
99     margin-top: 30px;
100     font-weight: 900;
101     display: block;
102     border: 1px solid white;
103     text-align: center;
104     max-width: 25%;
105     padding: 5px;
106}
107 .about-us-link:hover{
108     background-color: #fff;
109}
110/* Join */
111 .join {
112     min-height: 600px;
113     min-width: 1100px;
114     max-width: 100%;
115}
116 .join-header{
117     width: 100%;
118     text-align: center;
119     margin-top: 150px;
120     font-size: 40px;
121}
122 .container-boxes{
123     position: relative;
124     top: 0;
125     bottom: 0;
126     display: flex;
127     flex-wrap: wrap;
128     justify-content: space-evenly;
129     align-items: center;
130     min-height: 500px;
131     min-width: 1100px;
132}
133 .box {
134     position: relative;
135     overflow: hidden;
136     transition: 0.5s;
137     height: 200px;
138     width: 300px;
139}
140 .box:hover{
141     z-index: 1;
142     transform: scale(1.25);
143     box-shadow: 0 25px 40px rgba(0, 0, 0, .5);
144     cursor: pointer;
145}
146 .box .imgBX{
147     position: absolute;
148     top: 0;
149     left: 0;
150     width: 100%;
151     height: 100%;
152}
153 .box .imgBX img{
154     position: absolute;
155     top: 0;
156     left: 0;
157     width: 100%;
158     height: 100%;
159     object-fit: cover;
160}
161 .box .imgBX:before{
162     content: '';
163     position: absolute;
164     top: 0;
165     left: 0;
166     width: 100%;
167     height: 100%;
168     z-index: 1;
169     background: linear-gradient(180deg,rgba(0,0,0.7),#79dbc3);
170     mix-blend-mode: multiply;
171     opacity: 0;
172     transition: 0.5s;
173}
174 .box:hover .imgBX:before {
175     opacity: 1;
176}
177 .box .imgBX img{
178     position: absolute;
179     top: 0;
180     left: 0;
181     width: 100%;
182     height: 100%;
183     object-fit: cover;
184}
185 .content{
186     display: flex;
187     flex-direction: column;
188     text-align: center;
189     position: absolute;
190     top: 20%;
191     bottom: 40%;
192     width: 100%;
193     height: 100%;
194     z-index: 1;
195     padding: 20px;
196     visibility: hidden;
197}
198 .box:hover .content{
199     visibility: visible;
200}
201/* Quote section */
202 .quote-section {
203     display: flex;
204     justify-content: center;
205     max-width: 100%;
206     min-height: 500px;
207     min-width: 1100px;
208}
209 .quote-container {
210     display: flex;
211     flex-direction: column;
212     flex-wrap: wrap;
213     align-items: center;
214     justify-items: center;
215     max-width: 50%;
216     font-size: 22px;
217     text-align: center;
218}
219 .quote {
220     line-height: 90px;
221     font-size: 150px;
222     font-style: italic;
223     color: #11cc9e;
224     text-indent: -37px;
225     font-weight: 600;
226     width: 37px;
227}
228 .quote-img{
229     width: 90px;
230     margin: 40px auto;
231}
232 .person-name{
233     color: #ccc;
234}
235 .person-role{
236     font-size: 17px;
237     color: #ccc;
238}
239/* Footer */
240 footer {
241     text-align: center;
242     margin-top: 100px;
243     padding-top: 50px;
244     max-width: 100%;
245     min-height: 200px;
246     min-width: 1100px;
247     border-top: 1px solid #fff;
248}
1* {
2     margin: 0;
3     padding: 0;
4     box-sizing: border-box;
5}
6 body {
7     font-family: 'Source Sans Pro', sans-serif;
8     background-color: black;
9     color: white;
10     line-height: 30px;
11}
12 html {
13     width:100%;
14}
15 img {
16     width: 100%;
17}
18 h1 {
19     font-weight: 700;
20     font-size: 44px;
21     margin-bottom: 40px;
22     line-height: 50px;
23}
24 h3 {
25     width: 100%;
26}
27/* header */
28 header {
29     display: flex;
30     background-color: black;
31     height: 80px;
32     min-width: 1100px;
33     justify-content: right;
34     align-items: center;
35     margin-bottom: 50px;
36     border-bottom: 1px solid white;
37}
38 nav ul li {
39     display: inline-block;
40     list-style-type: none;
41     margin-right: 20px;
42}
43 .nav-links{
44     color: white;
45     font-size: 18px;
46}
47/* Banner */
48 .banner {
49     display: flex;
50     justify-content: space-around;
51     align-items: center;
52     min-height: 500px;
53     width: 100%;
54}
55 .banner-text-container {
56     max-width: 30%;
57     font-size: 22px;
58}
59 span {
60     color: #11cc9e;
61}
62 .consultation-link{
63     color: #11cc9e;
64     text-decoration: none;
65     margin-top: 30px;
66     font-weight: 900;
67     display: block;
68     border: 1px solid white;
69     max-width: 40%;
70     text-align: center;
71     padding: 5px;
72}
73 .consultation-link:hover{
74     background-color: #fff;
75}
76/* About */
77 .about {
78     display: flex;
79     justify-content: space-around;
80     align-items: center;
81     min-height: 600px;
82     min-width: 1100px;
83}
84 .about-text-container {
85     max-width: 40%;
86     font-size: 22px;
87     margin-left: 20px;
88}
89 .about-img{
90     width: 400px;
91     margin-right: 22px;
92}
93 .about-title {
94     margin-bottom: 40px;
95}
96 .about-us-link{
97     color: #11cc9e;
98     text-decoration: none;
99     margin-top: 30px;
100     font-weight: 900;
101     display: block;
102     border: 1px solid white;
103     text-align: center;
104     max-width: 25%;
105     padding: 5px;
106}
107 .about-us-link:hover{
108     background-color: #fff;
109}
110/* Join */
111 .join {
112     min-height: 600px;
113     min-width: 1100px;
114     max-width: 100%;
115}
116 .join-header{
117     width: 100%;
118     text-align: center;
119     margin-top: 150px;
120     font-size: 40px;
121}
122 .container-boxes{
123     position: relative;
124     top: 0;
125     bottom: 0;
126     display: flex;
127     flex-wrap: wrap;
128     justify-content: space-evenly;
129     align-items: center;
130     min-height: 500px;
131     min-width: 1100px;
132}
133 .box {
134     position: relative;
135     overflow: hidden;
136     transition: 0.5s;
137     height: 200px;
138     width: 300px;
139}
140 .box:hover{
141     z-index: 1;
142     transform: scale(1.25);
143     box-shadow: 0 25px 40px rgba(0, 0, 0, .5);
144     cursor: pointer;
145}
146 .box .imgBX{
147     position: absolute;
148     top: 0;
149     left: 0;
150     width: 100%;
151     height: 100%;
152}
153 .box .imgBX img{
154     position: absolute;
155     top: 0;
156     left: 0;
157     width: 100%;
158     height: 100%;
159     object-fit: cover;
160}
161 .box .imgBX:before{
162     content: '';
163     position: absolute;
164     top: 0;
165     left: 0;
166     width: 100%;
167     height: 100%;
168     z-index: 1;
169     background: linear-gradient(180deg,rgba(0,0,0.7),#79dbc3);
170     mix-blend-mode: multiply;
171     opacity: 0;
172     transition: 0.5s;
173}
174 .box:hover .imgBX:before {
175     opacity: 1;
176}
177 .box .imgBX img{
178     position: absolute;
179     top: 0;
180     left: 0;
181     width: 100%;
182     height: 100%;
183     object-fit: cover;
184}
185 .content{
186     display: flex;
187     flex-direction: column;
188     text-align: center;
189     position: absolute;
190     top: 20%;
191     bottom: 40%;
192     width: 100%;
193     height: 100%;
194     z-index: 1;
195     padding: 20px;
196     visibility: hidden;
197}
198 .box:hover .content{
199     visibility: visible;
200}
201/* Quote section */
202 .quote-section {
203     display: flex;
204     justify-content: center;
205     max-width: 100%;
206     min-height: 500px;
207     min-width: 1100px;
208}
209 .quote-container {
210     display: flex;
211     flex-direction: column;
212     flex-wrap: wrap;
213     align-items: center;
214     justify-items: center;
215     max-width: 50%;
216     font-size: 22px;
217     text-align: center;
218}
219 .quote {
220     line-height: 90px;
221     font-size: 150px;
222     font-style: italic;
223     color: #11cc9e;
224     text-indent: -37px;
225     font-weight: 600;
226     width: 37px;
227}
228 .quote-img{
229     width: 90px;
230     margin: 40px auto;
231}
232 .person-name{
233     color: #ccc;
234}
235 .person-role{
236     font-size: 17px;
237     color: #ccc;
238}
239/* Footer */
240 footer {
241     text-align: center;
242     margin-top: 100px;
243     padding-top: 50px;
244     max-width: 100%;
245     min-height: 200px;
246     min-width: 1100px;
247     border-top: 1px solid #fff;
248}<!DOCTYPE html>
249<html lang="en">
250   <head>
251      <title>Codes</title>
252      <link rel="preconnect" href="https://fonts.googleapis.com">
253      <ink rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
254      <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@400;600&display=swap" rel="stylesheet">
255      <meta charset="UTF-8">
256      <meta http-equiv="X-UA-Compatible" content="IE=edge">
257      <meta name="viewport" content="width=device-width, initial-scale=1">
258      <link rel="stylesheet" href="./Resources/styles.css">
259   </head>
260   <body>
261      <header>
262         <!-- insert logo -->
263         <nav class="nav-links">
264            <ul>
265               <li>About</li>
266               <li>Peer group</li>
267               <li>Review</li>
268            </ul>
269         </nav>
270      </header>
271      <section class="banner">
272         <div class="banner-text-container">
273            <h1>Build. Grow. <span class="color-Learn">Learn.</span></h1>
274            <p>Unlock your potential with your peers!, using Blockchain, Fintech or the IT outsourcing company Boosty Labs helps you create an innovative end to end product or augment your team with the right experts.</p>
275            <a class="consultation-link" href="#">Free consultation </a>
276         </div>
277         <div class="banner-img">
278            <img src="./Resources/Images/banner.png" alt="">
279         </div>
280      </section>
281      <section class="about">
282         <div class="about-text-container">
283            <h2 class="about-title">Who we are</h2>
284            <p>Here you can find our ,collection of coding, data science and statistics tutorials with examples in R, Python, JavaScript and Python. As you click through, you'll notice that some tutorials have ribbons on their logos - they are part of our free and self-paced online course Data Science for Ecologists and Environmental Scientists! Yellow for the Stats from Scratch stream, blue for Wiz of Data Viz and purple for Mastering Modelling.</p>
285            <a class="about-us-link" href="#">More about us </a>
286         </div>
287         <div class="about-img">
288            <img src="./Resources/Images/whoweare.png" alt="">
289         </div>
290      </section>
291      <section class="join">
292         <h3 class="join-header" >Join a peer group!</h3>
293         <div class="container-boxes">
294            <div class="box">
295               <div class="imgBX"> 
296                  <img src="./Resources/Images/box-1.png" alt="">
297               </div>
298               <div class="content">
299                  <h3>AI</h3>
300                  <P>Discover The Complete Range Of Artificial Intelligence Solutions.</P>
301               </div>
302            </div>
303            <div class="box">
304               <div class="imgBX">
305                  <img src="./Resources/Images/box-2.png" alt="">
306               </div>
307               <div class="content">
308                  <h3 class="frontend-title">Frontend Dev</h3>
309                  <p>Discover The Complete Range Of Frontend Solutions.</p>
310               </div>
311            </div>
312            <div class="box">
313               <div class="imgBX">
314                  <img src="./Resources/Images/box-3.png" alt="">
315               </div>
316               <div class="content">
317                  <h3>Microsoft systems</h3>
318                  <p>Discover The Complete Range Of Microsoft Solutions.</p>
319               </div>
320            </div>
321         </div>
322      </section>
323      <section class="quote-section">
324         <div class="quote-container">
325            <div class="quote">"</div>
326            <p class="p-quote">In coded, the progress of the topics and the exercises are really good. It's so nice to practice on good story told tasks. Also if you are stuck, it is nice to have a broad range of coders around in the peer groups  that you can get the answers you are looking for.</p>
327            <div class="quote-img">
328               <img src="./Resources/Images/person-img.png" alt="">
329            </div>
330            <div class="person-name">Peter Gangland </div>
331            <div class="person-role">Director of business dev at <span>Microsoft</span></div>
332         </div>
333      </section>
334      <footer>
335         <div id="contact">
336            <h2>
337            Contact us</h5>
338            <h5>coded@peers.com</h5>
339            <h5>831-867-5309</h5>
340         </div>
341         <div id="copyright">
342            <h5>@copyright coded Enterprises 2022</h5>
343         </div>
344      </footer>
345   </body>
346</html>

ANSWER

Answered 2022-Jan-15 at 19:43

For making your website responsive you need to use media queries. It's like you tell the browser how to style your website in different sizes. I think your problem with your sections might also get solved if you try to make your website responsive.

Source https://stackoverflow.com/questions/70724640

QUESTION

Pyttsx3 not working, process finished with exit code 0

Asked 2021-Dec-30 at 01:15

I am making an Artificial Intelligence (AI) assistant and I wrote this to make it speak:

1engine = pyttsx3.init('sapi5')
2voices = engine.getProperty('voices')
3engine.setProperty('voices', voices[0].id)
4
5
6def speak(audio):
7    engine.say(audio)
8    print(audio)
9    engine.runAndWait()
10

it does not speak and shows:

1engine = pyttsx3.init('sapi5')
2voices = engine.getProperty('voices')
3engine.setProperty('voices', voices[0].id)
4
5
6def speak(audio):
7    engine.say(audio)
8    print(audio)
9    engine.runAndWait()
10Process finished with exit code 0
11

how to fix it??

ANSWER

Answered 2021-Dec-30 at 01:15

You forgot to use the function. Use this code:

1engine = pyttsx3.init('sapi5')
2voices = engine.getProperty('voices')
3engine.setProperty('voices', voices[0].id)
4
5
6def speak(audio):
7    engine.say(audio)
8    print(audio)
9    engine.runAndWait()
10Process finished with exit code 0
11engine = pyttsx3.init('sapi5')
12voices = engine.getProperty('voices')
13engine.setProperty('voices', voices[0].id)
14
15
16def speak(audio):
17    engine.say(audio)
18    print(audio)
19    engine.runAndWait()
20
21
22# what you are missing
23# use your function to say something
24speak('Hello')
25

Hopefully, it works!

Source https://stackoverflow.com/questions/70517848

QUESTION

Expandable input and output in neural network

Asked 2021-Dec-18 at 14:30

What architecture/methods are used to make a neural network which can get infinite big input and/or return infinite big output?

I have an idea how to make infinite big output. I just need extra input neurons and after the first calculation send output (or part of it) to input neurons.

But I have no clue how to make extensible input. Maybe use multiple iterations, and plug output to input, and change the rest of the input neurons accordingly to the next portion of input data?

Artificial intelligence is new for me, so it is possible that I'm asking something that I don't want or something impossible. Please provide simple answers.

ANSWER

Answered 2021-Dec-17 at 20:52

The short answer is any RNN is capable of consuming, and producing, arbitrary length sequences. Depending on the structure of the data CNNs, Graph Nets etc. can also work with arbitrarily large inputs.

Source https://stackoverflow.com/questions/70392415

QUESTION

How to group elements of loop in a single list index

Asked 2021-Dec-01 at 15:36

I have a for loop in python which extracts data using beautifulsoup from a website and appends them into a list. I am trying to scrape tags from event names ex: AI, Big Data, ML etc.

My code:

1import requests
2from bs4 import BeautifulSoup
3
4URL = "https://aiml.events/"
5page = requests.get(URL)
6soup = BeautifulSoup(page.content, 'lxml')
7
8# Scrape Event Tags
9event_tags_list = []
10event_tag_div = soup.find_all('div', class_ = 'card-body')
11for event_div in event_tag_div:
12  event_span = event_div.find_all('span', class_  = 'badge badge-light badge-pill')
13  for event_tags in event_span:
14    print(event_tags.text)
15     
16

Tags I want to fetch

I am able to fetch the tags but they are all independent. I want to be able to group them together. Currently my list is like this:

1import requests
2from bs4 import BeautifulSoup
3
4URL = "https://aiml.events/"
5page = requests.get(URL)
6soup = BeautifulSoup(page.content, 'lxml')
7
8# Scrape Event Tags
9event_tags_list = []
10event_tag_div = soup.find_all('div', class_ = 'card-body')
11for event_div in event_tag_div:
12  event_span = event_div.find_all('span', class_  = 'badge badge-light badge-pill')
13  for event_tags in event_span:
14    print(event_tags.text)
15     
16tag_list = ['Artificial Intelligence', 'Artificial Intelligence','Machine Learning', 'Healthcare', 'Artificial Intelligence','Public Sector' ] 
17

My expectation:

1import requests
2from bs4 import BeautifulSoup
3
4URL = "https://aiml.events/"
5page = requests.get(URL)
6soup = BeautifulSoup(page.content, 'lxml')
7
8# Scrape Event Tags
9event_tags_list = []
10event_tag_div = soup.find_all('div', class_ = 'card-body')
11for event_div in event_tag_div:
12  event_span = event_div.find_all('span', class_  = 'badge badge-light badge-pill')
13  for event_tags in event_span:
14    print(event_tags.text)
15     
16tag_list = ['Artificial Intelligence', 'Artificial Intelligence','Machine Learning', 'Healthcare', 'Artificial Intelligence','Public Sector' ] 
17tag_list = ['Artificial Intelligence', 'Artificial Intelligence,Machine Learning, Healthcare', 'Artificial Intelligence,Public Sector' ] 
18

Any help is appreciated. Sorry if the question is too basic.

ANSWER

Answered 2021-Aug-30 at 15:45

Replace the inner loop with a generator that you join into a string.

1import requests
2from bs4 import BeautifulSoup
3
4URL = "https://aiml.events/"
5page = requests.get(URL)
6soup = BeautifulSoup(page.content, 'lxml')
7
8# Scrape Event Tags
9event_tags_list = []
10event_tag_div = soup.find_all('div', class_ = 'card-body')
11for event_div in event_tag_div:
12  event_span = event_div.find_all('span', class_  = 'badge badge-light badge-pill')
13  for event_tags in event_span:
14    print(event_tags.text)
15     
16tag_list = ['Artificial Intelligence', 'Artificial Intelligence','Machine Learning', 'Healthcare', 'Artificial Intelligence','Public Sector' ] 
17tag_list = ['Artificial Intelligence', 'Artificial Intelligence,Machine Learning, Healthcare', 'Artificial Intelligence,Public Sector' ] 
18for event_div in event_tag_div:
19    event_span = event_div.find_all('span', class_  = 'badge badge-light badge-pill')
20    event_tag_list.append(','.join(event_tag.text for event_tag in event_span))
21

Source https://stackoverflow.com/questions/68986779

QUESTION

Render image with json data | ReactJs

Asked 2021-Nov-19 at 18:00

So I'm trying to make the addition of project easier for me with a json data.

Basically I'm creating blocks of projects and each project comes with an image, however even when the id == to the name I gave the image, the image does not render. Is there is any option for that or should I just give up on json files ?


The reactjs code

1import Pdata from "../../api/projects.json";
2import p1 from "../../img/Project/PoleAnglais.png";
3import p2 from "../../img/Project/I-Art.png";
4import p3 from "../../img/Project/Hestia.png";
5import p4 from "../../img/Project/EvlV1.png";
6import p5 from "../../img/Project/Kelly.png";
7import p6 from "../../img/Project/EthLnyV2.png";
8import { Component } from "react";
9class Plist extends Component {
10  render() {
11    return (
12      <div
13        className="project-list"
14        data-aos="fade-right"
15        data-aos-duration="1200"
16      >
17        {Pdata.map((projectDetail, index) => {
18          return (
19            <div className="project-block">
20              <h2 className="project-title">{projectDetail.title}</h2>
21              <p className="date">{projectDetail.date}</p>
22              <p className="project-desc">{projectDetail.desc}</p>
23              <img src={projectDetail.id} alt="" />
24              <p className="madewith">made with {projectDetail.tags}</p>
25            </div>
26          );
27        })}
28      </div>
29    );
30  }
31}
32export default Plist;
33

The json data

1import Pdata from "../../api/projects.json";
2import p1 from "../../img/Project/PoleAnglais.png";
3import p2 from "../../img/Project/I-Art.png";
4import p3 from "../../img/Project/Hestia.png";
5import p4 from "../../img/Project/EvlV1.png";
6import p5 from "../../img/Project/Kelly.png";
7import p6 from "../../img/Project/EthLnyV2.png";
8import { Component } from "react";
9class Plist extends Component {
10  render() {
11    return (
12      <div
13        className="project-list"
14        data-aos="fade-right"
15        data-aos-duration="1200"
16      >
17        {Pdata.map((projectDetail, index) => {
18          return (
19            <div className="project-block">
20              <h2 className="project-title">{projectDetail.title}</h2>
21              <p className="date">{projectDetail.date}</p>
22              <p className="project-desc">{projectDetail.desc}</p>
23              <img src={projectDetail.id} alt="" />
24              <p className="madewith">made with {projectDetail.tags}</p>
25            </div>
26          );
27        })}
28      </div>
29    );
30  }
31}
32export default Plist;
33    [
34  {
35    "id": "p1",
36    "title": "Pole Anglais",
37    "date": "16/10/2019",
38    "desc": "This project was in association with Filip Zafirovski, my English teacher by the time who wanted students to get a source of inspiration by publishing articles and/or their work. It was my very first web project, and was kind of hard to pull off but I still enjoyed it.Since for the very first time i coded for a project and not myself.",
39    "tags": "Loads of crap"
40  },
41  {
42    "id": "p2",
43    "title": "Project I.Art",
44    "date": "3/07/2021",
45    "desc": "In France to go to college you have to get a diploma, which requires multiple exams to be validated. One of the subjects I had to do a presentation on was Art. I decided to create an idea around an Artificial Intelligence who would create art based on the likes and dislikes of the spectator. This panel is a website made for the occasion.",
46    "tags": "Html,Scss, & AOS librairie"
47  },
48  {
49    "id": "p3",
50    "title": "Hestia Real Estate",
51    "date": "18-26/10/2021",
52    "desc": "At the very start of my student life @hetic, They grouped student randomly to make a project. The subject of the project was to create an agency, a fake web-app and website that sells premium submarines to plus ultra rich people. For that project I designed the website of the agency, and the app for the complex.",
53    "tags": "Html & Scss"
54  },
55  {
56    "id": "p4",
57    "title": "EvL First Design",
58    "date": "30/10/2021",
59    "desc": "Before the design and dev of this portfolio, I had made a portfolio where I only putted my socials link. All of that because I had no idea of what to put on it. Even if I was satisfied with the first version it did not in any case represented the mood and emotion I wanted it to give. And so I gave birth to the actual design of the website on the 11/11/2021",
60    "tags": "Nextjs & Scss"
61  },
62  {
63    "id": "p5",
64    "title": "Kelly's Portfolio",
65    "date": "3/07/2021",
66    "desc": "Sometimes after arriving at my college, I met a freshly made friend who wanted to publish her portfolio. She knew how to design and do plenty others thing. To She didn't really like to code and was making her website with Wix. To which I proposed to remake her website by coding it myself.",
67    "tags": "VueJs & Scss"
68  },
69  {
70    "id": "p6",
71    "title": "EthLny V2",
72    "date": "11-12/11/2021",
73    "desc": "After doing the amazing portfolio of Kelly, I was kind of disappointed with my own. So I decided to remake a new design. Use a Random language, study the color psychology, searched a tagline. And TA-DA here it is, the website you're in right now is the result of 7 hours of researching, designing and coding and debugging.",
74    "tags": "ReactJs, Scss & AOS librairy"
75  }
76]
77

ANSWER

Answered 2021-Nov-19 at 17:53

I think the image is rendering but it is just too small to see

try adding width and height.

1import Pdata from "../../api/projects.json";
2import p1 from "../../img/Project/PoleAnglais.png";
3import p2 from "../../img/Project/I-Art.png";
4import p3 from "../../img/Project/Hestia.png";
5import p4 from "../../img/Project/EvlV1.png";
6import p5 from "../../img/Project/Kelly.png";
7import p6 from "../../img/Project/EthLnyV2.png";
8import { Component } from "react";
9class Plist extends Component {
10  render() {
11    return (
12      <div
13        className="project-list"
14        data-aos="fade-right"
15        data-aos-duration="1200"
16      >
17        {Pdata.map((projectDetail, index) => {
18          return (
19            <div className="project-block">
20              <h2 className="project-title">{projectDetail.title}</h2>
21              <p className="date">{projectDetail.date}</p>
22              <p className="project-desc">{projectDetail.desc}</p>
23              <img src={projectDetail.id} alt="" />
24              <p className="madewith">made with {projectDetail.tags}</p>
25            </div>
26          );
27        })}
28      </div>
29    );
30  }
31}
32export default Plist;
33    [
34  {
35    "id": "p1",
36    "title": "Pole Anglais",
37    "date": "16/10/2019",
38    "desc": "This project was in association with Filip Zafirovski, my English teacher by the time who wanted students to get a source of inspiration by publishing articles and/or their work. It was my very first web project, and was kind of hard to pull off but I still enjoyed it.Since for the very first time i coded for a project and not myself.",
39    "tags": "Loads of crap"
40  },
41  {
42    "id": "p2",
43    "title": "Project I.Art",
44    "date": "3/07/2021",
45    "desc": "In France to go to college you have to get a diploma, which requires multiple exams to be validated. One of the subjects I had to do a presentation on was Art. I decided to create an idea around an Artificial Intelligence who would create art based on the likes and dislikes of the spectator. This panel is a website made for the occasion.",
46    "tags": "Html,Scss, & AOS librairie"
47  },
48  {
49    "id": "p3",
50    "title": "Hestia Real Estate",
51    "date": "18-26/10/2021",
52    "desc": "At the very start of my student life @hetic, They grouped student randomly to make a project. The subject of the project was to create an agency, a fake web-app and website that sells premium submarines to plus ultra rich people. For that project I designed the website of the agency, and the app for the complex.",
53    "tags": "Html & Scss"
54  },
55  {
56    "id": "p4",
57    "title": "EvL First Design",
58    "date": "30/10/2021",
59    "desc": "Before the design and dev of this portfolio, I had made a portfolio where I only putted my socials link. All of that because I had no idea of what to put on it. Even if I was satisfied with the first version it did not in any case represented the mood and emotion I wanted it to give. And so I gave birth to the actual design of the website on the 11/11/2021",
60    "tags": "Nextjs & Scss"
61  },
62  {
63    "id": "p5",
64    "title": "Kelly's Portfolio",
65    "date": "3/07/2021",
66    "desc": "Sometimes after arriving at my college, I met a freshly made friend who wanted to publish her portfolio. She knew how to design and do plenty others thing. To She didn't really like to code and was making her website with Wix. To which I proposed to remake her website by coding it myself.",
67    "tags": "VueJs & Scss"
68  },
69  {
70    "id": "p6",
71    "title": "EthLny V2",
72    "date": "11-12/11/2021",
73    "desc": "After doing the amazing portfolio of Kelly, I was kind of disappointed with my own. So I decided to remake a new design. Use a Random language, study the color psychology, searched a tagline. And TA-DA here it is, the website you're in right now is the result of 7 hours of researching, designing and coding and debugging.",
74    "tags": "ReactJs, Scss & AOS librairy"
75  }
76]
77 <img style={{width: 200px, height: 200px}} src={projectDetail.id} alt="" />
78

Source https://stackoverflow.com/questions/70038925

QUESTION

Searching for a word/phrase in a string with all the possible approximations of the phrase

Asked 2021-Nov-18 at 17:53

Suppose I have the following string:

1string = 'machine learning ml is a type of artificial intelligence ai that allows software applications to become more accurate at predicting outcomes without being explicitly programmed to do so machine12 learning algorithms use historical data as input to predict new output values machines learning is good'
2

Further suppose that I have a tag defined as:

1string = 'machine learning ml is a type of artificial intelligence ai that allows software applications to become more accurate at predicting outcomes without being explicitly programmed to do so machine12 learning algorithms use historical data as input to predict new output values machines learning is good'
2tag = 'machine learning'
3

Now I wish to find the tag in my string. As you can see from my string there are three places that I have machine learning, one at the beginning of the string and one as machine12 learning and the last one as machines learning. I wish to find all of these and make an output list as

1string = 'machine learning ml is a type of artificial intelligence ai that allows software applications to become more accurate at predicting outcomes without being explicitly programmed to do so machine12 learning algorithms use historical data as input to predict new output values machines learning is good'
2tag = 'machine learning'
3['machine learning', 'machine12 learning', 'machines learning']
4

To be able to do this I was tried to tokenize my tag using nltk. That is

1string = 'machine learning ml is a type of artificial intelligence ai that allows software applications to become more accurate at predicting outcomes without being explicitly programmed to do so machine12 learning algorithms use historical data as input to predict new output values machines learning is good'
2tag = 'machine learning'
3['machine learning', 'machine12 learning', 'machines learning']
4tag_token = nltk.word_tokenize(tag)
5

I would then have ['machine','learning']. I would then search for tag[0].

I know that string.find(tag_token[0]) and data.rfind(tag_token[0]) would give the position of machine for the first and last finds, but what if I had more machine learning within the text (here we have 3)?

In that case I would not be able to extract them all. So my original idea to find all the occurrences of machine and then learning would have failed. I wished to use fuzzywuzzy to then analyze the ['machine learning', 'machine12 learning', 'machines learning'] with respect to the tag.

So my question is given then string I have, how can I search for the tag and its approximations and list them as follow?

1string = 'machine learning ml is a type of artificial intelligence ai that allows software applications to become more accurate at predicting outcomes without being explicitly programmed to do so machine12 learning algorithms use historical data as input to predict new output values machines learning is good'
2tag = 'machine learning'
3['machine learning', 'machine12 learning', 'machines learning']
4tag_token = nltk.word_tokenize(tag)
5['machine learning', 'machine12 learning', 'machines learning']
6

Update: I now know that I can do the followings:

1string = 'machine learning ml is a type of artificial intelligence ai that allows software applications to become more accurate at predicting outcomes without being explicitly programmed to do so machine12 learning algorithms use historical data as input to predict new output values machines learning is good'
2tag = 'machine learning'
3['machine learning', 'machine12 learning', 'machines learning']
4tag_token = nltk.word_tokenize(tag)
5['machine learning', 'machine12 learning', 'machines learning']
6pattern = re.compile(r"(machine[\s0-9]+learning)",re.IGNORECASE)
7matches = pattern.findall(data)
8#[output]: ['machine learning', 'machine12 learning']
9

also if I do

1string = 'machine learning ml is a type of artificial intelligence ai that allows software applications to become more accurate at predicting outcomes without being explicitly programmed to do so machine12 learning algorithms use historical data as input to predict new output values machines learning is good'
2tag = 'machine learning'
3['machine learning', 'machine12 learning', 'machines learning']
4tag_token = nltk.word_tokenize(tag)
5['machine learning', 'machine12 learning', 'machines learning']
6pattern = re.compile(r"(machine[\s0-9]+learning)",re.IGNORECASE)
7matches = pattern.findall(data)
8#[output]: ['machine learning', 'machine12 learning']
9pattern = re.compile(r"(machine[\sA-Za-z]+learning)",re.IGNORECASE)
10matches = pattern.findall(data)
11#[output]: ['machine learning', 'machines learning']
12

But certainly, this is not a generalizable solution as it stands. So I wonder if there is a smart way to search in such scenarios?

ANSWER

Answered 2021-Nov-18 at 17:53

Maybe use pattern like this (string\w*)?

1string = 'machine learning ml is a type of artificial intelligence ai that allows software applications to become more accurate at predicting outcomes without being explicitly programmed to do so machine12 learning algorithms use historical data as input to predict new output values machines learning is good'
2tag = 'machine learning'
3['machine learning', 'machine12 learning', 'machines learning']
4tag_token = nltk.word_tokenize(tag)
5['machine learning', 'machine12 learning', 'machines learning']
6pattern = re.compile(r"(machine[\s0-9]+learning)",re.IGNORECASE)
7matches = pattern.findall(data)
8#[output]: ['machine learning', 'machine12 learning']
9pattern = re.compile(r"(machine[\sA-Za-z]+learning)",re.IGNORECASE)
10matches = pattern.findall(data)
11#[output]: ['machine learning', 'machines learning']
12import re
13
14string = 'machine 12 learning ml is a type of artificial intelligence ai that allows software applications to become more accurate at predicting outcomes without being explicitly programmed to do so machine12 learning algorithms use historical data as input to predict new output values machines learning is good'
15
16tag_token=['machine','learning']
17
18pattern='('+''.join(e+'\w*\s+(?:\S*\s+)?' for e in tag_token)[:-14]+')'
19
20rgx=re.compile(pattern,re.IGNORECASE)
21rgx.findall(string)
22#output
23#['machine 12 learning', 'machine12 learning', 'machines learning']
24

it will be more difficult to find matches with the changing position of words in the tag

and this code will find all combinations from tag_token. E.g. machine s learning and machine learning and machine12 12 learning and learning machine ... Also you can create new string and new tag_token that containing more than 2 words. All combinations of these words will be found.

Example tag_token = ['1', '2', '3'] will match 1 2 3 and 1a 2 b 3 and 2b2 1sss 3 and 333 2tt 1

1string = 'machine learning ml is a type of artificial intelligence ai that allows software applications to become more accurate at predicting outcomes without being explicitly programmed to do so machine12 learning algorithms use historical data as input to predict new output values machines learning is good'
2tag = 'machine learning'
3['machine learning', 'machine12 learning', 'machines learning']
4tag_token = nltk.word_tokenize(tag)
5['machine learning', 'machine12 learning', 'machines learning']
6pattern = re.compile(r"(machine[\s0-9]+learning)",re.IGNORECASE)
7matches = pattern.findall(data)
8#[output]: ['machine learning', 'machine12 learning']
9pattern = re.compile(r"(machine[\sA-Za-z]+learning)",re.IGNORECASE)
10matches = pattern.findall(data)
11#[output]: ['machine learning', 'machines learning']
12import re
13
14string = 'machine 12 learning ml is a type of artificial intelligence ai that allows software applications to become more accurate at predicting outcomes without being explicitly programmed to do so machine12 learning algorithms use historical data as input to predict new output values machines learning is good'
15
16tag_token=['machine','learning']
17
18pattern='('+''.join(e+'\w*\s+(?:\S*\s+)?' for e in tag_token)[:-14]+')'
19
20rgx=re.compile(pattern,re.IGNORECASE)
21rgx.findall(string)
22#output
23#['machine 12 learning', 'machine12 learning', 'machines learning']
24import re
25import itertools
26
27string = 'machine 12 learning ml is a type of artificial intelligence ai that allows software applications to become more accurate at predicting outcomes without being explicitly programmed to do so machine12 learning algorithms use historical data as input to predict new output values machines learning is good. Learning machine can be used to train people. learning the machines is a great job'
28
29tag_token=['machine','learning']
30
31pattern='('
32for current_tag in itertools.permutations(tag_token, len(tag_token)):
33    pattern+=''.join(e+'\w*\s+(?:\S*\s+)?' for e in current_tag)[:-14]+'|'
34
35pattern=pattern.rstrip('|')+')'
36rgx=re.compile(pattern,re.IGNORECASE)
37
38rgx.findall(string)
39
40#output
41#['machine 12 learning', 'machine12 learning', 'machines learning', 'Learning machine', 'learning the machines']
42

Source https://stackoverflow.com/questions/69965741

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Artificial Intelligence

Tutorials and Learning Resources are not available at this moment for Artificial Intelligence

Share this Page

share link

Get latest updates on Artificial Intelligence