你肯定想學習的頂級Python項目(附代碼)

你肯定想學習的頂級Python項目(附代碼)


作者:Anirudh Rao

翻譯:張睿毅

校對:王婷

本文約4600字,建議閱讀20分鐘。

本文介紹了三種不同的階段去開發Python項目,旨在提供適合各種難度層次Python項目。


Python項目–Python的初級、中級和高級

在這個“Python 項目”博客中,讓我們來看3個級別的Python項目,通過這三個項目您將會學習掌握Python,以及從整體上測試項目的分析、開發和處理問題的技能。

如果我說Python的學習真的很有趣,很多人都會同意的。

我們先瀏覽下面的主題列表,之後開始閱讀這篇Python項目博客:

  • Python簡介
  • 如何學習Python項目?
  • 初級Python項目:用Python玩漢格曼遊戲
  • 中級Python項目:在Python中使用圖形
  • 高級Python項目:使用Python進行機器學習
  • 結論


我應當先向您簡單介紹一下Python。


Python簡介

Python是一種高級的、面向對象的、解釋性的編程語言。它在世界上享有廣泛關注。Stack Overflow發現38.8%的用戶主要使用Python來完成項目。

Python是由一個名為Guido Van Rossum的開發人員創建的。

Python是而且一直是很容易學習和掌握的。它對初學者非常友好,語法非常簡單,易於閱讀和理解。這特別讓我們高興,而令人更高興的是Python在全球擁有數百萬快樂的學習者!

根據該網站的調查,在2018年,Python的人氣超過了c#,就像它在2017年超過了php一樣。在GitHub平臺上,Python超越了Java成為第二個最常用的編程語言,在2017中比2016多獲得了40%的申請。

這使得Python認證成為最受歡迎的編程認證之一。


如何學習Python項目?

答案相當簡單直接:從學習Python的初級知識和所有基本知識開始。這是一個用於瞭解您使用Python舒適程度的評價指標。

下一個主要步驟是看一看基本、簡單的代碼,以熟悉代碼中的語法和邏輯流。這是一個非常重要的步驟,有助於為以後的工作打下堅實的基礎。

在這之後,您還要看看在現實生活中Python如何使用。這將成為您在開始就要學習Python的主要原因。

如果您不是剛入門Python,那麼您將會學習Python項目,並對自己的項目實施一些策略。接下來一定要看看您可以利用當前關於Python的知識進行處理哪些項目。深入研究Python會幫助您在各個階段評估自己。

項目基本上是用來解決眼下問題的。如果為各種簡單或複雜的問題提供解決方案是您的特長,那麼您一定要考慮學習Python的項目。

每當著手搞定幾個項目之後,您距離掌握Python將更近一步。這一點很重要,因為這樣您就能夠自然地將所學的知識應用到項目中,從簡單的程序如計算器,到輔助實現人工智能的學習。

讓我們從第一級的Python項目開始學習。

https://www.edureka.co/Python-programming-certification-training


初級Python項目:用Python實現《Hangman》遊戲

我們能想到的最好的入門項目是《Hangman》遊戲。我敢肯定讀過這篇Python項目博客的大多數人都曾在生活中某個時刻玩過《Hangman》。用一句話來解釋,它的主要目標是創建一個“猜詞”遊戲。儘管聽起來很簡單,但有一些關鍵的東西需要注意。

  • 需要用戶能夠輸入猜測的字母。
  • 需要限制他們的猜測次數。
  • 需要不停地告知用戶剩餘圈數。


這意味著你需要一種方法來獲取一個用於猜測的單詞。讓我們用簡單思維,使用文本文件輸入。文本文件包含了我們必須猜測的單詞。

您還需要一些函數去檢查用戶是否實際輸入了單個字母,檢查輸入的字母是否出現在單詞中(如果是,則檢查出現多少次),以及打印字母;還有一個計數器變量限制猜測的次數。

