### Evaluate a polynomial string


```python
def symbolize(s):
    """
    Converts a a string (equation) to a SymPy symbol object
    """
    from sympy import sympify
    s1=s.replace('.','*')
    s2=s1.replace('^','**')
    s3=sympify(s2)
    
    return(s3)
```


```python
def eval_multinomial(s,vals=None,symbolic_eval=False):
    """
    Evaluates polynomial at vals.
    vals can be simple list, dictionary, or tuple of values.
    vals can also contain symbols instead of real values provided those symbols have been declared before using SymPy
    """
    from sympy import Symbol
    sym_s=symbolize(s)
    sym_set=sym_s.atoms(Symbol)
    sym_lst=[]
    for s in sym_set:
        sym_lst.append(str(s))
    sym_lst.sort()
    if symbolic_eval==False and len(sym_set)!=len(vals):
        print("Length of the input values did not match number of variables and symbolic evaluation is not selected")
        return None
    else:
        if type(vals)==list:
            sub=list(zip(sym_lst,vals))
        elif type(vals)==dict:
            l=list(vals.keys())
            l.sort()
            lst=[]
            for i in l:
                lst.append(vals[i])
            sub=list(zip(sym_lst,lst))
        elif type(vals)==tuple:
            sub=list(zip(sym_lst,list(vals)))
        result=sym_s.subs(sub)
    
    return result
```

### Helper function for flipping binary values of a _ndarray_


```python
def flip(y,p):
    import numpy as np
    lst=[]
    for i in range(len(y)):
        f=np.random.choice([1,0],p=[p,1-p])
        lst.append(f)
    lst=np.array(lst)
    return np.array(np.logical_xor(y,lst),dtype=int)
```

### Classification sample generation based on a symbolic expression


```python
def gen_classification_symbolic(m=None,n_samples=100,n_features=2,flip_y=0.0):
    """
    Generates classification sample based on a symbolic expression.
    Calculates the output of the symbolic expression at randomly generated (Gaussian distribution) points and
    assigns binary classification based on sign.
    m: The symbolic expression. Needs x1, x2, etc as variables and regular python arithmatic symbols to be used.
    n_samples: Number of samples to be generated
    n_features: Number of variables. This is automatically inferred from the symbolic expression. So this is ignored 
                in case a symbolic expression is supplied. However if no symbolic expression is supplied then a 
                default simple polynomial can be invoked to generate classification samples with n_features.
    flip_y: Probability of flipping the classification labels randomly. A higher value introduces more noise and make
            the classification problem harder.
    Returns a numpy ndarray with dimension (n_samples,n_features+1). Last column is the response vector.
    """
    
    import numpy as np
    from sympy import Symbol,sympify
    
    if m==None:
        m=''
        for i in range(1,n_features+1):
            c='x'+str(i)
            c+=np.random.choice(['+','-'],p=[0.5,0.5])
            m+=c
        m=m[:-1]
    sym_m=sympify(m)
    n_features=len(sym_m.atoms(Symbol))
    evals=[]
    lst_features=[]
    for i in range(n_features):
        lst_features.append(np.random.normal(scale=5,size=n_samples))
    lst_features=np.array(lst_features)
    lst_features=lst_features.T
    for i in range(n_samples):
        evals.append(eval_multinomial(m,vals=list(lst_features[i])))
    
    evals=np.array(evals)
    evals_binary=evals>0
    evals_binary=evals_binary.flatten()
    evals_binary=np.array(evals_binary,dtype=int)
    evals_binary=flip(evals_binary,p=flip_y)
    evals_binary=evals_binary.reshape(n_samples,1)
    
    lst_features=lst_features.reshape(n_samples,n_features)
    x=np.hstack((lst_features,evals_binary))
    
    return (x)
```


```python
x=gen_classification_symbolic(m='2*x1+3*x2+5*x3',n_samples=10,flip_y=0.0)
```


```python
import pandas as pd
df=pd.DataFrame(x)
```


