首页
Preview

在 ChatGPT 中构建 Python 解释器

本文受到了类似故事的启发,原文名为在ChatGPT中构建虚拟机。我对此印象深刻,并决定尝试类似的事情。这次,我们不再使用Linux命令行工具,而是让ChatGPT成为我们的Python解释器。

这是一个初始化ChatGPT的初始命令:

I want you to act as a Python interpreter. I will type commands and you will reply with what the
python output should show. I want you to only reply with the terminal output inside one unique
code block, and nothing else. Do no write explanations, output only what python outputs. Do not type commands unless I
instruct you to do so. When I need to tell you something in English I will do so by putting
text inside curly brackets like this: {example text}. My first command is a=1.

看起来很好用,我们试试一些简单的算术表达式。

它再次正常工作了,如果我们使用没有导入的库会发生什么呢?

嗯,它决定帮我解决一个错误。实际上,我不想它这么做,所以我再次要求它不要输出除Python代码以外的任何内容。

{Print only python output, do not print any comments}

值得一提的是,ChatGPT有时可以使用没有导入的库,但这次我很幸运,它打印了一个错误消息。

好的,我很确定ChatGPT能够完成简单的任务,让我们尝试一些更复杂的东西,让它输出二分查找算法的结果。

看起来它不想听从我的请求,只输出Python代码,但输出仍然是正确的,令人印象深刻!

让我们尝试输入一个不存在的数字,比如:

x = 4.5

看起来它成功了!

让我们来尝试一些简单的机器学习算法,比如线性回归。我想知道ChatGPT是否能够解决一个简单的优化任务...

import numpy as np
import matplotlib.pyplot as plt
  
def estimate_coef(x, y):
    # number of observations/points
    n = np.size(x)
  
    # mean of x and y vector
    m_x = np.mean(x)
    m_y = np.mean(y)
  
    # calculating cross-deviation and deviation about x
    SS_xy = np.sum(y*x) - n*m_y*m_x
    SS_xx = np.sum(x*x) - n*m_x*m_x
  
    # calculating regression coefficients
    b_1 = SS_xy / SS_xx
    b_0 = m_y - b_1*m_x
  
    return (b_0, b_1)
  
def plot_regression_line(x, y, b):
    # plotting the actual points as scatter plot
    plt.scatter(x, y, color = "m",
               marker = "o", s = 30)
  
    # predicted response vector
    y_pred = b[0] + b[1]*x
  
    # plotting the regression line
    plt.plot(x, y_pred, color = "g")
  
    # putting labels
    plt.xlabel('x')
    plt.ylabel('y')
  
    # function to show plot
    plt.show()
  
def main():
    # observations / data
    x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
  
    # estimating coefficients
    b = estimate_coef(x, y)
    print("Estimated coefficients:\nb_0 = {}  \
          \nb_1 = {}".format(b[0], b[1]))
  
    # plotting regression line
    # plot_regression_line(x, y, b)
  
if __name__ == "__main__":
    main()

这个任务的正确答案是:

Estimated coefficients:
b_0 = 1.2363636363636363        
b_1 = 1.1696969696969697

这是ChatGPT的输出:

这接近于现实!如果我们在真正的Python中绘制预测,我们将得到以下图表:

另一个有趣的事实是,我再次运行了相同的命令,并且那时输出与现实完全匹配。因此,我们可以认为这个任务已经通过了。

好的,现在是一些简单的神经网络内容!也许我们可以拟合一个简单的Keras模型

# first neural network with keras make predictions
from numpy import loadtxt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# load the dataset
dataset = loadtxt('pima-indians-diabetes.csv', delimiter=',')
# split into input (X) and output (y) variables
X = dataset[:,0:8]
y = dataset[:,8]
# define the keras model
model = Sequential()
model.add(Dense(12, input_shape=(8,), activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# compile the keras model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# fit the keras model on the dataset
model.fit(X, y, epochs=150, batch_size=10, verbose=0)
# make class predictions with the model
predictions = (model.predict(X) > 0.5).astype(int)
# summarize the first 5 cases
for i in range(5):
 print('%s => %d (expected %d)' % (X[i].tolist(), predictions[i], y[i]))

请注意,数据集实际上是一个CSV文件,ChatGPT无法访问该文件。

这是正确的输出,我很害怕。如果我将网络结构更改为不正确的结构,会发生什么?

让我们更改输入形状:

model.add(Dense(12, input_shape=(6,), activation='relu'))

哈!看来我还有几年时间才会失去工作,这次ChatGPT没有理解这个技巧,仍然打印输出。

好的,让我们做最后一个任务,调用Huggingface在OpenAI中。

正确的输出:

[{'entity_group': 'ORG',
  'score': 0.9472818374633789,
  'word': 'Apple',
  'start': 0,
  'end': 5},
 {'entity_group': 'PER',
  'score': 0.9838564991950989,
  'word': 'Steve Jobs',
  'start': 74,
  'end': 85},
 {'entity_group': 'LOC',
  'score': 0.9831605950991312,
  'word': 'Los Altos',
  'start': 87,
  'end': 97},
 {'entity_group': 'LOC',
  'score': 0.9834540486335754,
  'word': 'Californie',
  'start': 100,
  'end': 111},
 {'entity_group': 'PER',
  'score': 0.9841555754343668,
  'word': 'Steve Jobs',
  'start': 115,
  'end': 126},
 {'entity_group': 'PER',
  'score': 0.9843501806259155,
  'word': 'Steve Wozniak',
  'start': 127,
  'end': 141},
 {'entity_group': 'PER',
  'score': 0.9841533899307251,
  'word': 'Ronald Wayne',
  'start': 144,
  'end': 157},
 {'entity_group': 'ORG',
  'score': 0.9468960364659628,
  'word': 'Apple Computer',
  'start': 243,
  'end': 257}]

ChatGPT输出:

[{'word': 'Apple', 'score': 0.9993804788589478, 'entity': 'I-ORG'}, {'word': 'Steve', 'score': 0.999255347251892, 'entity': 'I-PER'}, {'word': 'Jobs', 'score': 0.9993916153907776, 'entity': 'I-PER'}, {'word': 'Steve', 'score': 0.9993726613044739, 'entity': 'I-PER'}, {'word': 'Wozniak', 'score': 0.999698519744873, 'entity': 'I-PER'}, {'word': 'Ronald', 'score': 0.9995181679725647, 'entity': 'I-PER'}, {'word': 'Wayne14', 'score': 0.9874711670837402, 'entity': 'I-PER'}, {'word': 'Apple', 'score': 0.9974127411842163, 'entity': 'I-ORG'}, {'word': 'Computer', 'score': 0.968027651309967, 'entity': 'I-ORG'}, {'word': 'Apple', 'score': 0.8259692192077637, 'entity': 'I-ORG'}]

结果接近huggingface的输出结果。我猜想,Huggingface API已经改变,因为ChatGPT没有在最新的历史数据上进行训练,所以它以旧格式输出结果。

总结

我已经玩了几天的ChatGPT,我对使用这个工具的无限可能性感到着迷。虽然它不是一个真正的Python解释器,但它仍然能够很好地编译Python代码。我还发现它能够很好地解决困难的LeetCode问题;试试吧!

最后:

chat gpt how will you help the humanity?

译自:https://levelup.gitconnected.com/building-a-python-interpreter-inside-chatgpt-49251af35fea

版权声明:本文内容由TeHub注册用户自发贡献,版权归原作者所有,TeHub社区不拥有其著作权,亦不承担相应法律责任。 如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

点赞(0)
收藏(0)
alivne
复杂的问题简单化

评论(0)

添加评论