반응형

https://wikidocs.net/14606

 

3.1 ndarray

### 개념과 생성 NumPy와 패키지의 핵심은 `ndarray` 객체이다. * `ndarray`는 fixed-size homogeneous multidimensional …

wikidocs.net

3.1 ndarray

개념과 생성

NumPy와 패키지의 핵심은 ndarray 객체이다.

  • ndarray는 fixed-size homogeneous multidimensional array 정도로 이해할 수 있으며, 기본적으로 vectorization과 broadcasting을 지원한다.
  • Python에서 제공하는 list, tuple 등의 시퀀스 자료형은 서로 다른 데이터타입을 저장할 수 있고(heterogeneous sequence), 크기가 자동으로 커질 수 있다. 반면에 ndarray는 성능향상을 위해 같은 데이터타입만을 요소로 가질 수 있고, 크기 역시 고정되어 있다. 만약 크기를 변경하면 새로 메모리에 할당되고 이전 값은 삭제된다.
# https://wikidocs.net/14606
import numpy as np

print("x는 float64를 요소타입으로 갖는 크기 3의 1차원 배열이다.")
x = np.array((0.1,0.2,0.3))
print(x)
print(x.shape)  # 차원 : 1자원 배열의 shape는 (m,)
print(x.dtype) # 요소 타입 : float64

print("y는 int32를 요소 타입으로 하는 (2,3) 크기의 2차원 배열이다.")
y = np.array(((1,2,3),(4,5,6)))
print(y)
print(y.shape)  # 차원 : 2자원 배열의 shape는 (m,n)  3차원은 (p,q,r)
print(y.dtype) # 요소 타입 : int32

print("생성시 입력된 값을 통해 dtype을 추천하는데, 강제로 지정하는 것은 다음과 같다.")
z = np.array([1,2,3],dtype='float64')
print(z)
print(z.shape)
print(z.dtype)

"""_summary_
ndarray의 중요 속성을 정리하면 다음과 같다.

shape : 배열의 형태
dtype : 요소의 데이터 타입, int32, float32 등등
ndim : 차원수. x.ndim = 1, y.ndim=2 등이며 len(x.shape) 와 동일
size : 요소의 개수. shape의 모든 값의 곱. x.size = 3, y.size=6 등
itemsize : 요소 데이터 타입의 크기(byte 단위), x.itemsize=8 등
data : 실제 데이터. 직접 사용자가 접근할 필요는 없음
"""

print("초기화 관련 편의함수")
Y = np.zeros((3,3))
print(Y)
Y = np.ones((3,3),dtype='int32')
Z = np.empty((3,3))

print("\n미리 크기지정없이 순차적으로 만들때, 크기 0인 배열을 생성하고 append()를 수행")
A = np.array([])
for i in range(3):
    A = np.append(A,[1,2,3])

print(A)

print("단순한 시퀀스는 range() 함수의 실수버전인 arange(from,to,step)이나 \nlinspace(from,to,npoints)를 사용하면 편리하다. \n또한 단위행렬을 위한 eye(n) 함수를 제공한다.")
print(np.arange(1,2,0.1))
#array([ 1. ,  1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8,  1.9])
print(np.arange(10))   # start, step 생략가능. 정수로 생성
#array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(np.arange(10.))  # start, step 생략가능. 실수로 생성
#array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])
print(np.linspace(0.,20.,11))
#array([  0.,   2.,   4., ...,  16.,  18.,  20.])
print(np.eye(3))
#array([[ 1.,  0.,  0.],
#       [ 0.,  1.,  0.],
#       [ 0.,  0.,  1.]])

print("\n\nshape과 dtype 변경")
msg = "ndarray는 고정된 크기를 유지하면서 shape을 변경할 수 있다. 예를 들어 크기 9의 1차원 배열을 3*3 2차원 배열로 바꿀 수 있다. \n이때 사용하는 함수는 reshape() 인데 함수 또는 메쏘드 형태로 제공한다."
print(msg)

X = np.arange(0,9,1.)
print(X)
Y = np.reshape(X,(3,3)) # 또는 Y=X.reshape((3,3))
print(Y)

#만약 자기 자신을 대상을 변경하면 shape 속성을 강제로 변경하면 된다.
X.shape = (3,3)
print(X)

print("astype() 메쏘드를 사용하면 배열에서 dtype을 바꿀 수 있다.")

a = np.arange(3);
a.astype(int)  # a.astype('int34') 와 동일
a.astype('int34') 
a.astype('int64')
a.astype(float)    # a.astype('float64')
a.astype('float32')
a.astype('float64')
print(a)
반응형
반응형


error : Cannot interpret '<attribute 'dtype' of 'numpy.generic' objects>' as a data type 

 

    발생하면  pandas를 업그레이드 하라. 

 

pip install numpy --upgrade
pip install pandas --upgrade
반응형
반응형

