相关文章推荐
紧张的红金鱼  ·  PHP ...·  4 周前    · 
大力的椰子  ·  从 Amazon RDS for ...·  1 年前    · 

人工智能:百度文心一言4.0会员版实测编程写代码能力

刚打开百度文心一言,看到4.0出来了,就充值了一个玩玩。以前是3.5版本的。3.5版本感觉不如chatgpt 3.5好用,测试一下4.0版的百度文心一言。

用我以前写的一人工智能代码,来测试一下试试

一、计算相对论光缩尺寸

提示词:使用numpy写一个相对论的尺缩效应函数,并做图


结果

import numpy as np  
import matplotlib.pyplot as plt  
# 光速 (m/s)  
c = 299792458  
# 静止时的长度 (m)  
L0 = 1  
def length_contraction(v):  
    """计算尺缩效应下的长度"""  
    return L0 * np.sqrt(1 - (v**2) / (c**2))  
# 速度范围 (m/s)  
v_range = np.linspace(0, 0.9 * c, 100)  
# 计算在各个速度下的长度  
contracted_lengths = length_contraction(v_range)  
plt.figure(figsize=(8, 5))  
plt.plot(v_range / c, contracted_lengths / L0, label="Length contraction")  
plt.xlabel("v/c")  
plt.ylabel("L/L0")  
plt.title("Length contraction effect")  
plt.legend()  
plt.grid(True)  
plt.show()

运行效果

二、复变函数保角映射

提示词:写一个Python程序,实现复变函数的保角映射,需要画出图形,写出实例程序

结果

import numpy as np  
import matplotlib.pyplot as plt  
# 定义复变函数  
def f(z):  
    return (z - 1) / (z + 1)  
# 定义网格坐标  
x = np.linspace(-2, 2, 100)  
y = np.linspace(-2, 2, 100)  
X, Y = np.meshgrid(x, y)  
# 计算复平面上的点  
Z = X + 1j * Y  
# 计算保角映射后的点  
W = f(Z)  
# 计算映射后的坐标  
u = np.real(W)  
v = np.imag(W)  
# 绘制原复平面上的网格  
plt.figure(figsize=(10, 5))  
plt.subplot(121)  
plt.title('Original Complex Plane')  
plt.xlabel('Re(z)')  
plt.ylabel('Im(z)')  
plt.grid(True)  
plt.axis('equal')  
# 绘制映射后的图形  
plt.subplot(122)  
plt.title('Conformal Mapping')  
plt.xlabel('Re(w)')  
plt.ylabel('Im(w)')  
plt.quiver(X, Y, u, v, color='r', units='xy', scale=1)  
plt.grid(True)  
plt.axis('equal')  
# 显示图形  
plt.tight_layout()  
plt.show()

这个能运行,还不错,以前的出现复杂的3.5版的,好多不能运行。

三、根据要求写高斯滤波程序

提示词:

使用python写一个高斯滤波程序,画图显示:原始信号,噪声信号,处理后信号,比较初始信号和处理后信号。我的信号程序定义如下:

# 生成原始信号 t = np.linspace(0, 1, 1000) 
#x = np.sin(2 * np.pi * 10 * t) + np.sin(2 * np.pi * 20 * t) 
x_initi = np.sin(2 * np.pi * 5 * t) + np.sin(2 * np.pi * 10 * t) 
  x = np.sin(2 * np.pi * 5 * t) + np.sin(2 * np.pi * 10 * t) + np.random.normal(0, 0.2, len(t)) 
# 加入噪声 
noise = np.random.normal(0, 0.5, len(x)) x_noise = x + noise

结果:

