Monday, April 18, 2022

How to convert images to dataset Python

 Code 1

(.env) [boris@fedora35server PILLOW]$ cat imageShow.py

# load and display an image with Matplotlib

from matplotlib import image

from matplotlib import pyplot

# load image as pixel array

image = image.imread('coala.jpeg')

# summarize shape of the pixel array

print(image.dtype)

print(image.shape)

# display the array of pixels as an image

pyplot.imshow(image)

pyplot.show()





























Code 2

(.env) [boris@fedora35server PILLOW]$ cat imageToNDArray.py

from PIL import Image
from numpy import savetxt
from numpy import savez_compressed
from numpy import asarray


# load the image
image = Image.open('coala.jpeg')

# convert image to numpy array
data = asarray(image)
print(type(data))
print(data)

# unload 3D array to files via reshape
savetxt("data.txt", data.reshape((3,-1)), fmt="%s", header=str(data.shape))
savez_compressed("data.npz", data.reshape((3,-1)), fmt="%s", header=str(data.shape))
print("Both Unloads data done")


# summarize shape
print(data.shape)

# create Pillow image
image2 = Image.fromarray(data)
print(type(image2))
# summarize image details
print(image2.mode)
print(image2.size)

(.env) [boris@fedora35server PILLOW]$ python imageToNDArray.py
<class 'numpy.ndarray'>
[[[ 25  26  12]
  [ 25  26  12]
  [ 25  26  12]
  ...
  [113 106  52]
  [113 106  52]
  [114 107  53]]

 [[ 25  26  12]
  [ 25  26  12]
  [ 25  26  12]
  ...
  [113 106  52]
  [113 106  52]
  [114 107  53]]

 [[ 25  26  12]
  [ 25  26  12]
  [ 25  26  12]
  ...
  [112 105  51]
  [113 106  52]
  [113 106  52]]

 ...

 [[139 118  71]
  [136 115  68]
  [130 109  62]
  ...
  [ 67  91  91]
  [ 68  89  90]
  [ 66  88  86]]

 [[150 128  81]
  [143 121  74]
  [134 111  67]
  ...
  [ 73  93  91]
  [ 69  89  87]
  [ 65  85  83]]

 [[151 127  81]
  [144 120  74]
  [135 111  67]
  ...
  [ 74  93  91]
  [ 70  89  85]
  [ 66  85  81]]]
(450, 800, 3)
<class 'PIL.Image.Image'>
RGB
(800, 450)

Можно получить CSV сразу через 2-ух цветовую гамму

(.env) [boris@fedora35server PILLOW]$ cat imageToCSV.py
from PIL import Image
import numpy as np
import sys
import os
import csv

#Useful function
def createFileList(myDir, format='.jpeg'):
  fileList = []
  print(myDir)
  for root, dirs, files in os.walk(myDir, topdown=False):
      for name in files:
         if name.endswith(format):
              fullName = os.path.join(root, name)
              fileList.append(fullName)
  return fileList

# load the original image
myFileList = createFileList('./')

for file in myFileList:
    print(file)
    img_file = Image.open(file)
    # img_file.show()

    # get original image parameters...
    width, height = img_file.size
    format = img_file.format
    mode = img_file.mode

    # Make image Greyscale
    img_grey = img_file.convert('L')
    img_grey.save('result.png')
    img_grey.show()

    # Save Greyscale values
    value = np.asarray(img_grey.getdata(), dtype=int).reshape((img_grey.size[1], img_grey.size[0]))
    value = value.flatten()
    print(value)
    with open("img_pixels.csv", 'a') as f:
        writer = csv.writer(f)
        writer.writerow(value)































(.env) [boris@fedora35server PILLOW]$ python imageToCSV.py
./
./coala.jpeg
[24 24 24 ... 87 83 79]
(.env) [boris@fedora35server PILLOW]$ ll
total 4680
-rw-r--r--. 1 boris boris   44769 Apr 18 10:42 coala.jpeg
-rw-rw-r--. 1 boris boris     318 Apr 18 10:49 imageShow.py
-rw-rw-r--. 1 boris boris    1071 Apr 18 13:44 imageToCSV.py
-rw-rw-r--. 1 boris boris     691 Apr 18 13:33 imageToNDArray.py
-rw-rw-r--. 1 boris boris 2514008 Apr 18 13:52 img_pixels.csv
-rw-rw-r--. 1 boris boris  144709 Apr 18 13:52 result.png