這個Python項目中有一些關鍵的概念需要牢記:

  • 隨機
  • 變量
  • 布爾值
  • 輸入和輸出
  • 整形值
  • 字符型值
  • 字符串
  • 字符串長度
  • 打印


代碼:

1. Hangman.py

from string import ascii_lowercase
from words import get_random_word
def get_num_attempts():
"""Get user-inputted number of incorrect attempts for the game."""
while True:
num_attempts = input(
'How many incorrect attempts do you want? [1-25] ')
try:
num_attempts = int(num_attempts)
if 1 <= num_attempts <= 25:
return num_attempts
else:
print('{0} is not between 1 and 25'.format(num_attempts))
except ValueError:
print('{0} is not an integer between 1 and 25'.format(
num_attempts))
def get_min_word_length():
"""Get user-inputted minimum word length for the game."""
while True:
min_word_length = input(
'What minimum word length do you want? [4-16] ')
try:
min_word_length = int(min_word_length)
if 4 <= min_word_length <= 16: return min_word_length else: print('{0} is not between 4 and 16'.format(min_word_length)) except ValueError: print('{0} is not an integer between 4 and 16'.format( min_word_length)) def get_display_word(word, idxs): """Get the word suitable for display.""" if len(word) != len(idxs): raise ValueError('Word length and indices length are not the same') displayed_word = ''.join( [letter if idxs[i] else '*' for i, letter in enumerate(word)]) return displayed_word.strip() def get_next_letter(remaining_letters): """Get the user-inputted next letter.""" if len(remaining_letters) == 0: raise ValueError('There are no remaining letters') while True: next_letter = input('Choose the next letter: ').lower() if len(next_letter) != 1: print('{0} is not a single character'.format(next_letter)) elif next_letter not in ascii_lowercase: print('{0} is not a letter'.format(next_letter)) elif next_letter not in remaining_letters: print('{0} has been guessed before'.format(next_letter)) else: remaining_letters.remove(next_letter) return next_letter def play_hangman(): """Play a game of hangman. At the end of the game, returns if the player wants to retry. """ # Let player specify difficulty print('Starting a game of Hangman...') attempts_remaining = get_num_attempts() min_word_length = get_min_word_length() # Randomly select a word print('Selecting a word...') word = get_random_word(min_word_length) print() # Initialize game state variables idxs = [letter not in ascii_lowercase for letter in word] remaining_letters = set(ascii_lowercase) wrong_letters = [] word_solved = False # Main game loop while attempts_remaining > 0 and not word_solved:
# Print current game state
print('Word: {0}'.format(get_display_word(word, idxs)))
print('Attempts Remaining: {0}'.format(attempts_remaining))
print('Previous Guesses: {0}'.format(' '.join(wrong_letters)))
# Get player's next letter guess
next_letter = get_next_letter(remaining_letters)
# Check if letter guess is in word
if next_letter in word:
# Guessed correctly
print('{0} is in the word!'.format(next_letter))
# Reveal matching letters
for i in range(len(word)):
if word[i] == next_letter:
idxs[i] = True
else:
# Guessed incorrectly
print('{0} is NOT in the word!'.format(next_letter))
# Decrement num of attempts left and append guess to wrong guesses
attempts_remaining -= 1
wrong_letters.append(next_letter)
# Check if word is completely solved
if False not in idxs:
word_solved = True
print()

# The game is over: reveal the word
print('The word is {0}'.format(word))
# Notify player of victory or defeat
if word_solved:
print('Congratulations! You won!')
else:
print('Try again next time!')
# Ask player if he/she wants to try again
try_again = input('Would you like to try again? [y/Y] ')
return try_again.lower() == 'y'
if __name__ == '__main__':
while play_hangman():
print()

2.Words.py

