[Coursera] Deep learning 系列课程作业的一些报错问题总结及作业资源

Deep learning 系列课程作业的一些报错问题总结

  相信有小伙伴和我一样,在使用网上下载下来的作业资源在本地环境进行运行的时候会有一些报错问题,我总结了一下我遇到的问题,并给出了详细的解决方法,希望能对看到这篇文章的小伙伴有所帮助。

  这篇文章的部分内容来自:ImSEten 的这篇文章,但是由于有些问题他并没有解决,他也并没有更新完所有作业中遇到的报错问题,所有我还是重新整理了遇到的问题,同时我也会标记出从他那里 copy 过来的内容。

下载资源

修正后的空作业文件:(只包含了Course 1 - 4)

链接:https://pan.baidu.com/s/1qGESprT4lN4XhvDXGgKATA 提取码:dg2z

PS:因为 Tensorflow 和 Keras 的版本不兼容问题导致 Course 4 的第四个练习开始很难处理版本问题导致的报错,所以我决定后面的作业不做了,因此该资源中只修改了 Course 1 至 Course 4 的前三个作业的资源。若该文件依然存在与作业内容无关的报错希望能评论反馈给我进行修改。Course 5 的作业由于我原来找到的资源中就没有,也不打算做了所以就没有再找了,暂时无法提供。

Course 1 中的一些问题

一、PA0: Python basics with Numpy

没有错误

二、PA1: Logistic Regression as a Neural Network

1. 画图的 bug

报错位置:

# Example of a picture that was wrongly classified.
index = 1
plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))
print ("y = " + str(test_set_y[0,index]) + ", you predicted that it is a \"" + classes[d["Y_prediction_test"][0,index]].decode("utf-8") +  "\" picture.")

报错内容:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-8bf81a1a3731> in <module>
      1 # Example of a picture that was wrongly classified.
      2 index = 5
----> 3 plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))
      4 print ("y = " + str(test_set_y[0,index]) + ", you predicted that it is a \"" + classes[d["Y_prediction_test"][0,index]].decode("utf-8") +  "\" picture.")

TypeError: 'NoneType' object cannot be interpreted as an integer

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-31-50a2ff1ec91d> in <module>
      2 index = 1
      3 plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))
----> 4 print ("y = " + str(test_set_y[0,index]) + ", you predicted that it is a \"" + classes[d["Y_prediction_test"][0,index]].decode("utf-8") +  "\" picture.")

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

解决方法:

1、将 test_set_x[:,index].reshape((num_px, num_px, 3)) 替换成 test_set_x_orig[index]

2、将 classes[d["Y_prediction_test"][0,index]].decode("utf-8") 替换成 classes[np.squeeze(test_set_y[:, index])].decode("utf-8")

3、即将第二行和第三行替换成

plt.imshow(test_set_x_orig[index])
print ("y = " + str(test_set_y[0,index]) + ", you predicted that it is a \"" + classes[np.squeeze(test_set_y[:, index])].decode("utf-8") +  "\" picture.")
2. 预测自己的图片 imread 报错

这个是 scipy 版本不兼容导致的,可以将其降成 1.2.1,因为这个不影响前面的练习所以就没有去修改这个问题了

三、PA2: Planar data classification with one hidden layer

1. 画图的 bug

报错位置:

# Visualize the data:
plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);

报错内容:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in _parse_scatter_color_args(c, edgecolors, kwargs, xshape, yshape, get_next_color_func)
   4283             try:  # Then is 'c' acceptable as PathCollection facecolors?
-> 4284                 colors = mcolors.to_rgba_array(c)
   4285                 n_elem = colors.shape[0]

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in to_rgba_array(c, alpha)
    293     for i, cc in enumerate(c):
--> 294         result[i] = to_rgba(cc, alpha)
    295     return result

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    176     if rgba is None:  # Suppress exception chaining of cache lookup failure.
--> 177         rgba = _to_rgba_no_colorcycle(c, alpha)
    178         try:

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
    243     if len(c) not in [3, 4]:
--> 244         raise ValueError("RGBA sequence should have length 3 or 4")
    245     if len(c) == 3 and alpha is None:

ValueError: RGBA sequence should have length 3 or 4

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-3-8d7e20d0c82c> in <module>
      1 # Visualize the data:
----> 2 plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\pyplot.py in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, data, **kwargs)
   2841         vmin=None, vmax=None, alpha=None, linewidths=None, verts=None,
   2842         edgecolors=None, *, plotnonfinite=False, data=None, **kwargs):
-> 2843     __ret = gca().scatter(
   2844         x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
   2845         vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1597     def inner(ax, *args, data=None, **kwargs):
   1598         if data is None:
-> 1599             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1600 
   1601         bound = new_sig.bind(ax, *args, **kwargs)

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, **kwargs)
   4449 
   4450         c, colors, edgecolors = \
-> 4451             self._parse_scatter_color_args(
   4452                 c, edgecolors, kwargs, xshape, yshape,
   4453                 get_next_color_func=self._get_patches_for_fill.get_next_color)

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in _parse_scatter_color_args(c, edgecolors, kwargs, xshape, yshape, get_next_color_func)
   4291             except ValueError:
   4292                 if not valid_shape:  # but at least one conversion succeeded.
-> 4293                     raise ValueError(
   4294                         "'c' argument has {nc} elements, which is not "
   4295                         "acceptable for use with 'x' with size {xs}, "

ValueError: 'c' argument has 1 elements, which is not acceptable for use with 'x' with size 400, 'y' with size 400.

解决方法:

1、找到 plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral); 语句
2、将 c=Y 改为 c=Y.reshape(X[0,:].shape),即将 plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral); 改为 plt.scatter(X[0, :], X[1, :], c=Y.reshape(X[0,:].shape), s=40, cmap=plt.cm.Spectral);