Преобразование изображения с помощью Keras API

(.env) [boris@fedora35server PILLOW]$ cat imageConvTF.py
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.preprocessing.image import array_to_img
from tensorflow.keras.preprocessing.image import save_img

# load the image
img = load_img('coala.jpeg')
print("Orignal:" ,type(img))
print(type(img))
print(img.format)
print(img.mode)
print(img.size)
img.show()

# convert to numpy array
img_array = img_to_array(img)
print("NumPy array info:") 
print(type(img_array))    

print("type:",img_array.dtype)
print("shape:",img_array.shape)
print(img_array)
# convert back to image

img_pil = array_to_img(img_array)
print("converting NumPy array:",type(img_pil))































References

Wednesday, April 13, 2022

Using JSON in MariaDB

 Следую документу https://mariadb.com/resources/blog/using-json-in-mariadb/

Ставить MySQL 8.X на Fedory 35 - не лучшая идея.

Структурированные данные + Полуструктурированные данные

Существует множество вариантов использования, в которых имеет смысл комбинировать структурированные и полуструктурированные данные. Это просто мир разработки программного обеспечения для вас. Тем не менее, я всегда считал, что проще всего использовать новые технологии, сосредоточившись на простом, (надеюсь) подходящем сценарии использования, который вы затем можете использовать, чтобы получить свои собственные творческие соки.


Чтобы помочь разобраться с возможностями JSON, доступными в MariaDB, я буду использовать гипотетическое приложение. Это приложение будет содержать только одну таблицу, называемую местоположениями, в которой будут храниться, да, как вы уже догадались, местоположения. Достаточно просто, не так ли?

Введите JSON, который можно использовать для управления различной информацией для каждого типа местоположения. Таким образом, таблица местоположений будет содержать как структурированные, так и полуструктурированные данные.





СОЗДАНИЕ ТАБЛИЦ

Использовать JSON в MariaDB так же просто, как включить возможность хранить данные JSON в таблице. На самом деле SQL, используемый для создания новой таблицы местоположений, должен выглядеть очень знакомо.





MariaDB [verify]> create database datajs ;

Query OK, 1 row affected (0.001 sec)

MariaDB [verify]> use datajs ;

Database changed

MariaDB [datajs]> CREATE TABLE locations (

->     id INT NOT NULL AUTO_INCREMENT,

->     name VARCHAR(100) NOT NULL,  

->     type CHAR(1) NOT NULL,

->     latitude DECIMAL(9,6) NOT NULL,

->     longitude DECIMAL(9,6) NOT NULL,

->     attr JSON, 

->     PRIMARY KEY (id)

-> );

Query OK, 0 rows affected (0.010 sec)

MariaDB [datajs]> desc locations ;

+-----------+--------------+------+-----+---------+----------------+

| Field     | Type         | Null | Key | Default | Extra          |

+-----------+--------------+------+-----+---------+----------------+

| id        | int(11)      | NO   | PRI | NULL    | auto_increment |

| name      | varchar(100) | NO   |     | NULL    |                |

| type      | char(1)      | NO   |     | NULL    |                |

| latitude  | decimal(9,6) | NO   |     | NULL    |                |

| longitude | decimal(9,6) | NO   |     | NULL    |                |

| attr      | longtext     | YES  |     | NULL    |                |

+-----------+--------------+------+-----+---------+----------------+

6 rows in set (0.001 sec)

MariaDB [datajs]> INSERT INTO locations (type, name, latitude, longitude, attr) VALUES 

->     ('R', 'Lou Malnatis', 42.0021628, -87.7255662,

->       '{"details": {"foodType": "Pizza", "menu": 

'>     "https://www.loumalnatis.com/our-menu"}, 

'>     "favorites": [{"description": "Pepperoni deep dish", "price": 18.75}, 

'>          {"description": "The Lou", "price": 24.75}]}');

Query OK, 1 row affected, 2 warnings (0.001 sec)

=================

MariaDB [datajs]> INSERT INTO locations (type, name, latitude, longitude, attr) VALUES 

->     ('A', 'Cloud Gate', 41.8826572, -87.6233039, 

->           '{"category": "Landmark", "lastVisitDate": "11/10/2019"}');