"""Function to fetch words."""
import random
WORDLIST = 'wordlist.txt'
def get_random_word(min_word_length):
"""Get a random word from the wordlist using no extra memory."""
num_words_processed = 0
curr_word = None
with open(WORDLIST, 'r') as f:
for word in f:
if '(' in word or ')' in word:
continue
word = word.strip().lower()
if len(word) < min_word_length:
continue
num_words_processed += 1
if random.randint(1, num_words_processed) == 1:
curr_word = word
return curr_word

結果如圖


你肯定想學習的頂級Python項目(附代碼)


現在我們已經瞭解瞭如何處理像《hangman》這樣的初級項目,那麼讓我們稍微升級一下,嘗試一箇中級的Python項目。


中級Python項目:在Python中使用圖形

開始學習Python編程的中間階段的最好方法絕對是開始使用Python支持的庫。

在用Python進行編碼時,可以使用真正意義上的“n”個庫。有些庫是非常容易直接的,而有些可能需要一些時間來理解和掌握。

下面是一些您可以考慮入門學習的頂級庫:

  • NumPy
  • SciPy
  • Pandas
  • Matplotlib

NumPy總的來說是用於科學計算的。

SciPy使用數組,例如用於線性代數、微積分和其他類似概念的基本數據結構。

Pandas用於數據幀,而Matplotlib則以圖形和符號的形式顯示數據。

實現數據可視化可能是Python最好的應用之一。儘管數字化的數據輸出很有用,但對數據的可視化表示也有許多要求。

它通過可視化展現,只是一種抽象概括。從創建前端或圖形用戶界面(GUI)到將數字化數據繪製為圖上的點。

Matplotlib用於在圖形上繪製數據點。Matplotlib是一個繪圖庫,可以用於Python編程語言及其數字化數學擴展庫NumPy。它提供了一個面向對象的API,通過使用通用的GUI工具包(如Tkinter、wxPython、Qy或GTK+),將繪圖嵌入到應用中。

在Python中有許多用於三維繪圖的選項,但這裡有一些使用Matplotlib的常見簡單方法。

一般來說,第一步是創建一個三維座標軸,然後繪製出最能說明特定需求的數據的三維圖形。為了使用Matplotlib,必須導入Matplotlib安裝中包含的mplot3d工具包:

from mpl_toolkits import mplot3d

然後,要創建三維軸,可以執行以下代碼:

<pre id="3346" class="graf graf--pre graf-after--p">%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection=’3d’)</pre>


你肯定想學習的頂級Python項目(附代碼)


在這個三維座標軸中,可以繪製一個圖,重要的是要知道哪種類型的圖(或圖的組合)可以更好地描述數據。

此時,您需要注意的是,這一操作是我們進一步繪圖的基礎。

https://www.edureka.co/Python-programming-certification-training


點和線:

下圖結合了兩個繪圖,一個圖帶有一條線,該線穿過數據的每個點,另一個圖在本例中的每個特定1000個值上繪製一個點。

這個代碼分析時實際上非常簡單。我們利用標準三角函數繪製了一組隨機值,並利用這些數據生成三維投影。

代碼:

ax = plt.axes(projection=’3d’)# Data for a three-dimensional line
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline, ‘gray’)# Data for three-dimensional scattered points
zdata = 15 * np.random.random(100)
xdata = np.sin(zdata) + 0.1 * np.random.randn(100)
ydata = np.cos(zdata) + 0.1 * np.random.randn(100)
ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap=’Greens’);


你肯定想學習的頂級Python項目(附代碼)


三維等高線圖

由於需要二維網格上的數據,因此輪廓圖的輸入與上一個繪圖稍有不同。

請注意,在下面的示例中,在為x和y賦值之後,通過執行“np.meshgrid(x,y)”將它們組合到網格上,然後通過執行函數f(x,y)和網格值(z=f(x,y))創建z值。

再一次,基本的簡化三維圖為以下代碼:

def f(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='binary')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');


你肯定想學習的頂級Python項目(附代碼)