2. 画决策边界时的问题

报错位置:

# Plot the decision boundary for logistic regression
plot_decision_boundary(lambda x: clf.predict(x), X, Y)
plt.title("Logistic Regression")

# Print accuracy
LR_predictions = clf.predict(X.T)
print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +
       '% ' + "(percentage of correctly labelled datapoints)")

报错内容:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in _parse_scatter_color_args(c, edgecolors, kwargs, xshape, yshape, get_next_color_func)
   4283             try:  # Then is 'c' acceptable as PathCollection facecolors?
-> 4284                 colors = mcolors.to_rgba_array(c)
   4285                 n_elem = colors.shape[0]

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in to_rgba_array(c, alpha)
    293     for i, cc in enumerate(c):
--> 294         result[i] = to_rgba(cc, alpha)
    295     return result

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    176     if rgba is None:  # Suppress exception chaining of cache lookup failure.
--> 177         rgba = _to_rgba_no_colorcycle(c, alpha)
    178         try:

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
    243     if len(c) not in [3, 4]:
--> 244         raise ValueError("RGBA sequence should have length 3 or 4")
    245     if len(c) == 3 and alpha is None:

ValueError: RGBA sequence should have length 3 or 4

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-10-df7c6bdb6ec1> in <module>
      1 # Plot the decision boundary for logistic regression
----> 2 plot_decision_boundary(lambda x: clf.predict(x), X, Y)
      3 plt.title("Logistic Regression")
      4 
      5 # Print accuracy

D:\A_Study\B_self-study\A_Projects\deep learning HW\Course 1\Week 3 - PA 2 - Planar data classification with one hidden layer\planar_utils.py in plot_decision_boundary(model, X, y)
     19     plt.ylabel('x2')
     20     plt.xlabel('x1')
---> 21     plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)
     22 
     23 

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\pyplot.py in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, data, **kwargs)
   2841         vmin=None, vmax=None, alpha=None, linewidths=None, verts=None,
   2842         edgecolors=None, *, plotnonfinite=False, data=None, **kwargs):
-> 2843     __ret = gca().scatter(
   2844         x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
   2845         vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1597     def inner(ax, *args, data=None, **kwargs):
   1598         if data is None:
-> 1599             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1600 
   1601         bound = new_sig.bind(ax, *args, **kwargs)

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, **kwargs)
   4449 
   4450         c, colors, edgecolors = \
-> 4451             self._parse_scatter_color_args(
   4452                 c, edgecolors, kwargs, xshape, yshape,
   4453                 get_next_color_func=self._get_patches_for_fill.get_next_color)

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in _parse_scatter_color_args(c, edgecolors, kwargs, xshape, yshape, get_next_color_func)
   4291             except ValueError:
   4292                 if not valid_shape:  # but at least one conversion succeeded.
-> 4293                     raise ValueError(
   4294                         "'c' argument has {nc} elements, which is not "
   4295                         "acceptable for use with 'x' with size {xs}, "

ValueError: 'c' argument has 1 elements, which is not acceptable for use with 'x' with size 400, 'y' with size 400.

解决方法:

1、在代码文件夹中找到 planar_utils.py 文件

2、找到 plot_decision_boundary(model, X, y) 函数

3、找到 plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral) 语句
4、将 c=y 改为 c=y.reshape(X[0,:].shape),即将 plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral) 改为 plt.scatter(X[0, :], X[1, :], c=y.reshape(X[0,:].shape), cmap=plt.cm.Spectral)
5、重新启动内核。在 Jupyter notebook 中点击 Kernel->Restart & Clear Output 。或者重新启动 Jupyter notebook (关掉重开)

3. 画图的 bug

报错位置:

# Datasets
noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure = load_extra_datasets()

datasets = {"noisy_circles": noisy_circles,
            "noisy_moons": noisy_moons,
            "blobs": blobs,
            "gaussian_quantiles": gaussian_quantiles}

### START CODE HERE ### (choose your dataset)
dataset = "noisy_moons"
### END CODE HERE ###

X, Y = datasets[dataset]
X, Y = X.T, Y.reshape(1, Y.shape[0])

# make blobs binary
if dataset == "blobs":
    Y = Y%2

# Visualize the data
plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);

报错内容:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in _parse_scatter_color_args(c, edgecolors, kwargs, xshape, yshape, get_next_color_func)
   4283             try:  # Then is 'c' acceptable as PathCollection facecolors?
-> 4284                 colors = mcolors.to_rgba_array(c)
   4285                 n_elem = colors.shape[0]

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in to_rgba_array(c, alpha)
    293     for i, cc in enumerate(c):
--> 294         result[i] = to_rgba(cc, alpha)
    295     return result

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    176     if rgba is None:  # Suppress exception chaining of cache lookup failure.
--> 177         rgba = _to_rgba_no_colorcycle(c, alpha)
    178         try:

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
    243     if len(c) not in [3, 4]:
--> 244         raise ValueError("RGBA sequence should have length 3 or 4")
    245     if len(c) == 3 and alpha is None:

ValueError: RGBA sequence should have length 3 or 4

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-26-79d76217dc94> in <module>
     19 
     20 # Visualize the data
---> 21 plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\pyplot.py in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, data, **kwargs)
   2841         vmin=None, vmax=None, alpha=None, linewidths=None, verts=None,
   2842         edgecolors=None, *, plotnonfinite=False, data=None, **kwargs):
-> 2843     __ret = gca().scatter(
   2844         x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
   2845         vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1597     def inner(ax, *args, data=None, **kwargs):
   1598         if data is None:
-> 1599             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1600 
   1601         bound = new_sig.bind(ax, *args, **kwargs)

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, **kwargs)
   4449 
   4450         c, colors, edgecolors = \