Query OK, 1 row affected, 2 warnings (0.001 sec)

MariaDB [datajs]> SELECT name, latitude, longitude,

->     JSON_VALUE(attr, '$.details.foodType') AS food_type

-> FROM locations

-> WHERE type = 'R';

+--------------+-----------+------------+-----------+

| name         | latitude  | longitude  | food_type |

+--------------+-----------+------------+-----------+

| Lou Malnatis | 42.002163 | -87.725566 | Pizza     |

+--------------+-----------+------------+-----------+

1 row in set (0.001 sec)

===================

MariaDB [datajs]> SELECT name, latitude, longitude,

->     JSON_VALUE(attr, '$.details.foodType') AS food_type

-> FROM locations ;

+--------------+-----------+------------+-----------+

| name         | latitude  | longitude  | food_type |

+--------------+-----------+------------+-----------+

| Lou Malnatis | 42.002163 | -87.725566 | Pizza     |

| Cloud Gate   | 41.882657 | -87.623304 | NULL      |

+--------------+-----------+------------+-----------+

2 rows in set (0.001 sec)

==================

Index Creating

==================

MariaDB [datajs]> ALTER TABLE locations ADD COLUMN 

->     food_type VARCHAR(25) AS (JSON_VALUE(attr, '$.details.foodType')) VIRTUAL;

Query OK, 0 rows affected (0.009 sec)

Records: 0  Duplicates: 0  Warnings: 0

MariaDB [datajs]> CREATE INDEX foodtypes ON locations(food_type);

Query OK, 0 rows affected (0.008 sec)

Records: 0  Duplicates: 0  Warnings: 0

MariaDB [datajs]> select id from locations;

+----+

| id |

+----+

|  2 |

|  1 |

+----+

2 rows in set (0.001 sec)

MariaDB [datajs]> UPDATE locations

-> SET attr = JSON_INSERT(attr,'$.nickname','The Bean')

-> WHERE id = 1;

Query OK, 1 row affected (0.002 sec)

Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [datajs]> UPDATE locations

->     SET attr = JSON_INSERT(attr,

->                              '$.foodTypes',

->         JSON_ARRAY('Asian', 'Mexican'))

-> WHERE id = 1;

Query OK, 1 row affected (0.002 sec)

Rows matched: 1  Changed: 1  Warnings: 0

================================

[boris@fedora35server ~]$ mysql -u root -p

Enter password: 

Welcome to the MariaDB monitor.  Commands end with ; or \g.

Your MariaDB connection id is 13

Server version: 10.5.13-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

=================================

MariaDB [(none)]> use datajs;

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

Database changed

MariaDB [datajs]> desc locations;

+-----------+--------------+------+-----+---------+-------------------+

| Field     | Type         | Null | Key | Default | Extra             |

+-----------+--------------+------+-----+---------+-------------------+

| id        | int(11)      | NO   | PRI | NULL    | auto_increment    |

| name      | varchar(100) | NO   |     | NULL    |                   |

| type      | char(1)      | NO   |     | NULL    |                   |

| latitude  | decimal(9,6) | NO   |     | NULL    |                   |

| longitude | decimal(9,6) | NO   |     | NULL    |                   |

| attr      | longtext     | YES  |     | NULL    |                   |

| food_type | varchar(25)  | YES  | MUL | NULL    | VIRTUAL GENERATED |

+-----------+--------------+------+-----+---------+-------------------+

7 rows in set (0.002 sec)

MariaDB [datajs]> SELECT name, latitude, longitude,

->     JSON_VALUE(attr, '$.details.foodType') AS food_type

-> FROM locations

-> WHERE type = 'R';

+--------------+-----------+------------+-----------+

| name         | latitude  | longitude  | food_type |

+--------------+-----------+------------+-----------+

| Lou Malnatis | 42.002163 | -87.725566 | Pizza     |

+--------------+-----------+------------+-----------+

1 row in set (0.001 sec)

MariaDB [datajs]> SELECT name, latitude, longitude,

->     JSON_VALUE(attr, '$.details.foodType') AS food_type

-> FROM locations

-> ;

+--------------+-----------+------------+-----------+

| name         | latitude  | longitude  | food_type |

+--------------+-----------+------------+-----------+

| Lou Malnatis | 42.002163 | -87.725566 | Pizza     |