```python
df
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>0</th>
      <th>1</th>
      <th>2</th>
      <th>3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>-0.442614</td>
      <td>-0.523797</td>
      <td>2.300378</td>
      <td>1.0</td>
    </tr>
    <tr>
      <th>1</th>
      <td>-0.463687</td>
      <td>3.200522</td>
      <td>4.309449</td>
      <td>1.0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>-2.580825</td>
      <td>-2.606877</td>
      <td>5.845246</td>
      <td>1.0</td>
    </tr>
    <tr>
      <th>3</th>
      <td>0.888534</td>
      <td>3.727563</td>
      <td>-3.174944</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>4</th>
      <td>-1.120233</td>
      <td>-2.737827</td>
      <td>-8.308171</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>5</th>
      <td>-4.832498</td>
      <td>-6.591497</td>
      <td>5.565251</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>6</th>
      <td>-2.326688</td>
      <td>4.751803</td>
      <td>3.309559</td>
      <td>1.0</td>
    </tr>
    <tr>
      <th>7</th>
      <td>-1.213919</td>
      <td>-10.209268</td>
      <td>2.447471</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>8</th>
      <td>-1.320891</td>
      <td>0.770222</td>
      <td>-8.735817</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>9</th>
      <td>2.150437</td>
      <td>6.061752</td>
      <td>-6.733177</td>
      <td>0.0</td>
    </tr>
  </tbody>
</table>
</div>




```python
x=gen_classification_symbolic(m='12*x1/(x2+5*x3)',n_samples=10,flip_y=0.2)
df=pd.DataFrame(x)
df
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>0</th>
      <th>1</th>
      <th>2</th>
      <th>3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>5.566707</td>
      <td>7.645691</td>
      <td>0.559811</td>
      <td>1.0</td>
    </tr>
    <tr>
      <th>1</th>
      <td>-10.528796</td>
      <td>2.241197</td>
      <td>-4.216359</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>5.000866</td>
      <td>0.615997</td>
      <td>2.021055</td>
      <td>1.0</td>
    </tr>
    <tr>
      <th>3</th>
      <td>2.919458</td>
      <td>3.593280</td>
      <td>0.498438</td>
      <td>1.0</td>
    </tr>
    <tr>
      <th>4</th>
      <td>4.671159</td>
      <td>-0.679506</td>
      <td>-5.125242</td>
      <td>1.0</td>
    </tr>
    <tr>
      <th>5</th>
      <td>-4.484902</td>
      <td>-12.881067</td>
      <td>2.340985</td>
      <td>1.0</td>
    </tr>
    <tr>
      <th>6</th>
      <td>1.302499</td>
      <td>-5.054502</td>
      <td>-1.396578</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>7</th>
      <td>-2.321861</td>
      <td>-2.548314</td>
      <td>2.881654</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>8</th>
      <td>-7.021660</td>
      <td>4.530175</td>
      <td>2.701544</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>9</th>
      <td>-9.778964</td>
      <td>-0.132642</td>
      <td>4.021956</td>
      <td>0.0</td>
    </tr>
  </tbody>
</table>
</div>



### Regression sample generation based on a symbolic expression


```python
def gen_regression_symbolic(m=None,n_samples=100,n_features=2,noise=0.0,noise_dist='normal'):
    """
    Generates regression sample based on a symbolic expression. Calculates the output of the symbolic expression 
    at randomly generated (drawn from a Gaussian distribution) points
    m: The symbolic expression. Needs x1, x2, etc as variables and regular python arithmatic symbols to be used.
    n_samples: Number of samples to be generated
    n_features: Number of variables. This is automatically inferred from the symbolic expression. So this is ignored 
                in case a symbolic expression is supplied. However if no symbolic expression is supplied then a 
                default simple polynomial can be invoked to generate regression samples with n_features.
    noise: Magnitude of Gaussian noise to be introduced (added to the output).
    noise_dist: Type of the probability distribution of the noise signal. 
    Currently supports: Normal, Uniform, t, Beta, Gamma, Poission, Laplace

    Returns a numpy ndarray with dimension (n_samples,n_features+1). Last column is the response vector.
    """
    
    import numpy as np
    from sympy import Symbol,sympify
    
    if m==None:
        m=''
        for i in range(1,n_features+1):
            c='x'+str(i)
            c+=np.random.choice(['+','-'],p=[0.5,0.5])
            m+=c
        m=m[:-1]
    
    sym_m=sympify(m)
    n_features=len(sym_m.atoms(Symbol))
    evals=[]
    lst_features=[]
    
    for i in range(n_features):
        lst_features.append(np.random.normal(scale=5,size=n_samples))
    lst_features=np.array(lst_features)
    lst_features=lst_features.T
    lst_features=lst_features.reshape(n_samples,n_features)
    
    for i in range(n_samples):
        evals.append(eval_multinomial(m,vals=list(lst_features[i])))
    
    evals=np.array(evals)
    evals=evals.reshape(n_samples,1)
    
    if noise_dist=='normal':
        noise_sample=noise*np.random.normal(loc=0,scale=1.0,size=n_samples)
    elif noise_dist=='uniform':
        noise_sample=noise*np.random.uniform(low=0,high=1.0,size=n_samples)
    elif noise_dist=='beta':
        noise_sample=noise*np.random.beta(a=0.5,b=1.0,size=n_samples)
    elif noise_dist=='Gamma':
        noise_sample=noise*np.random.gamma(shape=1.0,scale=1.0,size=n_samples)
    elif noise_dist=='laplace':
        noise_sample=noise*np.random.laplace(loc=0.0,scale=1.0,size=n_samples)
        
    noise_sample=noise_sample.reshape(n_samples,1)
    evals=evals+noise_sample
        
    x=np.hstack((lst_features,evals))
    
    return (x)
```