-> 4451             self._parse_scatter_color_args(
   4452                 c, edgecolors, kwargs, xshape, yshape,
   4453                 get_next_color_func=self._get_patches_for_fill.get_next_color)

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in _parse_scatter_color_args(c, edgecolors, kwargs, xshape, yshape, get_next_color_func)
   4291             except ValueError:
   4292                 if not valid_shape:  # but at least one conversion succeeded.
-> 4293                     raise ValueError(
   4294                         "'c' argument has {nc} elements, which is not "
   4295                         "acceptable for use with 'x' with size {xs}, "

ValueError: 'c' argument has 1 elements, which is not acceptable for use with 'x' with size 200, 'y' with size 200.

解决方法:

1、找到 plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral); 语句
2、将 c=Y 改为 c=Y.reshape(X[0,:].shape),即将 plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral); 改为 plt.scatter(X[0, :], X[1, :], c=Y.reshape(X[0,:].shape), s=40, cmap=plt.cm.Spectral);

四、PA3: Building your Deep Neural Network - Step by Step

1. 输出报错

报错位置:

AL, Y_assess, caches = L_model_backward_test_case()
grads = L_model_backward(AL, Y_assess, caches)
print_grads(grads)

报错内容:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-19-e52805eb4e5d> in <module>
      1 AL, Y_assess, caches = L_model_backward_test_case()
      2 grads = L_model_backward(AL, Y_assess, caches)
----> 3 print_grads(grads)

D:\A_Study\B_self-study\A_Projects\deep learning HW\Course 1\Week 4 - PA 3 - Building your Deep Neural Network - Step by Step\testCases_v3.py in print_grads(grads)
    210     print ("dW1 = "+ str(grads["dW1"]))
    211     print ("db1 = "+ str(grads["db1"]))
--> 212     print ("dA1 = "+ str(grads["dA2"])) # this is done on purpose to be consistent with lecture where we normally start with A0
    213                                         # in this implementation we started with A1, hence we bump it up by 1.
    214 

KeyError: 'dA2'

解决方法:

1、在代码文件夹中找到 testCases_v3.py 文件

2、找到 def print_grads(grads) 函数

3、将 print ("dA1 = "+ str(grads["dA2"])) 修改为 print ("dA1 = "+ str(grads["dA1"]))

4、重新启动内核。在 Jupyter notebook 中点击 Kernel->Restart & Clear Output 。或者重新启动 Jupyter notebook (关掉重开)

五、PA4: Deep Neural Network Application

除了最后读自己的图片进行预测,其他没问题

Course 2 中的一些问题

一、 PA1: Initialization 作业中的报错问题

1. 画图的 bug

报错位置:

plt.title("Model with Zeros initialization")
axes = plt.gca()
axes.set_xlim([-1.5,1.5])
axes.set_ylim([-1.5,1.5])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)

报错内容:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    157     try:
--> 158         rgba = _colors_full_map.cache[c, alpha]
    159     except (KeyError, TypeError):  # Not in cache, or unhashable.

TypeError: unhashable type: 'numpy.ndarray'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\axes\_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, **kwargs)
   4220             try:  # Then is 'c' acceptable as PathCollection facecolors?
-> 4221                 colors = mcolors.to_rgba_array(c)
   4222                 n_elem = colors.shape[0]

c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\colors.py in to_rgba_array(c, alpha)
    258     for i, cc in enumerate(c):
--> 259         result[i] = to_rgba(cc, alpha)
    260     return result

c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    159     except (KeyError, TypeError):  # Not in cache, or unhashable.
--> 160         rgba = _to_rgba_no_colorcycle(c, alpha)
    161         try:

c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
    214     if len(c) not in [3, 4]:
--> 215         raise ValueError("RGBA sequence should have length 3 or 4")
    216     if len(c) == 3 and alpha is None:

ValueError: RGBA sequence should have length 3 or 4

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-7-0ec6f7c907fb> in <module>
      3 axes.set_xlim([-1.5,1.5])
      4 axes.set_ylim([-1.5,1.5])
----> 5 plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\HomeWork\第二课\第二课第一周编程作业\assignment1\init_utils.py in plot_decision_boundary(model, X, y)
    215     plt.ylabel('x2')
    216     plt.xlabel('x1')
--> 217     plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)
    218     plt.show()
    219 

c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\pyplot.py in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, data, **kwargs)
   2862         vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,
   2863         verts=verts, edgecolors=edgecolors, **({"data": data} if data
-> 2864         is not None else {}), **kwargs)
   2865     sci(__ret)
   2866     return __ret

c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1803                         "the Matplotlib list!)" % (label_namer, func.__name__),
   1804                         RuntimeWarning, stacklevel=2)
-> 1805             return func(ax, *args, **kwargs)
   1806 
   1807         inner.__doc__ = _add_data_doc(inner.__doc__,

c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\axes\_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, **kwargs)
   4232                         "acceptable for use with 'x' with size {xs}, "
   4233                         "'y' with size {ys}."
-> 4234                         .format(nc=n_elem, xs=x.size, ys=y.size)
   4235                     )
   4236                 # Both the mapping *and* the RGBA conversion failed: pretty

ValueError: 'c' argument has 1 elements, which is not acceptable for use with 'x' with size 300, 'y' with size 300.

解决方法:

1、在代码文件夹中找到 init_utils.py 文件

2、找到 plot_decision_boundary(model, X, y) 函数

3、找到 plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral) 语句
4、将 c=y 改为 c=y.reshape(X[0,:].shape),即将 plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral) 改为 plt.scatter(X[0, :], X[1, :], c=y.reshape(X[0,:].shape), cmap=plt.cm.Spectral)
5、重新启动内核。在 Jupyter notebook 中点击 Kernel->Restart & Clear Output 。或者重新启动 Jupyter notebook (关掉重开)

PS: 该解决方案来自:ImSEten

