鱼C论坛

 找回密码
 立即注册
查看: 392|回复: 3

[C\C++] 请改写成Python,"不到 100 行代码,用 C++ 创建生成式 AI 模型?"

[复制链接]
发表于 2024-5-21 08:35:23 | 显示全部楼层 |阅读模式
5鱼币
不到 100 行代码,用 C++ 创建生成式 AI 模型?https://blog.csdn.net/csdnsevenn ... 1000.2115.3001.5927  ,   https://learncplusplus.org/how-t ... ative-ai-code-in-c/
谁给改写成Python,帮助理解。
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <random>
 
std::random_device rnd;
std::mt19937 generator(rnd());
 
class GenerativeAI
{
 private:
    std::map<std::string, std::vector<std::string>> wordRel; // map to world releation
 
 public:
    // Method to learn word relations from a given string
    void learn_fromstring(const std::string &sentence)
    {
        std::istringstream iss(sentence);
        std::vector<std::string> tokens{ std::istream_iterator<std::string>{iss},
                                         std::istream_iterator<std::string>{} };
 
        for (size_t i = 0; i < tokens.size() - 1; ++i) {
            wordRel[tokens[i]].push_back(tokens[i + 1]);
        }
    }
 
    // Method to generate a sequence of words based on learned relations
    std::string sentence_generator(const std::string &startWord, int length)
    {
        std::string currentWord = startWord;
        std::string sequence = currentWord;
 
        for (int i = 0; i < length - 1; ++i)
        {
            if (wordRel.find(currentWord) == wordRel.end()) break;
 
            std::vector<std::string> nextWords = wordRel[currentWord];
            std::uniform_int_distribution<int> distribution(0, nextWords.size() - 1);
            currentWord = nextWords[distribution(generator)];
            sequence += " " + currentWord;
        }
 
        return sequence;
    }
 