#### Generate samples with a rational function as input 
### $$\frac{10x_1}{(3x_2+4x_3)}$$


```python
x=gen_regression_symbolic(m='10*x1/(3*x2+4*x3)',n_samples=10,noise=0.1)
df=pd.DataFrame(x)
df
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>0</th>
      <th>1</th>
      <th>2</th>
      <th>3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>-7.08499</td>
      <td>-4.35839</td>
      <td>8.10732</td>
      <td>-3.67783156896633</td>
    </tr>
    <tr>
      <th>1</th>
      <td>-10.6684</td>
      <td>0.779056</td>
      <td>-6.64651</td>
      <td>4.45796155973331</td>
    </tr>
    <tr>
      <th>2</th>
      <td>-6.69542</td>
      <td>-5.307</td>
      <td>1.17935</td>
      <td>5.95108211351032</td>
    </tr>
    <tr>
      <th>3</th>
      <td>-3.83581</td>
      <td>6.46401</td>
      <td>-5.99678</td>
      <td>8.28104884665168</td>
    </tr>
    <tr>
      <th>4</th>
      <td>-1.50995</td>
      <td>-1.46056</td>
      <td>-4.10213</td>
      <td>0.493224249022704</td>
    </tr>
    <tr>
      <th>5</th>
      <td>2.22995</td>
      <td>-1.12163</td>
      <td>4.41009</td>
      <td>1.51213441402200</td>
    </tr>
    <tr>
      <th>6</th>
      <td>4.26261</td>
      <td>0.982687</td>
      <td>7.0676</td>
      <td>1.31581579041464</td>
    </tr>
    <tr>
      <th>7</th>
      <td>0.787195</td>
      <td>2.20071</td>
      <td>-4.68889</td>
      <td>-0.724650906335961</td>
    </tr>
    <tr>
      <th>8</th>
      <td>0.720728</td>
      <td>-2.32469</td>
      <td>-0.468637</td>
      <td>-0.917106940761226</td>
    </tr>
    <tr>
      <th>9</th>
      <td>-3.04485</td>
      <td>-3.26701</td>
      <td>-3.19083</td>
      <td>1.40239700700260</td>
    </tr>
  </tbody>
</table>
</div>



#### Generate samples with no symbolic input and with 10 features


```python
x=gen_regression_symbolic(n_features=10,n_samples=10,noise=0.1)
df=pd.DataFrame(x)
df
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>0</th>
      <th>1</th>
      <th>2</th>
      <th>3</th>
      <th>4</th>
      <th>5</th>
      <th>6</th>
      <th>7</th>
      <th>8</th>
      <th>9</th>
      <th>10</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>-3.55302</td>
      <td>-3.60695</td>
      <td>-10.0729</td>
      <td>7.85252</td>
      <td>-3.76276</td>
      <td>7.78251</td>
      <td>-0.638193</td>
      <td>-4.75034</td>
      <td>-0.989603</td>
      <td>0.181414</td>
      <td>-10.2675547899900</td>
    </tr>
    <tr>
      <th>1</th>
      <td>-6.34778</td>
      <td>-2.74753</td>
      <td>-4.75187</td>
      <td>4.70489</td>
      <td>2.70014</td>
      <td>5.29475</td>
      <td>-0.190095</td>
      <td>4.85289</td>
      <td>-4.50207</td>
      <td>-1.22839</td>
      <td>-1.93507315813350</td>
    </tr>
    <tr>
      <th>2</th>
      <td>2.15057</td>
      <td>-0.43572</td>
      <td>-5.47805</td>
      <td>6.96074</td>
      <td>3.10096</td>
      <td>-1.50898</td>
      <td>1.09913</td>
      <td>4.73097</td>
      <td>-0.216513</td>
      <td>-3.25629</td>
      <td>4.91632094325713</td>
    </tr>
    <tr>
      <th>3</th>
      <td>1.11181</td>
      <td>5.62156</td>
      <td>0.0660036</td>
      <td>6.66565</td>
      <td>1.88656</td>
      <td>-4.57167</td>
      <td>-0.84389</td>
      <td>-2.44545</td>
      <td>1.66649</td>
      <td>7.36169</td>
      <td>18.0607243993836</td>
    </tr>
    <tr>
      <th>4</th>
      <td>-3.27857</td>
      <td>-4.13545</td>
      <td>4.36299</td>
      <td>-3.73405</td>
      <td>-1.3958</td>
      <td>-6.39237</td>
      <td>1.99202</td>
      <td>-0.216661</td>
      <td>-10.3905</td>
      <td>3.43896</td>
      <td>-23.7181534803553</td>
    </tr>
    <tr>
      <th>5</th>
      <td>-6.78726</td>
      <td>-7.76895</td>
      <td>-2.2653</td>
      <td>-3.4326</td>
      <td>-16.8937</td>
      <td>-1.79111</td>
      <td>4.79866</td>
      <td>-4.43692</td>
      <td>2.01342</td>
      <td>-3.46766</td>
      <td>-49.7886776301048</td>
    </tr>
    <tr>
      <th>6</th>
      <td>1.66157</td>
      <td>-4.34424</td>
      <td>6.69391</td>
      <td>-3.42321</td>
      <td>-8.63976</td>
      <td>0.862722</td>
      <td>2.70897</td>
      <td>-13.5047</td>
      <td>-7.14555</td>
      <td>-3.16143</td>
      <td>-33.7432854958296</td>
    </tr>
    <tr>
      <th>7</th>
      <td>3.46949</td>
      <td>7.11633</td>
      <td>-1.08523</td>
      <td>6.41709</td>
      <td>-1.23161</td>
      <td>7.07956</td>
      <td>6.6377</td>
      <td>6.06688</td>
      <td>-4.99262</td>
      <td>3.85005</td>
      <td>19.9862211512126</td>
    </tr>
    <tr>
      <th>8</th>
      <td>1.13155</td>
      <td>4.02597</td>
      <td>-3.05607</td>
      <td>4.9271</td>
      <td>-3.60454</td>
      <td>6.06252</td>
      <td>0.936673</td>
      <td>4.07096</td>
      <td>-2.04052</td>
      <td>5.11093</td>
      <td>15.8002295267657</td>
    </tr>
    <tr>
      <th>9</th>
      <td>-1.6051</td>
      <td>4.97768</td>
      <td>-7.69743</td>
      <td>-0.65865</td>
      <td>4.07053</td>
      <td>2.98333</td>
      <td>-10.9341</td>
      <td>4.9402</td>
      <td>2.9771</td>
      <td>0.68357</td>
      <td>21.5880195549236</td>
    </tr>
  </tbody>
