重新审视旧代码 – AI(无法运行)

几年前我参加了一个AI编程训练营,我们使用Python学习机器学习。我有很多.py文件,但无法运行这些代码。我将代码放入PyCharm并尝试运行,但显示缺少库。代码如下:

from skimage import transformimport randomimport tensorflow as tfimport matplotlib.pyplot as pltfrom skimage import dataimport osimport numpy as npfrom skimage.color import rgb2graydef load_data(data_directory):    directories = [d for d in os.listdir(data_directory)                   if os.path.isdir(os.path.join(data_directory, d))]    labels = []    images = []    for d in directories:        label_directory = os.path.join(data_directory, d)        file_names = [os.path.join(label_directory, f)                      for f in os.listdir(label_directory)                      if f.endswith(".ppm")]        for f in file_names:            images.append(data.imread(f))            labels.append(int(d))    return images, labelsROOT_PATH = "/home/student/Downloads"train_data_directory = os.path.join(ROOT_PATH, "Training")test_data_directory = os.path.join(ROOT_PATH, "Testing")images, labels = load_data(train_data_directory)traffic_signs = [300, 2250, 3650, 4000]plt.show()import matplotlib.pyplot as plt# Get the unique labelsunique_labels = set(labels)# Initialize the figureplt.figure(figsize=(15, 15))# Set a counteri = 1# Rescale the images in the `images` arrayimages28 = [transform.resize(image, (28, 28)) for image in images]# Convert `images28` to an arrayimages28 = np.array(images28)   # Convert `images28` to grayscale    images28 = rgb2gray(images28)    # For each unique label,    for label in unique_labels:        # You pick the first image for each label        image = images[labels.index(label)]        # Define 64 subplots    plt.subplot(8, 8, i)    # Don't include axes    plt.axis('off')    # Add a title to each subplot    plt.title("Label {0} ({1})".format(label, labels.count(label)))    # Add 1 to the counter    i += 1    # And you plot this first image    plt.imshow(image)for i in range(len(traffic_signs)):    plt.subplot(1, 4, i+1)    plt.axis('off')    plt.imshow(images28[traffic_signs[i]], cmap="gray")    plt.subplots_adjust(wspace=0.5)    print("shape: {0}, min: {1}, max: {2}".format(images28[traffic_signs[i]].shape,                                                  images28[traffic_signs[i]].min(),                                                  images28[traffic_signs[i]].max()))    # Show the plot# Import `tensorflow`import tensorflow as tf# Initialize placeholdersx = tf.placeholder(dtype = tf.float32, shape = [None, 28, 28])y = tf.placeholder(dtype = tf.int32, shape = [None])# Flatten the input dataimages_flat = tf.contrib.layers.flatten(x)# Fully connected layerlogits = tf.contrib.layers.fully_connected(images_flat, 62, tf.nn.relu)# Define a loss functionloss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels = y,                                                                logits = logits))# Define an optimizertrain_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)# Convert logits to label indexescorrect_pred = tf.argmax(logits, 1)# Define an accuracy metricaccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))tf.set_random_seed(1234)sess = tf.Session()sess.run(tf.global_variables_initializer())for i in range(201):    print('EPOCH', i)    _, accuracy_val = sess.run([train_op, accuracy], feed_dict={x: images28, y: labels})    if i % 10 == 0:        print("Loss: ", loss)    print('DONE WITH EPOCH')sample_indexes = random.sample(range(len(images28)), 10)sample_images = [images28[i] for i in sample_indexes]sample_labels = [labels[i] for i in sample_indexes]# Run the "correct_pred" operationpredicted = sess.run([correct_pred], feed_dict={x: sample_images})[0]# Print the real and predicted labelsprint(sample_labels)print(predicted)fig = plt.figure(figsize=(10, 10))for i in range(len(sample_images)):truth = sample_labels[i]prediction = predicted[i]plt.subplot(5, 2,1+i)plt.axis('off')color='green' if truth == prediction else 'red'plt.text(40, 10, "Truth:        {0}\nPrediction: {1}".format(truth, prediction),         fontsize=12, color=color)plt.imshow(sample_images[i],  cmap="gray")plt.show()test_images, test_labels = load_data(test_data_directory)# Transform the images to 28 by 28 pixelstest_images28 = [transform.resize(image, (28, 28)) for image in test_images]# Convert to grayscalefrom skimage.color import rgb2graytest_images28 = rgb2gray(np.array(test_images28))# Run predictions against the full test set.predicted = sess.run([correct_pred], feed_dict={x: test_images28})[0]# Calculate correct matchesmatch_count = sum([int(y == y_) for y, y_ in zip(test_labels, predicted)])# Calculate the accuracyaccuracy = match_count / len(test_labels)# Print the accuracyprint("Accuracy: {:.3f}".format(accuracy))

我知道一些其他东西(如文件的目录)与训练营时使用他们的电脑不同,我可以修正这些。然而,我无法解决“缺少模块”的问题。错误代码如下:

 Traceback (most recent call last):      File "C:/Users/Eric/PycharmProjects/Cartpole1/Try1.py", line 2, in <module>        from skimage import transform    ModuleNotFoundError: No module named 'skimage'

以及许多类似的错误。我需要下载某些东西,还是代码本身有问题?我记得当我将代码下载到我正在使用的U盘时是可以运行的。


回答:

你需要导入正确的PM(包管理器),确保你系统上安装了所有你需要的库,或者在这里引用它们。这里有一个链接,告诉你如何做。基本上,在每个有导入语句的地方,确保你已经安装了那个库。

https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注