二、 PA2: Regularization 作业中遇到的问题

1. 第一个问题

报错位置:

# import packages
import numpy as np
import matplotlib.pyplot as plt
from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec
from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters
import sklearn
import sklearn.datasets
import scipy.io
from testCases import *

%matplotlib inline
plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

报错内容:

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\HomeWork\第二课\第二课第一周编程作业\assignment1\reg_utils.py:85: SyntaxWarning: assertion is always true, perhaps remove parentheses?
  assert(parameters['W' + str(l)].shape == layer_dims[l], layer_dims[l-1])
C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\HomeWork\第二课\第二课第一周编程作业\assignment1\reg_utils.py:86: SyntaxWarning: assertion is always true, perhaps remove parentheses?
  assert(parameters['W' + str(l)].shape == layer_dims[l], 1)

解决方法:

1、在代码文件夹中找到 reg_utils.py 文件
2、找到 initialize_parameters(layer_dims) 函数
3、找到 assert(parameters['W' + str(l)].shape == layer_dims[l], layer_dims[l-1] 函数
4、对 layer_dims[l], layer_dims[l-1] 添加括号,即 (layer_dims[l], layer_dims[l-1]) ,即该语句变为 assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1])
5、找到 assert(parameters['W' + str(l)].shape == layer_dims[l], 1)) 函数
将W改为b,对 layer_dims[l], 1 添加括号,即 (layer_dims[l], 1),即该语句变为 assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))

PS:该解决方案来自:ImSEten ,但是要着重强调第 5 步需要把 W 变成 b ,不然在运行下面代码时会再次在这个地方出现报错,我第一次看的时候就没注意到加粗部分,只加了括号。

2. 加载数据的 bug

报错位置:

train_X, train_Y, test_X, test_Y = load_2D_dataset()

报错内容:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    157     try:
--> 158         rgba = _colors_full_map.cache[c, alpha]
    159     except (KeyError, TypeError):  # Not in cache, or unhashable.

TypeError: unhashable type: 'numpy.ndarray'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\axes\_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, **kwargs)
   4220             try:  # Then is 'c' acceptable as PathCollection facecolors?
-> 4221                 colors = mcolors.to_rgba_array(c)
   4222                 n_elem = colors.shape[0]

c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\colors.py in to_rgba_array(c, alpha)
    258     for i, cc in enumerate(c):
--> 259         result[i] = to_rgba(cc, alpha)
    260     return result

c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    159     except (KeyError, TypeError):  # Not in cache, or unhashable.
--> 160         rgba = _to_rgba_no_colorcycle(c, alpha)
    161         try:

c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
    214     if len(c) not in [3, 4]:
--> 215         raise ValueError("RGBA sequence should have length 3 or 4")
    216     if len(c) == 3 and alpha is None:

ValueError: RGBA sequence should have length 3 or 4

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-3-a9a84d38b990> in <module>
----> 1 train_X, train_Y, test_X, test_Y = load_2D_dataset()

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\HomeWork\第二课\第二课第一周编程作业\assignment1\reg_utils.py in load_2D_dataset()
    332     test_Y = data['yval'].T
    333 
--> 334     plt.scatter(train_X[0, :], train_X[1, :], c=train_Y, s=40, cmap=plt.cm.Spectral);
    335 
    336     return train_X, train_Y, test_X, test_Y

c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\pyplot.py in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, data, **kwargs)
   2862         vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,
   2863         verts=verts, edgecolors=edgecolors, **({"data": data} if data
-> 2864         is not None else {}), **kwargs)
   2865     sci(__ret)
   2866     return __ret

c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1803                         "the Matplotlib list!)" % (label_namer, func.__name__),
   1804                         RuntimeWarning, stacklevel=2)
-> 1805             return func(ax, *args, **kwargs)
   1806 
   1807         inner.__doc__ = _add_data_doc(inner.__doc__,

c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages\matplotlib\axes\_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, **kwargs)
   4232                         "acceptable for use with 'x' with size {xs}, "
   4233                         "'y' with size {ys}."
-> 4234                         .format(nc=n_elem, xs=x.size, ys=y.size)
   4235                     )
   4236                 # Both the mapping *and* the RGBA conversion failed: pretty

ValueError: 'c' argument has 1 elements, which is not acceptable for use with 'x' with size 211, 'y' with size 

解决办法:
1、找到 reg_utils.py文件
2、找到 load_2D_dataset() 函数
3、找到语句 plt.scatter(train_X[0, :], train_X[1, :], c=train_Y, s=40, cmap=plt.cm.Spectral)
4、修改为 plt.scatter(train_X[0, :], train_X[1, :], c=train_Y.reshape(train_X[0, :].shape), s=40, cmap=plt.cm.Spectral)
5、重新启动内核。在 Jupyter notebook 中点击 Kernel->Restart & Clear Output 。或者重新启动 notebook (关掉重开)

PS:该解决方案来自:ImSEten,这个问题和 Initialization 中的问题是一样的

3. 画图的 bug

报错位置:

plt.title("Model without regularization")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)

报错内容:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in _parse_scatter_color_args(c, edgecolors, kwargs, xshape, yshape, get_next_color_func)
   4283             try:  # Then is 'c' acceptable as PathCollection facecolors?
-> 4284                 colors = mcolors.to_rgba_array(c)
   4285                 n_elem = colors.shape[0]

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in to_rgba_array(c, alpha)
    293     for i, cc in enumerate(c):
--> 294         result[i] = to_rgba(cc, alpha)
    295     return result

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    176     if rgba is None:  # Suppress exception chaining of cache lookup failure.
--> 177         rgba = _to_rgba_no_colorcycle(c, alpha)
    178         try:

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
    243     if len(c) not in [3, 4]:
--> 244         raise ValueError("RGBA sequence should have length 3 or 4")
    245     if len(c) == 3 and alpha is None:

ValueError: RGBA sequence should have length 3 or 4

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-6-1c83d5b7143d> in <module>
      3 axes.set_xlim([-0.75,0.40])
      4 axes.set_ylim([-0.75,0.65])
----> 5 plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)

D:\A_Study\B_self-study\A_Projects\deep learning HW\Course 2\Week 1 - PA 2 - Regularization\reg_utils.py in plot_decision_boundary(model, X, y)
    322     plt.ylabel('x2')
    323     plt.xlabel('x1')
--> 324     plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)
    325     plt.show()
    326 

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\pyplot.py in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, data, **kwargs)
   2841         vmin=None, vmax=None, alpha=None, linewidths=None, verts=None,
   2842         edgecolors=None, *, plotnonfinite=False, data=None, **kwargs):
-> 2843     __ret = gca().scatter(
   2844         x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
   2845         vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1597     def inner(ax, *args, data=None, **kwargs):
   1598         if data is None:
-> 1599             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1600 
   1601         bound = new_sig.bind(ax, *args, **kwargs)

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, **kwargs)
   4449 
   4450         c, colors, edgecolors = \
-> 4451             self._parse_scatter_color_args(
   4452                 c, edgecolors, kwargs, xshape, yshape,
   4453                 get_next_color_func=self._get_patches_for_fill.get_next_color)

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in _parse_scatter_color_args(c, edgecolors, kwargs, xshape, yshape, get_next_color_func)
   4291             except ValueError:
   4292                 if not valid_shape:  # but at least one conversion succeeded.
-> 4293                     raise ValueError(
   4294                         "'c' argument has {nc} elements, which is not "
   4295                         "acceptable for use with 'x' with size {xs}, "

ValueError: 'c' argument has 1 elements, which is not acceptable for use with 'x' with size 211, 'y' with size 211.

解决方法:
1、在代码文件夹中找到 reg_utils.py
2、找到 plot_decision_boundary(model, X, y) 函数
3、找到 plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral) 语句
4、将 c=y 改为 c=y.reshape(X[0,:].shape),即将 plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral) 改为 plt.scatter(X[0, :], X[1, :], c=y.reshape(X[0,:].shape), cmap=plt.cm.Spectral)
5、重新启动内核。在 Jupyter notebook 中点击 Kernel->Restart & Clear Output 。或者重新启动notebook (关掉重开)

PS: 该解决方案来自:ImSEten

4. log() 函数报错

报错位置:

parameters = model(train_X, train_Y, keep_prob = 0.86, learning_rate = 0.3)

print ("On the train set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters)

报错内容:

D:\A_Study\B_self-study\A_Projects\deep learning HW\Course 2\Week 1 - PA 2 - Regularization\reg_utils.py:236: RuntimeWarning: divide by zero encountered in log
  logprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y)
D:\A_Study\B_self-study\A_Projects\deep learning HW\Course 2\Week 1 - PA 2 - Regularization\reg_utils.py:236: RuntimeWarning: invalid value encountered in multiply
  logprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y)

解决方案:

1、在代码文件夹中找到 reg_utils.py
2、找到 compute_cost(a3, Y) 函数
3、找到 logprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y) 语句
4、在两个 np.log() 函数里加 + 1e-8 ,即将 logprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y) 改为 logprobs = np.multiply(-np.log(a3 + 1e-8),Y) + np.multiply(-np.log(1 - a3 + + 1e-8), 1 - Y)
5、重新启动内核。在 Jupyter notebook 中点击 Kernel->Restart & Clear Output 。或者重新启动notebook (关掉重开)

PS:这个问题不该也可以运行,只是会提示报警

三、 PA3: Gradient Checking 作业中遇到的问题

这个作业没遇到问题

四、 PA4: Gradient Checking 作业中遇到的问题

1. 第一个问题

报错位置:

import numpy as np
import matplotlib.pyplot as plt
import scipy.io
import math
import sklearn
import sklearn.datasets

from opt_utils import load_params_and_grads, initialize_parameters, forward_propagation, backward_propagation
from opt_utils import compute_cost, predict, predict_dec, plot_decision_boundary, load_dataset
from testCases import *

%matplotlib inline
plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

报错内容:

D:\A_Study\B_self-study\A_Projects\deep learning HW\Course 2\Week 2 - PA 4 - Optimization Methods\opt_utils.py:76: SyntaxWarning: assertion is always true, perhaps remove parentheses?
  assert(parameters['W' + str(l)].shape == layer_dims[l], layer_dims[l-1])
D:\A_Study\B_self-study\A_Projects\deep learning HW\Course 2\Week 2 - PA 4 - Optimization Methods\opt_utils.py:77: SyntaxWarning: assertion is always true, perhaps remove parentheses?
  assert(parameters['W' + str(l)].shape == layer_dims[l], 1)

解决方案:

1、在代码文件夹中找到 opt_utils.py 文件
2、找到 initialize_parameters(layer_dims) 函数
3、找到 assert(parameters['W' + str(l)].shape == layer_dims[l], layer_dims[l-1] 函数
4、对 layer_dims[l], layer_dims[l-1] 添加括号,即 (layer_dims[l], layer_dims[l-1]) ,即该语句变为 assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1]))
5、找到 assert(parameters['W' + str(l)].shape == layer_dims[l], 1) 函数
将W改为b,对 layer_dims[l], 1 添加括号,即 (layer_dims[l], 1),即该语句变为 assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))

PS:这个问题和 Regularization 作业的第一个问题是一样的

2. 画图的 bug

报错位置:

# train 3-layer model
layers_dims = [train_X.shape[0], 5, 2, 1]
parameters = model(train_X, train_Y, layers_dims, optimizer = "gd")

# Predict
predictions = predict(train_X, train_Y, parameters)