import numpy as np  
import matplotlib.pyplot as plt  
from scipy.ndimage import gaussian_filter  
# 生成原始信号  
t = np.linspace(0, 1, 1000)  
x_initi = np.sin(2 * np.pi * 5 * t) + np.sin(2 * np.pi * 10 * t)   
# 加入噪声  
x = np.sin(2 * np.pi * 5 * t) + np.sin(2 * np.pi * 10 * t) + np.random.normal(0, 0.2, len(t))  
noise = np.random.normal(0, 0.5, len(x))  
x_noise = x + noise  
# 使用高斯滤波器处理噪声信号  
sigma = 1 # 你可以根据需要调整sigma的值  
x_filtered = gaussian_filter(x_noise, sigma)  
plt.figure(figsize=(10, 6))  
# 绘制原始信号  
plt.subplot(2, 1, 1)  
plt.plot(t, x_initi, label='Original Signal')  
plt.legend()  
# 绘制噪声信号和处理后的信号  
plt.subplot(2, 1, 2)  
plt.plot(t, x_noise, label='Noise Signal')  
plt.plot(t, x_filtered, label='Filtered Signal')  
plt.legend()  
plt.tight_layout()  
plt.show()

结果

四、使用三维显示随机游走

提示词:使用python写一个3维显示的2D随机游走程序,并显示出来

生成代码结果:

import matplotlib.pyplot as plt  
import numpy as np  
def random_walk_2d(n_steps):  
    # 初始化位置  
    position = [0, 0]  
    # 存储游走路径  
    path = [[0, 0]]  
    for _ in range(n_steps):  
        # 随机选择方向:上、下、左、右  
        direction = np.random.choice([-1, 1], size=2)  
        # 更新位置  
        position = [position[0] + direction[0], position[1] + direction[1]]  
        # 将新位置添加到路径中  
        path.append(position)  
    return path  
def plot_random_walk(path):  
    # 绘制游走路径  
    plt.figure(figsize=(8, 8))  
    plt.scatter(*zip(*path), c=range(len(path)), cmap='viridis')  
    plt.plot(*zip(*path), color='black', linewidth=0.5)  
    plt.xlabel('X')  
    plt.ylabel('Y')  
    plt.title('2D Random Walk')  
    plt.show()  
if __name__ == '__main__':  
    n_steps = 1000  # 设置游走步数  
    path = random_walk_2d(n_steps)  
    plot_random_walk(path)

结果:

结果能运行,但问题是没有使用3D函数来表示。

追加了一个提示词:把上面的程序改成在3维中显示


结果:

import matplotlib.pyplot as plt  
import numpy as np  
def random_walk_3d(n_steps):  
    # 初始化位置  
    position = [0, 0, 0]  
    # 存储游走路径  
    path = [[0, 0, 0]]  
    for _ in range(n_steps):  
        # 随机选择方向:上、下、左、右、前、后  
        direction = np.random.choice([-1, 1], size=3)  
        # 更新位置  
        position = [position[0] + direction[0], position[1] + direction[1], position[2] + direction[2]]  
        # 将新位置添加到路径中  
        path.append(position)  
    return path  
def plot_random_walk_3d(path):  
    # 绘制游走路径  
    fig = plt.figure()  
    ax = fig.add_subplot(111, projection='3d')  
    ax.scatter(*zip(*path), c=range(len(path)), cmap='viridis')  
    ax.plot(*zip(*path), color='black', linewidth=0.5)  
    ax.set_xlabel('X')  
    ax.set_ylabel('Y')  
    ax.set_zlabel('Z')  
    ax.set_title('3D Random Walk')  
    plt.show()  
if __name__ == '__main__':  
    n_steps = 1000  # 设置游走步数  
    path = random_walk_3d(n_steps)  
    plot_random_walk_3d(path)
 

显示结果

可见基本上可用。

五、使用t-SNE降维

提示词:

写一个t-SNE显示程序,使用下面的程序:
# 加载手写数字数据集
digits = load_digits()
X = digits.data
y = digits.target
# 使用t-SNE 算法进行降维

结果:

import matplotlib.pyplot as plt  
from sklearn import datasets  
from sklearn.manifold import TSNE  
# 加载手写数字数据集  
digits = datasets.load_digits()  
X = digits.data  
y = digits.target  
# 使用t-SNE算法进行降维  
tsne = TSNE(n_components=2, random_state=0)  
X_2d = tsne.fit_transform(X)  
# 可视化结果  
plt.figure(figsize=(6, 5))  
colors = 'r', 'g', 'b', 'c', 'm', 'y', 'k', 'w', 'orange', 'purple'  
for i, c, label in zip(range(10), colors, digits.target_names):  
    plt.scatter(X_2d[y == i, 0], X_2d[y == i, 1], c=c, label=label)  
