天天看點

如何在ChatGPT内建構一個Python解釋器

作者:小牆神遊

這個靈感來自于一個類似的故事,在ChatGPT裡面建立一個虛拟機()。給我留下了深刻的印象,并決定嘗試類似的東西,但這次不是用Linux指令行工具,而是讓ChatGPT成為我們的Python解釋器。

下面是初始化ChatGPT的指令:

我想讓你充當Python解釋器。我将輸入指令,你将用python解釋器輸出。我希望你隻回答終端輸出中的一個獨特的代碼塊,而不是其他。不要寫解釋,隻輸出python輸出的内容。不要輸入指令,除非我訓示你這樣做。當我需要用英語告訴你一些事情的時候,我會通過把文本放在大括号裡,就像這樣:{示例文本}。我的第一個指令是 a=1。

如何在ChatGPT内建構一個Python解釋器

從上圖不能看出效果很好,讓我們試試一些簡單的算術表達式。

如何在ChatGPT内建構一個Python解釋器

又成功了;如果我們使用一個沒有導入的庫,會發生什麼?

如何在ChatGPT内建構一個Python解釋器

雖然它決定幫我解決一個錯誤。其實我不希望它這樣做,是以我再次要求它不要輸出任何東西,除了python代碼。

{隻列印python輸出,不列印任何注釋}。

順便說一下,ChatGPT有時能夠使用沒有導入的庫,但這次我很幸運,它列印出了錯誤資訊。很顯然我很确定ChatGPT能夠完成簡單的任務,讓我們試試更複雜的東西,讓它輸出二進制搜尋算法的結果。

# Binary Search in python


def binarySearch(array, x, low, high):

    # Repeat until the pointers low and high meet each other
    while low <= high:

        mid = low + (high - low)//2

        if array[mid] == x:
            return mid

        elif array[mid] < x:
            low = mid + 1

        else:
            high = mid - 1

    return -1


array = [3, 4, 5, 6, 7, 8, 9]
x = 4

result = binarySearch(array, x, 0, len(array)-1)

if result != -1:
    print("Element is present at index " + str(result))
else:
    print("Not found")
           
如何在ChatGPT内建構一個Python解釋器

似乎它不想聽我的請求,隻聽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的輸出結果:

如何在ChatGPT内建構一個Python解釋器

這與真實結果很接近! 如果我們在真正的python中繪制預測圖,我們将得到以下圖表:

如何在ChatGPT内建構一個Python解釋器

關于這個任務的另一個有意思的點:我又運作了一次同樣的指令,當時的輸出結果與真實結果完全吻合。是以,我們可以認為ChatGPT通過了這個任務。

好了,現在是時候做一些簡單的神經網絡的事情了!也許我們可以裝一個簡單的Keras模型。也許我們可以裝一個簡單的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沒有權限通路這個檔案...

如何在ChatGPT内建構一個Python解釋器

好吧,這是正确的輸出,而我很害怕。如果我把網絡的結構改成一個不正确的結構,會發生什麼?讓我們改變一下輸入的shape。

model.add(Dense(12, input_shape=(6,), activation='relu'))
           
如何在ChatGPT内建構一個Python解釋器

看來我在失去工作之前還有幾年時間;這次ChatGPT沒有了解這個技巧,仍然列印了輸出。讓我們做最後一項任務--在OpenAI裡面調用Huggingface怎麼樣?

正确的輸出:

[{'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代碼方面仍然做得很好。我還發現,它能很好地解決Hard難度的 LEETCODE 代碼問題。

最後再多說一句:ChatGPT,你将如何幫助人類?

如何在ChatGPT内建構一個Python解釋器

如果你還沒有嘗試過ChatGPT,你一定要試試,因為它就是未來!