Gensim word vector visualization of various word vectors

web.stanford.edu/class/cs224n/materials/Gensim%20word%20vector%20visualization.html

 

Gensim word vector visualization

For looking at word vectors, I'll use Gensim. We also use it in hw1 for word vectors. Gensim isn't really a deep learning package. It's a package for for word and text similarity modeling, which started with (LDA-style) topic models and grew into SVD and n

web.stanford.edu

import numpy as np

# Get the interactive Tools for Matplotlib
%matplotlib notebook
import matplotlib.pyplot as plt
plt.style.use('ggplot')

from sklearn.decomposition import PCA

from gensim.test.utils import datapath, get_tmpfile
from gensim.models import KeyedVectors
from gensim.scripts.glove2word2vec import glove2word2vec
 
glove_file = datapath('/Users/manning/Corpora/GloVe/glove.6B.100d.txt')
word2vec_glove_file = get_tmpfile("glove.6B.100d.word2vec.txt")
glove2word2vec(glove_file, word2vec_glove_file)
model = KeyedVectors.load_word2vec_format(word2vec_glove_file)
model.most_similar('obama')
model.most_similar('banana')
model.most_similar(negative='banana')
result = model.most_similar(positive=['woman', 'king'], negative=['man'])
print("{}: {:.4f}".format(*result[0]))
def analogy(x1, x2, y1):
    result = model.most_similar(positive=[y1, x2], negative=[x1])
    return result[0][0]
Analogy

analogy('japan', 'japanese', 'australia')
analogy('australia', 'beer', 'france')
analogy('obama', 'clinton', 'reagan')
analogy('tall', 'tallest', 'long')
analogy('good', 'fantastic', 'bad')
print(model.doesnt_match("breakfast cereal dinner lunch".split()))
 
def display_pca_scatterplot(model, words=None, sample=0):
    if words == None:
        if sample > 0:
            words = np.random.choice(list(model.vocab.keys()), sample)
        else:
            words = [ word for word in model.vocab ]
        
    word_vectors = np.array([model[w] for w in words])

    twodim = PCA().fit_transform(word_vectors)[:,:2]
    
    plt.figure(figsize=(6,6))
    plt.scatter(twodim[:,0], twodim[:,1], edgecolors='k', c='r')
    for word, (x,y) in zip(words, twodim):
        plt.text(x+0.05, y+0.05, word)
 
display_pca_scatterplot(model, 
                        ['coffee', 'tea', 'beer', 'wine', 'brandy', 'rum', 'champagne', 'water',
                         'spaghetti', 'borscht', 'hamburger', 'pizza', 'falafel', 'sushi', 'meatballs',
                         'dog', 'horse', 'cat', 'monkey', 'parrot', 'koala', 'lizard',
                         'frog', 'toad', 'monkey', 'ape', 'kangaroo', 'wombat', 'wolf',
                         'france', 'germany', 'hungary', 'luxembourg', 'australia', 'fiji', 'china',
                         'homework', 'assignment', 'problem', 'exam', 'test', 'class',
                         'school', 'college', 'university', 'institute'])
display_pca_scatterplot(model, sample=300)
반응형
반응형

데이터 분석을 위한 필수 패키지 삼대장이 있습니다. 바로 Pandas와 Numpy 그리고 Matplotlib입니다. 

 

CMD는 "관리자 권한으로 실행" 하시오. 

 

판다스(Pandas)는 파이썬 데이터 처리를 위한 라이브러리입니다. 파이썬을 이용한 데이터 분석과 같은 작업에서 필수 라이브러리로 알려져있습니다. 참고 할 수 있는 Pandas 링크는 다음과 같습니다.

링크 : http://pandas.pydata.org/pandas-docs/stable/

아나콘다를 설치하지 않았다면 아래의 커맨드로 Pandas를 별도 설치할 수 있습니다.

pip install pandas
pip uninstall pandas

>import pandas as pd
>pd.__version__



Pandas는 총 세 가지의 데이터 구조를 사용합니다.
1. 시리즈(Series)
2. 데이터프레임(DataFrame)
3. 패널(Panel)

 

 

1. 시리즈(Series)

sr = pd.Series([17000, 18000, 1000, 5000],
       index=["피자", "치킨", "콜라", "맥주"])
print(sr)
피자    17000
치킨    18000
콜라     1000
맥주     5000
dtype: int64
print(sr.values)
[17000 18000  1000  5000]
print(sr.index)
Index(['피자', '치킨', '콜라', '맥주'], dtype='object')

2) 데이터프레임(DataFrame)

데이터프레임은 2차원 리스트를 매개변수로 전달합니다. 2차원이므로 행방향 인덱스(index)와 열방향 인덱스(column)가 존재합니다. 즉, 행과 열을 가지는 자료구조입니다. 시리즈가 인덱스(index)와 값(values)으로 구성된다면, 데이터프레임은 열(columns)까지 추가되어 열(columns), 인덱스(index), 값(values)으로 구성됩니다.

values = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
index = ['one', 'two', 'three']
columns = ['A', 'B', 'C']

df = pd.DataFrame(values, index=index, columns=columns)
print(df)
       A  B  C
one    1  2  3
two    4  5  6
three  7  8  9
print(df.index) # 인덱스 출력
Index(['one', 'two', 'three'], dtype='object')
print(df.columns) # 열 출력
Index(['A', 'B', 'C'], dtype='object')
print(df.values) # 값 출력
[[1 2 3]
 [4 5 6]
 [7 8 9]]

 

넘파이(Numpy)는 수치 데이터를 다루는 파이썬 패키지입니다. Numpy의 핵심이라고 불리는 다차원 행렬 자료구조인 ndarray를 통해 벡터 및 행렬을 사용하는 선형 대수 계산에서 주로 사용됩니다. Numpy는 편의성뿐만 아니라, 속도면에서도 순수 파이썬에 비해 압도적으로 빠르다는 장점이 있습니다.

pip install numpy
> ipython
...
In [1]: import numpy as np
In [2]: np.__version__
Out[2]: '1.16.5'

Numpy의 주요 모듈은 아래와 같습니다.
1. np.array() # 리스트, 튜플, 배열로 부터 ndarray를 생성
2. np.asarray() # 기존의 array로 부터 ndarray를 생성
3. np.arange() # range와 비슷
4. np.linspace(start, end, num) # [start, end] 균일한 간격으로 num개 생성
5. np.logspace(start, end, num) # [start, end] log scale 간격으로 num개 생성

 

 

맷플롯립(Matplotlib)은 데이터를 차트(chart)나 플롯(plot)으로 시각화(visulaization)하는 패키지입니다. 데이터 분석에서 Matplotlib은 데이터 분석 이전에 데이터 이해를 위한 시각화나, 데이터 분석 후에 결과를 시각화하기 위해서 사용됩니다.

%matplotlib inline
import matplotlib.pyplot as plt

plt.title('test')
plt.plot([1,2,3,4],[2,4,8,6])
plt.show()

 

wikidocs.net/32829

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net

 

반응형
반응형

pandas 설치 후 import 했는데 오류날때

fails to pass a sanity check due to a bug in the windows runtime. See this issue for more information: https://tinyurl.com/y3dm3h86

RuntimeError: The current Numpy installation fails to pass a sanity check due to a bug in the windows runtime [duplicate]

 

RuntimeError: The current Numpy installation fails to pass a sanity check due to a bug in the windows runtime

I am using Python 3.9 on Windows 10 version 2004 x64. PowerShell as Administrator. Python verion: Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Ins...

stackoverflow.com

pip install virtualenv
virtualenv foo
cd .\foo
.\Scripts\active
pip install numpy
pip install matplotlib

 

반응형
반응형

Python Numpy Tutorial



Table of contents:



반응형
반응형

TensorFlow-Tutorials

Introduction to deep learning based on Google's TensorFlow framework. These tutorials are direct ports of Newmu's Theano Tutorials.

Topics

Dependencies

  • TensorFlow 1.0 alpha
  • Numpy
  • matplotlib



# TensorFlow-Tutorials

[![Build Status](https://travis-ci.org/nlintz/TensorFlow-Tutorials.svg?branch=master)](https://travis-ci.org/nlintz/TensorFlow-Tutorials)

[![Codacy Badge](https://api.codacy.com/project/badge/grade/2d3ed69cdbec4249ab5c2f7e4286bb8f)](https://www.codacy.com/app/hunkim/TensorFlow-Tutorials)


Introduction to deep learning based on Google's TensorFlow framework. These tutorials are direct ports of

Newmu's [Theano Tutorials](https://github.com/Newmu/Theano-Tutorials).


***Topics***

* [Simple Multiplication](00_multiply.py)

* [Linear Regression](01_linear_regression.py)

* [Logistic Regression](02_logistic_regression.py)

* [Feedforward Neural Network (Multilayer Perceptron)](03_net.py)

* [Deep Feedforward Neural Network (Multilayer Perceptron with 2 Hidden Layers O.o)](04_modern_net.py)

* [Convolutional Neural Network](05_convolutional_net.py)

* [Denoising Autoencoder](06_autoencoder.py)

* [Recurrent Neural Network (LSTM)](07_lstm.py)

* [Word2vec](08_word2vec.py)

* [TensorBoard](09_tensorboard.py)

* [Save and restore net](10_save_restore_net.py)

* [Generative Adversarial Network](11_gan.py)


***Dependencies***

* TensorFlow 1.0 alpha

* Numpy

* matplotlib



.

반응형

+ Recent posts