| Cloud Gate   | 41.882657 | -87.623304 | NULL      |

+--------------+-----------+------------+-----------+

2 rows in set (0.001 sec)

MariaDB [datajs]> select * from locations ;

+----+--------------+------+-----------+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+

| id | name         | type | latitude  | longitude  | attr                                                                                                                                                                                                                                                             | food_type |

+----+--------------+------+-----------+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+

|  1 | Lou Malnatis | R    | 42.002163 | -87.725566 | {"details": {"foodType": "Pizza", "menu": "https://www.loumalnatis.com/our-menu"}, "favorites": [{"description": "Pepperoni deep dish", "price": 18.75}, {"description": "The Lou", "price": 24.75}], "nickname": "The Bean", "foodTypes": ["Asian", "Mexican"]} | Pizza     |

|  2 | Cloud Gate   | A    | 41.882657 | -87.623304 | {"category": "Landmark", "lastVisitDate": "11/10/2019"}                                                                                                                                                                                                          | NULL      |

+----+--------------+------+-----------+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+

2 rows in set (0.001 sec)


MariaDB [datajs]> SELECT name,latitude,longitude,

    ->     JSON_QUERY(attr, '$.details') AS details

    -> FROM locations

    -> WHERE type = 'R';

+--------------+-----------+------------+-----------------------------------------------------------------------+

| name         | latitude  | longitude  | details                                                               |

+--------------+-----------+------------+-----------------------------------------------------------------------+

| Lou Malnatis | 42.002163 | -87.725566 | {"foodType": "Pizza", "menu": "https://www.loumalnatis.com/our-menu"} |

+--------------+-----------+------------+-----------------------------------------------------------------------+

1 row in set (0.001 sec)


MariaDB [datajs]> SELECT name,latitude,longitude,

    ->     JSON_QUERY(attr, '$.favorites') AS favorites

    -> FROM locations

    -> WHERE type = 'R';

+--------------+-----------+------------+------------------------------------------------------------------------------------------------------+

| name         | latitude  | longitude  | favorites                                                                                            |

+--------------+-----------+------------+------------------------------------------------------------------------------------------------------+

| Lou Malnatis | 42.002163 | -87.725566 | [{"description": "Pepperoni deep dish", "price": 18.75}, {"description": "The Lou", "price": 24.75}] |

+--------------+-----------+------------+------------------------------------------------------------------------------------------------------+

1 row in set (0.000 sec)


Introduction to Random Forests in Scikit-Learn (sklearn)

Классификатор случайного леса — это то, что известно как алгоритм ансамбля. Причина этого в том, что он одновременно использует несколько экземпляров другого алгоритма для поиска результата. Помните, что деревья решений склонны к переобучению. Однако вы можете решить эту проблему, просто посадив больше деревьев!

Идея случайного леса — это автоматизированная обработка создания большего количества деревьев решений. Каждое дерево получает голосование с точки зрения того, как классифицировать. Некоторые из этих голосов будут сильно завышены и неточны. Однако при создании сотни деревьев классификация, возвращаемая большинством деревьев, скорее всего, будет наиболее точной. 

Модели машинного обучения имеют некоторые ограничения:

Они не могут работать с отсутствующими данными, и

Они не могут работать с категориальными строковыми данными.











Изучив информацию, возвращаемую методом .info(), вы увидите, что обе эти проблемы существуют в наборе данных. Чтобы иметь возможность использовать этот набор данных для классификации, вам сначала нужно найти способы работы с отсутствующими и категоричными данными. Это именно то, что вы узнаете в следующих двух разделах руководства.

==================================

Мы внедрим класс SimpleImputer из sklearn.impute и numpy.

Мы создалим экземпляр объекта SimpleImputer, ища отсутствующие значения, представленные np.NaN, и попросим Scikit-Learn использовать «среднее» в качестве своей стратегии. Это означает, что любые значения np.NaN будут вменены средним значением столбцов.Затем мы используем метод .fit() и передаем столбец. Наконец, мы используем метод .transform() для передачи вмененных значений в соответствующие столбцы.

====================

(.env) [boris@fedora35server DATARF]$ cat missDataRF1.py

# Loading the Penguins Dataset from Seaborn

import seaborn as sns

import pandas as pd

from sklearn.impute import SimpleImputer

import numpy as np


df = sns.load_dataset('penguins')