    // print the word releations
    void print_word_relations()
    {
        std::cout << "Word Relations:" << std::endl;
        for (const auto &pair : wordRel)
        {
            std::cout << pair.first << ":";
            for (const auto &word : pair.second)
            {
                std::cout << " " << word;
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }
};
 
int main()
{
    GenerativeAI generator;
 
 // Learn from sentences
    generator.learn_fromstring("I am generative AI test example");
    generator.learn_fromstring("I was a code");
    generator.learn_fromstring("I can develop applications in C++");
    generator.learn_fromstring("I have a generative code example");
    generator.learn_fromstring("I should generate different sentences");
    generator.learn_fromstring("I am easy with LearnCPlusPlus.org");
 
 // Print word releations that learnt
    generator.print_word_relations();
 
 // Generate new sentences
    for (int i = 0; i < 10; ++i)
    {
        std::cout << "Generated Sentence " << i + 1 << ": " << generator.sentence_generator( "I", 4+rnd()%2 ) << std::endl;
    }
 
    system("pause");
    return 0;
}

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-5-21 15:29:19 | 显示全部楼层
下面是将上述C++代码转换为Python的版本,实现了类似的生成式AI模型功能:

```python
import random
from collections import defaultdict

class GenerativeAI:
    def __init__(self):
        self.word_relations = defaultdict(list)

    def learn_from_string(self, sentence):
        tokens = sentence.split()
        for i in range(len(tokens) - 1):
            self.word_relations[tokens[i]].append(tokens[i + 1])

    def sentence_generator(self, start_word, length):
        current_word = start_word
        sequence = current_word

        for _ in range(length - 1):
            if current_word not in self.word_relations:
                break

            next_words = self.word_relations[current_word]
            current_word = random.choice(next_words)
            sequence += " " + current_word

        return sequence

    def print_word_relations(self):
        print("Word Relations:")
        for key, value in self.word_relations.items():
            print(f"{key}: {' '.join(value)}")
        print()

def main():
    generator = GenerativeAI()

    # Learn from sentences
    sentences = [
        "I am generative AI test example",
        "I was a code",
        "I can develop applications in C++",
        "I have a generative code example",
        "I should generate different sentences",
        "I am easy with LearnCPlusPlus.org"
    ]
    for sentence in sentences:
        generator.learn_from_string(sentence)

    # Print word relations that learnt
    generator.print_word_relations()

    # Generate new sentences
    for i in range(10):
        length = 4 + random.randint(0, 1)
        print(f"Generated Sentence {i + 1}: {generator.sentence_generator('I', length)}")

if __name__ == "__main__":
    main()
```

这段Python代码实现了与C++版本相似的功能,包括学习句子中的单词关系、打印这些关系以及基于学到的关系生成新的句子序列。Python代码中使用了`defaultdict`来简化单词关系的存储和处理逻辑,并且使用了内置的`random.choice()`函数来随机选择下一个单词。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-5-28 16:23:33 | 显示全部楼层
import random
from collections import defaultdict

class GenerativeAI:
    def __init__(self):
        self.wordRel = defaultdict(list)  # 存储单词关系的映射

    # 从给定的字符串中学习单词关系的方法
    def learn_fromstring(self, sentence):
        tokens = sentence.split()
        for i in range(len(tokens) - 1):
            self.wordRel[tokens[i]].append(tokens[i + 1])

    # 基于学习到的关系生成单词序列的方法
    def sentence_generator(self, start_word, length):
        current_word = start_word
        sequence = current_word

        for _ in range(length - 1):
            if current_word not in self.wordRel:
                break
            next_words = self.wordRel[current_word]
            current_word = random.choice(next_words)
            sequence += " " + current_word

        return sequence

    # 打印单词关系
    def print_word_relations(self):
        print("单词关系:")
        for key, value in self.wordRel.items():
            print(f"{key}: {' '.join(value)}")
        print()

def main():
    generator = GenerativeAI()

    # 从句子中学习
    generator.learn_fromstring("我 是 生成 式 AI 测试 例子")
    generator.learn_fromstring("我 是 一段 代码")
    generator.learn_fromstring("我 可以 开发 应用 在 Python 中")
    generator.learn_fromstring("我 有 一个 生成 式 代码 例子")
    generator.learn_fromstring("我 应该 生成 不同 的 句子")
    generator.learn_fromstring("我 在 LearnPython.org 学得 很 容易")

    # 打印学习到的单词关系
    generator.print_word_relations()

    # 生成新的句子
    for i in range(10):
        sentence = generator.sentence_generator("我", 4 + random.randint(0, 1))
        print(f"生成的句子 {i + 1}: {sentence}")

if __name__ == "__main__":
    main()
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-5-28 16:24:43 | 显示全部楼层
import random
from collections import defaultdict

class GenerativeAI:
    def __init__(self):
        self.wordRel = defaultdict(list)  # 存储单词关系的映射

    # 从给定的字符串中学习单词关系的方法
    def learn_fromstring(self, sentence):
        tokens = sentence.split()
        for i in range(len(tokens) - 1):
            self.wordRel[tokens[i]].append(tokens[i + 1])

    # 基于学习到的关系生成单词序列的方法
    def sentence_generator(self, start_word, length):
        current_word = start_word
        sequence = current_word

        for _ in range(length - 1):
            if current_word not in self.wordRel:
                break
            next_words = self.wordRel[current_word]
            current_word = random.choice(next_words)
            sequence += " " + current_word

        return sequence

    # 打印单词关系
    def print_word_relations(self):
        print("单词关系:")
        for key, value in self.wordRel.items():
            print(f"{key}: {' '.join(value)}")
        print()

def main():
    generator = GenerativeAI()

    # 从句子中学习
    generator.learn_fromstring("我 是 生成 式 AI 测试 例子")
    generator.learn_fromstring("我 是 一段 代码")
    generator.learn_fromstring("我 可以 开发 应用 在 Python 中")
    generator.learn_fromstring("我 有 一个 生成 式 代码 例子")
    generator.learn_fromstring("我 应该 生成 不同 的 句子")
    generator.learn_fromstring("我 在 LearnPython.org 学得 很 容易")

    # 打印学习到的单词关系
    generator.print_word_relations()

    # 生成新的句子
    for i in range(10):
        sentence = generator.sentence_generator("我", 4 + random.randint(0, 1))
        print(f"生成的句子 {i + 1}: {sentence}")

if __name__ == "__main__":
    main()
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-7-27 11:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表