# Plot decision boundary
plt.title("Model with Gradient Descent optimization")
axes = plt.gca()
axes.set_xlim([-1.5,2.5])
axes.set_ylim([-1,1.5])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)

报错内容:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in _parse_scatter_color_args(c, edgecolors, kwargs, xshape, yshape, get_next_color_func)
   4283             try:  # Then is 'c' acceptable as PathCollection facecolors?
-> 4284                 colors = mcolors.to_rgba_array(c)
   4285                 n_elem = colors.shape[0]

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in to_rgba_array(c, alpha)
    293     for i, cc in enumerate(c):
--> 294         result[i] = to_rgba(cc, alpha)
    295     return result

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    176     if rgba is None:  # Suppress exception chaining of cache lookup failure.
--> 177         rgba = _to_rgba_no_colorcycle(c, alpha)
    178         try:

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
    243     if len(c) not in [3, 4]:
--> 244         raise ValueError("RGBA sequence should have length 3 or 4")
    245     if len(c) == 3 and alpha is None:

ValueError: RGBA sequence should have length 3 or 4

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-20-6c6daf13604b> in <module>
     11 axes.set_xlim([-1.5,2.5])
     12 axes.set_ylim([-1,1.5])
---> 13 plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)

D:\A_Study\B_self-study\A_Projects\deep learning HW\Course 2\Week 2 - PA 4 - Optimization Methods\opt_utils.py in plot_decision_boundary(model, X, y)
    230     plt.ylabel('x2')
    231     plt.xlabel('x1')
--> 232     plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)
    233     plt.show()
    234 

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\pyplot.py in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, data, **kwargs)
   2841         vmin=None, vmax=None, alpha=None, linewidths=None, verts=None,
   2842         edgecolors=None, *, plotnonfinite=False, data=None, **kwargs):
-> 2843     __ret = gca().scatter(
   2844         x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
   2845         vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1597     def inner(ax, *args, data=None, **kwargs):
   1598         if data is None:
-> 1599             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1600 
   1601         bound = new_sig.bind(ax, *args, **kwargs)

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, plotnonfinite, **kwargs)
   4449 
   4450         c, colors, edgecolors = \
-> 4451             self._parse_scatter_color_args(
   4452                 c, edgecolors, kwargs, xshape, yshape,
   4453                 get_next_color_func=self._get_patches_for_fill.get_next_color)

E:\anaconda3\envs\ml\lib\site-packages\matplotlib\axes\_axes.py in _parse_scatter_color_args(c, edgecolors, kwargs, xshape, yshape, get_next_color_func)
   4291             except ValueError:
   4292                 if not valid_shape:  # but at least one conversion succeeded.
-> 4293                     raise ValueError(
   4294                         "'c' argument has {nc} elements, which is not "
   4295                         "acceptable for use with 'x' with size {xs}, "

ValueError: 'c' argument has 1 elements, which is not acceptable for use with 'x' with size 300, 'y' with size 300.

解决方法:
1、在代码文件夹中找到 opt_utils.py
2、找到 plot_decision_boundary(model, X, y) 函数
3、找到 plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral) 语句
4、将 c=y 改为 c=y.reshape(X[0,:].shape),即将 plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral) 改为 plt.scatter(X[0, :], X[1, :], c=y.reshape(X[0,:].shape), cmap=plt.cm.Spectral)
5、重新启动内核。在 Jupyter notebook 中点击 Kernel->Restart & Clear Output 。或者重新启动notebook (关掉重开)

PS:这个问题在前面也遇到过

五、PA5: TensorFlow Tutorial

1. 版本不兼容造成的报错

报错位置:

y_hat = tf.constant(36, name='y_hat')            # Define y_hat constant. Set to 36.
y = tf.constant(39, name='y')                    # Define y. Set to 39

loss = tf.Variable((y - y_hat)**2, name='loss')  # Create a variable for the loss

init = tf.global_variables_initializer()         # When init is run later (session.run(init)),
                                                 # the loss variable will be initialized and ready to be computed
with tf.Session() as session:                    # Create a session and print the output
    session.run(init)                            # Initializes the variables
    print(session.run(loss))                     # Prints the loss

报错内容:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-16-873eee88ff15> in <module>
      4 loss = tf.Variable((y - y_hat)**2, name='loss')  # Create a variable for the loss
      5 
----> 6 init = tf.global_variables_initializer()         # When init is run later (session.run(init)),
      7                                                  # the loss variable will be initialized and ready to be computed
      8 with tf.Session() as session:                    # Create a session and print the output

AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer'

解决方法:

1、找到第一个代码块的 import tensorflow as tf ,修改为 import tensorflow.compat.v1 as tf

2、在 from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict 下面加一行 tf.compat.v1.disable_eager_execution() ,最后第一个代码块就变成了如下:

import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow.compat.v1 as tf
from tensorflow.python.framework import ops
from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
tf.compat.v1.disable_eager_execution()

%matplotlib inline
np.random.seed(1)

3、从第一代码块开始重新运行

2. 初始化参数函数报错

报错位置:

tf.reset_default_graph()
with tf.Session() as sess:
    parameters = initialize_parameters()
    print("W1 = " + str(parameters["W1"]))
    print("b1 = " + str(parameters["b1"]))
    print("W2 = " + str(parameters["W2"]))
    print("b2 = " + str(parameters["b2"]))

报错内容:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-37-63028b6b5f4e> in <module>
      1 tf.reset_default_graph()
      2 with tf.Session() as sess:
----> 3     parameters = initialize_parameters()
      4     print("W1 = " + str(parameters["W1"]))
      5     print("b1 = " + str(parameters["b1"]))

<ipython-input-36-f347dd1505b7> in initialize_parameters()
     18 
     19     ### START CODE HERE ### (approx. 6 lines of code)