</table>
</div>




```python
import matplotlib.pyplot as plt
```

#### Generate samples with less noise and plot: $0.2x^2+1.2x+6+f_{noise}(x\mid{N=0.1})$


```python
x=gen_regression_symbolic(m='0.2*x**2+1.2*x+6',n_samples=100,noise=0.1)
df=pd.DataFrame(x)
plt.scatter(df[0],df[1])
plt.show()
```

#### Generate samples with more noise and plo: $0.2x^2+1.2x+6+f_{noise}(x\mid{N=10})$


```python
x=gen_regression_symbolic(m='0.2*x**2+1.2*x+6',n_samples=100,noise=10)
df=pd.DataFrame(x)
plt.scatter(df[0],df[1])
plt.show()
```

#### Generate samples with larger coefficent for the quadratic term and plot: $1.3x^2+1.2x+6+f_{noise}(x\mid{N=10})$


```python
x=gen_regression_symbolic(m='1.3*x**2+1.2*x+6',n_samples=100,noise=10)
df=pd.DataFrame(x)
plt.scatter(df[0],df[1])
plt.show()
```

725888460eae554617efe613ef07595548bd595b
ipynb
Jupyter Notebook
Random Function Generator/Symbolic regression classification generator.ipynb
jaymedina/Machine-Learning-with-Python
203ef467cfa6d180c5cb67ffa2fcbb0ee514047e
BSD-2-Clause
2018-11-26T20:53:23.000Z
2022-03-31T15:25:29.000Z
Random Function Generator/Symbolic regression classification generator.ipynb
jaymedina/Machine-Learning-with-Python
203ef467cfa6d180c5cb67ffa2fcbb0ee514047e
BSD-2-Clause
2019-02-05T04:09:57.000Z
2022-02-19T23:46:27.000Z
Random Function Generator/Symbolic regression classification generator.ipynb
jaymedina/Machine-Learning-with-Python
203ef467cfa6d180c5cb67ffa2fcbb0ee514047e
BSD-2-Clause
2018-11-28T19:48:55.000Z
2022-03-31T15:25:07.000Z
Qwen/Qwen-72B
1. YES
2. YES