質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Jupyter

Jupyter (旧IPython notebook)は、Notebook形式でドキュメント作成し、プログラムの記述・実行、その実行結果を記録するツールです。メモの作成や保存、共有、確認などもブラウザ上で行うことができます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

2回答

5464閲覧

jupyter notebookでCIFAR10の動かし方

0afnjosa

総合スコア7

Jupyter

Jupyter (旧IPython notebook)は、Notebook形式でドキュメント作成し、プログラムの記述・実行、その実行結果を記録するツールです。メモの作成や保存、共有、確認などもブラウザ上で行うことができます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/10/10 13:44

前提・実現したいこと

エラーの原因を知りたい。また、その改善策を知りたい。

発生している問題

jupyter notebook上でCIFAR10の画像を表示しようとしたらエラーが出てしまいました。
本に載っているコードをそのままコピーしているのでコードミスでは無いと思うのですが、原因が分かりません。

該当のソースコード

import numpy as np
from tensorflow.keras.datasets import cifar10
import matplotlib.pyplot as plt
%matplotlib inline

(X_train, y_train), (X_test, y_test) = cifar10.load_data()

print('X_train:',X_train.shape, 'y_train:', y_train.shape)
print('X_test :', X_test.shape, 'y_test :', y_test.shape)

num_classes = 10 # 分類先のクラスの数
pos = 1 # 画像の描画位置を保持する変数

for target_class in range(num_classes):

target_idx = [] for i in range(len(y_train)): if y_train[i][0] == target_class: target_idx.append(i) np.random.shuffle(target_idx) # クラスiの画像のインデックスをシャッフル plt.figure(figsize=(20, 20)) # 描画エリアを横25インチ、縦3インチにする for idx in target_idx[:10]: plt.subplot(10, 10, pos) # 10行、10列の描画領域のpos番目の位置を指定 plt.imshow(X_train[idx]) # Matplotlibのimshow()で画像を描画 pos += 1

plt.show()

エラーメッセージ

Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz

SSLCertVerificationError Traceback (most recent call last)
~\anaconda3\lib\urllib\request.py in do_open(self, http_class, req, **http_conn_args)
1353 try:
-> 1354 h.request(req.get_method(), req.selector, req.data, headers,
1355 encode_chunked=req.has_header('Transfer-encoding'))

~\anaconda3\lib\http\client.py in request(self, method, url, body, headers, encode_chunked)
1254 """Send a complete request to the server."""
-> 1255 self._send_request(method, url, body, headers, encode_chunked)
1256

~\anaconda3\lib\http\client.py in _send_request(self, method, url, body, headers, encode_chunked)
1300 body = _encode(body, 'body')
-> 1301 self.endheaders(body, encode_chunked=encode_chunked)
1302

~\anaconda3\lib\http\client.py in endheaders(self, message_body, encode_chunked)
1249 raise CannotSendHeader()
-> 1250 self._send_output(message_body, encode_chunked=encode_chunked)
1251

~\anaconda3\lib\http\client.py in _send_output(self, message_body, encode_chunked)
1009 del self._buffer[:]
-> 1010 self.send(msg)
1011

~\anaconda3\lib\http\client.py in send(self, data)
949 if self.auto_open:
--> 950 self.connect()
951 else:

~\anaconda3\lib\http\client.py in connect(self)
1423
-> 1424 self.sock = self._context.wrap_socket(self.sock,
1425 server_hostname=server_hostname)

~\anaconda3\lib\ssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, session)
499 # ctx._wrap_socket()
--> 500 return self.sslsocket_class._create(
501 sock=sock,

~\anaconda3\lib\ssl.py in _create(cls, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, context, session)
1039 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
-> 1040 self.do_handshake()
1041 except (OSError, ValueError):

~\anaconda3\lib\ssl.py in do_handshake(self, block)
1308 self.settimeout(None)
-> 1309 self._sslobj.do_handshake()
1310 finally:

SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1125)

During handling of the above exception, another exception occurred:

URLError Traceback (most recent call last)
~\anaconda3\lib\site-packages\keras\utils\data_utils.py in get_file(fname, origin, untar, md5_hash, file_hash, cache_subdir, hash_algorithm, extract, archive_format, cache_dir)
273 try:
--> 274 urlretrieve(origin, fpath, dl_progress)
275 except urllib.error.HTTPError as e:

~\anaconda3\lib\site-packages\keras\utils\data_utils.py in urlretrieve(url, filename, reporthook, data)
81
---> 82 response = urlopen(url, data)
83 with open(filename, 'wb') as fd:

~\anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
221 opener = _opener
--> 222 return opener.open(url, data, timeout)
223

~\anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
524 sys.audit('urllib.Request', req.full_url, req.data, req.headers, req.get_method())
--> 525 response = self._open(req, data)
526

~\anaconda3\lib\urllib\request.py in _open(self, req, data)
541 protocol = req.type
--> 542 result = self._call_chain(self.handle_open, protocol, protocol +
543 '_open', req)

~\anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
501 func = getattr(handler, meth_name)
--> 502 result = func(*args)
503 if result is not None:

~\anaconda3\lib\urllib\request.py in https_open(self, req)
1396 def https_open(self, req):
-> 1397 return self.do_open(http.client.HTTPSConnection, req,
1398 context=self._context, check_hostname=self._check_hostname)

~\anaconda3\lib\urllib\request.py in do_open(self, http_class, req, **http_conn_args)
1356 except OSError as err: # timeout error
-> 1357 raise URLError(err)
1358 r = h.getresponse()

URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1125)>

During handling of the above exception, another exception occurred:

Exception Traceback (most recent call last)
<ipython-input-3-577dfc82a816> in <module>
5
6 # CIFAR-10データセットをロード
----> 7 (X_train, y_train), (X_test, y_test) = cifar10.load_data()
8 # データの形状を出力
9 print('X_train:',X_train.shape, 'y_train:', y_train.shape)