plt.legend()  
plt.show()

显示结果

六、实现一个蚂群优化算法解决TSP旅行商问题

提示词:使用python写一个蚁群优化算法实例,并显示出运行后的结果

结果:

import numpy as np  
import random  
import matplotlib.pyplot as plt  
class AntColonyOptimization:  
    def __init__(self, distances, n_ants, n_best, n_iterations, decay, alpha=1, beta=1):  
        Args:  
            distances (2D numpy.ndarray): Square matrix of distances. Diagonal is assumed to be np.inf.  
            n_ants (int): Number of ants running per iteration  
            n_best (int): Number of best ants who deposit pheromone  
            n_iterations (int): Number of iterations  
            decay (float): Rate it which pheromone decays. The pheromone value is multiplied by decay, so 0.95 will lead to decay, 0.5 to much faster decay.  
            alpha (int or float): exponenet on pheromone, higher alpha gives pheromone more weight. Default=1  
            beta (int or float): exponent on distance, higher beta gives distance more weight. Default=1  
        self.distances  = distances  
        self.pheromone = np.ones(self.distances.shape) / len(distances)  
        self.all_inds = range(len(distances))  
        self.n_ants = n_ants  
        self.n_best = n_best  
        self.n_iterations = n_iterations  
        self.decay = decay  
        self.alpha = alpha  
        self.beta = beta  
    def run(self):  
        shortest_path = None  
        all_time_shortest_path = ("placeholder", np.inf)  
        for i in range(self.n_iterations):  
            all_paths = self.gen_all_paths()  
            self.spread_pheronome(all_paths, self.n_best, shortest_path=shortest_path)  
            shortest_path = min(all_paths, key=lambda x: x[1])  
            print (f"Shortest path found in iteration {i+1}: {shortest_path}")  
            if shortest_path[1] < all_time_shortest_path[1]:  
                all_time_shortest_path = shortest_path              
            self.pheromone * self.decay              
        return all_time_shortest_path  
    def spread_pheronome(self, all_paths, n_best, shortest_path):  
        sorted_paths = sorted(all_paths, key=lambda x: x[1])  
        for path, dist in sorted_paths[:n_best]:  
            for move in path:  
                self.pheromone[move] += 1.0 / self.distances[move]  
    def gen_path_dist(self, path):  
        total_dist = 0  
        for ele in path:  
            total_dist += self.distances[ele]  
        return total_dist  
    def gen_all_paths(self):  
        all_paths = []  
        for i in range(self.n_ants):  
            path = self.gen_path(0)  
            all_paths.append((path, self.gen_path_dist(path)))  
        return all_paths  
    def gen_path(self, start):  
        path = []  
        visited = set()  
        visited.add(start)  
        prev = start  
        for i in range(len(self.distances) - 1):  
            move = self.pick_move(self.pheromone[prev], self.distances[prev], visited)  
            path.append((prev, move))  
            prev = move  
            visited.add(move)  
        path.append((prev, start)) # going back to where we started      
        return path  
    def pick_move(self, pheromone, dist, visited):  
        pheromone = np.copy(pheromone)  
        pheromone[list(visited)] = 0  
        row = pheromone ** self.alpha * (( 1.0 / dist) ** self.beta)  
        norm_row = row / row.sum()  
        move = np.random.choice(self.all_inds, 1, p=norm_row)[0]  
        return move  
# 继续前面的代码  
    def plot_path(self, path):  
        x, y = zip(*path)  
        plt.plot(x, y, 'r-')  
        plt.title('Ant Colony Optimization Result')  
        plt.xlabel('City Index')  
        plt.ylabel('Distance')  
        plt.show()  
# 在主函数运行蚁群优化算法并显示结果  
if __name__ == "__main__":  
    # 我们这里假设有一个10x10的距离矩阵,实际应用中你需要将其替换为实际的距离矩阵  
    distances = np.random.rand(10, 10)  
    np.fill_diagonal(distances, np.inf)  
    aco = AntColonyOptimization(distances, n_ants=10, n_best=2, n_iterations=100, decay=0.95)  
    shortest_path = aco.run()  
    print("Shortest path: ", shortest_path)  
    aco.plot_path(shortest_path[0])