---> 20     W1 = tf.get_variable("W1", [25,12288], initializer = tf.contrib.layers.xavier_initializer(seed = 1))
     21     b1 = tf.get_variable("b1", [25,1], initializer = tf.zeros_initializer())
     22     W2 = tf.get_variable("W2", [12,25], initializer = tf.contrib.layers.xavier_initializer(seed = 1))

AttributeError: module 'tensorflow.compat.v1' has no attribute 'contrib'

解决方法:

1、找到 2.2 的第一个代码块,其中有一个 def initialize_parameters() 函数

2、将题目中提示的初始化 W 的方法 W1 = tf.get_variable("W1", [25,12288], initializer = tf.contrib.layers.xavier_initializer(seed = 1)) 中的 tf.contrib.layers.xavier_initializer(seed = 1)) 改成使用 tf.glorot_uniform_initializer(seed=1)

3、则变成初始化 W1 使用的代码是 W1 = tf.get_variable("W1", [25,12288], initializer = tf.glorot_uniform_initializer(seed=1)) ,W2、W3同

PS:tf.contrib.layers.xavier_initializer(seed = 1)) 函数在 tensorflow 2.0中不存在了,所以需要改成替代的函数

Course 4 中的一些问题

一、PA1: Convolutional Model step by step

没有遇到问题

二、PA2: Convolutional Model application

1. Tensorflow 版本不兼容报错

报错位置:

X, Y = create_placeholders(64, 64, 3, 6)
print ("X = " + str(X))
print ("Y = " + str(Y))

报错内容:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-b900d089d9ad> in <module>
----> 1 X, Y = create_placeholders(64, 64, 3, 6)
      2 print ("X = " + str(X))
      3 print ("Y = " + str(Y))

<ipython-input-6-8e668699e435> in create_placeholders(n_H0, n_W0, n_C0, n_y)
     17 
     18     ### START CODE HERE ### (≈2 lines)
---> 19     X = tf.placeholder(tf.float32, [None, n_H0, n_W0, n_C0], name = "X")
     20     Y = tf.placeholder(tf.float32, [None, n_y], name = "Y")
     21     ### END CODE HERE ###

AttributeError: module 'tensorflow' has no attribute 'placeholder'

解决方法:

1、找到第一个代码块

import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
import tensorflow as tf
from tensorflow.python.framework import ops
from cnn_utils import *

%matplotlib inline
np.random.seed(1)

2、将其中的 from cnn_utils import * 放到 import tensorflow as tf 前面

3、将 import tensorflow as tf 改为 import tensorflow.compat.v1 as tf ,并在 %matplotlib inline 上面加一行 tf.compat.v1.disable_eager_execution()

4、改完后第一个代码块变成了

import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import scipy
from PIL import Image
from scipy import ndimage
from cnn_utils import *
import tensorflow.compat.v1 as tf
from tensorflow.python.framework import ops

tf.compat.v1.disable_eager_execution()
%matplotlib inline
np.random.seed(1)

PS:将 from cnn_utils import * 放到前面是 cnn_utils.py 文件中也调用了 import tensorflow as tf ,会将这里的 import tensorflow.compat.v1 as tf 覆盖掉,保险起见可以将 cnn_utils.py 文件中的 import tensorflow as tf 也做和这里一样的修改。

2. 参数初始化报错

报错位置:

tf.reset_default_graph()
with tf.Session() as sess_test:
    parameters = initialize_parameters()
    init = tf.global_variables_initializer()
    sess_test.run(init)
    print("W1 = " + str(parameters["W1"].eval()[1,1,1]))
    print("W2 = " + str(parameters["W2"].eval()[1,1,1]))

报错内容:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-d1bb58300342> in <module>
      1 tf.reset_default_graph()
      2 with tf.Session() as sess_test:
----> 3     parameters = initialize_parameters()
      4     init = tf.global_variables_initializer()
      5     sess_test.run(init)

<ipython-input-7-49d61ce0535b> in initialize_parameters()
     13 
     14     ### START CODE HERE ### (approx. 2 lines of code)
---> 15     W1 = tf.get_variable("W1", [4, 4, 3, 8], initializer = tf.contrib.layers.xavier_initializer(seed = 0))
     16     W2 = tf.get_variable("W2", [2, 2, 8, 16], initializer = tf.contrib.layers.xavier_initializer(seed = 0))
     17     ### END CODE HERE ###

AttributeError: module 'tensorflow.compat.v1' has no attribute 'contrib'

解决方法:

1、不要使用提示里使用的 tf.contrib.layers.xavier_initializer(seed = 0) 来初始化参数,使用其替代函数 tf.glorot_uniform_initializer(seed=0)

PS:这个问题和 Course2 的第五个编程作业 Tensorflow Tutorial 中的问题是一样的。

3. 版本不兼容报错

报错位置:

tf.reset_default_graph()

with tf.Session() as sess:
    np.random.seed(1)
    X, Y = create_placeholders(64, 64, 3, 6)
    parameters = initialize_parameters()
    Z3 = forward_propagation(X, parameters)
    init = tf.global_variables_initializer()
    sess.run(init)
    a = sess.run(Z3, {X: np.random.randn(2,64,64,3), Y: np.random.randn(2,6)})
    print("Z3 = " + str(a))

报错内容:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-30-8d225709836c> in <module>
      5     X, Y = create_placeholders(64, 64, 3, 6)
      6     parameters = initialize_parameters()
----> 7     Z3 = forward_propagation(X, parameters)
      8     init = tf.global_variables_initializer()
      9     sess.run(init)

<ipython-input-29-e2218c56a6d2> in forward_propagation(X, parameters)
     33     P2 = tf.nn.max_pool(A2, ksize = [1,4,4,1], strides = [1,4,4,1], padding = 'SAME')
     34     # FLATTEN