在以前的圖形中,數據是按順序生成的,但在現實生活中,有時數據是不按順序生成的,對於這些情況,三角網格曲面測量非常有用,因為它通過查找相鄰點之間形成的三角形集來創建曲面。


表面三角測量:

theta = 2 * np.pi * np.random.random(1000)
r = 6 * np.random.random(1000)
x = np.ravel(r * np.sin(theta))
y = np.ravel(r * np.cos(theta))
z = f(x, y)
ax = plt.axes(projection=’3d’)
ax.plot_trisurf(x, y, z,cmap=’viridis’, edgecolor=’none’);


你肯定想學習的頂級Python項目(附代碼)


現在我們已經熟悉瞭如何通過查看外部庫來擴展我們對Python的學習,那麼我們就可以研究下一個高級級別的Python項目。


Python 高級項目

Python有著廣泛的應用——從“Hello World”一路走到實現人工智能。

實際上,您可以使用Python進行無限多的項目,但如果您想深入瞭解Python的核心,可以考慮以下幾個主要的項目。

  • 使用PyTorch、TensorFlow、Keras和您喜歡的任何機器學習庫進行機器學習。
  • 使用OpenCV和PIL研究計算機視覺。
  • 使用測試和文檔,創建和發佈自己的pip模塊。

在這些裡面,我最喜歡的就是機器學習和深度學習。讓我們看一個非常好的用例以便深入學習Python。

在Python中使用TensorFlow實現CIFAR10

讓我們訓練一個網絡,對CIFAR10數據集中的圖像進行分類。可以使用TensorFlow內置的卷積神經網絡。


你肯定想學習的頂級Python項目(附代碼)

為理解用例的工作原理,我們考慮以下流程圖:


你肯定想學習的頂級Python項目(附代碼)


我們把這個流程圖分解成簡單的組分:

  • 首先將圖像加載到程序中
  • 這些圖像存儲在程序可以訪問的位置
  • 將數據規範化,因為我們需要Python來理解當前的信息。
  • 定義神經網絡的基礎。
  • 定義損失函數以確保我們在數據集上獲得最大精度
  • 訓練實際模型,瞭解一些它所一直看到的數據
  • 對模型進行測試,以分析其準確性,並迭代整個訓練過程,以獲得更好的精度。


這個用例分為兩個程序。一個是訓練網絡,另一個是測試網絡。

我們先訓練一下這個網絡。

訓練網絡