中间没有完全显示,打了一个“继续后面的显示”。运行结果

七、写一个FP-Growth 算法实例


提示词:写一个FP-Growth 算法实例,并显示出来画图结果

结果:

import pyfpgrowth  
import matplotlib.pyplot as plt  
# 输入数据集(以列表的形式表示事务)  
dataset = [['apple', 'banana', 'cherry'],  
           ['apple', 'banana'],  
           ['banana', 'cherry'],  
           ['apple', 'cherry'],  
           ['apple', 'banana', 'cherry'],  
           ['orange']]  
# 使用pyfpgrowth库找出频繁项集  
frequent_itemsets = pyfpgrowth.find_frequent_patterns(dataset, 2)  
rules = pyfpgrowth.generate_association_rules(frequent_itemsets, confidence=0.7)  
# 打印频繁项集和关联规则  
print("频繁项集:")  
for itemset, support in frequent_itemsets.items():  
    print(f"{itemset} - 支持度: {support}")  
print("\n关联规则:")  
for rule, confidence in rules.items():  
    premise, conclusion = rule  
    print(f"{premise} => {conclusion} - 置信度: {confidence}")  
# 绘制频繁项集的柱状图  
plt.figure(figsize=(10, 5))  
plt.bar(frequent_itemsets.keys(), frequent_itemsets.values(), color='blue')  
plt.xlabel('频繁项集')  
plt.ylabel('支持度')  
plt.title('FP-Growth算法结果')  
plt.show()
 

运行结果,出现错误:

Traceback (most recent call last):
File "d:\myprg2023\pyfpgrowth_test.py", line 14, in <module>
rules = pyfpgrowth.generate_association_rules(frequent_itemsets, confidence=0.7)
TypeError: generate_association_rules() got an unexpected keyword argument 'confidence'

可能我是安装的最新版本不兼容,把错误发给它,也没能解决,就不弄了。

八、Q 学习(Q-Learning)算法实例

提示词:写一个Q 学习(Q-Learning)算法实例

生成代码:

import numpy as np  
# 初始化迷宫  
maze = np.array([  
    [0, 0, 0, 0, 0, 0],  
    [0, 1, 1, 0, 1, 0],  
    [0, 0, 0, 1, 0, 0],  
    [0, 1, 1, 1, 1, 0],  
    [0, 0, 0, 1, 0, 2]  
# 初始化Q表格  
Q = np.zeros((5, 6, 4))  
# 参数设置  
gamma = 0.8  # 折扣因子  
alpha = 0.5  # 学习率  
epsilon = 0.1  # ε-贪婪策略的ε  
# 动作映射  
actions = ['up', 'right', 'down', 'left']  
# 获取可用动作  
def available_actions(state):  
    return [actions[i] for i in range(4) if maze[state[0], state[1], i] == 0]  
# ε-贪婪策略选择动作  
def select_action(state, epsilon):  
    if np.random.uniform() < epsilon:  
        return np.random.choice(available_actions(state))  
    else:  
        return max(available_actions(state), key=lambda action: Q[state[0], state[1], actions.index(action)])  
# 更新Q值  
def update_Q(state, action, reward, next_state):  
    Q[state[0], state[1], actions.index(action)] = (1 - alpha) * Q[state[0], state[1], actions.index(action)] + alpha * (reward + gamma * max(Q[next_state[0], next_state[1], :]))  
# Q学习算法主体  
def Q_learning():  
    for episode in range(100):  
        # 用于记录本episode的路径  
        path = []  
        state = (0, 0)  # 初始状态  
        while state != (4, 5):  # 终态为(4,5)  
            path.append(state)  # 将当前状态添加到路径中  
            action = select_action(state, epsilon)  # 选择动作 
            next_state = (state[0] + maze[state[0], state[1], actions.index('up')], state[1] + maze[state[0], state[1], actions.index('right')])  # 执行动作,获取下一个状态  
            reward = maze[next_state[0], next_state[1]]  # 获取奖励  
            update_Q(state, action, reward, next_state)  # 更新Q值  
            state = next_state  # 进入下一个状态  
        # 打印Q表格  
        print("Q Table:")  
        for i in range(5):  
            for j in range(6):  
                print(Q[i, j, :])  
        # 打印路径  
        print("Path:")  
        for state in path:  
            print(state)  
        print("Episode finished.")
Q_learning()

这个需要显示多个,继续显示,但最后还是运行错误

Traceback (most recent call last):
File "d:\myprg2023\Q_learning.py", line 68, in <module>
Q_learning()
File "d:\myprg2023\Q_learning.py", line 47, in Q_learning
action = select_action(state, epsilon) # 选择动作
File "d:\myprg2023\Q_learning.py", line 32, in select_action
return max(available_actions(state), key=lambda action: Q[state[0], state[1], actions.index(action)])
File "d:\myprg2023\Q_learning.py", line 25, in available_actions
return [actions[i] for i in range(4) if maze[state[0], state[1], i] == 0]
File "d:\myprg2023\Q_learning.py", line 25, in <listcomp>
return [actions[i] for i in range(4) if maze[state[0], state[1], i] == 0]
IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed

我把错误发给它的提示修改这一条:

return [actions[i] for i in range(4) if maze[state[0], state[1]] == 0]  

但还是出现错误,后面就不试了。

九、使用对数函数能降低计算

提示词:使用对数函数能降低计算时,写出一些python实例

结果:

确实,对数函数可以降低某些计算的复杂性。下面是一些使用Python中对数函数的实例:


实例1:计算复利

在金融和经济学中,复利是一个常见的概念。如果你有一个初始的投资金额,每年以一定的百分比增长,那么使用对数函数可以很容易地计算经过多年后的总金额。

import math  
# 初始投资金额  
initial_investment = 1000  
# 年利率  
annual_interest_rate = 0.05  
# 投资年数  
years = 10  
# 计算总金额  
final_amount = initial_investment * math.pow((1 + annual_interest_rate), years)  
print("Final amount after {} years: ${:.2f}".format(years, final_amount))

实例2:计算声音的强度

声音的强度与其感知的响度不是线性关系,而是对数关系。这就是为什么我们使用分贝来测量声音强度。

# 声音的强度(以瓦特为单位)  
sound_intensity = 1000  
# 转换为分贝  
decibels = 10 * math.log10(sound_intensity)  
print("Sound intensity in decibels: {:.2f} dB".format(decibels))

实例3:计算数据的熵

在信息论中,熵是衡量数据的不确定性或随机性的度量。熵的计算涉及到对数函数。

import numpy as np  
# 数据的概率分布  
probabilities = [0.1, 0.2, 0.3, 0.4]  
# 计算熵  
entropy = -np.sum(np.array(probabilities) * np.log2(np.array(probabilities)))  
print("Entropy: {:.2f} bits".format(entropy))

应该基本上正确

十、写一个四元数实现旋转角度的程序

提示词:使用Python定义一个四元数,并实现旋转向量的程序,同时画图,标出旋转前的向量的位置和旋转后的位置

结果:

import numpy as np  
import matplotlib.pyplot as plt  
class Quaternion:  
    def __init__(self, w, i, j, k):  
        self.w = w  
        self.i = i  
        self.j = j  
        self.k = k  
    def __mul__(self, other):  
        w = self.w*other.w - self.i*other.i - self.j*other.j - self.k*other.k  
        i = self.w*other.i + self.i*other.w + self.j*other.k - self.k*other.j  
        j = self.w*other.j - self.i*other.k + self.j*other.w + self.k*other.i  
        k = self.w*other.k + self.i*other.j - self.j*other.i + self.k*other.w  
        return Quaternion(w, i, j, k)  
    def rotate_vector(self, vector):  
        q_vector = Quaternion(0, vector[0], vector[1], vector[2])  
        q_conjugate = Quaternion(self.w, -self.i, -self.j, -self.k)  
        rotated = self * q_vector * q_conjugate  
        return np.array([rotated.i, rotated.j, rotated.k])  
# 创建一个四元数,用于旋转  
q = Quaternion(np.cos(np.radians(45)), np.sin(np.radians(45)), 0, 0)  
# 创建一个向量  
v = np.array([1, 1, 0])  
# 通过四元数旋转向量  
v_rotated = q.rotate_vector(v)