---> 35     P2 = tf.contrib.layers.flatten(P2)
     36     # FULLY-CONNECTED without non-linear activation function (not not call softmax).
     37     # 6 neurons in output layer. Hint: one of the arguments should be "activation_fn=None"

AttributeError: module 'tensorflow.compat.v1' has no attribute 'contrib'

解决方法:

1、不要使用提示中的 tf.contrib.layers.flatten(P) ,把 contrib 去掉,变成tf.layers.flatten(P)

2、不要使用提示中的 tf.contrib.layers.fully_connected(F, num_outputs) 来做全连接层,使用 tf.layers.dense(F, num_outputs)

PS:由于使用了替代函数,我得到的结果与答案不同,不确定是我哪有有问题还是替代函数造成的差异,我得到的结果如下:

Z3 = [[ 0.9927579 -1.9926488 0.40574205 -1.0828865 0.5642381 -1.7546117 ]
[ 0.93642586 -1.8676597 0.10536456 -1.0255287 0.7649098 -1.9162732 ]]

除此之外后面的所有输出都与答案不同,不过最后训练的模型表现和答案不相上下,故在此贴出后面的练习的我的结果:

compute_cost:

cost = 2.695238

model:

**Cost after epoch 0 =** 1.921844
**Cost after epoch 5 =** 1.586086
**Train Accuracy =** 0.93703705
**Test Accuracy =** 0.84166664
4. 最后一个代码块 imread 报错不做处理

三、PA3: Keras Tutorial

1. Keras 版本不兼容报错

报错位置:

### START CODE HERE ### (1 line)
happyModel = HappyModel((64, 64, 3))
### END CODE HERE ###

报错内容:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
E:\anaconda3\envs\ml\lib\site-packages\keras\backend\tensorflow_backend.py in _get_default_graph()
     65     try:
---> 66         return tf.get_default_graph()
     67     except AttributeError:

AttributeError: module 'tensorflow' has no attribute 'get_default_graph'

During handling of the above exception, another exception occurred:

RuntimeError                              Traceback (most recent call last)
<ipython-input-4-e002e0fd465c> in <module>
      1 ### START CODE HERE ### (1 line)
----> 2 happyModel = HappyModel((64, 64, 3))
      3 ### END CODE HERE ###

<ipython-input-3-7d55dd6a9b72> in HappyModel(input_shape)
     16     # exercise (including the later portions of this notebook) once. The come back also try out other
     17     # network architectures as well.
---> 18     X = Input(input_shape)
     19 
     20     # Zero-Padding: pads the border of X_input with zeroes

E:\anaconda3\envs\ml\lib\site-packages\keras\engine\input_layer.py in Input(shape, batch_shape, name, dtype, sparse, tensor)
    173     if not dtype:
    174         dtype = K.floatx()
--> 175     input_layer = InputLayer(batch_input_shape=batch_shape,
    176                              name=name, dtype=dtype,
    177                              sparse=sparse,

E:\anaconda3\envs\ml\lib\site-packages\keras\legacy\interfaces.py in wrapper(*args, **kwargs)
     89                 warnings.warn('Update your `' + object_name + '` call to the ' +
     90                               'Keras 2 API: ' + signature, stacklevel=2)
---> 91             return func(*args, **kwargs)
     92         wrapper._original_function = func
     93         return wrapper

E:\anaconda3\envs\ml\lib\site-packages\keras\engine\input_layer.py in __init__(self, input_shape, batch_size, batch_input_shape, dtype, input_tensor, sparse, name)
     37         if not name:
     38             prefix = 'input'
---> 39             name = prefix + '_' + str(K.get_uid(prefix))
     40         super(InputLayer, self).__init__(dtype=dtype, name=name)
     41 

E:\anaconda3\envs\ml\lib\site-packages\keras\backend\tensorflow_backend.py in get_uid(prefix)
     84     """
     85     global _GRAPH_UID_DICTS
---> 86     graph = _get_default_graph()
     87     if graph not in _GRAPH_UID_DICTS:
     88         _GRAPH_UID_DICTS[graph] = defaultdict(int)

E:\anaconda3\envs\ml\lib\site-packages\keras\backend\tensorflow_backend.py in _get_default_graph()
     66         return tf.get_default_graph()
     67     except AttributeError:
---> 68         raise RuntimeError(
     69             'It looks like you are trying to use '
     70             'a version of multi-backend Keras that '

RuntimeError: It looks like you are trying to use a version of multi-backend Keras that does not support TensorFlow 2.0. We recommend using `tf.keras`, or alternatively, downgrading to TensorFlow 1.14.

解决方法:

1、找到第一个代码块

import numpy as np
from keras import layers
from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
from keras.models import Model
from keras.preprocessing import image
from keras.utils import layer_utils
from keras.utils.data_utils import get_file
from keras.applications.imagenet_utils import preprocess_input
import pydot
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
from keras.utils import plot_model
from kt_utils import *

import keras.backend as K
K.set_image_data_format('channels_last')
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow

%matplotlib inline

2、把里面除了 keras.utilskeras.backend 的其他 keras 前加上 tensorflow.python.

3、改完后变成了:

import numpy as np
from tensorflow.python.keras import layers
from tensorflow.python.keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from tensorflow.python.keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
from tensorflow.python.keras.models import Model
from tensorflow.python.keras.preprocessing import image
from tensorflow.python.keras.utils import layer_utils
from tensorflow.python.keras.utils.data_utils import get_file
from tensorflow.python.keras.applications.imagenet_utils import preprocess_input
import pydot
from IPython.display import SVG
from tensorflow.python.keras.utils.vis_utils import model_to_dot
from keras.utils import plot_model
from kt_utils import *

import keras.backend as K
K.set_image_data_format('channels_last')
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow

%matplotlib inline
2. 最后一个代码块的报错不怎么重要就不处理了
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值