import numpy as np
import tensorflow as tf
from time import time
import math
from include.data import get_data_set
from include.model import model, lr
train_x, train_y = get_data_set("train")
test_x, test_y = get_data_set("test")
tf.set_random_seed(21)
x, y, output, y_pred_cls, global_step, learning_rate = model()
global_accuracy = 0
epoch_start = 0
# PARAMS
_BATCH_SIZE = 128
_EPOCH = 60
_SAVE_PATH = "./tensorboard/cifar-10-v1.0.0/"
# LOSS AND OPTIMIZER
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=output, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=0.9,
beta2=0.999,
epsilon=1e-08).minimize(loss, global_step=global_step)
# PREDICTION AND ACCURACY CALCULATION
correct_prediction = tf.equal(y_pred_cls, tf.argmax(y, axis=1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# SAVER
merged = tf.summary.merge_all()
saver = tf.train.Saver()

sess = tf.Session()

train_writer = tf.summary.FileWriter(_SAVE_PATH, sess.graph)
try:

print("\nTrying to restore last checkpoint ...")
last_chk_path = tf.train.latest_checkpoint(checkpoint_dir=_SAVE_PATH)
saver.restore(sess, save_path=last_chk_path)
print("Restored checkpoint from:", last_chk_path)
except ValueError:
print("\nFailed to restore checkpoint. Initializing variables instead.")
sess.run(tf.global_variables_initializer())
def train(epoch):
global epoch_start
epoch_start = time()
batch_size = int(math.ceil(len(train_x) / _BATCH_SIZE))
i_global = 0
for s in range(batch_size):
batch_xs = train_x[s*_BATCH_SIZE: (s+1)*_BATCH_SIZE]
batch_ys = train_y[s*_BATCH_SIZE: (s+1)*_BATCH_SIZE]
start_time = time()
i_global, _, batch_loss, batch_acc = sess.run(
[global_step, optimizer, loss, accuracy],
feed_dict={x: batch_xs, y: batch_ys, learning_rate: lr(epoch)})
duration = time() - start_time
if s % 10 == 0:
percentage = int(round((s/batch_size)*100))
bar_len = 29
filled_len = int((bar_len*int(percentage))/100)
bar = '=' * filled_len + '>' + '-' * (bar_len - filled_len)
msg = "Global step: {:>5} - [{}] {:>3}% - acc: {:.4f} - loss: {:.4f} - {:.1f} sample/sec"
print(msg.format(i_global, bar, percentage, batch_acc, batch_loss, _BATCH_SIZE / duration))
test_and_save(i_global, epoch)
def test_and_save(_global_step, epoch):
global global_accuracy
global epoch_start
i = 0
predicted_class = np.zeros(shape=len(test_x), dtype=np.int)
while i < len(test_x): j = min(i + _BATCH_SIZE, len(test_x)) batch_xs = test_x[i:j, :] batch_ys = test_y[i:j, :] predicted_class[i:j] = sess.run( y_pred_cls, feed_dict={x: batch_xs, y: batch_ys, learning_rate: lr(epoch)} ) i = j correct = (np.argmax(test_y, axis=1) == predicted_class) acc = correct.mean()*100 correct_numbers = correct.sum() hours, rem = divmod(time() - epoch_start, 3600) minutes, seconds = divmod(rem, 60) mes = "\nEpoch {} - accuracy: {:.2f}% ({}/{}) - time: {:0>2}:{:0>2}:{:05.2f}"
print(mes.format((epoch+1), acc, correct_numbers, len(test_x), int(hours), int(minutes), seconds))
if global_accuracy != 0 and global_accuracy < acc: summary = tf.Summary(value=[ tf.Summary.Value(tag="Accuracy/test", simple_value=acc), ]) train_writer.add_summary(summary, _global_step) saver.save(sess, save_path=_SAVE_PATH, global_step=_global_step) mes = "This epoch receive better accuracy: {:.2f} > {:.2f}. Saving session..."
print(mes.format(acc, global_accuracy))

global_accuracy = acc

elif global_accuracy == 0:
global_accuracy = acc
print("###########################################################################################################")
def main():
train_start = time()
for i in range(_EPOCH):
print("\nEpoch: {}/{}\n".format((i+1), _EPOCH))
train(i)
hours, rem = divmod(time() - train_start, 3600)
minutes, seconds = divmod(rem, 60)
mes = "Best accuracy pre session: {:.2f}, time: {:0>2}:{:0>2}:{:05.2f}"
print(mes.format(global_accuracy, int(hours), int(minutes), seconds))
if __name__ == "__main__":
main()
sess.close()
輸出:

Epoch: 60/60

Global step: 23070 - [>-----------------------------] 0% - acc: 0.9531 - loss: 1.5081 - 7045.4 sample/sec
Global step: 23080 - [>-----------------------------] 3% - acc: 0.9453 - loss: 1.5159 - 7147.6 sample/sec
Global step: 23090 - [=>----------------------------] 5% - acc: 0.9844 - loss: 1.4764 - 7154.6 sample/sec
Global step: 23100 - [==>---------------------------] 8% - acc: 0.9297 - loss: 1.5307 - 7104.4 sample/sec
Global step: 23110 - [==>---------------------------] 10% - acc: 0.9141 - loss: 1.5462 - 7091.4 sample/sec
Global step: 23120 - [===>--------------------------] 13% - acc: 0.9297 - loss: 1.5314 - 7162.9 sample/sec
Global step: 23130 - [====>-------------------------] 15% - acc: 0.9297 - loss: 1.5307 - 7174.8 sample/sec
Global step: 23140 - [=====>------------------------] 18% - acc: 0.9375 - loss: 1.5231 - 7140.0 sample/sec
Global step: 23150 - [=====>------------------------] 20% - acc: 0.9297 - loss: 1.5301 - 7152.8 sample/sec
Global step: 23160 - [======>-----------------------] 23% - acc: 0.9531 - loss: 1.5080 - 7112.3 sample/sec
Global step: 23170 - [=======>----------------------] 26% - acc: 0.9609 - loss: 1.5000 - 7154.0 sample/sec
Global step: 23180 - [========>---------------------] 28% - acc: 0.9531 - loss: 1.5074 - 6862.2 sample/sec
Global step: 23190 - [========>---------------------] 31% - acc: 0.9609 - loss: 1.4993 - 7134.5 sample/sec
Global step: 23200 - [=========>--------------------] 33% - acc: 0.9609 - loss: 1.4995 - 7166.0 sample/sec
Global step: 23210 - [==========>-------------------] 36% - acc: 0.9375 - loss: 1.5231 - 7116.7 sample/sec
Global step: 23220 - [===========>------------------] 38% - acc: 0.9453 - loss: 1.5153 - 7134.1 sample/sec
Global step: 23230 - [===========>------------------] 41% - acc: 0.9375 - loss: 1.5233 - 7074.5 sample/sec
Global step: 23240 - [============>-----------------] 43% - acc: 0.9219 - loss: 1.5387 - 7176.9 sample/sec
Global step: 23250 - [=============>----------------] 46% - acc: 0.8828 - loss: 1.5769 - 7144.1 sample/sec
Global step: 23260 - [==============>---------------] 49% - acc: 0.9219 - loss: 1.5383 - 7059.7 sample/sec
Global step: 23270 - [==============>---------------] 51% - acc: 0.8984 - loss: 1.5618 - 6638.6 sample/sec
Global step: 23280 - [===============>--------------] 54% - acc: 0.9453 - loss: 1.5151 - 7035.7 sample/sec
Global step: 23290 - [================>-------------] 56% -acc: 0.9609 - loss: 1.4996 - 7129.0 sample/sec
Global step: 23300 - [=================>------------] 59% - acc: 0.9609 - loss: 1.4997 - 7075.4 sample/sec
Global step: 23310 - [=================>------------] 61% - acc: 0.8750 - loss: 1.5842 - 7117.8 sample/sec
Global step: 23320 - [==================>-----------] 64% - acc: 0.9141 - loss: 1.5463 - 7157.2 sample/sec
Global step: 23330 - [===================>----------] 66% - acc:0.9062 - loss: 1.5549 - 7169.3 sample/sec
Global step: 23340 - [====================>---------] 69% - acc: 0.9219 - loss: 1.5389 - 7164.4 sample/sec
Global step: 23350 - [====================>---------] 72% - acc: 0.9609 - loss: 1.5002 - 7135.4 sample/sec
Global step: 23360 - [=====================>--------] 74% - acc: 0.9766 - loss: 1.4842 - 7124.2 sample/sec
Global step: 23370 - [======================>-------] 77% - acc: 0.9375 - loss: 1.5231 - 7168.5 sample/sec
Global step: 23380 - [======================>-------] 79% - acc: 0.8906 - loss: 1.5695 - 7175.2 sample/sec
Global step: 23390 - [=======================>------] 82% - acc: 0.9375 - loss: 1.5225 - 7132.1 sample/sec
Global step: 23400 - [========================>-----] 84% - acc: 0.9844 - loss: 1.4768 - 7100.1 sample/sec
Global step: 23410 - [=========================>----] 87% - acc: 0.9766 - loss: 1.4840 - 7172.0 sample/sec
Global step: 23420 - [==========================>---] 90% - acc: 0.9062 - loss: 1.5542 - 7122.1 sample/sec
Global step: 23430 - [==========================>---] 92% - acc:0.9297 - loss: 1.5313 - 7145.3 sample/sec
Global step: 23440 - [===========================>--] 95% - acc: 0.9297 - loss: 1.5301 - 7133.3 sample/sec
Global step: 23450 - [============================>-] 97% - acc: 0.9375 - loss: 1.5231 - 7135.7 sample/sec
Global step: 23460 - [=============================>] 100% - acc: 0.9250 - loss: 1.5362 - 10297.5 sample/sec

Epoch 60 - accuracy: 78.81% (7881/10000)
This epoch receive better accuracy: 78.81 > 78.78. Saving session...

在測試數據集上運行網絡

import numpy as np
import tensorflow as tf
from include.data import get_data_set
from include.model import model
test_x, test_y = get_data_set("test")
x, y, output, y_pred_cls, global_step, learning_rate = model()
_BATCH_SIZE = 128
_CLASS_SIZE = 10
_SAVE_PATH = "./tensorboard/cifar-10-v1.0.0/"
saver = tf.train.Saver()
sess = tf.Session()
try:
print("\nTrying to restore last checkpoint ...")
last_chk_path = tf.train.latest_checkpoint(checkpoint_dir=_SAVE_PATH)
saver.restore(sess, save_path=last_chk_path)
print("Restored checkpoint from:", last_chk_path)
except ValueError:
print("\nFailed to restore checkpoint. Initializing variables instead.")
sess.run(tf.global_variables_initializer())
def main():
i = 0
predicted_class = np.zeros(shape=len(test_x), dtype=np.int)
while i < len(test_x):
j = min(i + _BATCH_SIZE, len(test_x))
batch_xs = test_x[i:j, :]

batch_ys = test_y[i:j, :]

predicted_class[i:j] = sess.run(y_pred_cls, feed_dict={x: batch_xs, y: batch_ys})

i = j
correct = (np.argmax(test_y, axis=1) == predicted_class)

acc = correct.mean() * 100
correct_numbers = correct.sum()
print()
print("Accuracy on Test-Set: {0:.2f}% ({1} / {2})".format(acc, correct_numbers, len(test_x)))
if __name__ == "__main__":
main()
sess.close()

簡單輸出:

Trying to restore last checkpoint ...
Restored checkpoint from: ./tensorboard/cifar-10-v1.0.0/-23460
Accuracy on Test-Set: 78.81% (7881 / 10000)

這難道不是一個非常有趣的用例嗎?至此,我們瞭解了機器學習是如何工作的,開發了一個基本程序,並使用Python中的TensorFlow來實現了它。

原文標題:

Top Python Projects You Should Consider Learning

原文鏈接:

https://www.edureka.co/blog/python-projects/

編輯:王菁

校對:龔力


譯者簡介

你肯定想學習的頂級Python項目(附代碼)


張睿毅,北京郵電大學大二物聯網在讀。我是一個愛自由的人。在郵電大學讀第一年書我就四處跑去蹭課,折騰整一年驚覺,與其在當下焦慮,不如在前輩中沉澱。於是在大二以來,堅持讀書,不敢稍歇。資本主義國家的科學觀不斷刷新我的認知框架,同時因為出國考試很早出分,也更早地感受到自己才是那個一直被束縛著的人。太多真英雄在社會上各自閃耀著光芒。這才開始,立志終身向遇到的每一個人學習。做一個純粹的計算機科學裡面的小學生。喜歡算法,數據挖掘,圖像識別,自然語言處理,神經網絡,人工智能等方向。

— 完 —

關注清華-青島數據科學研究院官方微信公眾平臺“THU數據派”及姊妹號“數據派THU”獲取更多講座福利及優質內容。

相關推薦

推薦中...