print(df.head())

print("Seeing missing data")

print("=========================")

print(df.isnull().sum())


# Create a SimpleImputer Class

imputer = SimpleImputer(missing_values=np.NaN, strategy='mean')


# Fit the columns to the object

columns = ['bill_depth_mm', 'bill_length_mm', 'flipper_length_mm', 'body_mass_g']

imputer=imputer.fit(df[columns])


# Transform the DataFrames column with the fitted data

df[columns]=imputer.transform(df[columns])

print(df.head())

print("Seeing missing data again")

print("=========================")

print(df.isnull().sum())

(.env) [boris@fedora35server DATARF]$ python missDataRF1.py

  species     island  bill_length_mm  ...  flipper_length_mm  body_mass_g     sex

0  Adelie  Torgersen            39.1  ...              181.0       3750.0    Male

1  Adelie  Torgersen            39.5  ...              186.0       3800.0  Female

2  Adelie  Torgersen            40.3  ...              195.0       3250.0  Female

3  Adelie  Torgersen             NaN  ...                NaN          NaN     NaN

4  Adelie  Torgersen            36.7  ...              193.0       3450.0  Female


[5 rows x 7 columns]

Seeing missing data

=========================

species               0

island                0

bill_length_mm        2

bill_depth_mm         2

flipper_length_mm     2

body_mass_g           2

sex                  11

dtype: int64

  species     island  bill_length_mm  ...  flipper_length_mm  body_mass_g     sex

0  Adelie  Torgersen        39.10000  ...         181.000000  3750.000000    Male

1  Adelie  Torgersen        39.50000  ...         186.000000  3800.000000  Female

2  Adelie  Torgersen        40.30000  ...         195.000000  3250.000000  Female

3  Adelie  Torgersen        43.92193  ...         200.915205  4201.754386     NaN

4  Adelie  Torgersen        36.70000  ...         193.000000  3450.000000  Female


[5 rows x 7 columns]

Seeing missing data again

=========================

species               0

island                0

bill_length_mm        0

bill_depth_mm         0

flipper_length_mm     0

body_mass_g           0

sex                  11

dtype: int64















Полная версия кода

(.env) [boris@fedora35server DATARF]$ cat missDataRF.py

# Loading the Penguins Dataset from Seaborn

import seaborn as sns

import pandas as pd

from sklearn.impute import SimpleImputer

import numpy as np

from sklearn.model_selection import train_test_split

from sklearn.ensemble import RandomForestClassifier

import matplotlib.pyplot as plt

from sklearn.tree import plot_tree

from sklearn.preprocessing import OneHotEncoder


df = sns.load_dataset('penguins')

print(df.head())

print("Seeing missing data")

print("=========================")

print(df.isnull().sum())


# Create a SimpleImputer Class

imputer = SimpleImputer(missing_values=np.NaN, strategy='mean')


# Fit the columns to the object

columns = ['bill_depth_mm', 'bill_length_mm', 'flipper_length_mm', 'body_mass_g']

imputer=imputer.fit(df[columns])


# Transform the DataFrames column with the fitted data

df[columns]=imputer.transform(df[columns])

print(df.head())

print("Seeing missing data again")

print("=========================")

print(df.isnull().sum())


#  Dropping missing records in the sex column

df = df.dropna(subset=['sex'])

print(df.isnull().sum())


df['sex int'] = df['sex'].map({'Male': 0, 'Female': 1})

print(df['island'].unique())


# One-hot Encoding the Island Feature

one_hot = OneHotEncoder()

encoded = one_hot.fit_transform(df[['island']])

df[one_hot.categories_[0]] = encoded.toarray()

# Drop unneeded columns

df = df.drop(columns=['island', 'sex'])


# Splitting the data and creating a model

X = df.iloc[:, 1:]

y = df['species']

X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.3, random_state=100)

forest = RandomForestClassifier(n_estimators=100, random_state=100)

forest.fit(X_train,y_train)

predictions = forest.predict(X_test)

# Another import

from sklearn import metrics

print("Accuracy:",metrics.accuracy_score(y_test, predictions))

# Plotting results

fig = plt.figure(figsize=(15, 10))

plot_tree(forest.estimators_[0],

          feature_names=X.columns,

          class_names=df['species'].unique(),

          filled=True, rounded=True)

plt.show()





























Reference