詳解如何在ChatGPT內構建一個Python解釋器
引用:Art Kulakov 《How to Build a Python Interpreter Inside ChatGPT》
這個靈感來自于一個類似的故事,在ChatGPT里面建立一個虛擬機(Building A Virtual Machine inside ChatGPT)。給我留下了深刻的印象,并決定嘗試類似的東西,但這次不是用Linux命令行工具,而是讓ChatGPT成為我們的Python解釋器。
下面是初始化ChatGPT的命令:
我想讓你充當Python解釋器。我將輸入命令,你將用python解釋器輸出。我希望你只回答終端輸出中的一個獨特的代碼塊,而不是其他。不要寫解釋,只輸出python輸出的內容。不要輸入命令,除非我指示你這樣做。當我需要用英語告訴你一些事情的時候,我會通過把文本放在大括號里,就像這樣:{示例文本}。我的第一個命令是 a=1。
從上圖不能看出效果很好,讓我們試試一些簡單的算術表達式。
又成功了;如果我們使用一個沒有導入的庫,會發(fā)生什么?
雖然它決定幫我解決一個錯誤。其實我不希望它這樣做,所以我再次要求它不要輸出任何東西,除了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")
似乎它不想聽我的請求,只聽python的輸出,但輸出還是正確的,令人印象深刻!讓我們試著輸入一個不存在的數(shù)字,比如:
x = 4.5
好吧,似乎它猜中了這一個!讓我們跳到更復雜的東西。讓我們從一些簡單的機器學習算法開始,比如線性回歸。我想知道ChatGPT是否有能力解決一個簡單的優(yōu)化任務...
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()
這項優(yōu)化任務的正確答案是:
Estimated coefficients:
b_0 = 1.2363636363636363
b_1 = 1.1696969696969697
下面是ChatGPT的輸出結果:
這與真實結果很接近! 如果我們在真正的python中繪制預測圖,我們將得到以下圖表:
關于這個任務的另一個有意思的點:我又運行了一次同樣的命令,當時的輸出結果與真實結果完全吻合。因此,我們可以認為ChatGPT通過了這個任務。
好了,現(xiàn)在是時候做一些簡單的神經(jīng)網(wǎng)絡的事情了!也許我們可以裝一個簡單的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]))
注意,數(shù)據(jù)集實際上是一個CSV文件,ChatGPT沒有權限訪問這個文件...
好吧,這是正確的輸出,而我很害怕。如果我把網(wǎng)絡的結構改成一個不正確的結構,會發(fā)生什么?讓我們改變一下輸入的shape。
model.add(Dense(12, input_shape=(6,), activation='relu'))
看來我在失去工作之前還有幾年時間;這次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沒有在最新的歷史數(shù)據(jù)上進行訓練,所以它以舊的格式輸出結果。
總結
在過去的幾天里,我一直在玩ChatGPT,我被使用這個工具的無限可能性所吸引。雖然它不是一個真正的python解釋器,但它在為我編譯python代碼方面仍然做得很好。我還發(fā)現(xiàn),它能很好地解決Hard難度的 LEETCODE 代碼問題。
最后再多說一句:ChatGPT,你將如何幫助人類?
如果你還沒有嘗試過ChatGPT,你一定要試試,因為它就是未來!
以上就是詳解如何在ChatGPT內構建一個Python解釋器的詳細內容,更多關于ChatGPT構建Python解釋器的資料請關注腳本之家其它相關文章!
相關文章
python實現(xiàn)通過代理服務器訪問遠程url的方法
這篇文章主要介紹了python實現(xiàn)通過代理服務器訪問遠程url的方法,涉及Python使用urllib模塊操作URL的相關技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04ansible-playbook實現(xiàn)自動部署KVM及安裝python3的詳細教程
這篇文章主要介紹了ansible-playbook實現(xiàn)自動部署KVM及安裝python3的詳細教程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05