~\anaconda3\lib\site-packages\keras\datasets\cifar10.py in load_data()
77 dirname = 'cifar-10-batches-py'
78 origin = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'
---> 79 path = get_file(
80 dirname,
81 origin=origin,

~\anaconda3\lib\site-packages\keras\utils\data_utils.py in get_file(fname, origin, untar, md5_hash, file_hash, cache_subdir, hash_algorithm, extract, archive_format, cache_dir)
276 raise Exception(error_msg.format(origin, e.code, e.msg))
277 except urllib.error.URLError as e:
--> 278 raise Exception(error_msg.format(origin, e.errno, e.reason))
279 except (Exception, KeyboardInterrupt) as e:
280 if os.path.exists(fpath):

Exception: URL fetch failure on https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz: None -- [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1125)

#その他
長くなってしまい申し訳ありませんが、何か分かる方教えて頂けるとありがたいです。
よろしくお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

jbpb0

2021/10/10 13:54 編集

もしかして、コードを実行したパソコンがつながってるネットワークは、プロキシ下ではありませんか?
0afnjosa

2021/10/10 14:47

ご回答ありがとうございます。 自宅のネットワークを調べてみたところ、プロキシサーバーなしとでました。 しかし、初回実行時は出先でイオンのWi-Fiを使っていたのでその時はプロキシ下だったかもしれません。
0afnjosa

2021/10/10 15:17

頂いたコードを加えた結果、ダウンロード開始できたようです。 大変助かりました。夜遅くにありがとうございました。
guest

回答2

0

ベストアンサー

投稿2021/10/11 00:31

編集2021/10/11 00:33
jbpb0

総合スコア7651

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

以下のプログラムを実行してみてください。

python

1import requests 2 3r = requests.get('https://teratail.com/questions/363780') 4print(r.text)

これで同じようなエラーが出るのであれば、jbpb0さんが書かれているようにネットワークの問題です。

イントラネット内で外部へのアクセスが制限されているのであれば、組織内のネットワーク管理者に相談しましょう。
家庭のPCでVMを使っている場合は、VMのネットワーク設定を確認してください。

もしも上記のコードは正しく動くのであれば、それを回答に追加してください。

投稿2021/10/10 14:50

ppaul

総合スコア24666

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0afnjosa

2021/10/10 15:07

いただいた実行した結果です。 <!DOCTYPE html> <html lang="ja" itemscope itemtype="http://schema.org/QAPage"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="viewport" content="width=1024"> <meta name="robots" content="index,follow"> <link rel="canonical" href="https://teratail.com/questions/363780"> <meta property="og:title" content="jupyter notebookでCIFAR10の動かし方|teratail"/><meta property="og:type" content="article"/><meta property="og:description" content="前提・実現したいことエラーの原因を知りたい。また、その改善策を知りたい。 発生している問題jupyter&nbsp;notebook上でCIFAR10の画像を表示しようとしたらエラーが出てしまいました。本に載っているコードをそのままコピーしているのでコードミスでは無いと思うのですが、原因が分かりま" itemprop="description"/><meta property="og:url" content="https://teratail.com/questions/363780" itemprop="url"/><meta property="og:image" content="https://teratail.com/img/imgFacebookShare.png"/><meta property="og:site_name" content="teratail[テラテイル]"/><meta property="og:locale" content="ja_JP"/><meta property="fb:app_id" content="313209618817050"/> <meta property="twitter:card" content="summary"/><meta property="twitter:site" content="@teratail"/><meta property="twitter:image" content="https://teratail.com/img/imgTwitterCard.png"/><meta property="twitter:description" content="前提・実現したいことエラーの原因を知りたい。また、その改善策を知りたい。 発生している問題jupyter&nbsp;notebook上でCIFAR10の画像を表示しようとしたらエラーが出てしまいました。本に載っているコードをそのままコピーしているのでコードミスでは無いと思うのですが、原因が分かりま"/><meta property="twitter:title" content="jupyter notebookでCIFAR10の動かし方|teratail"/><title>Python - jupyter notebookでCIFAR10の動かし方|teratail</title> <link rel="stylesheet" type="text/css" href="/css/material-icons.css?1632990936"/><link rel="stylesheet" type="text/css" href="/css/Pages/qaDetail.css?1632990936"/><link rel="stylesheet" type="text/css" href="/css/plugins/bootstrap-markdown.min.css?1632990234"/><link rel="stylesheet" type="text/css" href="/css/plugins/bootstrap-tagsinput.css?1632990234"/><link rel="stylesheet" type="text/css" href="/css/plugins/highlight/common/default.css?1632990234"/><link rel="stylesheet" type="text/css" href="/css/plugins/highlight/common/highlight.css?1632990234"/> <link rel='apple-touch-icon-precomposed' size='72x72' href='/img/favicon/apple-touch-icon-72x72-precomposed.png'> <link rel='apple-touch-icon-precomposed' size='114x114' href='/img/favicon/apple-touch-icon-114x114-precomposed.png'> <link rel='apple-touch-icon-precomposed' size='144x144' href='/img/favicon/apple-touch-icon-144x144-precomposed.png'> <link rel='apple-touch-icon-precomposed' size='152x152' href='/img/favicon/apple-touch-icon-152x152-precomposed.png'> <link rel='apple-touch-icon-precomposed' size='180x180' href='/img/favicon/apple-touch-icon-180x180-precomposed.png'> <link rel='icon' type='image/png' sizes='32x32' href='/img/favicon/favicon-32x32.png'> <link rel='icon' type='image/png' sizes='16x16' href='/img/favicon/favicon-16x16.png'> <link rel='mask-icon' href='/img/favicon/safari-pinned-tab.svg' color='#f4c51c'> <link rel='icon' href='/favicon.ico'> <meta name="msapplication-TileColor" content="#000000"> <meta name="msapplication-config" content="/browserconfig.xml"> <meta name='theme-color' content='#ffffff'> <style>.async-hide { opacity: 0 !important} </style> <script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date; h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')}; (a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c; })(window,document.documentElement,'async-hide','dataLayer',4000, {'GTM-PTDVPV8':true});</script> <style>.async-hide { opacity: 0 !important} </style> <script src="https://www.googleoptimize.com/optimize.js?id=OPT-5PFC3S8"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('require', 'OPT-5PFC3S8'); ga('create', 'UA-45098004-1', { 'cookieDomain': 'teratail.com' }); ga('set', 'dimension15', 'web,web-backend,dataanalytics,lt-web,flc'); var getCookie = (function(){ return function() { var result = []; var cookies = document.cookie; if(cookies != ''){ var cookieArray = cookies.split(';'); for(var i = 0; i < cookieArray.length; i++){ var cookie = cookieArray[i].split('='); var key = cookie[0].replace(/^\s+|\s+$/g, ""); result[key] = decodeURIComponent(cookie[1]); } } return result; }; })(); ga('set', 'dimension13', getCookie().tt_stc); ga('set', 'dimension14', 0); ga('require', 'GTM-PTDVPV8'); var is_login = 0; var num_replies = 1; var is_resolved = 0; var virtual_url = location.pathname + '/s' + is_login + '_a' + num_replies + '_ba' + is_resolved + location.search; ga('send', 'pageview', virtual_url); </script> <script> if (document.referrer.match(/google.(com|co.jp)/gi) && document.referrer.match(/cd/gi)) { var myString = document.referrer; var r = myString.match(/cd=(.*?)&/); var rank = parseInt(r[1]); var kw = myString.match(/q=(.*?)&/); if (kw[1].length > 0) { var keyWord = decodeURI(kw[1]); } else { keyWord = "(not provided)"; } var p = document.location.pathname; ga('send', 'event', 'RankTracker', keyWord, p, rank, true); } </script> <script async='async' src='https://www.googletagservices.com/tag/js/gpt.js'></script> <script> var googletag = googletag || {}; googletag.cmd = googletag.cmd || []; </script> <script> var gptAdSlots = []; var refreshedSlots = []; googletag.cmd.push(function() { // サイズ マッピング オブジェクトを定義。addSuze の最初のパラメータは // ビューポートのサイズ、2番目のパラメータは使用できる広告のサイズ var mapping0 = googletag.sizeMapping(). addSize([0, 0], ['fluid', [300, 250], [1, 1]]). // タブレット addSize([1217, 690], ['fluid', [300, 250], [336, 280], [1, 1]]). // パソコン build(); gptAdSlots[0] = googletag.defineSlot('/83555300/leverages/teratail/pc_article_underarticleleft', [[1,1], 'fluid', [300, 250], [336, 280]], 'pc_article_underarticleleft'). defineSizeMapping(mapping0). setCollapseEmptyDiv(true). addService(googletag.pubads()); var mapping1 = googletag.sizeMapping(). addSize([0, 0], ['fluid', [300, 250], [1, 1]]). // タブレット addSize([1217, 690], ['fluid', [300, 250], [336, 280], [1, 1]]). // パソコン build(); gptAdSlots[1] = googletag.defineSlot('/83555300/leverages/teratail/pc_article_underarticleright', [[1,1], 'fluid', [300, 250], [336, 280]], 'pc_article_underarticleright'). defineSizeMapping(mapping1). setCollapseEmptyDiv(true). addService(googletag.pubads()); googletag.defineSlot('/83555300/leverages/teratail/pc_all_right_1', [[300, 250], 'fluid', [1, 1]], 'pc_all_right_1').addService(googletag.pubads()); refreshedSlots = [ googletag.defineSlot('/83555300/leverages/teratail/pc_all_right_2', [[1, 1], 'fluid', [300, 250], [300, 600], [120, 600], [160, 600]], 'pc_all_right_2').addService(googletag.pubads()) ]; 10000文字以内で入力してくださいとあったので削りましたが、このような出力がされました。
0afnjosa

2021/10/10 15:29

jbpb0さんの方法で解決いたしました。 ppaulさんも解決案を提示して頂き助かりました。ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問